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