first steps to transport_api cleanup
[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, "Configuration for plugin `%s' did not work!\n", tc->name);
166   }
167   else
168   {
169     fprintf (stderr, "Configuration for plugin `%s' is working!\n", tc->name);
170   }
171   if (GNUNET_SCHEDULER_NO_TASK != tc->tsk)
172   {
173     GNUNET_SCHEDULER_cancel (tc->tsk);
174     tc->tsk = GNUNET_SCHEDULER_NO_TASK;
175   }
176   if (NULL != tc->tst)
177   {
178     GNUNET_NAT_test_stop (tc->tst);
179     tc->tst = NULL;
180   }
181   GNUNET_free (tc);
182   resolver_users--;
183   if ((0 == resolver_users) && (NULL != resolver))
184   {
185     GNUNET_break (0 == GNUNET_OS_process_kill (resolver, SIGTERM));
186     GNUNET_OS_process_close (resolver);
187     resolver = NULL;
188   }
189 }
190
191
192 /**
193  * Function called by NAT on success.
194  * Clean up and update GUI (with success).
195  *
196  * @param cls test context
197  * @param success currently always GNUNET_OK
198  */
199 static void
200 result_callback (void *cls, int success)
201 {
202   struct TestContext *tc = cls;
203
204   display_test_result (tc, success);
205 }
206
207
208 /**
209  * Function called if NAT failed to confirm success.
210  * Clean up and update GUI (with failure).
211  *
212  * @param cls test context
213  * @param tc scheduler callback
214  */
215 static void
216 fail_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
217 {
218   struct TestContext *tstc = cls;
219
220   tstc->tsk = GNUNET_SCHEDULER_NO_TASK;
221   display_test_result (tstc, GNUNET_NO);
222 }
223
224
225 /**
226  * Test our plugin's configuration (NAT traversal, etc.).
227  *
228  * @param cfg configuration to test
229  */
230 static void
231 do_test_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
232 {
233   char *plugins;
234   char *tok;
235   unsigned long long bnd_port;
236   unsigned long long adv_port;
237   struct TestContext *tc;
238
239   if (GNUNET_OK !=
240       GNUNET_CONFIGURATION_get_value_string (cfg, "transport", "plugins",
241                                              &plugins))
242   {
243     fprintf (stderr,
244              _
245              ("No transport plugins configured, peer will never communicate\n"));
246     ret = 4;
247     return;
248   }
249   for (tok = strtok (plugins, " "); tok != NULL; tok = strtok (NULL, " "))
250   {
251     char section[12 + strlen (tok)];
252
253     GNUNET_snprintf (section, sizeof (section), "transport-%s", tok);
254     if (GNUNET_OK !=
255         GNUNET_CONFIGURATION_get_value_number (cfg, section, "PORT", &bnd_port))
256     {
257       fprintf (stderr,
258                _("No port configured for plugin `%s', cannot test it\n"), tok);
259       continue;
260     }
261     if (GNUNET_OK !=
262         GNUNET_CONFIGURATION_get_value_number (cfg, section, "ADVERTISED_PORT",
263                                                &adv_port))
264       adv_port = bnd_port;
265     if (NULL == resolver)
266       resolver =
267           GNUNET_OS_start_process (NULL, NULL, "gnunet-service-resolver",
268                                    "gnunet-service-resolver", NULL);
269     resolver_users++;
270     GNUNET_RESOLVER_connect (cfg);
271     tc = GNUNET_malloc (sizeof (struct TestContext));
272     tc->name = GNUNET_strdup (tok);
273     tc->tst =
274         GNUNET_NAT_test_start (cfg,
275                                (0 ==
276                                 strcasecmp (tok,
277                                             "udp")) ? GNUNET_NO : GNUNET_YES,
278                                (uint16_t) bnd_port, (uint16_t) adv_port,
279                                &result_callback, tc);
280     if (NULL == tc->tst)
281     {
282       display_test_result (tc, GNUNET_SYSERR);
283       continue;
284     }
285     tc->tsk = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &fail_timeout, tc);
286   }
287   GNUNET_free (plugins);
288 }
289
290
291 /**
292  * Shutdown, print statistics.
293  */
294 static void
295 do_disconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
296 {
297   struct GNUNET_TIME_Relative duration;
298
299   if (NULL != th)
300   {
301     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
302     th = NULL;
303   }
304   GNUNET_TRANSPORT_disconnect (handle);
305   if (benchmark_receive)
306   {
307     duration = GNUNET_TIME_absolute_get_duration (start_time);
308     fprintf (stdout, _("Received %llu bytes/s (%llu bytes in %llu ms)\n"),
309              1000 * traffic_received / (1 + duration.rel_value),
310              traffic_received, (unsigned long long) duration.rel_value);
311   }
312   if (benchmark_send)
313   {
314     duration = GNUNET_TIME_absolute_get_duration (start_time);
315     fprintf (stdout, _("Transmitted %llu bytes/s (%llu bytes in %llu ms)\n"),
316              1000 * traffic_sent / (1 + duration.rel_value), traffic_sent,
317              (unsigned long long) duration.rel_value);
318   }
319 }
320
321
322 /**
323  * Function called to notify a client about the socket
324  * begin ready to queue more data.  "buf" will be
325  * NULL and "size" zero if the socket was closed for
326  * writing in the meantime.
327  *
328  * @param cls closure
329  * @param size number of bytes available in buf
330  * @param buf where the callee should write the message
331  * @return number of bytes written to buf
332  */
333 static size_t
334 transmit_data (void *cls, size_t size, void *buf)
335 {
336   struct GNUNET_MessageHeader *m = buf;
337
338   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
339   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
340   m->size = ntohs (size);
341   m->type = ntohs (GNUNET_MESSAGE_TYPE_DUMMY);
342   memset (&m[1], 52, size - sizeof (struct GNUNET_MessageHeader));
343   traffic_sent += size;
344   th = GNUNET_TRANSPORT_notify_transmit_ready (handle, &pid, 32 * 1024, 0,
345                                                GNUNET_TIME_UNIT_FOREVER_REL,
346                                                &transmit_data, NULL);
347   if (verbosity > 0)
348     fprintf (stdout, _("Transmitting %u bytes to %s\n"), (unsigned int) size,
349              GNUNET_i2s (&pid));
350   return size;
351 }
352
353
354 /**
355  * Function called to notify transport users that another
356  * peer connected to us.
357  *
358  * @param cls closure
359  * @param peer the peer that connected
360  * @param ats performance data
361  * @param ats_count number of entries in ats (excluding 0-termination)
362  */
363 static void
364 notify_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
365                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
366 {
367   if (verbosity > 0)
368     fprintf (stdout, _("Connected to %s\n"), GNUNET_i2s (peer));
369   if (0 != memcmp (&pid, peer, sizeof (struct GNUNET_PeerIdentity)))
370     return;
371   ret = 0;
372   if (benchmark_send)
373   {
374     start_time = GNUNET_TIME_absolute_get ();
375     th = GNUNET_TRANSPORT_notify_transmit_ready (handle, peer, 32 * 1024, 0,
376                                                  GNUNET_TIME_UNIT_FOREVER_REL,
377                                                  &transmit_data, NULL);
378   }
379   else
380   {
381     /* all done, terminate instantly */
382     GNUNET_SCHEDULER_cancel (end);
383     end = GNUNET_SCHEDULER_add_now (&do_disconnect, NULL);
384   }
385 }
386
387
388 /**
389  * Function called to notify transport users that another
390  * peer disconnected from us.
391  *
392  * @param cls closure
393  * @param peer the peer that disconnected
394  */
395 static void
396 notify_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
397 {
398   if (verbosity > 0)
399     fprintf (stdout, _("Disconnected from %s\n"), GNUNET_i2s (peer));
400   if ((0 == memcmp (&pid, peer, sizeof (struct GNUNET_PeerIdentity))) &&
401       (NULL != th))
402   {
403     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
404     th = NULL;
405     GNUNET_SCHEDULER_cancel (end);
406     end = GNUNET_SCHEDULER_add_now (&do_disconnect, NULL);
407   }
408 }
409
410
411 /**
412  * Function called by the transport for each received message.
413  *
414  * @param cls closure
415  * @param peer (claimed) identity of the other peer
416  * @param message the message
417  * @param ats performance data
418  * @param ats_count number of entries in ats
419  */
420 static void
421 notify_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
422                 const struct GNUNET_MessageHeader *message,
423                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
424 {
425   if (!benchmark_receive)
426     return;
427   if (verbosity > 0)
428     fprintf (stdout, _("Received %u bytes from %s\n"),
429              (unsigned int) ntohs (message->size), GNUNET_i2s (peer));
430   if (traffic_received == 0)
431     start_time = GNUNET_TIME_absolute_get ();
432   traffic_received += ntohs (message->size);
433 }
434
435
436 /**
437  * Function to call with a human-readable format of an address
438  *
439  * @param cls closure
440  * @param peer identity of the peer
441  * @param transport name of the plugin
442  * @param addr binary address
443  * @param addrlen number of bytes in addr
444  */
445 static void
446 process_address (void *cls, const struct GNUNET_HELLO_Address *address)
447 {
448   if ((address->transport_name != NULL) ||
449       ((address->address != NULL) && (address->address_length > 0)))
450   {
451     /* Call GNUNET_TRANSPORT_address_to_string to convert to human readable */
452     //GNUNET_TRANSPORT_address_to_string(cfg, address, GNUNET_NO)
453
454 #if 0
455     fprintf (stdout, _("Peer `%s' plugin: `%s' address `%s'\n"),
456              (peer != NULL) ? GNUNET_i2s (peer) : "<unknown>",
457              (transport != NULL) ? transport : "<unknown>", ((addr != NULL) &&
458                                                              (addrlen > 0) &&
459                                                              (transport !=
460                                                               NULL)) ?
461              "how do i resolve the name without transport service?" :
462              "<unknown>");
463 #endif
464   }
465 }
466
467
468 /**
469  * Main function that will be run by the scheduler.
470  *
471  * @param cls closure
472  * @param args remaining command-line arguments
473  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
474  * @param cfg configuration
475  */
476 static void
477 run (void *cls, char *const *args, const char *cfgfile,
478      const struct GNUNET_CONFIGURATION_Handle *cfg)
479 {
480   if (test_configuration)
481   {
482     do_test_configuration (cfg);
483   }
484   if (benchmark_send && (NULL == cpid))
485   {
486     fprintf (stderr, _("Option `%s' makes no sense without option `%s'.\n"),
487              "-s", "-C");
488     return;
489   }
490   if (NULL != cpid)
491   {
492     ret = 1;
493     if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (cpid, &pid.hashPubKey))
494     {
495       fprintf (stderr, _("Failed to parse peer identity `%s'\n"), cpid);
496       return;
497     }
498     handle =
499         GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive,
500                                   &notify_connect, &notify_disconnect);
501     GNUNET_TRANSPORT_try_connect (handle, &pid);
502     end =
503         GNUNET_SCHEDULER_add_delayed (benchmark_send ?
504                                       GNUNET_TIME_UNIT_FOREVER_REL :
505                                       GNUNET_TIME_UNIT_SECONDS, &do_disconnect,
506                                       NULL);
507   }
508   else if (benchmark_receive)
509   {
510     handle =
511         GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive,
512                                   &notify_connect, &notify_disconnect);
513     GNUNET_TRANSPORT_try_connect (handle, &pid);
514     end =
515         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
516                                       &do_disconnect, NULL);
517   }
518   if (iterate_connections)
519   {
520     GNUNET_TRANSPORT_address_iterate (cfg, GNUNET_TIME_UNIT_MINUTES,
521                                       &process_address, NULL);
522   }
523 }
524
525
526 int
527 main (int argc, char *const *argv)
528 {
529   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
530     {'b', "benchmark", NULL,
531      gettext_noop ("measure how fast we are receiving data (until CTRL-C)"),
532      0, &GNUNET_GETOPT_set_one, &benchmark_receive},
533     {'C', "connect", "PEER",
534      gettext_noop ("try to connect to the given peer"),
535      1, &GNUNET_GETOPT_set_string, &cpid},
536     {'i', "information", NULL,
537      gettext_noop ("provide information about all current connections (once)"),
538      0, &GNUNET_GETOPT_set_one, &iterate_connections},
539     {'s', "send", NULL,
540      gettext_noop
541      ("send data for benchmarking to the other peer (until CTRL-C)"),
542      0, &GNUNET_GETOPT_set_one, &benchmark_send},
543     {'t', "test", NULL,
544      gettext_noop ("test transport configuration (involves external server)"),
545      0, &GNUNET_GETOPT_set_one, &test_configuration},
546     GNUNET_GETOPT_OPTION_VERBOSE (&verbosity),
547     GNUNET_GETOPT_OPTION_END
548   };
549   return (GNUNET_OK ==
550           GNUNET_PROGRAM_run (argc, argv, "gnunet-transport",
551                               gettext_noop
552                               ("Direct access to transport service."), options,
553                               &run, NULL)) ? ret : 1;
554 }
555
556
557 /* end of gnunet-transport.c */