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