transport reliabilities checken
[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   cl_active = cl;
621   GNUNET_free_non_null (peer_name);
622   peer_name = GNUNET_strdup (cl->caller_id);
623   phone_state = PS_ACCEPTED;
624   GNUNET_CONVERSATION_caller_pick_up (cl->caller,
625                                       &caller_event_handler,
626                                       cl,
627                                       speaker,
628                                       mic);
629 }
630
631
632 /**
633  * Print address information for this phone.
634  *
635  * @param args arguments given to the command
636  */
637 static void
638 do_address (const char *args)
639 {
640   if (NULL == address)
641   {
642     FPRINTF (stdout,
643              "%s",
644              _("We currently do not have an address.\n"));
645     return;
646   }
647   FPRINTF (stdout,
648            "%s\n",
649            address);
650 }
651
652
653 /**
654  * Accepting an incoming call
655  *
656  * @param args arguments given to the command
657  */
658 static void
659 do_status (const char *args)
660 {
661   struct CallList *cl;
662
663   switch (phone_state)
664   {
665   case PS_LOOKUP_EGO:
666     FPRINTF (stdout,
667              _("We are currently trying to locate the private key for the ego `%s'.\n"),
668              ego_name);
669     break;
670   case PS_LISTEN:
671     FPRINTF (stdout,
672              _("We are listening for incoming calls for ego `%s' on line %u.\n"),
673              ego_name,
674              line);
675     break;
676   case PS_ACCEPTED:
677     FPRINTF (stdout,
678              _("You are having a conversation with `%s'.\n"),
679              peer_name);
680     break;
681   case PS_ERROR:
682     FPRINTF (stdout,
683              _("We had an internal error setting up our phone line. You can still make calls.\n"));
684     break;
685   }
686   if (NULL != call)
687   {
688     switch (call_state)
689     {
690     case CS_RESOLVING:
691       FPRINTF (stdout,
692                _("We are trying to find the network address to call `%s'.\n"),
693                peer_name);
694       break;
695     case CS_RINGING:
696       FPRINTF (stdout,
697                _("We are calling `%s', his phone should be ringing.\n"),
698                peer_name);
699       break;
700     case CS_CONNECTED:
701       FPRINTF (stdout,
702                _("You are having a conversation with `%s'.\n"),
703                peer_name);
704       break;
705     case CS_SUSPENDED:
706       /* ok to accept incoming call right now */
707       break;
708     }
709   }
710   if ( (NULL != cl_head) &&
711        ( (cl_head != cl_active) ||
712          (cl_head != cl_tail) ) )
713   {
714     FPRINTF (stdout,
715              "%s",
716              _("Calls waiting:\n"));
717     for (cl = cl_head; NULL != cl; cl = cl->next)
718     {
719       if (cl == cl_active)
720         continue;
721       FPRINTF (stdout,
722                _("#%u: `%s'\n"),
723                cl->caller_num,
724                cl->caller_id);
725     }
726     FPRINTF (stdout,
727              "%s",
728              "\n");
729   }
730 }
731
732
733 /**
734  * Suspending a call
735  *
736  * @param args arguments given to the command
737  */
738 static void
739 do_suspend (const char *args)
740 {
741   if (NULL != call)
742   {
743     switch (call_state)
744     {
745     case CS_RESOLVING:
746     case CS_RINGING:
747     case CS_SUSPENDED:
748       FPRINTF (stderr,
749                "%s",
750                _("There is no call that could be suspended right now.\n"));
751       return;
752     case CS_CONNECTED:
753       call_state = CS_SUSPENDED;
754       GNUNET_CONVERSATION_call_suspend (call);
755       return;
756     }
757   }
758   switch (phone_state)
759   {
760   case PS_LOOKUP_EGO:
761   case PS_LISTEN:
762   case PS_ERROR:
763     FPRINTF (stderr,
764              "%s",
765              _("There is no call that could be suspended right now.\n"));
766     return;
767   case PS_ACCEPTED:
768     /* expected state, do rejection logic */
769     break;
770   }
771   GNUNET_assert (NULL != cl_active);
772   GNUNET_CONVERSATION_caller_suspend (cl_active->caller);
773   cl_active = NULL;
774   phone_state = PS_LISTEN;
775 }
776
777
778 /**
779  * Resuming a call
780  *
781  * @param args arguments given to the command
782  */
783 static void
784 do_resume (const char *args)
785 {
786   struct CallList *cl;
787   char buf[32];
788
789   if (NULL != call)
790   {
791     switch (call_state)
792     {
793     case CS_RESOLVING:
794     case CS_RINGING:
795     case CS_CONNECTED:
796       FPRINTF (stderr,
797                "%s",
798                _("There is no call that could be resumed right now.\n"));
799       return;
800     case CS_SUSPENDED:
801       call_state = CS_CONNECTED;
802       GNUNET_CONVERSATION_call_resume (call,
803                                        speaker,
804                                        mic);
805       return;
806     }
807   }
808   switch (phone_state)
809   {
810   case PS_LOOKUP_EGO:
811   case PS_ERROR:
812     FPRINTF (stderr,
813              "%s",
814              _("There is no call that could be resumed right now.\n"));
815     return;
816   case PS_LISTEN:
817     /* expected state, do resume logic */
818     break;
819   case PS_ACCEPTED:
820     FPRINTF (stderr,
821              _("Already talking with `%s', cannot resume a call right now.\n"),
822              peer_name);
823     return;
824   }
825   GNUNET_assert (NULL == cl_active);
826   cl = cl_head;
827   if (NULL == cl)
828   {
829     FPRINTF (stderr,
830              _("There is no incoming call to resume here!\n"));
831     return;
832   }
833   if ( (NULL != cl->next) || (NULL != args) )
834   {
835     for (cl = cl_head; NULL != cl; cl = cl->next)
836     {
837       GNUNET_snprintf (buf, sizeof (buf),
838                        "%u",
839                        cl->caller_num);
840       if (0 == strcmp (buf, args))
841         break;
842     }
843   }
844   if (NULL == cl)
845   {
846     FPRINTF (stderr,
847              _("There is no incoming call `%s' to resume right now!\n"),
848              args);
849     return;
850   }
851   cl_active = cl;
852   GNUNET_CONVERSATION_caller_resume (cl_active->caller,
853                                      speaker,
854                                      mic);
855   phone_state = PS_ACCEPTED;
856 }
857
858
859 /**
860  * Rejecting a call
861  *
862  * @param args arguments given to the command
863  */
864 static void
865 do_reject (const char *args)
866 {
867   struct CallList *cl;
868   char buf[32];
869
870   if (NULL != call)
871   {
872     GNUNET_CONVERSATION_call_stop (call);
873     call = NULL;
874     return;
875   }
876   switch (phone_state)
877   {
878   case PS_LOOKUP_EGO:
879   case PS_ERROR:
880     FPRINTF (stderr,
881              "%s",
882              _("There is no call that could be cancelled right now.\n"));
883     return;
884   case PS_LISTEN:
885     /* look for active incoming calls to refuse */
886     cl = cl_head;
887     if (NULL == cl)
888     {
889       FPRINTF (stderr,
890                _("There is no incoming call to refuse here!\n"));
891       return;
892     }
893     if ( (NULL != cl->next) || (NULL != args) )
894     {
895       for (cl = cl_head; NULL != cl; cl = cl->next)
896       {
897         GNUNET_snprintf (buf, sizeof (buf),
898                          "%u",
899                          cl->caller_num);
900         if (0 == strcmp (buf, args))
901           break;
902       }
903     }
904     if (NULL == cl)
905     {
906       FPRINTF (stderr,
907                _("There is no incoming call `%s' to refuse right now!\n"),
908                args);
909       return;
910     }
911     GNUNET_CONVERSATION_caller_hang_up (cl->caller);
912     GNUNET_CONTAINER_DLL_remove (cl_head,
913                                  cl_tail,
914                                  cl);
915     GNUNET_free (cl->caller_id);
916     GNUNET_free (cl);
917     break;
918   case PS_ACCEPTED:
919     /* expected state, do rejection logic */
920     GNUNET_assert (NULL != cl_active);
921     GNUNET_CONVERSATION_caller_hang_up (cl_active->caller);
922     cl_active = NULL;
923     phone_state = PS_LISTEN;
924     break;
925   }
926 }
927
928
929 /**
930  * List of supported commands.
931  */
932 static struct VoipCommand commands[] = {
933   {"/address", &do_address,
934    gettext_noop ("Use `/address' to find out which address this phone should have in GNS")},
935   {"/call", &do_call,
936    gettext_noop ("Use `/call USER.gnu' to call USER")},
937   {"/accept", &do_accept,
938    gettext_noop ("Use `/accept #NUM' to accept incoming call #NUM")},
939   {"/suspend", &do_suspend,
940    gettext_noop ("Use `/suspend' to suspend the active call")},
941   {"/resume", &do_resume,
942    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.")},
943   {"/cancel", &do_reject,
944    gettext_noop ("Use `/cancel' to reject or terminate a call")},
945   {"/status", &do_status,
946    gettext_noop ("Use `/status' to print status information")},
947   {"/quit", &do_quit,
948    gettext_noop ("Use `/quit' to terminate gnunet-conversation")},
949   {"/help", &do_help,
950    gettext_noop ("Use `/help command' to get help for a specific command")},
951   {"", &do_unknown,
952    NULL},
953   {NULL, NULL, NULL},
954 };
955
956
957 /**
958  * Action function to print help for the command shell.
959  *
960  * @param args arguments given to the command
961  */
962 static void
963 do_help (const char *args)
964 {
965   unsigned int i;
966
967   i = 0;
968   while ( (NULL != args) &&
969           (0 != strlen (args)) &&
970           (commands[i].Action != &do_help))
971   {
972     if (0 ==
973         strncasecmp (&args[1], &commands[i].command[1], strlen (args) - 1))
974     {
975       FPRINTF (stdout,
976                "%s\n",
977                gettext (commands[i].helptext));
978       return;
979     }
980     i++;
981   }
982   i = 0;
983   FPRINTF (stdout,
984            "%s",
985            "Available commands:\n");
986   while (commands[i].Action != &do_help)
987   {
988     FPRINTF (stdout,
989              "%s\n",
990              gettext (commands[i].command));
991     i++;
992   }
993   FPRINTF (stdout,
994            "%s",
995            "\n");
996   FPRINTF (stdout,
997            "%s\n",
998            gettext (commands[i].helptext));
999 }
1000
1001
1002 /**
1003  * Task run during shutdown.
1004  *
1005  * @param cls NULL
1006  * @param tc unused
1007  */
1008 static void
1009 do_stop_task (void *cls,
1010               const struct GNUNET_SCHEDULER_TaskContext *tc)
1011 {
1012 #ifdef WINDOWS
1013   if (NULL != stdin_hlp)
1014   {
1015     GNUNET_HELPER_stop (stdin_hlp, GNUNET_NO);
1016     stdin_hlp = NULL;
1017   }
1018 #endif
1019   if (NULL != call)
1020   {
1021     GNUNET_CONVERSATION_call_stop (call);
1022     call = NULL;
1023   }
1024   if (NULL != phone)
1025   {
1026     GNUNET_CONVERSATION_phone_destroy (phone);
1027     phone = NULL;
1028   }
1029   if (GNUNET_SCHEDULER_NO_TASK != handle_cmd_task)
1030   {
1031     GNUNET_SCHEDULER_cancel (handle_cmd_task);
1032     handle_cmd_task = GNUNET_SCHEDULER_NO_TASK;
1033   }
1034   if (NULL != id)
1035   {
1036     GNUNET_IDENTITY_disconnect (id);
1037     id = NULL;
1038   }
1039   GNUNET_SPEAKER_destroy (speaker);
1040   speaker = NULL;
1041   GNUNET_MICROPHONE_destroy (mic);
1042   mic = NULL;
1043   GNUNET_free (ego_name);
1044   ego_name = NULL;
1045   GNUNET_free_non_null (peer_name);
1046   phone_state = PS_ERROR;
1047 }
1048
1049 static void
1050 handle_command_string (char *message, size_t str_len)
1051 {
1052   size_t i;
1053   const char *ptr;
1054
1055   if (0 == str_len)
1056     return;
1057   if (message[str_len - 1] == '\n')
1058     message[str_len - 1] = '\0';
1059   if (message[str_len - 2] == '\r')
1060     message[str_len - 2] = '\0';
1061   if (0 == strlen (message))
1062     return;
1063   i = 0;
1064   while ((NULL != commands[i].command) &&
1065          (0 != strncasecmp (commands[i].command, message,
1066                             strlen (commands[i].command))))
1067     i++;
1068   ptr = &message[strlen (commands[i].command)];
1069   while (isspace ((int) *ptr))
1070     ptr++;
1071   if ('\0' == *ptr)
1072     ptr = NULL;
1073   commands[i].Action (ptr);
1074 }
1075
1076
1077 #ifdef WINDOWS
1078 int
1079 console_reader_chars (void *cls, void *client,
1080     const struct GNUNET_MessageHeader *message)
1081 {
1082   char *chars;
1083   size_t str_size;
1084   switch (ntohs (message->type))
1085   {
1086   case GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_CHARS:
1087     chars = (char *) &message[1];
1088     str_size = ntohs (message->size) - sizeof (struct GNUNET_MessageHeader);
1089     if (chars[str_size - 1] != '\0')
1090       return GNUNET_SYSERR;
1091     /* FIXME: is it ok that we pass part of a const struct to
1092      * this function that may mangle the contents?
1093      */
1094     handle_command_string (chars, str_size - 1);
1095     break;
1096   default:
1097     GNUNET_break (0);
1098     break;
1099   }
1100   return GNUNET_OK;
1101 }
1102 #endif
1103
1104 /**
1105  * Task to handle commands from the terminal.
1106  *
1107  * @param cls NULL
1108  * @param tc scheduler context
1109  */
1110 static void
1111 handle_command (void *cls,
1112                 const struct GNUNET_SCHEDULER_TaskContext *tc)
1113 {
1114   char message[MAX_MESSAGE_LENGTH + 1];
1115
1116   handle_cmd_task =
1117     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1118                                     stdin_fh,
1119                                     &handle_command, NULL);
1120   /* read message from command line and handle it */
1121   memset (message, 0, MAX_MESSAGE_LENGTH + 1);
1122   if (NULL == fgets (message, MAX_MESSAGE_LENGTH, stdin))
1123     return;
1124   handle_command_string (message, strlen (message));
1125 }
1126
1127
1128 /**
1129  * Function called by identity service with information about egos.
1130  *
1131  * @param cls NULL
1132  * @param ego ego handle
1133  * @param ctx unused
1134  * @param name name of the ego
1135  */
1136 static void
1137 identity_cb (void *cls,
1138              struct GNUNET_IDENTITY_Ego *ego,
1139              void **ctx,
1140              const char *name)
1141 {
1142   if (NULL == name)
1143     return;
1144   if (ego == caller_id)
1145   {
1146     if (verbose)
1147       FPRINTF (stdout,
1148                _("Name of our ego changed to `%s'\n"),
1149                name);
1150     GNUNET_free (ego_name);
1151     ego_name = GNUNET_strdup (name);
1152     return;
1153   }
1154   if (0 != strcmp (name,
1155                    ego_name))
1156     return;
1157   if (NULL == ego)
1158   {
1159     if (verbose)
1160       FPRINTF (stdout,
1161                _("Our ego `%s' was deleted!\n"),
1162                ego_name);
1163     caller_id = NULL;
1164     return;
1165   }
1166   caller_id = ego;
1167   GNUNET_CONFIGURATION_set_value_number (cfg,
1168                                          "CONVERSATION",
1169                                          "LINE",
1170                                          line);
1171   start_phone ();
1172 }
1173
1174
1175 /**
1176  * Main function that will be run by the scheduler.
1177  *
1178  * @param cls closure
1179  * @param args remaining command-line arguments
1180  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1181  * @param c configuration
1182  */
1183 static void
1184 run (void *cls,
1185      char *const *args,
1186      const char *cfgfile,
1187      const struct GNUNET_CONFIGURATION_Handle *c)
1188 {
1189   cfg = GNUNET_CONFIGURATION_dup (c);
1190   speaker = GNUNET_SPEAKER_create_from_hardware (cfg);
1191   mic = GNUNET_MICROPHONE_create_from_hardware (cfg);
1192   if (NULL == ego_name)
1193   {
1194     FPRINTF (stderr,
1195              "%s",
1196              _("You must specify the NAME of an ego to use\n"));
1197     return;
1198   }
1199   id = GNUNET_IDENTITY_connect (cfg,
1200                                 &identity_cb,
1201                                 NULL);
1202 #ifdef WINDOWS
1203   if (stdin_fh == NULL)
1204   {
1205     static char cpid[64];
1206     static char *args[] = {"gnunet-helper-w32-console.exe", "chars",
1207         XSTRINGIFY (MAX_MESSAGE_LENGTH), cpid, NULL};
1208     snprintf (cpid, 64, "%d", GetCurrentProcessId ());
1209     stdin_hlp = GNUNET_HELPER_start (
1210         GNUNET_NO,
1211         "gnunet-helper-w32-console",
1212         args,
1213         console_reader_chars,
1214         NULL,
1215         NULL);
1216     if (NULL == stdin_hlp)
1217     {
1218       FPRINTF (stderr,
1219                "%s",
1220                _("Failed to start gnunet-helper-w32-console\n"));
1221       return;
1222     }
1223   }
1224   else
1225 #endif
1226   handle_cmd_task =
1227     GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_UI,
1228                                         &handle_command, NULL);
1229   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_stop_task,
1230                                 NULL);
1231 }
1232
1233
1234 /**
1235  * The main function to conversation.
1236  *
1237  * @param argc number of arguments from the command line
1238  * @param argv command line arguments
1239  * @return 0 ok, 1 on error
1240  */
1241 int
1242 main (int argc, char *const *argv)
1243 {
1244   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1245     {'e', "ego", "NAME",
1246      gettext_noop ("sets the NAME of the ego to use for the phone (and name resolution)"),
1247      1, &GNUNET_GETOPT_set_string, &ego_name},
1248     {'p', "phone", "LINE",
1249       gettext_noop ("sets the LINE to use for the phone"),
1250      1, &GNUNET_GETOPT_set_uint, &line},
1251     GNUNET_GETOPT_OPTION_END
1252   };
1253   int ret;
1254 #ifndef WINDOWS
1255   int flags;
1256   flags = fcntl (0, F_GETFL, 0);
1257   flags |= O_NONBLOCK;
1258   fcntl (0, F_SETFL, flags);
1259   stdin_fh = GNUNET_DISK_get_handle_from_int_fd (0);
1260 #else
1261   if (FILE_TYPE_CHAR == GetFileType ((HANDLE) _get_osfhandle (0)))
1262   {
1263     stdin_fh = NULL;
1264   }
1265   else
1266     stdin_fh = GNUNET_DISK_get_handle_from_int_fd (0);
1267 #endif
1268
1269   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1270     return 2;
1271   ret = GNUNET_PROGRAM_run (argc, argv,
1272                             "gnunet-conversation",
1273                             gettext_noop ("Enables having a conversation with other GNUnet users."),
1274                             options, &run, NULL);
1275   GNUNET_free ((void *) argv);
1276   if (NULL != cfg)
1277   {
1278     GNUNET_CONFIGURATION_destroy (cfg);
1279     cfg = NULL;
1280   }
1281   return (GNUNET_OK == ret) ? 0 : 1;
1282 }
1283
1284 /* end of gnunet-conversation.c */