log: add \n
[oweals/gnunet.git] / src / conversation / gnunet-conversation.c
1 /*
2   This file is part of GNUnet.
3   Copyright (C) 2013 GNUnet e.V.
4
5   GNUnet is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published
7   by the Free Software Foundation; either version 3, or (at your
8   option) any later version.
9
10   GNUnet is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with GNUnet; see the file COPYING.  If not, write to the
17   Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18   Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file conversation/gnunet-conversation.c
22  * @brief conversation implementation
23  * @author Simon Dieterle
24  * @author Andreas Fuchs
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_gnsrecord_lib.h"
30 #include "gnunet_conversation_service.h"
31 #include "gnunet_namestore_service.h"
32 #ifdef WINDOWS
33 #include "../util/gnunet-helper-w32-console.h"
34 #endif
35
36 /**
37  * Maximum length allowed for the command line input.
38  */
39 #define MAX_MESSAGE_LENGTH 1024
40
41 #define XSTRINGIFY(x) STRINGIFY(x)
42
43 #define STRINGIFY(x) (#x)
44
45 #ifdef WINDOWS
46 /**
47  * Helper that reads the console for us.
48  */
49 struct GNUNET_HELPER_Handle *stdin_hlp;
50 #endif
51
52 /**
53  * Possible states of the phone.
54  */
55 enum PhoneState
56 {
57   /**
58    * We're waiting for our own idenitty.
59    */
60   PS_LOOKUP_EGO,
61
62   /**
63    * We're listening for calls
64    */
65   PS_LISTEN,
66
67   /**
68    * We accepted an incoming phone call.
69    */
70   PS_ACCEPTED,
71
72   /**
73    * Internal error
74    */
75   PS_ERROR
76 };
77
78
79 /**
80  * States for current outgoing call.
81  */
82 enum CallState
83 {
84   /**
85    * We are looking up some other participant.
86    */
87   CS_RESOLVING,
88
89   /**
90    * We are now ringing the other participant.
91    */
92   CS_RINGING,
93
94   /**
95    * The other party accepted our call and we are now connected.
96    */
97   CS_CONNECTED,
98
99   /**
100    * The call is currently suspended (by us).
101    */
102   CS_SUSPENDED
103
104 };
105
106
107 /**
108  * List of incoming calls
109  */
110 struct CallList
111 {
112
113   /**
114    * A DLL.
115    */
116   struct CallList *prev;
117
118   /**
119    * A DLL.
120    */
121   struct CallList *next;
122
123   /**
124    * Handle to hang up or activate.
125    */
126   struct GNUNET_CONVERSATION_Caller *caller;
127
128   /**
129    * Public key identifying the caller.
130    */
131   struct GNUNET_CRYPTO_EcdsaPublicKey caller_id;
132
133   /**
134    * Unique number of the call.
135    */
136   unsigned int caller_num;
137
138 };
139
140
141
142 /**
143  * Phone handle
144  */
145 static struct GNUNET_CONVERSATION_Phone *phone;
146
147 /**
148  * Call handle (for active outgoing call).
149  */
150 static struct GNUNET_CONVERSATION_Call *call;
151
152 /**
153  * Caller handle (for active incoming call).
154  * This call handler is NOT in the #cl_head / #cl_tail list.
155  */
156 static struct CallList *cl_active;
157
158 /**
159  * Head of calls waiting to be accepted.
160  */
161 static struct CallList *cl_head;
162
163 /**
164  * Tail of calls waiting to be accepted.
165  */
166 static struct CallList *cl_tail;
167
168 /**
169  * Desired phone line (string to be converted to a hash).
170  */
171 static char *line;
172
173 /**
174  * Task which handles the commands
175  */
176 static struct GNUNET_SCHEDULER_Task * handle_cmd_task;
177
178 /**
179  * Our speaker.
180  */
181 static struct GNUNET_SPEAKER_Handle *speaker;
182
183 /**
184  * Our microphone.
185  */
186 static struct GNUNET_MICROPHONE_Handle *mic;
187
188 /**
189  * Our configuration.
190  */
191 static struct GNUNET_CONFIGURATION_Handle *cfg;
192
193 /**
194  * Our ego.
195  */
196 static struct GNUNET_IDENTITY_Ego *my_caller_id;
197
198 /**
199  * Handle to identity service.
200  */
201 static struct GNUNET_IDENTITY_Handle *id;
202
203 /**
204  * Name of our ego.
205  */
206 static char *ego_name;
207
208 /**
209  * Public key of active conversation partner (if any).
210  */
211 static struct GNUNET_CRYPTO_EcdsaPublicKey peer_key;
212
213 /**
214  * Name of active conversation partner (if any).
215  */
216 static char *peer_name;
217
218 /**
219  * File handle for stdin.
220  */
221 static struct GNUNET_DISK_FileHandle *stdin_fh;
222
223 /**
224  * Our phone's current state.
225  */
226 static enum PhoneState phone_state;
227
228 /**
229  * Our call's current state.
230  */
231 static enum CallState call_state;
232
233 /**
234  * Counts the number of incoming calls we have had so far.
235  */
236 static unsigned int caller_num_gen;
237
238 /**
239  * GNS address for this phone.
240  */
241 static char *address;
242
243 /**
244  * Be verbose.
245  */
246 static int verbose;
247
248
249 /**
250  * Function called with an event emitted by a phone.
251  *
252  * @param cls closure
253  * @param code type of the event
254  * @param caller handle for the caller
255  * @param caller_id public key of the caller (in GNS)
256  */
257 static void
258 phone_event_handler (void *cls,
259                      enum GNUNET_CONVERSATION_PhoneEventCode code,
260                      struct GNUNET_CONVERSATION_Caller *caller,
261                      const struct GNUNET_CRYPTO_EcdsaPublicKey *caller_id)
262 {
263   struct CallList *cl;
264
265   switch (code)
266   {
267   case GNUNET_CONVERSATION_EC_PHONE_RING:
268     FPRINTF (stdout,
269              _("Incoming call from `%s'. Please /accept %u or /cancel %u the call.\n"),
270              GNUNET_GNSRECORD_pkey_to_zkey (caller_id),
271              caller_num_gen,
272              caller_num_gen);
273     cl = GNUNET_new (struct CallList);
274     cl->caller = caller;
275     cl->caller_id = *caller_id;
276     cl->caller_num = caller_num_gen++;
277     GNUNET_CONTAINER_DLL_insert (cl_head,
278                                  cl_tail,
279                                  cl);
280     break;
281   case GNUNET_CONVERSATION_EC_PHONE_HUNG_UP:
282     for (cl = cl_head; NULL != cl; cl = cl->next)
283       if (caller == cl->caller)
284         break;
285     if ( (NULL == cl) &&
286          (caller == cl_active->caller) )
287       cl = cl_active;
288     if (NULL == cl)
289     {
290       GNUNET_break (0);
291       return;
292     }
293     FPRINTF (stdout,
294              _("Call from `%s' terminated\n"),
295              GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id));
296     if (cl == cl_active)
297     {
298       cl_active = NULL;
299       phone_state = PS_LISTEN;
300     }
301     else
302     {
303       GNUNET_CONTAINER_DLL_remove (cl_head,
304                                    cl_tail,
305                                    cl);
306     }
307     GNUNET_free (cl);
308     break;
309   }
310 }
311
312
313 /**
314  * Function called with an event emitted by a caller.
315  *
316  * @param cls closure with the `struct CallList` of the caller
317  * @param code type of the event issued by the caller
318  */
319 static void
320 caller_event_handler (void *cls,
321                       enum GNUNET_CONVERSATION_CallerEventCode code)
322 {
323   struct CallList *cl = cls;
324
325   switch (code)
326   {
327   case GNUNET_CONVERSATION_EC_CALLER_SUSPEND:
328     FPRINTF (stdout,
329              _("Call from `%s' suspended by other user\n"),
330              GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id));
331     break;
332   case GNUNET_CONVERSATION_EC_CALLER_RESUME:
333     FPRINTF (stdout,
334              _("Call from `%s' resumed by other user\n"),
335              GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id));
336     break;
337   }
338 }
339
340
341 /**
342  * Start our phone.
343  */
344 static void
345 start_phone ()
346 {
347   struct GNUNET_GNSRECORD_Data rd;
348
349   if (NULL == my_caller_id)
350   {
351     FPRINTF (stderr,
352              _("Ego `%s' no longer available, phone is now down.\n"),
353              ego_name);
354     phone_state = PS_LOOKUP_EGO;
355     return;
356   }
357   GNUNET_assert (NULL == phone);
358   phone = GNUNET_CONVERSATION_phone_create (cfg,
359                                             my_caller_id,
360                                             &phone_event_handler,
361                                             NULL);
362   /* FIXME: get record and print full GNS record info later here... */
363   if (NULL == phone)
364   {
365     FPRINTF (stderr,
366              "%s",
367              _("Failed to setup phone (internal error)\n"));
368     phone_state = PS_ERROR;
369   }
370   else
371   {
372     GNUNET_CONVERSATION_phone_get_record (phone,
373                                           &rd);
374     GNUNET_free_non_null (address);
375     address = GNUNET_GNSRECORD_value_to_string (rd.record_type,
376                                                 rd.data,
377                                                 rd.data_size);
378     FPRINTF (stdout,
379              _("Phone active at `%s'.  Type `/help' for a list of available commands\n"),
380              address);
381     phone_state = PS_LISTEN;
382   }
383 }
384
385
386 /**
387  * Function called with an event emitted by a call.
388  *
389  * @param cls closure, NULL
390  * @param code type of the event on the call
391  */
392 static void
393 call_event_handler (void *cls,
394                     enum GNUNET_CONVERSATION_CallEventCode code)
395 {
396   switch (code)
397   {
398   case GNUNET_CONVERSATION_EC_CALL_RINGING:
399     GNUNET_break (CS_RESOLVING == call_state);
400     FPRINTF (stdout,
401              _("Resolved address of `%s'. Now ringing other party.\n"),
402              peer_name);
403     call_state = CS_RINGING;
404     break;
405   case GNUNET_CONVERSATION_EC_CALL_PICKED_UP:
406     GNUNET_break (CS_RINGING == call_state);
407     FPRINTF (stdout,
408              _("Connection established to `%s'\n"),
409              peer_name);
410     call_state = CS_CONNECTED;
411     break;
412   case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL:
413     GNUNET_break (CS_RESOLVING == call_state);
414     FPRINTF (stdout,
415              _("Failed to resolve `%s'\n"),
416              peer_name);
417     GNUNET_free (peer_name);
418     peer_name = NULL;
419     call = NULL;
420     break;
421   case GNUNET_CONVERSATION_EC_CALL_HUNG_UP:
422     FPRINTF (stdout,
423              _("Call to `%s' terminated\n"),
424              peer_name);
425     GNUNET_free (peer_name);
426     peer_name = NULL;
427     call = NULL;
428     break;
429   case GNUNET_CONVERSATION_EC_CALL_SUSPENDED:
430     GNUNET_break (CS_CONNECTED == call_state);
431     FPRINTF (stdout,
432              _("Connection to `%s' suspended (by other user)\n"),
433              peer_name);
434     break;
435   case GNUNET_CONVERSATION_EC_CALL_RESUMED:
436     GNUNET_break (CS_CONNECTED == call_state);
437     FPRINTF (stdout,
438              _("Connection to `%s' resumed (by other user)\n"),
439              peer_name);
440     break;
441   case GNUNET_CONVERSATION_EC_CALL_ERROR:
442     FPRINTF (stdout,
443              _("Error with the call, restarting it\n"));
444     GNUNET_free (peer_name);
445     peer_name = NULL;
446     call = NULL;
447     break;
448   }
449 }
450
451
452 /**
453  * Function declareation for executing a action
454  *
455  * @param arguments arguments given to the function
456  */
457 typedef void (*ActionFunction) (const char *arguments);
458
459
460 /**
461  * Structure which defines a command
462  */
463 struct VoipCommand
464 {
465   /**
466    * Command the user needs to enter.
467    */
468   const char *command;
469
470   /**
471    * Function to call on command.
472    */
473   ActionFunction Action;
474
475   /**
476    * Help text for the command.
477    */
478   const char *helptext;
479 };
480
481
482 /**
483  * Action function to print help for the command shell.
484  *
485  * @param args arguments given to the command
486  */
487 static void
488 do_help (const char *args);
489
490
491 /**
492  * Terminate the client
493  *
494  * @param args arguments given to the command
495  */
496 static void
497 do_quit (const char *args)
498 {
499   GNUNET_SCHEDULER_shutdown ();
500 }
501
502
503 /**
504  * Handler for unknown command.
505  *
506  * @param msg arguments given to the command
507  */
508 static void
509 do_unknown (const char *msg)
510 {
511   FPRINTF (stderr,
512            _("Unknown command `%s'\n"),
513            msg);
514 }
515
516
517 /**
518  * Initiating a new call
519  *
520  * @param arg arguments given to the command
521  */
522 static void
523 do_call (const char *arg)
524 {
525   if (NULL == my_caller_id)
526   {
527     FPRINTF (stderr,
528              _("Ego `%s' not available\n"),
529              ego_name);
530     return;
531   }
532   if (NULL != call)
533   {
534     FPRINTF (stderr,
535              _("You are calling someone else already, hang up first!\n"));
536     return;
537   }
538   switch (phone_state)
539   {
540   case PS_LOOKUP_EGO:
541     FPRINTF (stderr,
542              _("Ego `%s' not available\n"),
543              ego_name);
544     return;
545   case PS_LISTEN:
546     /* ok to call! */
547     break;
548   case PS_ACCEPTED:
549     FPRINTF (stderr,
550              _("You are answering call from `%s', hang up or suspend that call first!\n"),
551              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));
552     return;
553   case PS_ERROR:
554     /* ok to call */
555     break;
556   }
557   if (NULL == arg)
558   {
559     FPRINTF (stderr,
560              _("Call recipient missing.\n"));
561     do_help ("/call");
562     return;
563   }
564   peer_name = GNUNET_strdup (arg);
565   call_state = CS_RESOLVING;
566   GNUNET_assert (NULL == call);
567   call = GNUNET_CONVERSATION_call_start (cfg,
568                                          my_caller_id,
569                                          my_caller_id,
570                                          arg,
571                                          speaker,
572                                          mic,
573                                          &call_event_handler, NULL);
574 }
575
576
577 /**
578  * Accepting an incoming call
579  *
580  * @param args arguments given to the command
581  */
582 static void
583 do_accept (const char *args)
584 {
585   struct CallList *cl;
586   char buf[32];
587
588   if ( (NULL != call) &&
589        (CS_SUSPENDED != call_state) )
590   {
591     FPRINTF (stderr,
592              _("You are calling someone else already, hang up first!\n"));
593     return;
594   }
595   switch (phone_state)
596   {
597   case PS_LOOKUP_EGO:
598     GNUNET_break (0);
599     break;
600   case PS_LISTEN:
601     /* this is the expected state */
602     break;
603   case PS_ACCEPTED:
604     FPRINTF (stderr,
605              _("You are answering call from `%s', hang up or suspend that call first!\n"),
606              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));
607     return;
608   case PS_ERROR:
609     GNUNET_break (0);
610     break;
611   }
612   cl = cl_head;
613   if (NULL == cl)
614   {
615     FPRINTF (stderr,
616              _("There is no incoming call to accept here!\n"));
617     return;
618   }
619   if ( (NULL != cl->next) || (NULL != args) )
620   {
621     for (cl = cl_head; NULL != cl; cl = cl->next)
622     {
623       GNUNET_snprintf (buf, sizeof (buf),
624                        "%u",
625                        cl->caller_num);
626       if (0 == strcmp (buf, args))
627         break;
628     }
629   }
630   if (NULL == cl)
631   {
632     FPRINTF (stderr,
633              _("There is no incoming call `%s' to accept right now!\n"),
634              args);
635     return;
636   }
637   GNUNET_CONTAINER_DLL_remove (cl_head,
638                                cl_tail,
639                                cl);
640   cl_active = cl;
641   peer_key = cl->caller_id;
642   phone_state = PS_ACCEPTED;
643   GNUNET_CONVERSATION_caller_pick_up (cl->caller,
644                                       &caller_event_handler,
645                                       cl,
646                                       speaker,
647                                       mic);
648 }
649
650
651 /**
652  * Print address information for this phone.
653  *
654  * @param args arguments given to the command
655  */
656 static void
657 do_address (const char *args)
658 {
659   if (NULL == address)
660   {
661     FPRINTF (stdout,
662              "%s",
663              _("We currently do not have an address.\n"));
664     return;
665   }
666   FPRINTF (stdout,
667            "%s\n",
668            address);
669 }
670
671
672 /**
673  * Accepting an incoming call
674  *
675  * @param args arguments given to the command
676  */
677 static void
678 do_status (const char *args)
679 {
680   struct CallList *cl;
681
682   switch (phone_state)
683   {
684   case PS_LOOKUP_EGO:
685     FPRINTF (stdout,
686              _("We are currently trying to locate the private key for the ego `%s'.\n"),
687              ego_name);
688     break;
689   case PS_LISTEN:
690     FPRINTF (stdout,
691              _("We are listening for incoming calls for ego `%s' on line `%s'.\n"),
692              ego_name,
693              line);
694     break;
695   case PS_ACCEPTED:
696     FPRINTF (stdout,
697              _("You are having a conversation with `%s'.\n"),
698              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));;
699     break;
700   case PS_ERROR:
701     FPRINTF (stdout,
702              _("We had an internal error setting up our phone line. You can still make calls.\n"));
703     break;
704   }
705   if (NULL != call)
706   {
707     switch (call_state)
708     {
709     case CS_RESOLVING:
710       FPRINTF (stdout,
711                _("We are trying to find the network address to call `%s'.\n"),
712                peer_name);
713       break;
714     case CS_RINGING:
715       FPRINTF (stdout,
716                _("We are calling `%s', his phone should be ringing.\n"),
717                peer_name);
718       break;
719     case CS_CONNECTED:
720       FPRINTF (stdout,
721                _("You are having a conversation with `%s'.\n"),
722                peer_name);
723       break;
724     case CS_SUSPENDED:
725       /* ok to accept incoming call right now */
726       break;
727     }
728   }
729   if ( (NULL != cl_head) &&
730        ( (cl_head != cl_active) ||
731          (cl_head != cl_tail) ) )
732   {
733     FPRINTF (stdout,
734              "%s",
735              _("Calls waiting:\n"));
736     for (cl = cl_head; NULL != cl; cl = cl->next)
737     {
738       if (cl == cl_active)
739         continue;
740       FPRINTF (stdout,
741                _("#%u: `%s'\n"),
742                cl->caller_num,
743                GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id));
744     }
745     FPRINTF (stdout,
746              "%s",
747              "\n");
748   }
749 }
750
751
752 /**
753  * Suspending a call
754  *
755  * @param args arguments given to the command
756  */
757 static void
758 do_suspend (const char *args)
759 {
760   if (NULL != call)
761   {
762     switch (call_state)
763     {
764     case CS_RESOLVING:
765     case CS_RINGING:
766     case CS_SUSPENDED:
767       FPRINTF (stderr,
768                "%s",
769                _("There is no call that could be suspended right now.\n"));
770       return;
771     case CS_CONNECTED:
772       call_state = CS_SUSPENDED;
773       GNUNET_CONVERSATION_call_suspend (call);
774       return;
775     }
776   }
777   switch (phone_state)
778   {
779   case PS_LOOKUP_EGO:
780   case PS_LISTEN:
781   case PS_ERROR:
782     FPRINTF (stderr,
783              "%s",
784              _("There is no call that could be suspended right now.\n"));
785     return;
786   case PS_ACCEPTED:
787     /* expected state, do rejection logic */
788     break;
789   }
790   GNUNET_assert (NULL != cl_active);
791   GNUNET_CONVERSATION_caller_suspend (cl_active->caller);
792   cl_active = NULL;
793   phone_state = PS_LISTEN;
794 }
795
796
797 /**
798  * Resuming a call
799  *
800  * @param args arguments given to the command
801  */
802 static void
803 do_resume (const char *args)
804 {
805   struct CallList *cl;
806   char buf[32];
807
808   if (NULL != call)
809   {
810     switch (call_state)
811     {
812     case CS_RESOLVING:
813     case CS_RINGING:
814     case CS_CONNECTED:
815       FPRINTF (stderr,
816                "%s",
817                _("There is no call that could be resumed right now.\n"));
818       return;
819     case CS_SUSPENDED:
820       call_state = CS_CONNECTED;
821       GNUNET_CONVERSATION_call_resume (call,
822                                        speaker,
823                                        mic);
824       return;
825     }
826   }
827   switch (phone_state)
828   {
829   case PS_LOOKUP_EGO:
830   case PS_ERROR:
831     FPRINTF (stderr,
832              "%s",
833              _("There is no call that could be resumed right now.\n"));
834     return;
835   case PS_LISTEN:
836     /* expected state, do resume logic */
837     break;
838   case PS_ACCEPTED:
839     FPRINTF (stderr,
840              _("Already talking with `%s', cannot resume a call right now.\n"),
841              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));
842     return;
843   }
844   GNUNET_assert (NULL == cl_active);
845   cl = cl_head;
846   if (NULL == cl)
847   {
848     FPRINTF (stderr,
849              _("There is no incoming call to resume here!\n"));
850     return;
851   }
852   if ( (NULL != cl->next) || (NULL != args) )
853   {
854     for (cl = cl_head; NULL != cl; cl = cl->next)
855     {
856       GNUNET_snprintf (buf, sizeof (buf),
857                        "%u",
858                        cl->caller_num);
859       if (0 == strcmp (buf, args))
860         break;
861     }
862   }
863   if (NULL == cl)
864   {
865     FPRINTF (stderr,
866              _("There is no incoming call `%s' to resume right now!\n"),
867              args);
868     return;
869   }
870   cl_active = cl;
871   GNUNET_CONVERSATION_caller_resume (cl_active->caller,
872                                      speaker,
873                                      mic);
874   phone_state = PS_ACCEPTED;
875 }
876
877
878 /**
879  * Rejecting a call
880  *
881  * @param args arguments given to the command
882  */
883 static void
884 do_reject (const char *args)
885 {
886   struct CallList *cl;
887   char buf[32];
888
889   if (NULL != call)
890   {
891     GNUNET_CONVERSATION_call_stop (call);
892     call = NULL;
893     return;
894   }
895   switch (phone_state)
896   {
897   case PS_LOOKUP_EGO:
898   case PS_ERROR:
899     FPRINTF (stderr,
900              "%s",
901              _("There is no call that could be cancelled right now.\n"));
902     return;
903   case PS_LISTEN:
904     /* look for active incoming calls to refuse */
905     cl = cl_head;
906     if (NULL == cl)
907     {
908       FPRINTF (stderr,
909                _("There is no incoming call to refuse here!\n"));
910       return;
911     }
912     if ( (NULL != cl->next) || (NULL != args) )
913     {
914       for (cl = cl_head; NULL != cl; cl = cl->next)
915       {
916         GNUNET_snprintf (buf, sizeof (buf),
917                          "%u",
918                          cl->caller_num);
919         if (0 == strcmp (buf, args))
920           break;
921       }
922     }
923     if (NULL == cl)
924     {
925       FPRINTF (stderr,
926                _("There is no incoming call `%s' to refuse right now!\n"),
927                args);
928       return;
929     }
930     GNUNET_CONVERSATION_caller_hang_up (cl->caller);
931     GNUNET_CONTAINER_DLL_remove (cl_head,
932                                  cl_tail,
933                                  cl);
934     GNUNET_free (cl);
935     break;
936   case PS_ACCEPTED:
937     /* expected state, do rejection logic */
938     GNUNET_assert (NULL != cl_active);
939     GNUNET_CONVERSATION_caller_hang_up (cl_active->caller);
940     cl_active = NULL;
941     phone_state = PS_LISTEN;
942     break;
943   }
944 }
945
946
947 /**
948  * List of supported commands.
949  */
950 static struct VoipCommand commands[] = {
951   {"/address", &do_address,
952    gettext_noop ("Use `/address' to find out which address this phone should have in GNS")},
953   {"/call", &do_call,
954    gettext_noop ("Use `/call USER.gnu' to call USER")},
955   {"/accept", &do_accept,
956    gettext_noop ("Use `/accept #NUM' to accept incoming call #NUM")},
957   {"/suspend", &do_suspend,
958    gettext_noop ("Use `/suspend' to suspend the active call")},
959   {"/resume", &do_resume,
960    gettext_noop ("Use `/resume [#NUM]' to resume a call, #NUM is needed to resume incoming calls, no argument is needed to resume the current outgoing call.")},
961   {"/cancel", &do_reject,
962    gettext_noop ("Use `/cancel' to reject or terminate a call")},
963   {"/status", &do_status,
964    gettext_noop ("Use `/status' to print status information")},
965   {"/quit", &do_quit,
966    gettext_noop ("Use `/quit' to terminate gnunet-conversation")},
967   {"/help", &do_help,
968    gettext_noop ("Use `/help command' to get help for a specific command")},
969   {"", &do_unknown,
970    NULL},
971   {NULL, NULL, NULL},
972 };
973
974
975 /**
976  * Action function to print help for the command shell.
977  *
978  * @param args arguments given to the command
979  */
980 static void
981 do_help (const char *args)
982 {
983   unsigned int i;
984
985   i = 0;
986   while ( (NULL != args) &&
987           (0 != strlen (args)) &&
988           (commands[i].Action != &do_help))
989   {
990     if (0 ==
991         strncasecmp (&args[1], &commands[i].command[1], strlen (args) - 1))
992     {
993       FPRINTF (stdout,
994                "%s\n",
995                gettext (commands[i].helptext));
996       return;
997     }
998     i++;
999   }
1000   i = 0;
1001   FPRINTF (stdout,
1002            "%s",
1003            "Available commands:\n");
1004   while (commands[i].Action != &do_help)
1005   {
1006     FPRINTF (stdout,
1007              "%s\n",
1008              gettext (commands[i].command));
1009     i++;
1010   }
1011   FPRINTF (stdout,
1012            "%s",
1013            "\n");
1014   FPRINTF (stdout,
1015            "%s\n",
1016            gettext (commands[i].helptext));
1017 }
1018
1019
1020 /**
1021  * Task run during shutdown.
1022  *
1023  * @param cls NULL
1024  */
1025 static void
1026 do_stop_task (void *cls)
1027 {
1028 #ifdef WINDOWS
1029   if (NULL != stdin_hlp)
1030   {
1031     GNUNET_HELPER_stop (stdin_hlp, GNUNET_NO);
1032     stdin_hlp = NULL;
1033   }
1034 #endif
1035   if (NULL != call)
1036   {
1037     GNUNET_CONVERSATION_call_stop (call);
1038     call = NULL;
1039   }
1040   if (NULL != phone)
1041   {
1042     GNUNET_CONVERSATION_phone_destroy (phone);
1043     phone = NULL;
1044   }
1045   if (NULL != handle_cmd_task)
1046   {
1047     GNUNET_SCHEDULER_cancel (handle_cmd_task);
1048     handle_cmd_task = NULL;
1049   }
1050   if (NULL != id)
1051   {
1052     GNUNET_IDENTITY_disconnect (id);
1053     id = NULL;
1054   }
1055   GNUNET_SPEAKER_destroy (speaker);
1056   speaker = NULL;
1057   GNUNET_MICROPHONE_destroy (mic);
1058   mic = NULL;
1059   GNUNET_free (ego_name);
1060   ego_name = NULL;
1061   GNUNET_free_non_null (peer_name);
1062   peer_name = NULL;
1063   phone_state = PS_ERROR;
1064 }
1065
1066
1067 /**
1068  * Handle user command.
1069  *
1070  * @param message command the user typed in
1071  * @param str_len number of bytes to process in @a message
1072  */
1073 static void
1074 handle_command_string (char *message,
1075                        size_t str_len)
1076 {
1077   size_t i;
1078   const char *ptr;
1079
1080   if (0 == str_len)
1081     return;
1082   if (message[str_len - 1] == '\n')
1083     message[str_len - 1] = '\0';
1084   if (message[str_len - 2] == '\r')
1085     message[str_len - 2] = '\0';
1086   if (0 == strlen (message))
1087     return;
1088   i = 0;
1089   while ((NULL != commands[i].command) &&
1090          (0 != strncasecmp (commands[i].command, message,
1091                             strlen (commands[i].command))))
1092     i++;
1093   ptr = &message[strlen (commands[i].command)];
1094   while (isspace ((int) *ptr))
1095     ptr++;
1096   if ('\0' == *ptr)
1097     ptr = NULL;
1098   commands[i].Action (ptr);
1099 }
1100
1101
1102 #ifdef WINDOWS
1103 static int
1104 console_reader_chars (void *cls,
1105                       void *client,
1106                       const struct GNUNET_MessageHeader *message)
1107 {
1108   char *chars;
1109   size_t str_size;
1110   switch (ntohs (message->type))
1111   {
1112   case GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_CHARS:
1113     chars = (char *) &message[1];
1114     str_size = ntohs (message->size) - sizeof (struct GNUNET_MessageHeader);
1115     if (chars[str_size - 1] != '\0')
1116       return GNUNET_SYSERR;
1117     /* FIXME: is it ok that we pass part of a const struct to
1118      * this function that may mangle the contents?
1119      */
1120     handle_command_string (chars, str_size - 1);
1121     break;
1122   default:
1123     GNUNET_break (0);
1124     break;
1125   }
1126   return GNUNET_OK;
1127 }
1128 #endif
1129
1130 /**
1131  * Task to handle commands from the terminal.
1132  *
1133  * @param cls NULL
1134  */
1135 static void
1136 handle_command (void *cls)
1137 {
1138   char message[MAX_MESSAGE_LENGTH + 1];
1139
1140   handle_cmd_task =
1141     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1142                                     stdin_fh,
1143                                     &handle_command, NULL);
1144   /* read message from command line and handle it */
1145   memset (message, 0, MAX_MESSAGE_LENGTH + 1);
1146   if (NULL == fgets (message, MAX_MESSAGE_LENGTH, stdin))
1147     return;
1148   handle_command_string (message, strlen (message));
1149 }
1150
1151
1152 /**
1153  * Function called by identity service with information about egos.
1154  *
1155  * @param cls NULL
1156  * @param ego ego handle
1157  * @param ctx unused
1158  * @param name name of the ego
1159  */
1160 static void
1161 identity_cb (void *cls,
1162              struct GNUNET_IDENTITY_Ego *ego,
1163              void **ctx,
1164              const char *name)
1165 {
1166   if (NULL == name)
1167     return;
1168   if (ego == my_caller_id)
1169   {
1170     if (verbose)
1171       FPRINTF (stdout,
1172                _("Name of our ego changed to `%s'\n"),
1173                name);
1174     GNUNET_free (ego_name);
1175     ego_name = GNUNET_strdup (name);
1176     return;
1177   }
1178   if (0 != strcmp (name,
1179                    ego_name))
1180     return;
1181   if (NULL == ego)
1182   {
1183     if (verbose)
1184       FPRINTF (stdout,
1185                _("Our ego `%s' was deleted!\n"),
1186                ego_name);
1187     my_caller_id = NULL;
1188     return;
1189   }
1190   my_caller_id = ego;
1191   GNUNET_CONFIGURATION_set_value_string (cfg,
1192                                          "CONVERSATION",
1193                                          "LINE",
1194                                          line);
1195   start_phone ();
1196 }
1197
1198
1199 /**
1200  * Main function that will be run by the scheduler.
1201  *
1202  * @param cls closure
1203  * @param args remaining command-line arguments
1204  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1205  * @param c configuration
1206  */
1207 static void
1208 run (void *cls,
1209      char *const *args,
1210      const char *cfgfile,
1211      const struct GNUNET_CONFIGURATION_Handle *c)
1212 {
1213   cfg = GNUNET_CONFIGURATION_dup (c);
1214   speaker = GNUNET_SPEAKER_create_from_hardware (cfg);
1215   mic = GNUNET_MICROPHONE_create_from_hardware (cfg);
1216   if (NULL == ego_name)
1217   {
1218     FPRINTF (stderr,
1219              "%s",
1220              _("You must specify the NAME of an ego to use\n"));
1221     return;
1222   }
1223   id = GNUNET_IDENTITY_connect (cfg,
1224                                 &identity_cb,
1225                                 NULL);
1226 #ifdef WINDOWS
1227   if (stdin_fh == NULL)
1228   {
1229     static char cpid[64];
1230     static char *args[] = {"gnunet-helper-w32-console.exe", "chars",
1231         XSTRINGIFY (MAX_MESSAGE_LENGTH), cpid, NULL};
1232     snprintf (cpid, 64, "%d", GetCurrentProcessId ());
1233     stdin_hlp = GNUNET_HELPER_start (
1234         GNUNET_NO,
1235         "gnunet-helper-w32-console",
1236         args,
1237         console_reader_chars,
1238         NULL,
1239         NULL);
1240     if (NULL == stdin_hlp)
1241     {
1242       FPRINTF (stderr,
1243                "%s",
1244                _("Failed to start gnunet-helper-w32-console\n"));
1245       return;
1246     }
1247   }
1248   else
1249 #endif
1250   handle_cmd_task =
1251     GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_UI,
1252                                         &handle_command, NULL);
1253   GNUNET_SCHEDULER_add_shutdown (&do_stop_task,
1254                                  NULL);
1255 }
1256
1257
1258 /**
1259  * The main function to conversation.
1260  *
1261  * @param argc number of arguments from the command line
1262  * @param argv command line arguments
1263  * @return 0 ok, 1 on error
1264  */
1265 int
1266 main (int argc, char *const *argv)
1267 {
1268   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1269     {'e', "ego", "NAME",
1270      gettext_noop ("sets the NAME of the ego to use for the phone (and name resolution)"),
1271      1, &GNUNET_GETOPT_set_string, &ego_name},
1272     {'p', "phone", "LINE",
1273       gettext_noop ("sets the LINE to use for the phone"),
1274      1, &GNUNET_GETOPT_set_string, &line},
1275     GNUNET_GETOPT_OPTION_END
1276   };
1277   int ret;
1278 #ifndef WINDOWS
1279   int flags;
1280   flags = fcntl (0, F_GETFL, 0);
1281   flags |= O_NONBLOCK;
1282   if (0 != fcntl (0, F_SETFL, flags))
1283     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1284                          "fcntl");
1285   stdin_fh = GNUNET_DISK_get_handle_from_int_fd (0);
1286 #else
1287   if (FILE_TYPE_CHAR == GetFileType ((HANDLE) _get_osfhandle (0)))
1288   {
1289     stdin_fh = NULL;
1290   }
1291   else
1292     stdin_fh = GNUNET_DISK_get_handle_from_int_fd (0);
1293 #endif
1294
1295   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1296     return 2;
1297   ret = GNUNET_PROGRAM_run (argc, argv,
1298                             "gnunet-conversation",
1299                             gettext_noop ("Enables having a conversation with other GNUnet users."),
1300                             options, &run, NULL);
1301   GNUNET_free ((void *) argv);
1302   if (NULL != cfg)
1303   {
1304     GNUNET_CONFIGURATION_destroy (cfg);
1305     cfg = NULL;
1306   }
1307   return (GNUNET_OK == ret) ? 0 : 1;
1308 }
1309
1310 /* end of gnunet-conversation.c */