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