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