Merge branch 'master' of gnunet.org:gnunet
[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   (void) cls;
266   switch (code)
267   {
268   case GNUNET_CONVERSATION_EC_PHONE_RING:
269     FPRINTF (stdout,
270              _("Incoming call from `%s'. Please /accept %u or /cancel %u the call.\n"),
271              GNUNET_GNSRECORD_pkey_to_zkey (caller_id),
272              caller_num_gen,
273              caller_num_gen);
274     cl = GNUNET_new (struct CallList);
275     cl->caller = caller;
276     cl->caller_id = *caller_id;
277     cl->caller_num = caller_num_gen++;
278     GNUNET_CONTAINER_DLL_insert (cl_head,
279                                  cl_tail,
280                                  cl);
281     break;
282   case GNUNET_CONVERSATION_EC_PHONE_HUNG_UP:
283     for (cl = cl_head; NULL != cl; cl = cl->next)
284       if (caller == cl->caller)
285         break;
286     if ( (NULL == cl) &&
287          (caller == cl_active->caller) )
288       cl = cl_active;
289     if (NULL == cl)
290     {
291       GNUNET_break (0);
292       return;
293     }
294     FPRINTF (stdout,
295              _("Call from `%s' terminated\n"),
296              GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id));
297     if (cl == cl_active)
298     {
299       cl_active = NULL;
300       phone_state = PS_LISTEN;
301     }
302     else
303     {
304       GNUNET_CONTAINER_DLL_remove (cl_head,
305                                    cl_tail,
306                                    cl);
307     }
308     GNUNET_free (cl);
309     break;
310   }
311 }
312
313
314 /**
315  * Function called with an event emitted by a caller.
316  *
317  * @param cls closure with the `struct CallList` of the caller
318  * @param code type of the event issued by the caller
319  */
320 static void
321 caller_event_handler (void *cls,
322                       enum GNUNET_CONVERSATION_CallerEventCode code)
323 {
324   struct CallList *cl = cls;
325
326   switch (code)
327   {
328   case GNUNET_CONVERSATION_EC_CALLER_SUSPEND:
329     FPRINTF (stdout,
330              _("Call from `%s' suspended by other user\n"),
331              GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id));
332     break;
333   case GNUNET_CONVERSATION_EC_CALLER_RESUME:
334     FPRINTF (stdout,
335              _("Call from `%s' resumed by other user\n"),
336              GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id));
337     break;
338   }
339 }
340
341
342 /**
343  * Start our phone.
344  */
345 static void
346 start_phone ()
347 {
348   struct GNUNET_GNSRECORD_Data rd;
349
350   if (NULL == my_caller_id)
351   {
352     FPRINTF (stderr,
353              _("Ego `%s' no longer available, phone is now down.\n"),
354              ego_name);
355     phone_state = PS_LOOKUP_EGO;
356     return;
357   }
358   GNUNET_assert (NULL == phone);
359   phone = GNUNET_CONVERSATION_phone_create (cfg,
360                                             my_caller_id,
361                                             &phone_event_handler,
362                                             NULL);
363   /* FIXME: get record and print full GNS record info later here... */
364   if (NULL == phone)
365   {
366     FPRINTF (stderr,
367              "%s",
368              _("Failed to setup phone (internal error)\n"));
369     phone_state = PS_ERROR;
370   }
371   else
372   {
373     GNUNET_CONVERSATION_phone_get_record (phone,
374                                           &rd);
375     GNUNET_free_non_null (address);
376     address = GNUNET_GNSRECORD_value_to_string (rd.record_type,
377                                                 rd.data,
378                                                 rd.data_size);
379     FPRINTF (stdout,
380              _("Phone active at `%s'.  Type `/help' for a list of available commands\n"),
381              address);
382     phone_state = PS_LISTEN;
383   }
384 }
385
386
387 /**
388  * Function called with an event emitted by a call.
389  *
390  * @param cls closure, NULL
391  * @param code type of the event on the call
392  */
393 static void
394 call_event_handler (void *cls,
395                     enum GNUNET_CONVERSATION_CallEventCode code)
396 {
397   (void) cls;
398   
399   switch (code)
400   {
401   case GNUNET_CONVERSATION_EC_CALL_RINGING:
402     GNUNET_break (CS_RESOLVING == call_state);
403     FPRINTF (stdout,
404              _("Resolved address of `%s'. Now ringing other party.\n"),
405              peer_name);
406     call_state = CS_RINGING;
407     break;
408   case GNUNET_CONVERSATION_EC_CALL_PICKED_UP:
409     GNUNET_break (CS_RINGING == call_state);
410     FPRINTF (stdout,
411              _("Connection established to `%s'\n"),
412              peer_name);
413     call_state = CS_CONNECTED;
414     break;
415   case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL:
416     GNUNET_break (CS_RESOLVING == call_state);
417     FPRINTF (stdout,
418              _("Failed to resolve `%s'\n"),
419              peer_name);
420     GNUNET_free (peer_name);
421     peer_name = NULL;
422     call = NULL;
423     break;
424   case GNUNET_CONVERSATION_EC_CALL_HUNG_UP:
425     FPRINTF (stdout,
426              _("Call to `%s' terminated\n"),
427              peer_name);
428     GNUNET_free (peer_name);
429     peer_name = NULL;
430     call = NULL;
431     break;
432   case GNUNET_CONVERSATION_EC_CALL_SUSPENDED:
433     GNUNET_break (CS_CONNECTED == call_state);
434     FPRINTF (stdout,
435              _("Connection to `%s' suspended (by other user)\n"),
436              peer_name);
437     break;
438   case GNUNET_CONVERSATION_EC_CALL_RESUMED:
439     GNUNET_break (CS_CONNECTED == call_state);
440     FPRINTF (stdout,
441              _("Connection to `%s' resumed (by other user)\n"),
442              peer_name);
443     break;
444   case GNUNET_CONVERSATION_EC_CALL_ERROR:
445     FPRINTF (stdout,
446              _("Error with the call, restarting it\n"));
447     GNUNET_free (peer_name);
448     peer_name = NULL;
449     call = NULL;
450     break;
451   }
452 }
453
454
455 /**
456  * Function declareation for executing a action
457  *
458  * @param arguments arguments given to the function
459  */
460 typedef void
461 (*ActionFunction) (const char *arguments);
462
463
464 /**
465  * Structure which defines a command
466  */
467 struct VoipCommand
468 {
469   /**
470    * Command the user needs to enter.
471    */
472   const char *command;
473
474   /**
475    * Function to call on command.
476    */
477   ActionFunction Action;
478
479   /**
480    * Help text for the command.
481    */
482   const char *helptext;
483 };
484
485
486 /**
487  * Action function to print help for the command shell.
488  *
489  * @param args arguments given to the command
490  */
491 static void
492 do_help (const char *args);
493
494
495 /**
496  * Terminate the client
497  *
498  * @param args arguments given to the command
499  */
500 static void
501 do_quit (const char *args)
502 {
503   (void) args;
504   GNUNET_SCHEDULER_shutdown ();
505 }
506
507
508 /**
509  * Handler for unknown command.
510  *
511  * @param msg arguments given to the command
512  */
513 static void
514 do_unknown (const char *msg)
515 {
516   FPRINTF (stderr,
517            _("Unknown command `%s'\n"),
518            msg);
519 }
520
521
522 /**
523  * Initiating a new call
524  *
525  * @param arg arguments given to the command
526  */
527 static void
528 do_call (const char *arg)
529 {
530   if (NULL == my_caller_id)
531   {
532     FPRINTF (stderr,
533              _("Ego `%s' not available\n"),
534              ego_name);
535     return;
536   }
537   if (NULL != call)
538   {
539     FPRINTF (stderr,
540              _("You are calling someone else already, hang up first!\n"));
541     return;
542   }
543   switch (phone_state)
544   {
545   case PS_LOOKUP_EGO:
546     FPRINTF (stderr,
547              _("Ego `%s' not available\n"),
548              ego_name);
549     return;
550   case PS_LISTEN:
551     /* ok to call! */
552     break;
553   case PS_ACCEPTED:
554     FPRINTF (stderr,
555              _("You are answering call from `%s', hang up or suspend that call first!\n"),
556              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));
557     return;
558   case PS_ERROR:
559     /* ok to call */
560     break;
561   }
562   if (NULL == arg)
563   {
564     FPRINTF (stderr,
565              _("Call recipient missing.\n"));
566     do_help ("/call");
567     return;
568   }
569   peer_name = GNUNET_strdup (arg);
570   call_state = CS_RESOLVING;
571   GNUNET_assert (NULL == call);
572   call = GNUNET_CONVERSATION_call_start (cfg,
573                                          my_caller_id,
574                                          arg,
575                                          speaker,
576                                          mic,
577                                          &call_event_handler, NULL);
578 }
579
580
581 /**
582  * Accepting an incoming call
583  *
584  * @param args arguments given to the command
585  */
586 static void
587 do_accept (const char *args)
588 {
589   struct CallList *cl;
590   char buf[32];
591
592   if ( (NULL != call) &&
593        (CS_SUSPENDED != call_state) )
594   {
595     FPRINTF (stderr,
596              _("You are calling someone else already, hang up first!\n"));
597     return;
598   }
599   switch (phone_state)
600   {
601   case PS_LOOKUP_EGO:
602     GNUNET_break (0);
603     break;
604   case PS_LISTEN:
605     /* this is the expected state */
606     break;
607   case PS_ACCEPTED:
608     FPRINTF (stderr,
609              _("You are answering call from `%s', hang up or suspend that call first!\n"),
610              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));
611     return;
612   case PS_ERROR:
613     GNUNET_break (0);
614     break;
615   }
616   cl = cl_head;
617   if (NULL == cl)
618   {
619     FPRINTF (stderr,
620              _("There is no incoming call to accept here!\n"));
621     return;
622   }
623   if ( (NULL != cl->next) || (NULL != args) )
624   {
625     for (cl = cl_head; NULL != cl; cl = cl->next)
626     {
627       GNUNET_snprintf (buf, sizeof (buf),
628                        "%u",
629                        cl->caller_num);
630       if (0 == strcmp (buf, args))
631         break;
632     }
633   }
634   if (NULL == cl)
635   {
636     FPRINTF (stderr,
637              _("There is no incoming call `%s' to accept right now!\n"),
638              args);
639     return;
640   }
641   GNUNET_CONTAINER_DLL_remove (cl_head,
642                                cl_tail,
643                                cl);
644   cl_active = cl;
645   peer_key = cl->caller_id;
646   phone_state = PS_ACCEPTED;
647   GNUNET_CONVERSATION_caller_pick_up (cl->caller,
648                                       &caller_event_handler,
649                                       cl,
650                                       speaker,
651                                       mic);
652 }
653
654
655 /**
656  * Print address information for this phone.
657  *
658  * @param args arguments given to the command
659  */
660 static void
661 do_address (const char *args)
662 {
663   (void) args;
664   if (NULL == address)
665   {
666     FPRINTF (stdout,
667              "%s",
668              _("We currently do not have an address.\n"));
669     return;
670   }
671   FPRINTF (stdout,
672            "%s\n",
673            address);
674 }
675
676
677 /**
678  * Accepting an incoming call
679  *
680  * @param args arguments given to the command
681  */
682 static void
683 do_status (const char *args)
684 {
685   struct CallList *cl;
686
687   (void) args;
688   switch (phone_state)
689   {
690   case PS_LOOKUP_EGO:
691     FPRINTF (stdout,
692              _("We are currently trying to locate the private key for the ego `%s'.\n"),
693              ego_name);
694     break;
695   case PS_LISTEN:
696     FPRINTF (stdout,
697              _("We are listening for incoming calls for ego `%s' on line `%s'.\n"),
698              ego_name,
699              line);
700     break;
701   case PS_ACCEPTED:
702     FPRINTF (stdout,
703              _("You are having a conversation with `%s'.\n"),
704              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));;
705     break;
706   case PS_ERROR:
707     FPRINTF (stdout,
708              _("We had an internal error setting up our phone line. You can still make calls.\n"));
709     break;
710   }
711   if (NULL != call)
712   {
713     switch (call_state)
714     {
715     case CS_RESOLVING:
716       FPRINTF (stdout,
717                _("We are trying to find the network address to call `%s'.\n"),
718                peer_name);
719       break;
720     case CS_RINGING:
721       FPRINTF (stdout,
722                _("We are calling `%s', his phone should be ringing.\n"),
723                peer_name);
724       break;
725     case CS_CONNECTED:
726       FPRINTF (stdout,
727                _("You are having a conversation with `%s'.\n"),
728                peer_name);
729       break;
730     case CS_SUSPENDED:
731       /* ok to accept incoming call right now */
732       break;
733     }
734   }
735   if ( (NULL != cl_head) &&
736        ( (cl_head != cl_active) ||
737          (cl_head != cl_tail) ) )
738   {
739     FPRINTF (stdout,
740              "%s",
741              _("Calls waiting:\n"));
742     for (cl = cl_head; NULL != cl; cl = cl->next)
743     {
744       if (cl == cl_active)
745         continue;
746       FPRINTF (stdout,
747                _("#%u: `%s'\n"),
748                cl->caller_num,
749                GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id));
750     }
751     FPRINTF (stdout,
752              "%s",
753              "\n");
754   }
755 }
756
757
758 /**
759  * Suspending a call
760  *
761  * @param args arguments given to the command
762  */
763 static void
764 do_suspend (const char *args)
765 {
766   (void) args;
767   if (NULL != call)
768   {
769     switch (call_state)
770     {
771     case CS_RESOLVING:
772     case CS_RINGING:
773     case CS_SUSPENDED:
774       FPRINTF (stderr,
775                "%s",
776                _("There is no call that could be suspended right now.\n"));
777       return;
778     case CS_CONNECTED:
779       call_state = CS_SUSPENDED;
780       GNUNET_CONVERSATION_call_suspend (call);
781       return;
782     }
783   }
784   switch (phone_state)
785   {
786   case PS_LOOKUP_EGO:
787   case PS_LISTEN:
788   case PS_ERROR:
789     FPRINTF (stderr,
790              "%s",
791              _("There is no call that could be suspended right now.\n"));
792     return;
793   case PS_ACCEPTED:
794     /* expected state, do rejection logic */
795     break;
796   }
797   GNUNET_assert (NULL != cl_active);
798   GNUNET_CONVERSATION_caller_suspend (cl_active->caller);
799   cl_active = NULL;
800   phone_state = PS_LISTEN;
801 }
802
803
804 /**
805  * Resuming a call
806  *
807  * @param args arguments given to the command
808  */
809 static void
810 do_resume (const char *args)
811 {
812   struct CallList *cl;
813   char buf[32];
814
815   if (NULL != call)
816   {
817     switch (call_state)
818     {
819     case CS_RESOLVING:
820     case CS_RINGING:
821     case CS_CONNECTED:
822       FPRINTF (stderr,
823                "%s",
824                _("There is no call that could be resumed right now.\n"));
825       return;
826     case CS_SUSPENDED:
827       call_state = CS_CONNECTED;
828       GNUNET_CONVERSATION_call_resume (call,
829                                        speaker,
830                                        mic);
831       return;
832     }
833   }
834   switch (phone_state)
835   {
836   case PS_LOOKUP_EGO:
837   case PS_ERROR:
838     FPRINTF (stderr,
839              "%s",
840              _("There is no call that could be resumed right now.\n"));
841     return;
842   case PS_LISTEN:
843     /* expected state, do resume logic */
844     break;
845   case PS_ACCEPTED:
846     FPRINTF (stderr,
847              _("Already talking with `%s', cannot resume a call right now.\n"),
848              GNUNET_GNSRECORD_pkey_to_zkey (&peer_key));
849     return;
850   }
851   GNUNET_assert (NULL == cl_active);
852   cl = cl_head;
853   if (NULL == cl)
854   {
855     FPRINTF (stderr,
856              _("There is no incoming call to resume here!\n"));
857     return;
858   }
859   if ( (NULL != cl->next) || (NULL != args) )
860   {
861     for (cl = cl_head; NULL != cl; cl = cl->next)
862     {
863       GNUNET_snprintf (buf, sizeof (buf),
864                        "%u",
865                        cl->caller_num);
866       if (0 == strcmp (buf, args))
867         break;
868     }
869   }
870   if (NULL == cl)
871   {
872     FPRINTF (stderr,
873              _("There is no incoming call `%s' to resume right now!\n"),
874              args);
875     return;
876   }
877   cl_active = cl;
878   GNUNET_CONVERSATION_caller_resume (cl_active->caller,
879                                      speaker,
880                                      mic);
881   phone_state = PS_ACCEPTED;
882 }
883
884
885 /**
886  * Rejecting a call
887  *
888  * @param args arguments given to the command
889  */
890 static void
891 do_reject (const char *args)
892 {
893   struct CallList *cl;
894   char buf[32];
895
896   if (NULL != call)
897   {
898     GNUNET_CONVERSATION_call_stop (call);
899     call = NULL;
900     return;
901   }
902   switch (phone_state)
903   {
904   case PS_LOOKUP_EGO:
905   case PS_ERROR:
906     FPRINTF (stderr,
907              "%s",
908              _("There is no call that could be cancelled right now.\n"));
909     return;
910   case PS_LISTEN:
911     /* look for active incoming calls to refuse */
912     cl = cl_head;
913     if (NULL == cl)
914     {
915       FPRINTF (stderr,
916                _("There is no incoming call to refuse here!\n"));
917       return;
918     }
919     if ( (NULL != cl->next) || (NULL != args) )
920     {
921       for (cl = cl_head; NULL != cl; cl = cl->next)
922       {
923         GNUNET_snprintf (buf, sizeof (buf),
924                          "%u",
925                          cl->caller_num);
926         if (0 == strcmp (buf, args))
927           break;
928       }
929     }
930     if (NULL == cl)
931     {
932       FPRINTF (stderr,
933                _("There is no incoming call `%s' to refuse right now!\n"),
934                args);
935       return;
936     }
937     GNUNET_CONVERSATION_caller_hang_up (cl->caller);
938     GNUNET_CONTAINER_DLL_remove (cl_head,
939                                  cl_tail,
940                                  cl);
941     GNUNET_free (cl);
942     break;
943   case PS_ACCEPTED:
944     /* expected state, do rejection logic */
945     GNUNET_assert (NULL != cl_active);
946     GNUNET_CONVERSATION_caller_hang_up (cl_active->caller);
947     cl_active = NULL;
948     phone_state = PS_LISTEN;
949     break;
950   }
951 }
952
953
954 /**
955  * List of supported commands.
956  */
957 static struct VoipCommand commands[] = {
958   {"/address", &do_address,
959    gettext_noop ("Use `/address' to find out which address this phone should have in GNS")},
960   {"/call", &do_call,
961    gettext_noop ("Use `/call USER.gnu' to call USER")},
962   {"/accept", &do_accept,
963    gettext_noop ("Use `/accept #NUM' to accept incoming call #NUM")},
964   {"/suspend", &do_suspend,
965    gettext_noop ("Use `/suspend' to suspend the active call")},
966   {"/resume", &do_resume,
967    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.")},
968   {"/cancel", &do_reject,
969    gettext_noop ("Use `/cancel' to reject or terminate a call")},
970   {"/status", &do_status,
971    gettext_noop ("Use `/status' to print status information")},
972   {"/quit", &do_quit,
973    gettext_noop ("Use `/quit' to terminate gnunet-conversation")},
974   {"/help", &do_help,
975    gettext_noop ("Use `/help command' to get help for a specific command")},
976   {"", &do_unknown,
977    NULL},
978   {NULL, NULL, NULL},
979 };
980
981
982 /**
983  * Action function to print help for the command shell.
984  *
985  * @param args arguments given to the command
986  */
987 static void
988 do_help (const char *args)
989 {
990   unsigned int i;
991
992   i = 0;
993   while ( (NULL != args) &&
994           (0 != strlen (args)) &&
995           (commands[i].Action != &do_help))
996   {
997     if (0 ==
998         strncasecmp (&args[1], &commands[i].command[1], strlen (args) - 1))
999     {
1000       FPRINTF (stdout,
1001                "%s\n",
1002                gettext (commands[i].helptext));
1003       return;
1004     }
1005     i++;
1006   }
1007   i = 0;
1008   FPRINTF (stdout,
1009            "%s",
1010            "Available commands:\n");
1011   while (commands[i].Action != &do_help)
1012   {
1013     FPRINTF (stdout,
1014              "%s\n",
1015              gettext (commands[i].command));
1016     i++;
1017   }
1018   FPRINTF (stdout,
1019            "%s",
1020            "\n");
1021   FPRINTF (stdout,
1022            "%s\n",
1023            gettext (commands[i].helptext));
1024 }
1025
1026
1027 /**
1028  * Task run during shutdown.
1029  *
1030  * @param cls NULL
1031  */
1032 static void
1033 do_stop_task (void *cls)
1034 {
1035   (void) cls;
1036 #ifdef WINDOWS
1037   if (NULL != stdin_hlp)
1038   {
1039     GNUNET_HELPER_stop (stdin_hlp, GNUNET_NO);
1040     stdin_hlp = NULL;
1041   }
1042 #endif
1043   if (NULL != call)
1044   {
1045     GNUNET_CONVERSATION_call_stop (call);
1046     call = NULL;
1047   }
1048   if (NULL != phone)
1049   {
1050     GNUNET_CONVERSATION_phone_destroy (phone);
1051     phone = NULL;
1052   }
1053   if (NULL != handle_cmd_task)
1054   {
1055     GNUNET_SCHEDULER_cancel (handle_cmd_task);
1056     handle_cmd_task = NULL;
1057   }
1058   if (NULL != id)
1059   {
1060     GNUNET_IDENTITY_disconnect (id);
1061     id = NULL;
1062   }
1063   GNUNET_SPEAKER_destroy (speaker);
1064   speaker = NULL;
1065   GNUNET_MICROPHONE_destroy (mic);
1066   mic = NULL;
1067   GNUNET_free (ego_name);
1068   ego_name = NULL;
1069   GNUNET_free_non_null (peer_name);
1070   peer_name = NULL;
1071   phone_state = PS_ERROR;
1072 }
1073
1074
1075 /**
1076  * Handle user command.
1077  *
1078  * @param message command the user typed in
1079  * @param str_len number of bytes to process in @a message
1080  */
1081 static void
1082 handle_command_string (char *message,
1083                        size_t str_len)
1084 {
1085   size_t i;
1086   const char *ptr;
1087
1088   if (0 == str_len)
1089     return;
1090   if (message[str_len - 1] == '\n')
1091     message[str_len - 1] = '\0';
1092   if (message[str_len - 2] == '\r')
1093     message[str_len - 2] = '\0';
1094   if (0 == strlen (message))
1095     return;
1096   i = 0;
1097   while ((NULL != commands[i].command) &&
1098          (0 != strncasecmp (commands[i].command, message,
1099                             strlen (commands[i].command))))
1100     i++;
1101   ptr = &message[strlen (commands[i].command)];
1102   while (isspace ((unsigned char) *ptr))
1103     ptr++;
1104   if ('\0' == *ptr)
1105     ptr = NULL;
1106   commands[i].Action (ptr);
1107 }
1108
1109
1110 #ifdef WINDOWS
1111 static int
1112 console_reader_chars (void *cls,
1113                       void *client,
1114                       const struct GNUNET_MessageHeader *message)
1115 {
1116   char *chars;
1117   size_t str_size;
1118
1119   (void) cls;
1120   switch (ntohs (message->type))
1121   {
1122   case GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_CHARS:
1123     chars = (char *) &message[1];
1124     str_size = ntohs (message->size) - sizeof (struct GNUNET_MessageHeader);
1125     if (chars[str_size - 1] != '\0')
1126       return GNUNET_SYSERR;
1127     /* FIXME: is it ok that we pass part of a const struct to
1128      * this function that may mangle the contents?
1129      */
1130     handle_command_string (chars, str_size - 1);
1131     break;
1132   default:
1133     GNUNET_break (0);
1134     break;
1135   }
1136   return GNUNET_OK;
1137 }
1138 #endif
1139
1140
1141 /**
1142  * Task to handle commands from the terminal.
1143  *
1144  * @param cls NULL
1145  */
1146 static void
1147 handle_command (void *cls)
1148 {
1149   char message[MAX_MESSAGE_LENGTH + 1];
1150
1151   (void) cls;
1152   handle_cmd_task =
1153     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1154                                     stdin_fh,
1155                                     &handle_command, NULL);
1156   /* read message from command line and handle it */
1157   memset (message,
1158           0,
1159           MAX_MESSAGE_LENGTH + 1);
1160   if (NULL == fgets (message,
1161                      MAX_MESSAGE_LENGTH,
1162                      stdin))
1163     return;
1164   handle_command_string (message,
1165                          strlen (message));
1166 }
1167
1168
1169 /**
1170  * Function called by identity service with information about egos.
1171  *
1172  * @param cls NULL
1173  * @param ego ego handle
1174  * @param ctx unused
1175  * @param name name of the ego
1176  */
1177 static void
1178 identity_cb (void *cls,
1179              struct GNUNET_IDENTITY_Ego *ego,
1180              void **ctx,
1181              const char *name)
1182 {
1183   (void) cls;
1184   (void) ctx;
1185   if (NULL == name)
1186     return;
1187   if (ego == my_caller_id)
1188   {
1189     if (verbose)
1190       FPRINTF (stdout,
1191                _("Name of our ego changed to `%s'\n"),
1192                name);
1193     GNUNET_free (ego_name);
1194     ego_name = GNUNET_strdup (name);
1195     return;
1196   }
1197   if (0 != strcmp (name,
1198                    ego_name))
1199     return;
1200   if (NULL == ego)
1201   {
1202     if (verbose)
1203       FPRINTF (stdout,
1204                _("Our ego `%s' was deleted!\n"),
1205                ego_name);
1206     my_caller_id = NULL;
1207     return;
1208   }
1209   my_caller_id = ego;
1210   GNUNET_CONFIGURATION_set_value_string (cfg,
1211                                          "CONVERSATION",
1212                                          "LINE",
1213                                          line);
1214   start_phone ();
1215 }
1216
1217
1218 /**
1219  * Main function that will be run by the scheduler.
1220  *
1221  * @param cls closure
1222  * @param args remaining command-line arguments
1223  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1224  * @param c configuration
1225  */
1226 static void
1227 run (void *cls,
1228      char *const *args,
1229      const char *cfgfile,
1230      const struct GNUNET_CONFIGURATION_Handle *c)
1231 {
1232   (void) cls;
1233   (void) args;
1234   (void) cfgfile;
1235   cfg = GNUNET_CONFIGURATION_dup (c);
1236   speaker = GNUNET_SPEAKER_create_from_hardware (cfg);
1237   mic = GNUNET_MICROPHONE_create_from_hardware (cfg);
1238   if (NULL == ego_name)
1239   {
1240     FPRINTF (stderr,
1241              "%s",
1242              _("You must specify the NAME of an ego to use\n"));
1243     return;
1244   }
1245   id = GNUNET_IDENTITY_connect (cfg,
1246                                 &identity_cb,
1247                                 NULL);
1248 #ifdef WINDOWS
1249   if (stdin_fh == NULL)
1250   {
1251     static char cpid[64];
1252     static char *args[] = {"gnunet-helper-w32-console.exe", "chars",
1253         XSTRINGIFY (MAX_MESSAGE_LENGTH), cpid, NULL};
1254     snprintf (cpid, 64, "%d", GetCurrentProcessId ());
1255     stdin_hlp = GNUNET_HELPER_start (
1256         GNUNET_NO,
1257         "gnunet-helper-w32-console",
1258         args,
1259         console_reader_chars,
1260         NULL,
1261         NULL);
1262     if (NULL == stdin_hlp)
1263     {
1264       FPRINTF (stderr,
1265                "%s",
1266                _("Failed to start gnunet-helper-w32-console\n"));
1267       return;
1268     }
1269   }
1270   else
1271 #endif
1272   handle_cmd_task =
1273     GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_UI,
1274                                         &handle_command, NULL);
1275   GNUNET_SCHEDULER_add_shutdown (&do_stop_task,
1276                                  NULL);
1277 }
1278
1279
1280 /**
1281  * The main function to conversation.
1282  *
1283  * @param argc number of arguments from the command line
1284  * @param argv command line arguments
1285  * @return 0 ok, 1 on error
1286  */
1287 int
1288 main (int argc,
1289       char *const *argv)
1290 {
1291   struct GNUNET_GETOPT_CommandLineOption options[] = {
1292     GNUNET_GETOPT_option_string ('e',
1293                                  "ego",
1294                                  "NAME",
1295                                  gettext_noop ("sets the NAME of the ego to use for the caller ID"),
1296                                  &ego_name),
1297     GNUNET_GETOPT_option_string ('p',
1298                                  "phone",
1299                                  "LINE",
1300                                  gettext_noop ("sets the LINE to use for the phone"),
1301                                  &line),
1302     GNUNET_GETOPT_OPTION_END
1303   };
1304   int ret;
1305 #ifndef WINDOWS
1306   int flags;
1307   flags = fcntl (0, F_GETFL, 0);
1308   flags |= O_NONBLOCK;
1309   if (0 != fcntl (0, F_SETFL, flags))
1310     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1311                          "fcntl");
1312   stdin_fh = GNUNET_DISK_get_handle_from_int_fd (0);
1313 #else
1314   if (FILE_TYPE_CHAR == GetFileType ((HANDLE) _get_osfhandle (0)))
1315   {
1316     stdin_fh = NULL;
1317   }
1318   else
1319     stdin_fh = GNUNET_DISK_get_handle_from_int_fd (0);
1320 #endif
1321
1322   if (GNUNET_OK !=
1323       GNUNET_STRINGS_get_utf8_args (argc, argv,
1324                                     &argc, &argv))
1325     return 2;
1326   ret = GNUNET_PROGRAM_run (argc,
1327                             argv,
1328                             "gnunet-conversation",
1329                             gettext_noop ("Enables having a conversation with other GNUnet users."),
1330                             options,
1331                             &run, NULL);
1332   GNUNET_free ((void *) argv);
1333   if (NULL != cfg)
1334   {
1335     GNUNET_CONFIGURATION_destroy (cfg);
1336     cfg = NULL;
1337   }
1338   return (GNUNET_OK == ret) ? 0 : 1;
1339 }
1340
1341 /* end of gnunet-conversation.c */