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