more code
[oweals/gnunet.git] / src / transport / gnunet-transport.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 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 /**
22  * @file src/transport/gnunet-transport.c
23  * @brief Tool to help configure, measure and control the transport subsystem.
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  *
27  * This utility can be used to test if a transport mechanism for
28  * GNUnet is properly configured.
29  */
30
31 #include "platform.h"
32 #include "gnunet_util_lib.h"
33 #include "gnunet_resolver_service.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_transport_service.h"
36 #include "gnunet_nat_lib.h"
37
38 /**
39  * How long do we wait for the NAT test to report success?
40  * Should match NAT_SERVER_TIMEOUT in 'nat_test.c'.
41  */
42 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
43 #define RESOLUTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
44
45 /**
46  * Which peer should we connect to?
47  */
48 static char *cpid;
49
50 /**
51  * Handle to transport service.
52  */
53 static struct GNUNET_TRANSPORT_Handle *handle;
54
55 /**
56  * Option -s.
57  */
58 static int benchmark_send;
59
60 /**
61  * Option -b.
62  */
63 static int benchmark_receive;
64
65 /**
66  * Option -l.
67  */
68 static int benchmark_receive;
69
70 /**
71  * Option -i.
72  */
73 static int iterate_connections;
74
75 /**
76  * Option -t.
77  */
78 static int test_configuration;
79
80 /**
81  * Option -m.
82  */
83 static int monitor_connections;
84
85 /**
86  * Option -n.
87  */
88 static int numeric;
89
90 /**
91  * Global return value (0 success).
92  */
93 static int ret;
94
95 /**
96  * Current number of connections in monitor mode
97  */
98 static int monitor_connections_counter;
99
100 /**
101  * Number of bytes of traffic we received so far.
102  */
103 static unsigned long long traffic_received;
104
105 /**
106  * Number of bytes of traffic we sent so far.
107  */
108 static unsigned long long traffic_sent;
109
110 /**
111  * Starting time of transmitting/receiving data.
112  */
113 static struct GNUNET_TIME_Absolute start_time;
114
115 /**
116  * Handle for current transmission request.
117  */
118 static struct GNUNET_TRANSPORT_TransmitHandle *th;
119
120 /**
121  * Identity of the peer we transmit to / connect to.
122  * (equivalent to 'cpid' string).
123  */
124 static struct GNUNET_PeerIdentity pid;
125
126 /**
127  * Task scheduled for cleanup / termination of the process.
128  */
129 static GNUNET_SCHEDULER_TaskIdentifier end;
130
131 static struct GNUNET_CONTAINER_MultiHashMap *peers;
132
133 /**
134  * Selected level of verbosity.
135  */
136 static int verbosity;
137
138 /**
139  * Resolver process handle.
140  */
141 struct GNUNET_OS_Process *resolver;
142
143 /**
144  * Number of tasks running that still need the resolver.
145  */
146 static unsigned int resolver_users;
147
148
149 /**
150  * Context for a plugin test.
151  */
152 struct TestContext
153 {
154
155   /**
156    * Handle to the active NAT test.
157    */
158   struct GNUNET_NAT_Test *tst;
159
160   /**
161    * Task identifier for the timeout.
162    */
163   GNUNET_SCHEDULER_TaskIdentifier tsk;
164
165   /**
166    * Name of plugin under test.
167    */
168   const char *name;
169
170 };
171
172
173 /**
174  * Display the result of the test.
175  *
176  * @param tc test context
177  * @param result GNUNET_YES on success
178  */
179 static void
180 display_test_result (struct TestContext *tc, int result)
181 {
182   if (GNUNET_YES != result)
183   {
184     FPRINTF (stderr, "Configuration for plugin `%s' did not work!\n", tc->name);
185   }
186   else
187   {
188     FPRINTF (stderr, "Configuration for plugin `%s' is working!\n", tc->name);
189   }
190   if (GNUNET_SCHEDULER_NO_TASK != tc->tsk)
191   {
192     GNUNET_SCHEDULER_cancel (tc->tsk);
193     tc->tsk = GNUNET_SCHEDULER_NO_TASK;
194   }
195   if (NULL != tc->tst)
196   {
197     GNUNET_NAT_test_stop (tc->tst);
198     tc->tst = NULL;
199   }
200   GNUNET_free (tc);
201   resolver_users--;
202   if ((0 == resolver_users) && (NULL != resolver))
203   {
204     GNUNET_break (0 == GNUNET_OS_process_kill (resolver, SIGTERM));
205     GNUNET_OS_process_destroy (resolver);
206     resolver = NULL;
207   }
208 }
209
210
211 /**
212  * Function called by NAT on success.
213  * Clean up and update GUI (with success).
214  *
215  * @param cls test context
216  * @param success currently always GNUNET_OK
217  */
218 static void
219 result_callback (void *cls, int success)
220 {
221   struct TestContext *tc = cls;
222
223   display_test_result (tc, success);
224 }
225
226
227 /**
228  * Function called if NAT failed to confirm success.
229  * Clean up and update GUI (with failure).
230  *
231  * @param cls test context
232  * @param tc scheduler callback
233  */
234 static void
235 fail_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
236 {
237   struct TestContext *tstc = cls;
238
239   tstc->tsk = GNUNET_SCHEDULER_NO_TASK;
240   display_test_result (tstc, GNUNET_NO);
241 }
242
243
244 /**
245  * Test our plugin's configuration (NAT traversal, etc.).
246  *
247  * @param cfg configuration to test
248  */
249 static void
250 do_test_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
251 {
252   char *plugins;
253   char *tok;
254   unsigned long long bnd_port;
255   unsigned long long adv_port;
256   struct TestContext *tc;
257
258   if (GNUNET_OK !=
259       GNUNET_CONFIGURATION_get_value_string (cfg, "transport", "plugins",
260                                              &plugins))
261   {
262     FPRINTF (stderr,
263              "%s",
264              _
265              ("No transport plugins configured, peer will never communicate\n"));
266     ret = 4;
267     return;
268   }
269   for (tok = strtok (plugins, " "); tok != NULL; tok = strtok (NULL, " "))
270   {
271     char section[12 + strlen (tok)];
272
273     GNUNET_snprintf (section, sizeof (section), "transport-%s", tok);
274     if (GNUNET_OK !=
275         GNUNET_CONFIGURATION_get_value_number (cfg, section, "PORT", &bnd_port))
276     {
277       FPRINTF (stderr,
278                _("No port configured for plugin `%s', cannot test it\n"), tok);
279       continue;
280     }
281     if (GNUNET_OK !=
282         GNUNET_CONFIGURATION_get_value_number (cfg, section, "ADVERTISED_PORT",
283                                                &adv_port))
284       adv_port = bnd_port;
285     if (NULL == resolver)
286       resolver =
287           GNUNET_OS_start_process (GNUNET_YES, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, "gnunet-service-resolver",
288                                    "gnunet-service-resolver", NULL);
289     resolver_users++;
290     GNUNET_RESOLVER_connect (cfg);
291     tc = GNUNET_malloc (sizeof (struct TestContext));
292     tc->name = GNUNET_strdup (tok);
293     tc->tst =
294         GNUNET_NAT_test_start (cfg,
295                                (0 ==
296                                 strcasecmp (tok,
297                                             "udp")) ? GNUNET_NO : GNUNET_YES,
298                                (uint16_t) bnd_port, (uint16_t) adv_port,
299                                &result_callback, tc);
300     if (NULL == tc->tst)
301     {
302       display_test_result (tc, GNUNET_SYSERR);
303       continue;
304     }
305     tc->tsk = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &fail_timeout, tc);
306   }
307   GNUNET_free (plugins);
308 }
309
310
311 /**
312  * Shutdown, print statistics.
313  */
314 static void
315 do_disconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
316 {
317   struct GNUNET_TIME_Relative duration;
318
319   if (NULL != th)
320   {
321     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
322     th = NULL;
323   }
324   GNUNET_TRANSPORT_disconnect (handle);
325   if (benchmark_receive)
326   {
327     duration = GNUNET_TIME_absolute_get_duration (start_time);
328     FPRINTF (stdout, _("Received %llu bytes/s (%llu bytes in %llu ms)\n"),
329              1000 * traffic_received / (1 + duration.rel_value),
330              traffic_received, (unsigned long long) duration.rel_value);
331   }
332   if (benchmark_send)
333   {
334     duration = GNUNET_TIME_absolute_get_duration (start_time);
335     FPRINTF (stdout, _("Transmitted %llu bytes/s (%llu bytes in %llu ms)\n"),
336              1000 * traffic_sent / (1 + duration.rel_value), traffic_sent,
337              (unsigned long long) duration.rel_value);
338   }
339 }
340
341
342 /**
343  * Function called to notify a client about the socket
344  * begin ready to queue more data.  "buf" will be
345  * NULL and "size" zero if the socket was closed for
346  * writing in the meantime.
347  *
348  * @param cls closure
349  * @param size number of bytes available in buf
350  * @param buf where the callee should write the message
351  * @return number of bytes written to buf
352  */
353 static size_t
354 transmit_data (void *cls, size_t size, void *buf)
355 {
356   struct GNUNET_MessageHeader *m = buf;
357
358   if ((NULL == buf) && (0 == size))
359   {
360     th = NULL;
361     return 0;
362   }
363
364   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
365   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
366   m->size = ntohs (size);
367   m->type = ntohs (GNUNET_MESSAGE_TYPE_DUMMY);
368   memset (&m[1], 52, size - sizeof (struct GNUNET_MessageHeader));
369   traffic_sent += size;
370   th = GNUNET_TRANSPORT_notify_transmit_ready (handle, &pid, 32 * 1024, 0,
371                                                GNUNET_TIME_UNIT_FOREVER_REL,
372                                                &transmit_data, NULL);
373   if (verbosity > 0)
374     FPRINTF (stdout, _("Transmitting %u bytes to %s\n"), (unsigned int) size,
375              GNUNET_i2s (&pid));
376   return size;
377 }
378
379
380 /**
381  * Function called to notify transport users that another
382  * peer connected to us.
383  *
384  * @param cls closure
385  * @param peer the peer that connected
386  * @param ats performance data
387  * @param ats_count number of entries in ats (excluding 0-termination)
388  */
389 static void
390 notify_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
391                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
392 {
393   if (verbosity > 0)
394     FPRINTF (stdout, _("Connected to %s\n"), GNUNET_i2s (peer));
395   if (0 != memcmp (&pid, peer, sizeof (struct GNUNET_PeerIdentity)))
396     return;
397   ret = 0;
398   if (benchmark_send)
399   {
400     start_time = GNUNET_TIME_absolute_get ();
401     if (NULL == th)
402       th = GNUNET_TRANSPORT_notify_transmit_ready (handle, peer, 32 * 1024, 0,
403                                                  GNUNET_TIME_UNIT_FOREVER_REL,
404                                                  &transmit_data, NULL);
405   }
406   else
407   {
408     /* all done, terminate instantly */
409     GNUNET_SCHEDULER_cancel (end);
410     end = GNUNET_SCHEDULER_add_now (&do_disconnect, NULL);
411   }
412 }
413
414
415 /**
416  * Function called to notify transport users that another
417  * peer disconnected from us.
418  *
419  * @param cls closure
420  * @param peer the peer that disconnected
421  */
422 static void
423 notify_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
424 {
425   if (verbosity > 0)
426     FPRINTF (stdout, _("Disconnected from %s\n"), GNUNET_i2s (peer));
427   if (NULL != th)
428   {
429     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
430     th = NULL;
431   }
432
433 }
434
435 /**
436  * Function called to notify transport users that another
437  * peer connected to us.
438  *
439  * @param cls closure
440  * @param peer the peer that connected
441  * @param ats performance data
442  * @param ats_count number of entries in ats (excluding 0-termination)
443  */
444 static void
445 monitor_notify_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
446                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
447 {
448   monitor_connections_counter ++;
449   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
450   char *now_str = GNUNET_STRINGS_absolute_time_to_string (now);
451   FPRINTF (stdout, _("%24s: %-17s %4s   (%u connections in total)\n"),
452            now_str,
453            _("Connected to"),
454            GNUNET_i2s (peer),
455            monitor_connections_counter);
456
457   GNUNET_free (now_str);
458 }
459
460
461 /**
462  * Function called to notify transport users that another
463  * peer disconnected from us.
464  *
465  * @param cls closure
466  * @param peer the peer that disconnected
467  */
468 static void
469 monitor_notify_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
470 {
471   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
472   char *now_str = GNUNET_STRINGS_absolute_time_to_string (now);
473
474   GNUNET_assert (monitor_connections_counter > 0);
475   monitor_connections_counter --;
476
477   FPRINTF (stdout, _("%24s: %-17s %4s   (%u connections in total)\n"),
478            now_str,
479            _("Disconnected from"),
480            GNUNET_i2s (peer),
481            monitor_connections_counter);
482   GNUNET_free (now_str);
483 }
484
485
486
487 /**
488  * Function called by the transport for each received message.
489  *
490  * @param cls closure
491  * @param peer (claimed) identity of the other peer
492  * @param message the message
493  * @param ats performance data
494  * @param ats_count number of entries in ats
495  */
496 static void
497 notify_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
498                 const struct GNUNET_MessageHeader *message,
499                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
500 {
501   if (!benchmark_receive)
502     return;
503   if (GNUNET_MESSAGE_TYPE_DUMMY != ntohs (message->type))
504     return;
505   if (verbosity > 0)
506     FPRINTF (stdout, _("Received %u bytes from %s\n"),
507              (unsigned int) ntohs (message->size), GNUNET_i2s (peer));
508   if (traffic_received == 0)
509     start_time = GNUNET_TIME_absolute_get ();
510   traffic_received += ntohs (message->size);
511 }
512
513 struct ResolutionContext
514 {
515   struct GNUNET_HELLO_Address *addrcp;
516
517   int printed;
518 };
519
520
521 static void
522 process_string (void *cls, const char *address)
523 {
524   struct ResolutionContext *rc = cls;
525   struct GNUNET_HELLO_Address *addrcp = rc->addrcp;
526
527   if (address != NULL)
528   {
529     FPRINTF (stdout, _("Peer `%s': %s %s\n"), GNUNET_i2s (&addrcp->peer), addrcp->transport_name, address);
530     rc->printed = GNUNET_YES;
531   }
532   else
533   {
534     /* done */
535     if (GNUNET_NO == rc->printed)
536       FPRINTF (stdout, _("Peer `%s': %s <unable to resolve address>\n"), GNUNET_i2s (&addrcp->peer), addrcp->transport_name);
537     GNUNET_free (rc->addrcp);
538     GNUNET_free (rc);
539   }
540 }
541
542 /**
543  * Function to call with a binary address
544  *
545  * @param cls closure
546  * @param peer identity of the peer
547  * @param address binary address (NULL on disconnect)
548  */
549 static void
550 process_address (void *cls, const struct GNUNET_PeerIdentity *peer,
551                  const struct GNUNET_HELLO_Address *address)
552 {
553   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
554   struct ResolutionContext *rc;
555
556   if (peer == NULL)
557   {
558     /* done */
559     return;
560   }
561
562   if (address == NULL)
563   {
564     FPRINTF (stdout, _("Peer `%s' disconnected\n"), GNUNET_i2s (peer));
565     return;
566   }
567
568   rc = GNUNET_malloc(sizeof (struct ResolutionContext));
569   rc->addrcp = GNUNET_HELLO_address_copy(address);
570   rc->printed = GNUNET_NO;
571
572   GNUNET_assert (NULL != rc);
573
574   /* Resolve address to string */
575   GNUNET_TRANSPORT_address_to_string (cfg, address, numeric,
576                                       RESOLUTION_TIMEOUT, &process_string,
577                                       rc);
578 }
579
580
581 /**
582  * Task run in monitor mode when the user presses CTRL-C to abort.
583  * Stops monitoring activity.
584  * 
585  * @param cls the 'struct GNUNET_TRANSPORT_PeerIterateContext *'
586  * @param tc scheduler context
587  */
588 static void
589 shutdown_task (void *cls,
590                const struct GNUNET_SCHEDULER_TaskContext *tc)
591 {
592   if (NULL != th)
593   {
594     GNUNET_TRANSPORT_notify_transmit_ready_cancel(th);
595     th = NULL;
596   }
597   if (NULL != handle)
598   {
599     GNUNET_TRANSPORT_disconnect(handle);
600     handle = NULL;
601   }
602
603   if (NULL != peers)
604   {
605     GNUNET_CONTAINER_multihashmap_destroy (peers);
606     peers = NULL;
607   }
608 }
609
610 static void
611 testservice_task (void *cls,
612                   const struct GNUNET_SCHEDULER_TaskContext *tc)
613 {
614   struct GNUNET_CONFIGURATION_Handle *cfg = cls;
615
616   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
617   {
618       FPRINTF (stderr, _("Service `%s' is not running\n"), "transport");
619       return;
620   }
621
622   if (benchmark_send && (NULL == cpid))
623   {
624     FPRINTF (stderr, _("Option `%s' makes no sense without option `%s'.\n"),
625              "-s", "-C");
626     return;
627   }
628   if (NULL != cpid)
629   {
630     ret = 1;
631     if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (cpid, &pid.hashPubKey))
632     {
633       FPRINTF (stderr, _("Failed to parse peer identity `%s'\n"), cpid);
634       return;
635     }
636     handle =
637         GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive,
638                                   &notify_connect, &notify_disconnect);
639     GNUNET_TRANSPORT_try_connect (handle, &pid);
640     end =
641         GNUNET_SCHEDULER_add_delayed (benchmark_send ?
642                                       GNUNET_TIME_UNIT_FOREVER_REL :
643                                       GNUNET_TIME_UNIT_SECONDS, &do_disconnect,
644                                       NULL);
645   }
646   else if (benchmark_receive)
647   {
648     handle =
649         GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive,
650                                   &notify_connect, &notify_disconnect);
651     GNUNET_TRANSPORT_try_connect (handle, &pid);
652     start_time = GNUNET_TIME_absolute_get ();
653     end =
654         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
655                                       &do_disconnect, NULL);
656   }
657   if (iterate_connections)
658   {
659     peers = GNUNET_CONTAINER_multihashmap_create (20);
660     GNUNET_TRANSPORT_peer_get_active_addresses (cfg, NULL, GNUNET_YES,
661                                                 TIMEOUT,
662                                                 &process_address, (void *) cfg);
663   }
664   if (monitor_connections)
665   {
666     monitor_connections_counter = 0;
667     handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL,
668                                        &monitor_notify_connect,
669                                        &monitor_notify_disconnect);
670     if (NULL == handle)
671     {
672       GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
673     }
674     else
675     {
676       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
677                                     &shutdown_task,
678                                     NULL);
679     }
680   }
681
682
683 }
684
685
686 /**
687  * Main function that will be run by the scheduler.
688  *
689  * @param cls closure
690  * @param args remaining command-line arguments
691  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
692  * @param cfg configuration
693  */
694 static void
695 run (void *cls, char *const *args, const char *cfgfile,
696      const struct GNUNET_CONFIGURATION_Handle *cfg)
697 {
698   if (test_configuration)
699   {
700     do_test_configuration (cfg);
701   }
702
703   GNUNET_CLIENT_service_test ("transport", cfg,
704       GNUNET_TIME_UNIT_SECONDS,
705       &testservice_task,
706       (void *) cfg);
707 }
708
709
710 int
711 main (int argc, char *const *argv)
712 {
713   int res;
714   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
715     {'b', "benchmark", NULL,
716      gettext_noop ("measure how fast we are receiving data (until CTRL-C)"),
717      0, &GNUNET_GETOPT_set_one, &benchmark_receive},
718     {'C', "connect", "PEER",
719      gettext_noop ("try to connect to the given peer"),
720      1, &GNUNET_GETOPT_set_string, &cpid},
721     {'i', "information", NULL,
722      gettext_noop ("provide information about all current connections (once)"),
723      0, &GNUNET_GETOPT_set_one, &iterate_connections},
724     {'m', "monitor", NULL,
725      gettext_noop ("provide information about all current connections (continuously)"),
726      0, &GNUNET_GETOPT_set_one, &monitor_connections},
727     {'n', "numeric", NULL,
728      gettext_noop ("do not resolve hostnames"),
729      0, &GNUNET_GETOPT_set_one, &numeric},
730     {'s', "send", NULL,
731      gettext_noop
732      ("send data for benchmarking to the other peer (until CTRL-C)"),
733      0, &GNUNET_GETOPT_set_one, &benchmark_send},
734     {'t', "test", NULL,
735      gettext_noop ("test transport configuration (involves external server)"),
736      0, &GNUNET_GETOPT_set_one, &test_configuration},
737     GNUNET_GETOPT_OPTION_VERBOSE (&verbosity),
738     GNUNET_GETOPT_OPTION_END
739   };
740
741   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
742     return 2;
743
744   res = GNUNET_PROGRAM_run (argc, argv, "gnunet-transport",
745                               gettext_noop
746                               ("Direct access to transport service."), options,
747                               &run, NULL);
748   GNUNET_free ((void *) argv);
749
750   if (GNUNET_OK == res)
751     return ret;
752   else
753     return 1;
754
755
756 }
757
758
759 /* end of gnunet-transport.c */