-makefile for new test_stream_local (commented)
[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  * Number of bytes of traffic we received so far.
97  */
98 static unsigned long long traffic_received;
99
100 /**
101  * Number of bytes of traffic we sent so far.
102  */
103 static unsigned long long traffic_sent;
104
105 /**
106  * Starting time of transmitting/receiving data.
107  */
108 static struct GNUNET_TIME_Absolute start_time;
109
110 /**
111  * Handle for current transmission request.
112  */
113 static struct GNUNET_TRANSPORT_TransmitHandle *th;
114
115 /**
116  * Identity of the peer we transmit to / connect to.
117  * (equivalent to 'cpid' string).
118  */
119 static struct GNUNET_PeerIdentity pid;
120
121 /**
122  * Task scheduled for cleanup / termination of the process.
123  */
124 static GNUNET_SCHEDULER_TaskIdentifier end;
125
126 static struct GNUNET_CONTAINER_MultiHashMap *peers;
127
128 /**
129  * Selected level of verbosity.
130  */
131 static int verbosity;
132
133 /**
134  * Resolver process handle.
135  */
136 struct GNUNET_OS_Process *resolver;
137
138 /**
139  * Number of tasks running that still need the resolver.
140  */
141 static unsigned int resolver_users;
142
143
144 /**
145  * Context for a plugin test.
146  */
147 struct TestContext
148 {
149
150   /**
151    * Handle to the active NAT test.
152    */
153   struct GNUNET_NAT_Test *tst;
154
155   /**
156    * Task identifier for the timeout.
157    */
158   GNUNET_SCHEDULER_TaskIdentifier tsk;
159
160   /**
161    * Name of plugin under test.
162    */
163   const char *name;
164
165 };
166
167
168 /**
169  * Display the result of the test.
170  *
171  * @param tc test context
172  * @param result GNUNET_YES on success
173  */
174 static void
175 display_test_result (struct TestContext *tc, int result)
176 {
177   if (GNUNET_YES != result)
178   {
179     FPRINTF (stderr, "Configuration for plugin `%s' did not work!\n", tc->name);
180   }
181   else
182   {
183     FPRINTF (stderr, "Configuration for plugin `%s' is working!\n", tc->name);
184   }
185   if (GNUNET_SCHEDULER_NO_TASK != tc->tsk)
186   {
187     GNUNET_SCHEDULER_cancel (tc->tsk);
188     tc->tsk = GNUNET_SCHEDULER_NO_TASK;
189   }
190   if (NULL != tc->tst)
191   {
192     GNUNET_NAT_test_stop (tc->tst);
193     tc->tst = NULL;
194   }
195   GNUNET_free (tc);
196   resolver_users--;
197   if ((0 == resolver_users) && (NULL != resolver))
198   {
199     GNUNET_break (0 == GNUNET_OS_process_kill (resolver, SIGTERM));
200     GNUNET_OS_process_close (resolver);
201     resolver = NULL;
202   }
203 }
204
205
206 /**
207  * Function called by NAT on success.
208  * Clean up and update GUI (with success).
209  *
210  * @param cls test context
211  * @param success currently always GNUNET_OK
212  */
213 static void
214 result_callback (void *cls, int success)
215 {
216   struct TestContext *tc = cls;
217
218   display_test_result (tc, success);
219 }
220
221
222 /**
223  * Function called if NAT failed to confirm success.
224  * Clean up and update GUI (with failure).
225  *
226  * @param cls test context
227  * @param tc scheduler callback
228  */
229 static void
230 fail_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
231 {
232   struct TestContext *tstc = cls;
233
234   tstc->tsk = GNUNET_SCHEDULER_NO_TASK;
235   display_test_result (tstc, GNUNET_NO);
236 }
237
238
239 /**
240  * Test our plugin's configuration (NAT traversal, etc.).
241  *
242  * @param cfg configuration to test
243  */
244 static void
245 do_test_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
246 {
247   char *plugins;
248   char *tok;
249   unsigned long long bnd_port;
250   unsigned long long adv_port;
251   struct TestContext *tc;
252
253   if (GNUNET_OK !=
254       GNUNET_CONFIGURATION_get_value_string (cfg, "transport", "plugins",
255                                              &plugins))
256   {
257     FPRINTF (stderr,
258              "%s",
259              _
260              ("No transport plugins configured, peer will never communicate\n"));
261     ret = 4;
262     return;
263   }
264   for (tok = strtok (plugins, " "); tok != NULL; tok = strtok (NULL, " "))
265   {
266     char section[12 + strlen (tok)];
267
268     GNUNET_snprintf (section, sizeof (section), "transport-%s", tok);
269     if (GNUNET_OK !=
270         GNUNET_CONFIGURATION_get_value_number (cfg, section, "PORT", &bnd_port))
271     {
272       FPRINTF (stderr,
273                _("No port configured for plugin `%s', cannot test it\n"), tok);
274       continue;
275     }
276     if (GNUNET_OK !=
277         GNUNET_CONFIGURATION_get_value_number (cfg, section, "ADVERTISED_PORT",
278                                                &adv_port))
279       adv_port = bnd_port;
280     if (NULL == resolver)
281       resolver =
282           GNUNET_OS_start_process (GNUNET_YES, NULL, NULL, "gnunet-service-resolver",
283                                    "gnunet-service-resolver", NULL);
284     resolver_users++;
285     GNUNET_RESOLVER_connect (cfg);
286     tc = GNUNET_malloc (sizeof (struct TestContext));
287     tc->name = GNUNET_strdup (tok);
288     tc->tst =
289         GNUNET_NAT_test_start (cfg,
290                                (0 ==
291                                 strcasecmp (tok,
292                                             "udp")) ? GNUNET_NO : GNUNET_YES,
293                                (uint16_t) bnd_port, (uint16_t) adv_port,
294                                &result_callback, tc);
295     if (NULL == tc->tst)
296     {
297       display_test_result (tc, GNUNET_SYSERR);
298       continue;
299     }
300     tc->tsk = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &fail_timeout, tc);
301   }
302   GNUNET_free (plugins);
303 }
304
305
306 /**
307  * Shutdown, print statistics.
308  */
309 static void
310 do_disconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
311 {
312   struct GNUNET_TIME_Relative duration;
313
314   if (NULL != th)
315   {
316     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
317     th = NULL;
318   }
319   GNUNET_TRANSPORT_disconnect (handle);
320   if (benchmark_receive)
321   {
322     duration = GNUNET_TIME_absolute_get_duration (start_time);
323     FPRINTF (stdout, _("Received %llu bytes/s (%llu bytes in %llu ms)\n"),
324              1000 * traffic_received / (1 + duration.rel_value),
325              traffic_received, (unsigned long long) duration.rel_value);
326   }
327   if (benchmark_send)
328   {
329     duration = GNUNET_TIME_absolute_get_duration (start_time);
330     FPRINTF (stdout, _("Transmitted %llu bytes/s (%llu bytes in %llu ms)\n"),
331              1000 * traffic_sent / (1 + duration.rel_value), traffic_sent,
332              (unsigned long long) duration.rel_value);
333   }
334 }
335
336
337 /**
338  * Function called to notify a client about the socket
339  * begin ready to queue more data.  "buf" will be
340  * NULL and "size" zero if the socket was closed for
341  * writing in the meantime.
342  *
343  * @param cls closure
344  * @param size number of bytes available in buf
345  * @param buf where the callee should write the message
346  * @return number of bytes written to buf
347  */
348 static size_t
349 transmit_data (void *cls, size_t size, void *buf)
350 {
351   struct GNUNET_MessageHeader *m = buf;
352
353   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
354   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
355   m->size = ntohs (size);
356   m->type = ntohs (GNUNET_MESSAGE_TYPE_DUMMY);
357   memset (&m[1], 52, size - sizeof (struct GNUNET_MessageHeader));
358   traffic_sent += size;
359   th = GNUNET_TRANSPORT_notify_transmit_ready (handle, &pid, 32 * 1024, 0,
360                                                GNUNET_TIME_UNIT_FOREVER_REL,
361                                                &transmit_data, NULL);
362   if (verbosity > 0)
363     FPRINTF (stdout, _("Transmitting %u bytes to %s\n"), (unsigned int) size,
364              GNUNET_i2s (&pid));
365   return size;
366 }
367
368
369 /**
370  * Function called to notify transport users that another
371  * peer connected to us.
372  *
373  * @param cls closure
374  * @param peer the peer that connected
375  * @param ats performance data
376  * @param ats_count number of entries in ats (excluding 0-termination)
377  */
378 static void
379 notify_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
380                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
381 {
382   if (verbosity > 0)
383     FPRINTF (stdout, _("Connected to %s\n"), GNUNET_i2s (peer));
384   if (0 != memcmp (&pid, peer, sizeof (struct GNUNET_PeerIdentity)))
385     return;
386   ret = 0;
387   if (benchmark_send)
388   {
389     start_time = GNUNET_TIME_absolute_get ();
390     th = GNUNET_TRANSPORT_notify_transmit_ready (handle, peer, 32 * 1024, 0,
391                                                  GNUNET_TIME_UNIT_FOREVER_REL,
392                                                  &transmit_data, NULL);
393   }
394   else
395   {
396     /* all done, terminate instantly */
397     GNUNET_SCHEDULER_cancel (end);
398     end = GNUNET_SCHEDULER_add_now (&do_disconnect, NULL);
399   }
400 }
401
402
403 /**
404  * Function called to notify transport users that another
405  * peer disconnected from us.
406  *
407  * @param cls closure
408  * @param peer the peer that disconnected
409  */
410 static void
411 notify_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
412 {
413   if (verbosity > 0)
414     FPRINTF (stdout, _("Disconnected from %s\n"), GNUNET_i2s (peer));
415   if ((0 == memcmp (&pid, peer, sizeof (struct GNUNET_PeerIdentity))) &&
416       (NULL != th))
417   {
418     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
419     th = NULL;
420     GNUNET_SCHEDULER_cancel (end);
421     end = GNUNET_SCHEDULER_add_now (&do_disconnect, NULL);
422   }
423 }
424
425
426 /**
427  * Function called by the transport for each received message.
428  *
429  * @param cls closure
430  * @param peer (claimed) identity of the other peer
431  * @param message the message
432  * @param ats performance data
433  * @param ats_count number of entries in ats
434  */
435 static void
436 notify_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
437                 const struct GNUNET_MessageHeader *message,
438                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
439 {
440   if (!benchmark_receive)
441     return;
442   if (verbosity > 0)
443     FPRINTF (stdout, _("Received %u bytes from %s\n"),
444              (unsigned int) ntohs (message->size), GNUNET_i2s (peer));
445   if (traffic_received == 0)
446     start_time = GNUNET_TIME_absolute_get ();
447   traffic_received += ntohs (message->size);
448 }
449
450 struct ResolutionContext
451 {
452   struct GNUNET_HELLO_Address *addrcp;
453
454   int printed;
455 };
456
457 void
458 process_string (void *cls, const char *address)
459 {
460   struct ResolutionContext *rc = cls;
461   struct GNUNET_HELLO_Address *addrcp = rc->addrcp;
462
463   if (address != NULL)
464   {
465     FPRINTF (stdout, _("Peer `%s': %s %s\n"), GNUNET_i2s (&addrcp->peer), addrcp->transport_name, address);
466     rc->printed = GNUNET_YES;
467   }
468   else
469   {
470     /* done */
471     if (GNUNET_NO == rc->printed)
472       FPRINTF (stdout, _("Peer `%s': %s <unable to resolve address>\n"), GNUNET_i2s (&addrcp->peer), addrcp->transport_name);
473     GNUNET_free (rc->addrcp);
474     GNUNET_free (rc);
475   }
476 }
477
478 /**
479  * Function to call with a binary address
480  *
481  * @param cls closure
482  * @param peer identity of the peer
483  * @param address binary address (NULL on disconnect)
484  */
485 static void
486 process_address (void *cls, const struct GNUNET_PeerIdentity *peer,
487                  const struct GNUNET_HELLO_Address *address)
488 {
489   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
490   struct ResolutionContext *rc;
491
492   if (peer == NULL)
493   {
494     /* done */
495     return;
496   }
497
498   if (address == NULL)
499   {
500     FPRINTF (stdout, _("Peer `%s' disconnected\n"), GNUNET_i2s (peer));
501     return;
502   }
503
504   rc = GNUNET_malloc(sizeof (struct ResolutionContext));
505   rc->addrcp = GNUNET_HELLO_address_copy(address);
506   rc->printed = GNUNET_NO;
507
508   GNUNET_assert (NULL != rc);
509
510   /* Resolve address to string */
511   GNUNET_TRANSPORT_address_to_string (cfg, address, numeric,
512                                       RESOLUTION_TIMEOUT, &process_string,
513                                       rc);
514 }
515
516
517 /**
518  * Task run in monitor mode when the user presses CTRL-C to abort.
519  * Stops monitoring activity.
520  * 
521  * @param cls the 'struct GNUNET_TRANSPORT_PeerIterateContext *'
522  * @param tc scheduler context
523  */
524 static void
525 shutdown_task (void *cls,
526                const struct GNUNET_SCHEDULER_TaskContext *tc)
527 {
528   struct GNUNET_TRANSPORT_PeerIterateContext *pic = cls;
529
530   GNUNET_TRANSPORT_peer_get_active_addresses_cancel (pic);
531
532   if (NULL != peers)
533   {
534     GNUNET_CONTAINER_multihashmap_destroy (peers);
535     peers = NULL;
536   }
537 }
538
539
540
541 /**
542  * Main function that will be run by the scheduler.
543  *
544  * @param cls closure
545  * @param args remaining command-line arguments
546  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
547  * @param cfg configuration
548  */
549 static void
550 run (void *cls, char *const *args, const char *cfgfile,
551      const struct GNUNET_CONFIGURATION_Handle *cfg)
552 {
553   if (test_configuration)
554   {
555     do_test_configuration (cfg);
556   }
557   if (benchmark_send && (NULL == cpid))
558   {
559     FPRINTF (stderr, _("Option `%s' makes no sense without option `%s'.\n"),
560              "-s", "-C");
561     return;
562   }
563   if (NULL != cpid)
564   {
565     ret = 1;
566     if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (cpid, &pid.hashPubKey))
567     {
568       FPRINTF (stderr, _("Failed to parse peer identity `%s'\n"), cpid);
569       return;
570     }
571     handle =
572         GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive,
573                                   &notify_connect, &notify_disconnect);
574     GNUNET_TRANSPORT_try_connect (handle, &pid);
575     end =
576         GNUNET_SCHEDULER_add_delayed (benchmark_send ?
577                                       GNUNET_TIME_UNIT_FOREVER_REL :
578                                       GNUNET_TIME_UNIT_SECONDS, &do_disconnect,
579                                       NULL);
580   }
581   else if (benchmark_receive)
582   {
583     handle =
584         GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive,
585                                   &notify_connect, &notify_disconnect);
586     GNUNET_TRANSPORT_try_connect (handle, &pid);
587     end =
588         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
589                                       &do_disconnect, NULL);
590   }
591   if (iterate_connections)
592   {
593     peers = GNUNET_CONTAINER_multihashmap_create (20);
594     GNUNET_TRANSPORT_peer_get_active_addresses (cfg, NULL, GNUNET_YES,
595                                                 TIMEOUT,
596                                                 &process_address, (void *) cfg);
597   }
598   if (monitor_connections)
599   {
600     struct GNUNET_TRANSPORT_PeerIterateContext *pic;
601
602     pic = GNUNET_TRANSPORT_peer_get_active_addresses (cfg, NULL, GNUNET_NO,
603                                                       GNUNET_TIME_UNIT_FOREVER_REL,
604                                                       &process_address, (void *) cfg);
605     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
606                                   &shutdown_task,
607                                   pic);
608   }
609 }
610
611
612 int
613 main (int argc, char *const *argv)
614 {
615   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
616     {'b', "benchmark", NULL,
617      gettext_noop ("measure how fast we are receiving data (until CTRL-C)"),
618      0, &GNUNET_GETOPT_set_one, &benchmark_receive},
619     {'C', "connect", "PEER",
620      gettext_noop ("try to connect to the given peer"),
621      1, &GNUNET_GETOPT_set_string, &cpid},
622     {'i', "information", NULL,
623      gettext_noop ("provide information about all current connections (once)"),
624      0, &GNUNET_GETOPT_set_one, &iterate_connections},
625     {'m', "monitor", NULL,
626      gettext_noop ("provide information about all current connections (continuously)"),
627      0, &GNUNET_GETOPT_set_one, &monitor_connections},
628     {'n', "numeric", NULL,
629      gettext_noop ("do not resolve hostnames"),
630      0, &GNUNET_GETOPT_set_one, &numeric},
631     {'s', "send", NULL,
632      gettext_noop
633      ("send data for benchmarking to the other peer (until CTRL-C)"),
634      0, &GNUNET_GETOPT_set_one, &benchmark_send},
635     {'t', "test", NULL,
636      gettext_noop ("test transport configuration (involves external server)"),
637      0, &GNUNET_GETOPT_set_one, &test_configuration},
638     GNUNET_GETOPT_OPTION_VERBOSE (&verbosity),
639     GNUNET_GETOPT_OPTION_END
640   };
641   return (GNUNET_OK ==
642           GNUNET_PROGRAM_run (argc, argv, "gnunet-transport",
643                               gettext_noop
644                               ("Direct access to transport service."), options,
645                               &run, NULL)) ? ret : 1;
646 }
647
648
649 /* end of gnunet-transport.c */