-bringing copyright tags up to FSF standard
[oweals/gnunet.git] / src / conversation / gnunet-conversation.c
1 /*
2   This file is part of GNUnet.
3   Copyright (C) 2013 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18   Boston, MA 02111-1307, 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.
170  */
171 static unsigned int 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, NULL);
361   /* FIXME: get record and print full GNS record info later here... */
362   if (NULL == phone)
363   {
364     FPRINTF (stderr,
365              "%s",
366              _("Failed to setup phone (internal error)\n"));
367     phone_state = PS_ERROR;
368   }
369   else
370   {
371     GNUNET_CONVERSATION_phone_get_record (phone,
372                                           &rd);
373     GNUNET_free_non_null (address);
374     address = GNUNET_GNSRECORD_value_to_string (rd.record_type,
375                                                 rd.data,
376                                                 rd.data_size);
377     FPRINTF (stdout,
378              _("Phone active on line %u.  Type `/help' for a list of available commands\n"),
379              (unsigned int) line);
380     phone_state = PS_LISTEN;
381   }
382 }
383
384
385 /**
386  * Function called with an event emitted by a call.
387  *
388  * @param cls closure, NULL
389  * @param code type of the event on the call
390  */
391 static void
392 call_event_handler (void *cls,
393                     enum GNUNET_CONVERSATION_CallEventCode code)
394 {
395   switch (code)
396   {
397   case GNUNET_CONVERSATION_EC_CALL_RINGING:
398     GNUNET_break (CS_RESOLVING == call_state);
399     FPRINTF (stdout,
400              _("Resolved address of `%s'. Now ringing other party.\n"),
401              peer_name);
402     call_state = CS_RINGING;
403     break;
404   case GNUNET_CONVERSATION_EC_CALL_PICKED_UP:
405     GNUNET_break (CS_RINGING == call_state);
406     FPRINTF (stdout,
407              _("Connection established to `%s'\n"),
408              peer_name);
409     call_state = CS_CONNECTED;
410     break;
411   case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL:
412     GNUNET_break (CS_RESOLVING == call_state);
413     FPRINTF (stdout,
414              _("Failed to resolve `%s'\n"),
415              peer_name);
416     GNUNET_free (peer_name);
417     peer_name = NULL;
418     call = NULL;
419     break;
420   case GNUNET_CONVERSATION_EC_CALL_HUNG_UP:
421     FPRINTF (stdout,
422              _("Call to `%s' terminated\n"),
423              peer_name);
424     GNUNET_free (peer_name);
425     peer_name = NULL;
426     call = NULL;
427     break;
428   case GNUNET_CONVERSATION_EC_CALL_SUSPENDED:
429     GNUNET_break (CS_CONNECTED == call_state);
430     FPRINTF (stdout,
431              _("Connection to `%s' suspended (by other user)\n"),
432              peer_name);
433     break;
434   case GNUNET_CONVERSATION_EC_CALL_RESUMED:
435     GNUNET_break (CS_CONNECTED == call_state);
436     FPRINTF (stdout,
437              _("Connection to `%s' resumed (by other user)\n"),
438              peer_name);
439     break;
440   case GNUNET_CONVERSATION_EC_CALL_ERROR:
441     FPRINTF (stdout,
442              _("Error with the call, restarting it\n"));
443     GNUNET_free (peer_name);
444     peer_name = NULL;
445     call = NULL;
446     break;
447   }
448 }
449
450
451 /**
452  * Function declareation for executing a action
453  *
454  * @param arguments arguments given to the function
455  */
456 typedef void (*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   GNUNET_SCHEDULER_shutdown ();
499 }
500
501
502 /**
503  * Handler for unknown command.
504  *
505  * @param msg arguments given to the command
506  */
507 static void
508 do_unknown (const char *msg)
509 {
510   FPRINTF (stderr,
511            _("Unknown command `%s'\n"),
512            msg);
513 }
514
515
516 /**
517  * Initiating a new call
518  *
519  * @param arg arguments given to the command
520  */
521 static void
522 do_call (const char *arg)
523 {
524   if (NULL == my_caller_id)
525   {
526     FPRINTF (stderr,
527              _("Ego `%s' not available\n"),
528              ego_name);
529     return;
530   }
531   if (NULL != call)
532   {
533     FPRINTF (stderr,
534              _("You are calling someone else already, hang up first!\n"));
535     return;
536   }
537   switch (phone_state)
538   {
539   case PS_LOOKUP_EGO:
540     FPRINTF (stderr,
541              _("Ego `%s' not available\n"),
542              ego_name);
543     return;
544   case PS_LISTEN:
545     /* ok to call! */
546     break;
547   case PS_ACCEPTED:
548     FPRINTF (stderr,
549              _("You are answering call from `%s', hang up or suspend that call first!\n"),
550              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));
551     return;
552   case PS_ERROR:
553     /* ok to call */
554     break;
555   }
556   if (NULL == arg)
557   {
558     FPRINTF (stderr,
559              _("Call recipient missing.\n"));
560     do_help ("/call");
561     return;
562   }
563   peer_name = GNUNET_strdup (arg);
564   call_state = CS_RESOLVING;
565   GNUNET_assert (NULL == call);
566   call = GNUNET_CONVERSATION_call_start (cfg,
567                                          my_caller_id,
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   if (NULL == address)
659   {
660     FPRINTF (stdout,
661              "%s",
662              _("We currently do not have an address.\n"));
663     return;
664   }
665   FPRINTF (stdout,
666            "%s\n",
667            address);
668 }
669
670
671 /**
672  * Accepting an incoming call
673  *
674  * @param args arguments given to the command
675  */
676 static void
677 do_status (const char *args)
678 {
679   struct CallList *cl;
680
681   switch (phone_state)
682   {
683   case PS_LOOKUP_EGO:
684     FPRINTF (stdout,
685              _("We are currently trying to locate the private key for the ego `%s'.\n"),
686              ego_name);
687     break;
688   case PS_LISTEN:
689     FPRINTF (stdout,
690              _("We are listening for incoming calls for ego `%s' on line %u.\n"),
691              ego_name,
692              line);
693     break;
694   case PS_ACCEPTED:
695     FPRINTF (stdout,
696              _("You are having a conversation with `%s'.\n"),
697              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));;
698     break;
699   case PS_ERROR:
700     FPRINTF (stdout,
701              _("We had an internal error setting up our phone line. You can still make calls.\n"));
702     break;
703   }
704   if (NULL != call)
705   {
706     switch (call_state)
707     {
708     case CS_RESOLVING:
709       FPRINTF (stdout,
710                _("We are trying to find the network address to call `%s'.\n"),
711                peer_name);
712       break;
713     case CS_RINGING:
714       FPRINTF (stdout,
715                _("We are calling `%s', his phone should be ringing.\n"),
716                peer_name);
717       break;
718     case CS_CONNECTED:
719       FPRINTF (stdout,
720                _("You are having a conversation with `%s'.\n"),
721                peer_name);
722       break;
723     case CS_SUSPENDED:
724       /* ok to accept incoming call right now */
725       break;
726     }
727   }
728   if ( (NULL != cl_head) &&
729        ( (cl_head != cl_active) ||
730          (cl_head != cl_tail) ) )
731   {
732     FPRINTF (stdout,
733              "%s",
734              _("Calls waiting:\n"));
735     for (cl = cl_head; NULL != cl; cl = cl->next)
736     {
737       if (cl == cl_active)
738         continue;
739       FPRINTF (stdout,
740                _("#%u: `%s'\n"),
741                cl->caller_num,
742                GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id));
743     }
744     FPRINTF (stdout,
745              "%s",
746              "\n");
747   }
748 }
749
750
751 /**
752  * Suspending a call
753  *
754  * @param args arguments given to the command
755  */
756 static void
757 do_suspend (const char *args)
758 {
759   if (NULL != call)
760   {
761     switch (call_state)
762     {
763     case CS_RESOLVING:
764     case CS_RINGING:
765     case CS_SUSPENDED:
766       FPRINTF (stderr,
767                "%s",
768                _("There is no call that could be suspended right now.\n"));
769       return;
770     case CS_CONNECTED:
771       call_state = CS_SUSPENDED;
772       GNUNET_CONVERSATION_call_suspend (call);
773       return;
774     }
775   }
776   switch (phone_state)
777   {
778   case PS_LOOKUP_EGO:
779   case PS_LISTEN:
780   case PS_ERROR:
781     FPRINTF (stderr,
782              "%s",
783              _("There is no call that could be suspended right now.\n"));
784     return;
785   case PS_ACCEPTED:
786     /* expected state, do rejection logic */
787     break;
788   }
789   GNUNET_assert (NULL != cl_active);
790   GNUNET_CONVERSATION_caller_suspend (cl_active->caller);
791   cl_active = NULL;
792   phone_state = PS_LISTEN;
793 }
794
795
796 /**
797  * Resuming a call
798  *
799  * @param args arguments given to the command
800  */
801 static void
802 do_resume (const char *args)
803 {
804   struct CallList *cl;
805   char buf[32];
806
807   if (NULL != call)
808   {
809     switch (call_state)
810     {
811     case CS_RESOLVING:
812     case CS_RINGING:
813     case CS_CONNECTED:
814       FPRINTF (stderr,
815                "%s",
816                _("There is no call that could be resumed right now.\n"));
817       return;
818     case CS_SUSPENDED:
819       call_state = CS_CONNECTED;
820       GNUNET_CONVERSATION_call_resume (call,
821                                        speaker,
822                                        mic);
823       return;
824     }
825   }
826   switch (phone_state)
827   {
828   case PS_LOOKUP_EGO:
829   case PS_ERROR:
830     FPRINTF (stderr,
831              "%s",
832              _("There is no call that could be resumed right now.\n"));
833     return;
834   case PS_LISTEN:
835     /* expected state, do resume logic */
836     break;
837   case PS_ACCEPTED:
838     FPRINTF (stderr,
839              _("Already talking with `%s', cannot resume a call right now.\n"),
840              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));
841     return;
842   }
843   GNUNET_assert (NULL == cl_active);
844   cl = cl_head;
845   if (NULL == cl)
846   {
847     FPRINTF (stderr,
848              _("There is no incoming call to resume here!\n"));
849     return;
850   }
851   if ( (NULL != cl->next) || (NULL != args) )
852   {
853     for (cl = cl_head; NULL != cl; cl = cl->next)
854     {
855       GNUNET_snprintf (buf, sizeof (buf),
856                        "%u",
857                        cl->caller_num);
858       if (0 == strcmp (buf, args))
859         break;
860     }
861   }
862   if (NULL == cl)
863   {
864     FPRINTF (stderr,
865              _("There is no incoming call `%s' to resume right now!\n"),
866              args);
867     return;
868   }
869   cl_active = cl;
870   GNUNET_CONVERSATION_caller_resume (cl_active->caller,
871                                      speaker,
872                                      mic);
873   phone_state = PS_ACCEPTED;
874 }
875
876
877 /**
878  * Rejecting a call
879  *
880  * @param args arguments given to the command
881  */
882 static void
883 do_reject (const char *args)
884 {
885   struct CallList *cl;
886   char buf[32];
887
888   if (NULL != call)
889   {
890     GNUNET_CONVERSATION_call_stop (call);
891     call = NULL;
892     return;
893   }
894   switch (phone_state)
895   {
896   case PS_LOOKUP_EGO:
897   case PS_ERROR:
898     FPRINTF (stderr,
899              "%s",
900              _("There is no call that could be cancelled right now.\n"));
901     return;
902   case PS_LISTEN:
903     /* look for active incoming calls to refuse */
904     cl = cl_head;
905     if (NULL == cl)
906     {
907       FPRINTF (stderr,
908                _("There is no incoming call to refuse here!\n"));
909       return;
910     }
911     if ( (NULL != cl->next) || (NULL != args) )
912     {
913       for (cl = cl_head; NULL != cl; cl = cl->next)
914       {
915         GNUNET_snprintf (buf, sizeof (buf),
916                          "%u",
917                          cl->caller_num);
918         if (0 == strcmp (buf, args))
919           break;
920       }
921     }
922     if (NULL == cl)
923     {
924       FPRINTF (stderr,
925                _("There is no incoming call `%s' to refuse right now!\n"),
926                args);
927       return;
928     }
929     GNUNET_CONVERSATION_caller_hang_up (cl->caller);
930     GNUNET_CONTAINER_DLL_remove (cl_head,
931                                  cl_tail,
932                                  cl);
933     GNUNET_free (cl);
934     break;
935   case PS_ACCEPTED:
936     /* expected state, do rejection logic */
937     GNUNET_assert (NULL != cl_active);
938     GNUNET_CONVERSATION_caller_hang_up (cl_active->caller);
939     cl_active = NULL;
940     phone_state = PS_LISTEN;
941     break;
942   }
943 }
944
945
946 /**
947  * List of supported commands.
948  */
949 static struct VoipCommand commands[] = {
950   {"/address", &do_address,
951    gettext_noop ("Use `/address' to find out which address this phone should have in GNS")},
952   {"/call", &do_call,
953    gettext_noop ("Use `/call USER.gnu' to call USER")},
954   {"/accept", &do_accept,
955    gettext_noop ("Use `/accept #NUM' to accept incoming call #NUM")},
956   {"/suspend", &do_suspend,
957    gettext_noop ("Use `/suspend' to suspend the active call")},
958   {"/resume", &do_resume,
959    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.")},
960   {"/cancel", &do_reject,
961    gettext_noop ("Use `/cancel' to reject or terminate a call")},
962   {"/status", &do_status,
963    gettext_noop ("Use `/status' to print status information")},
964   {"/quit", &do_quit,
965    gettext_noop ("Use `/quit' to terminate gnunet-conversation")},
966   {"/help", &do_help,
967    gettext_noop ("Use `/help command' to get help for a specific command")},
968   {"", &do_unknown,
969    NULL},
970   {NULL, NULL, NULL},
971 };
972
973
974 /**
975  * Action function to print help for the command shell.
976  *
977  * @param args arguments given to the command
978  */
979 static void
980 do_help (const char *args)
981 {
982   unsigned int i;
983
984   i = 0;
985   while ( (NULL != args) &&
986           (0 != strlen (args)) &&
987           (commands[i].Action != &do_help))
988   {
989     if (0 ==
990         strncasecmp (&args[1], &commands[i].command[1], strlen (args) - 1))
991     {
992       FPRINTF (stdout,
993                "%s\n",
994                gettext (commands[i].helptext));
995       return;
996     }
997     i++;
998   }
999   i = 0;
1000   FPRINTF (stdout,
1001            "%s",
1002            "Available commands:\n");
1003   while (commands[i].Action != &do_help)
1004   {
1005     FPRINTF (stdout,
1006              "%s\n",
1007              gettext (commands[i].command));
1008     i++;
1009   }
1010   FPRINTF (stdout,
1011            "%s",
1012            "\n");
1013   FPRINTF (stdout,
1014            "%s\n",
1015            gettext (commands[i].helptext));
1016 }
1017
1018
1019 /**
1020  * Task run during shutdown.
1021  *
1022  * @param cls NULL
1023  * @param tc unused
1024  */
1025 static void
1026 do_stop_task (void *cls,
1027               const struct GNUNET_SCHEDULER_TaskContext *tc)
1028 {
1029 #ifdef WINDOWS
1030   if (NULL != stdin_hlp)
1031   {
1032     GNUNET_HELPER_stop (stdin_hlp, GNUNET_NO);
1033     stdin_hlp = NULL;
1034   }
1035 #endif
1036   if (NULL != call)
1037   {
1038     GNUNET_CONVERSATION_call_stop (call);
1039     call = NULL;
1040   }
1041   if (NULL != phone)
1042   {
1043     GNUNET_CONVERSATION_phone_destroy (phone);
1044     phone = NULL;
1045   }
1046   if (NULL != handle_cmd_task)
1047   {
1048     GNUNET_SCHEDULER_cancel (handle_cmd_task);
1049     handle_cmd_task = NULL;
1050   }
1051   if (NULL != id)
1052   {
1053     GNUNET_IDENTITY_disconnect (id);
1054     id = NULL;
1055   }
1056   GNUNET_SPEAKER_destroy (speaker);
1057   speaker = NULL;
1058   GNUNET_MICROPHONE_destroy (mic);
1059   mic = NULL;
1060   GNUNET_free (ego_name);
1061   ego_name = NULL;
1062   GNUNET_free_non_null (peer_name);
1063   peer_name = NULL;
1064   phone_state = PS_ERROR;
1065 }
1066
1067
1068 /**
1069  * Handle user command.
1070  *
1071  * @param message command the user typed in
1072  * @param str_len number of bytes to process in @a message
1073  */
1074 static void
1075 handle_command_string (char *message,
1076                        size_t str_len)
1077 {
1078   size_t i;
1079   const char *ptr;
1080
1081   if (0 == str_len)
1082     return;
1083   if (message[str_len - 1] == '\n')
1084     message[str_len - 1] = '\0';
1085   if (message[str_len - 2] == '\r')
1086     message[str_len - 2] = '\0';
1087   if (0 == strlen (message))
1088     return;
1089   i = 0;
1090   while ((NULL != commands[i].command) &&
1091          (0 != strncasecmp (commands[i].command, message,
1092                             strlen (commands[i].command))))
1093     i++;
1094   ptr = &message[strlen (commands[i].command)];
1095   while (isspace ((int) *ptr))
1096     ptr++;
1097   if ('\0' == *ptr)
1098     ptr = NULL;
1099   commands[i].Action (ptr);
1100 }
1101
1102
1103 #ifdef WINDOWS
1104 static int
1105 console_reader_chars (void *cls,
1106                       void *client,
1107                       const struct GNUNET_MessageHeader *message)
1108 {
1109   char *chars;
1110   size_t str_size;
1111   switch (ntohs (message->type))
1112   {
1113   case GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_CHARS:
1114     chars = (char *) &message[1];
1115     str_size = ntohs (message->size) - sizeof (struct GNUNET_MessageHeader);
1116     if (chars[str_size - 1] != '\0')
1117       return GNUNET_SYSERR;
1118     /* FIXME: is it ok that we pass part of a const struct to
1119      * this function that may mangle the contents?
1120      */
1121     handle_command_string (chars, str_size - 1);
1122     break;
1123   default:
1124     GNUNET_break (0);
1125     break;
1126   }
1127   return GNUNET_OK;
1128 }
1129 #endif
1130
1131 /**
1132  * Task to handle commands from the terminal.
1133  *
1134  * @param cls NULL
1135  * @param tc scheduler context
1136  */
1137 static void
1138 handle_command (void *cls,
1139                 const struct GNUNET_SCHEDULER_TaskContext *tc)
1140 {
1141   char message[MAX_MESSAGE_LENGTH + 1];
1142
1143   handle_cmd_task =
1144     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1145                                     stdin_fh,
1146                                     &handle_command, NULL);
1147   /* read message from command line and handle it */
1148   memset (message, 0, MAX_MESSAGE_LENGTH + 1);
1149   if (NULL == fgets (message, MAX_MESSAGE_LENGTH, stdin))
1150     return;
1151   handle_command_string (message, strlen (message));
1152 }
1153
1154
1155 /**
1156  * Function called by identity service with information about egos.
1157  *
1158  * @param cls NULL
1159  * @param ego ego handle
1160  * @param ctx unused
1161  * @param name name of the ego
1162  */
1163 static void
1164 identity_cb (void *cls,
1165              struct GNUNET_IDENTITY_Ego *ego,
1166              void **ctx,
1167              const char *name)
1168 {
1169   if (NULL == name)
1170     return;
1171   if (ego == my_caller_id)
1172   {
1173     if (verbose)
1174       FPRINTF (stdout,
1175                _("Name of our ego changed to `%s'\n"),
1176                name);
1177     GNUNET_free (ego_name);
1178     ego_name = GNUNET_strdup (name);
1179     return;
1180   }
1181   if (0 != strcmp (name,
1182                    ego_name))
1183     return;
1184   if (NULL == ego)
1185   {
1186     if (verbose)
1187       FPRINTF (stdout,
1188                _("Our ego `%s' was deleted!\n"),
1189                ego_name);
1190     my_caller_id = NULL;
1191     return;
1192   }
1193   my_caller_id = ego;
1194   GNUNET_CONFIGURATION_set_value_number (cfg,
1195                                          "CONVERSATION",
1196                                          "LINE",
1197                                          line);
1198   start_phone ();
1199 }
1200
1201
1202 /**
1203  * Main function that will be run by the scheduler.
1204  *
1205  * @param cls closure
1206  * @param args remaining command-line arguments
1207  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1208  * @param c configuration
1209  */
1210 static void
1211 run (void *cls,
1212      char *const *args,
1213      const char *cfgfile,
1214      const struct GNUNET_CONFIGURATION_Handle *c)
1215 {
1216   cfg = GNUNET_CONFIGURATION_dup (c);
1217   speaker = GNUNET_SPEAKER_create_from_hardware (cfg);
1218   mic = GNUNET_MICROPHONE_create_from_hardware (cfg);
1219   if (NULL == ego_name)
1220   {
1221     FPRINTF (stderr,
1222              "%s",
1223              _("You must specify the NAME of an ego to use\n"));
1224     return;
1225   }
1226   id = GNUNET_IDENTITY_connect (cfg,
1227                                 &identity_cb,
1228                                 NULL);
1229 #ifdef WINDOWS
1230   if (stdin_fh == NULL)
1231   {
1232     static char cpid[64];
1233     static char *args[] = {"gnunet-helper-w32-console.exe", "chars",
1234         XSTRINGIFY (MAX_MESSAGE_LENGTH), cpid, NULL};
1235     snprintf (cpid, 64, "%d", GetCurrentProcessId ());
1236     stdin_hlp = GNUNET_HELPER_start (
1237         GNUNET_NO,
1238         "gnunet-helper-w32-console",
1239         args,
1240         console_reader_chars,
1241         NULL,
1242         NULL);
1243     if (NULL == stdin_hlp)
1244     {
1245       FPRINTF (stderr,
1246                "%s",
1247                _("Failed to start gnunet-helper-w32-console\n"));
1248       return;
1249     }
1250   }
1251   else
1252 #endif
1253   handle_cmd_task =
1254     GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_UI,
1255                                         &handle_command, NULL);
1256   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_stop_task,
1257                                 NULL);
1258 }
1259
1260
1261 /**
1262  * The main function to conversation.
1263  *
1264  * @param argc number of arguments from the command line
1265  * @param argv command line arguments
1266  * @return 0 ok, 1 on error
1267  */
1268 int
1269 main (int argc, char *const *argv)
1270 {
1271   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1272     {'e', "ego", "NAME",
1273      gettext_noop ("sets the NAME of the ego to use for the phone (and name resolution)"),
1274      1, &GNUNET_GETOPT_set_string, &ego_name},
1275     {'p', "phone", "LINE",
1276       gettext_noop ("sets the LINE to use for the phone"),
1277      1, &GNUNET_GETOPT_set_uint, &line},
1278     GNUNET_GETOPT_OPTION_END
1279   };
1280   int ret;
1281 #ifndef WINDOWS
1282   int flags;
1283   flags = fcntl (0, F_GETFL, 0);
1284   flags |= O_NONBLOCK;
1285   if (0 != fcntl (0, F_SETFL, flags))
1286     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1287                          "fcntl");
1288   stdin_fh = GNUNET_DISK_get_handle_from_int_fd (0);
1289 #else
1290   if (FILE_TYPE_CHAR == GetFileType ((HANDLE) _get_osfhandle (0)))
1291   {
1292     stdin_fh = NULL;
1293   }
1294   else
1295     stdin_fh = GNUNET_DISK_get_handle_from_int_fd (0);
1296 #endif
1297
1298   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1299     return 2;
1300   ret = GNUNET_PROGRAM_run (argc, argv,
1301                             "gnunet-conversation",
1302                             gettext_noop ("Enables having a conversation with other GNUnet users."),
1303                             options, &run, NULL);
1304   GNUNET_free ((void *) argv);
1305   if (NULL != cfg)
1306   {
1307     GNUNET_CONFIGURATION_destroy (cfg);
1308     cfg = NULL;
1309   }
1310   return (GNUNET_OK == ret) ? 0 : 1;
1311 }
1312
1313 /* end of gnunet-conversation.c */