changing time measurement from milliseconds to microseconds
[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, 60)
43 #define RESOLUTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
44 #define OP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
45
46 /**
47  * Benchmarking block size in KB
48  */
49 #define BLOCKSIZE 4
50
51
52 /**
53  * Which peer should we connect to?
54  */
55 static char *cpid;
56
57 /**
58  * Handle to transport service.
59  */
60 static struct GNUNET_TRANSPORT_Handle *handle;
61
62 /**
63  * Configuration handle
64  */
65 static struct GNUNET_CONFIGURATION_Handle *cfg;
66
67 /**
68  * Try_connect handle
69  */
70 struct GNUNET_TRANSPORT_TryConnectHandle * tc_handle;
71
72 /**
73  * Option -s.
74  */
75 static int benchmark_send;
76
77 /**
78  * Option -b.
79  */
80 static int benchmark_receive;
81
82 /**
83  * Option -l.
84  */
85 static int benchmark_receive;
86
87 /**
88  * Option -i.
89  */
90 static int iterate_connections;
91
92 /**
93  * Option -t.
94  */
95 static int test_configuration;
96
97 /**
98  * Option -c.
99  */
100 static int monitor_connects;
101
102 /**
103  * Option -m.
104  */
105 static int monitor_connections;
106
107 /**
108  * Option -C.
109  */
110 static int try_connect;
111
112 /**
113  * Option -n.
114  */
115 static int numeric;
116
117 /**
118  * Global return value (0 success).
119  */
120 static int ret;
121
122 /**
123  * Current number of connections in monitor mode
124  */
125 static int monitor_connect_counter;
126
127 /**
128  * Number of bytes of traffic we received so far.
129  */
130 static unsigned long long traffic_received;
131
132 /**
133  * Number of bytes of traffic we sent so far.
134  */
135 static unsigned long long traffic_sent;
136
137 /**
138  * Starting time of transmitting/receiving data.
139  */
140 static struct GNUNET_TIME_Absolute start_time;
141
142 /**
143  * Handle for current transmission request.
144  */
145 static struct GNUNET_TRANSPORT_TransmitHandle *th;
146
147 /**
148  *
149  */
150 struct GNUNET_TRANSPORT_PeerIterateContext *pic;
151
152 /**
153  * Identity of the peer we transmit to / connect to.
154  * (equivalent to 'cpid' string).
155  */
156 static struct GNUNET_PeerIdentity pid;
157
158 /**
159  * Task scheduled for cleanup / termination of the process.
160  */
161 static GNUNET_SCHEDULER_TaskIdentifier end;
162
163 /**
164  * Task for operation timeout
165  */
166 static GNUNET_SCHEDULER_TaskIdentifier op_timeout;
167
168
169 static struct GNUNET_CONTAINER_MultiHashMap *peers;
170
171 /**
172  * Selected level of verbosity.
173  */
174 static int verbosity;
175
176 /**
177  * Resolver process handle.
178  */
179 struct GNUNET_OS_Process *resolver;
180
181 /**
182  * Number of tasks running that still need the resolver.
183  */
184 static unsigned int resolver_users;
185
186 /**
187  * Number of address resolutions pending
188  */
189 static unsigned int address_resolutions;
190
191 /**
192  * Address resolutions pending in progress
193  */
194 static unsigned int address_resolution_in_progress;
195
196 /**
197  * Context for a plugin test.
198  */
199 struct TestContext
200 {
201
202   /**
203    * Handle to the active NAT test.
204    */
205   struct GNUNET_NAT_Test *tst;
206
207   /**
208    * Task identifier for the timeout.
209    */
210   GNUNET_SCHEDULER_TaskIdentifier tsk;
211
212   /**
213    * Name of plugin under test.
214    */
215   const char *name;
216
217 };
218
219
220 /**
221  * Task run in monitor mode when the user presses CTRL-C to abort.
222  * Stops monitoring activity.
223  *
224  * @param cls the 'struct GNUNET_TRANSPORT_PeerIterateContext *'
225  * @param tc scheduler context
226  */
227 static void
228 shutdown_task (void *cls,
229                const struct GNUNET_SCHEDULER_TaskContext *tc)
230 {
231   struct GNUNET_TIME_Relative duration;
232   end = GNUNET_SCHEDULER_NO_TASK;
233   if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
234   {
235       GNUNET_SCHEDULER_cancel (op_timeout);
236       op_timeout = GNUNET_SCHEDULER_NO_TASK;
237   }
238   if (NULL != tc_handle)
239   {
240       GNUNET_TRANSPORT_try_connect_cancel (tc_handle);
241       tc_handle = NULL;
242   }
243   if (NULL != pic)
244   {
245       GNUNET_TRANSPORT_peer_get_active_addresses_cancel (pic);
246       pic = NULL;
247   }
248   if (NULL != th)
249   {
250     GNUNET_TRANSPORT_notify_transmit_ready_cancel(th);
251     th = NULL;
252   }
253   if (NULL != handle)
254   {
255     GNUNET_TRANSPORT_disconnect(handle);
256     handle = NULL;
257   }
258   if (NULL != peers)
259   {
260     GNUNET_CONTAINER_multihashmap_destroy (peers);
261     peers = NULL;
262   }
263   if (benchmark_send)
264   {
265     duration = GNUNET_TIME_absolute_get_duration (start_time);
266     FPRINTF (stdout, _("Transmitted %llu bytes/s (%llu bytes in %s)\n"),
267              1000LL * 1000LL * traffic_sent / (1 + duration.rel_value_us), traffic_sent,
268              GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
269   }
270   if (benchmark_receive)
271   {
272     duration = GNUNET_TIME_absolute_get_duration (start_time);
273     FPRINTF (stdout, _("Received %llu bytes/s (%llu bytes in %s)\n"),
274              1000LL * 1000LL * traffic_received / (1 + duration.rel_value_us),
275              traffic_received,
276              GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
277   }
278 }
279
280 struct ResolutionContext *rc_head;
281 struct ResolutionContext *rc_tail;
282
283 struct ResolutionContext
284 {
285         struct ResolutionContext *next;
286         struct ResolutionContext *prev;
287   struct GNUNET_HELLO_Address *addrcp;
288   struct GNUNET_TRANSPORT_AddressToStringContext *asc;
289   int printed;
290 };
291
292
293 static void
294 operation_timeout (void *cls,
295                const struct GNUNET_SCHEDULER_TaskContext *tc)
296 {
297         struct ResolutionContext *cur;
298         struct ResolutionContext *next;
299   op_timeout = GNUNET_SCHEDULER_NO_TASK;
300   if ((try_connect) || (benchmark_send) ||
301                 (benchmark_receive))
302   {
303       FPRINTF (stdout, _("Failed to connect to `%s'\n"), GNUNET_h2s_full (&pid.hashPubKey));
304       if (GNUNET_SCHEDULER_NO_TASK != end)
305         GNUNET_SCHEDULER_cancel (end);
306       end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
307       ret = 1;
308       return;
309   }
310   if (iterate_connections)
311   {
312                 next = rc_head;
313                 while (NULL != (cur = next))
314                 {
315                                 next = cur->next;
316                                 FPRINTF (stdout, _("Failed to resolve address for peer `%s'\n"),
317                                                 GNUNET_i2s (&cur->addrcp->peer));
318
319                                 GNUNET_CONTAINER_DLL_remove (rc_head, rc_tail, cur);
320                                 GNUNET_TRANSPORT_address_to_string_cancel (cur->asc);
321                                 GNUNET_free (cur->addrcp);
322                                 GNUNET_free (cur);
323
324                 }
325                 FPRINTF (stdout, "%s", _("Failed to list connections, timeout occured\n"));
326       if (GNUNET_SCHEDULER_NO_TASK != end)
327         GNUNET_SCHEDULER_cancel (end);
328       end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
329       ret = 1;
330       return;
331   }
332
333 }
334
335
336
337 /**
338  * Display the result of the test.
339  *
340  * @param tc test context
341  * @param result GNUNET_YES on success
342  */
343 static void
344 display_test_result (struct TestContext *tc, int result)
345 {
346   if (GNUNET_YES != result)
347   {
348     FPRINTF (stderr, "Configuration for plugin `%s' did not work!\n", tc->name);
349   }
350   else
351   {
352     FPRINTF (stderr, "Configuration for plugin `%s' is working!\n", tc->name);
353   }
354   if (GNUNET_SCHEDULER_NO_TASK != tc->tsk)
355   {
356     GNUNET_SCHEDULER_cancel (tc->tsk);
357     tc->tsk = GNUNET_SCHEDULER_NO_TASK;
358   }
359   if (NULL != tc->tst)
360   {
361     GNUNET_NAT_test_stop (tc->tst);
362     tc->tst = NULL;
363   }
364   GNUNET_free (tc);
365   resolver_users--;
366   if ((0 == resolver_users) && (NULL != resolver))
367   {
368     GNUNET_break (0 == GNUNET_OS_process_kill (resolver, SIGTERM));
369     GNUNET_OS_process_destroy (resolver);
370     resolver = NULL;
371   }
372 }
373
374
375 /**
376  * Function called by NAT on success.
377  * Clean up and update GUI (with success).
378  *
379  * @param cls test context
380  * @param success currently always GNUNET_OK
381  */
382 static void
383 result_callback (void *cls, int success)
384 {
385   struct TestContext *tc = cls;
386
387   display_test_result (tc, success);
388 }
389
390
391 /**
392  * Function called if NAT failed to confirm success.
393  * Clean up and update GUI (with failure).
394  *
395  * @param cls test context
396  * @param tc scheduler callback
397  */
398 static void
399 fail_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
400 {
401   struct TestContext *tstc = cls;
402
403   tstc->tsk = GNUNET_SCHEDULER_NO_TASK;
404   display_test_result (tstc, GNUNET_NO);
405 }
406
407
408 /**
409  * Test our plugin's configuration (NAT traversal, etc.).
410  *
411  * @param cfg configuration to test
412  */
413 static void
414 do_test_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
415 {
416   char *plugins;
417   char *tok;
418   unsigned long long bnd_port;
419   unsigned long long adv_port;
420   struct TestContext *tc;
421
422   if (GNUNET_OK !=
423       GNUNET_CONFIGURATION_get_value_string (cfg, "transport", "plugins",
424                                              &plugins))
425   {
426     FPRINTF (stderr,
427              "%s",
428              _
429              ("No transport plugins configured, peer will never communicate\n"));
430     ret = 4;
431     return;
432   }
433   for (tok = strtok (plugins, " "); tok != NULL; tok = strtok (NULL, " "))
434   {
435     char section[12 + strlen (tok)];
436
437     GNUNET_snprintf (section, sizeof (section), "transport-%s", tok);
438     if (GNUNET_OK !=
439         GNUNET_CONFIGURATION_get_value_number (cfg, section, "PORT", &bnd_port))
440     {
441       FPRINTF (stderr,
442                _("No port configured for plugin `%s', cannot test it\n"), tok);
443       continue;
444     }
445     if (GNUNET_OK !=
446         GNUNET_CONFIGURATION_get_value_number (cfg, section, "ADVERTISED_PORT",
447                                                &adv_port))
448       adv_port = bnd_port;
449     if (NULL == resolver)
450       resolver =
451           GNUNET_OS_start_process (GNUNET_YES, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, "gnunet-service-resolver",
452                                    "gnunet-service-resolver", NULL);
453     resolver_users++;
454     GNUNET_RESOLVER_connect (cfg);
455     tc = GNUNET_malloc (sizeof (struct TestContext));
456     tc->name = GNUNET_strdup (tok);
457     tc->tst =
458         GNUNET_NAT_test_start (cfg,
459                                (0 ==
460                                 strcasecmp (tok,
461                                             "udp")) ? GNUNET_NO : GNUNET_YES,
462                                (uint16_t) bnd_port, (uint16_t) adv_port,
463                                &result_callback, tc);
464     if (NULL == tc->tst)
465     {
466       display_test_result (tc, GNUNET_SYSERR);
467       continue;
468     }
469     tc->tsk = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &fail_timeout, tc);
470   }
471   GNUNET_free (plugins);
472 }
473
474 /**
475  * Function called to notify a client about the socket
476  * begin ready to queue more data.  "buf" will be
477  * NULL and "size" zero if the socket was closed for
478  * writing in the meantime.
479  *
480  * @param cls closure
481  * @param size number of bytes available in buf
482  * @param buf where the callee should write the message
483  * @return number of bytes written to buf
484  */
485 static size_t
486 transmit_data (void *cls, size_t size, void *buf)
487 {
488   struct GNUNET_MessageHeader *m = buf;
489
490   if ((NULL == buf) && (0 == size))
491   {
492     th = NULL;
493     return 0;
494   }
495
496   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
497   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
498   m->size = ntohs (size);
499   m->type = ntohs (GNUNET_MESSAGE_TYPE_DUMMY);
500   memset (&m[1], 52, size - sizeof (struct GNUNET_MessageHeader));
501   traffic_sent += size;
502   th = GNUNET_TRANSPORT_notify_transmit_ready (handle, &pid, BLOCKSIZE * 1024, 0,
503                                                GNUNET_TIME_UNIT_FOREVER_REL,
504                                                &transmit_data, NULL);
505   if (verbosity > 0)
506     FPRINTF (stdout, _("Transmitting %u bytes to %s\n"), (unsigned int) size,
507              GNUNET_i2s (&pid));
508   return size;
509 }
510
511
512 /**
513  * Function called to notify transport users that another
514  * peer connected to us.
515  *
516  * @param cls closure
517  * @param peer the peer that connected
518  */
519 static void
520 notify_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
521 {
522   if (0 != memcmp (&pid, peer, sizeof (struct GNUNET_PeerIdentity)))
523     return;
524   ret = 0;
525   if (try_connect)
526   {
527       /* all done, terminate instantly */
528       FPRINTF (stdout, _("Successfully connected to `%s'\n"), GNUNET_h2s_full (&peer->hashPubKey));
529       ret = 0;
530
531       if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
532       {
533         GNUNET_SCHEDULER_cancel (op_timeout);
534         op_timeout = GNUNET_SCHEDULER_NO_TASK;
535       }
536
537       if (GNUNET_SCHEDULER_NO_TASK != end)
538         GNUNET_SCHEDULER_cancel (end);
539       end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
540       return;
541   }
542   if (benchmark_send)
543   {
544     if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
545     {
546       GNUNET_SCHEDULER_cancel (op_timeout);
547       op_timeout = GNUNET_SCHEDULER_NO_TASK;
548     }
549     if (verbosity > 0)
550       FPRINTF (stdout, _("Successfully connected to `%s', starting to send benchmark data in %u Kb blocks\n"),
551           GNUNET_i2s (&pid), BLOCKSIZE);
552     start_time = GNUNET_TIME_absolute_get ();
553     if (NULL == th)
554       th = GNUNET_TRANSPORT_notify_transmit_ready (handle, peer,
555                                                    BLOCKSIZE * 1024, 0,
556                                                    GNUNET_TIME_UNIT_FOREVER_REL,
557                                                    &transmit_data, NULL);
558     else
559       GNUNET_break (0);
560     return;
561   }
562 }
563
564
565 /**
566  * Function called to notify transport users that another
567  * peer disconnected from us.
568  *
569  * @param cls closure
570  * @param peer the peer that disconnected
571  */
572 static void
573 notify_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
574 {
575   if (0 != memcmp (&pid, peer, sizeof (struct GNUNET_PeerIdentity)))
576     return;
577
578   if (NULL != th)
579   {
580     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
581     th = NULL;
582   }
583   if (benchmark_send)
584   {
585       FPRINTF (stdout, _("Disconnected from peer `%s' while benchmarking\n"), GNUNET_i2s (&pid));
586       if (GNUNET_SCHEDULER_NO_TASK != end)
587         GNUNET_SCHEDULER_cancel (end);
588       return;
589   }
590 }
591
592 /**
593  * Function called to notify transport users that another
594  * peer connected to us.
595  *
596  * @param cls closure
597  * @param peer the peer that connected
598  */
599 static void
600 monitor_notify_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
601 {
602   monitor_connect_counter ++;
603   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
604   const char *now_str = GNUNET_STRINGS_absolute_time_to_string (now);
605
606   FPRINTF (stdout, _("%24s: %-17s %4s   (%u connections in total)\n"),
607            now_str,
608            _("Connected to"),
609            GNUNET_i2s (peer),
610            monitor_connect_counter);
611 }
612
613
614 /**
615  * Function called to notify transport users that another
616  * peer disconnected from us.
617  *
618  * @param cls closure
619  * @param peer the peer that disconnected
620  */
621 static void
622 monitor_notify_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
623 {
624   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
625   const char *now_str = GNUNET_STRINGS_absolute_time_to_string (now);
626
627   GNUNET_assert (monitor_connect_counter > 0);
628   monitor_connect_counter --;
629
630   FPRINTF (stdout, _("%24s: %-17s %4s   (%u connections in total)\n"),
631            now_str,
632            _("Disconnected from"),
633            GNUNET_i2s (peer),
634            monitor_connect_counter);
635 }
636
637
638
639 /**
640  * Function called by the transport for each received message.
641  *
642  * @param cls closure
643  * @param peer (claimed) identity of the other peer
644  * @param message the message
645  */
646 static void
647 notify_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
648                 const struct GNUNET_MessageHeader *message)
649 {
650   if (benchmark_receive)
651   {
652     if (GNUNET_MESSAGE_TYPE_DUMMY != ntohs (message->type))
653       return;
654     if (verbosity > 0)
655       FPRINTF (stdout, _("Received %u bytes from %s\n"),
656                (unsigned int) ntohs (message->size), GNUNET_i2s (peer));
657
658     if (traffic_received == 0)
659       start_time = GNUNET_TIME_absolute_get ();
660     traffic_received += ntohs (message->size);
661     return;
662   }
663 }
664
665
666 static void resolve_address (const struct GNUNET_HELLO_Address *address,
667                                                                                                                  int numeric);
668
669
670 static void
671 process_string (void *cls, const char *address)
672 {
673   struct ResolutionContext *rc = cls;
674   struct GNUNET_HELLO_Address *addrcp = rc->addrcp;
675
676   if (address != NULL)
677   {
678     FPRINTF (stdout, _("Peer `%s': %s %s\n"), GNUNET_i2s (&addrcp->peer), addrcp->transport_name, address);
679     rc->printed = GNUNET_YES;
680   }
681   else
682   {
683     /* done */
684     GNUNET_assert (address_resolutions > 0);
685     address_resolutions --;
686     if (GNUNET_NO == rc->printed)
687     {
688         if (numeric == GNUNET_NO)
689         {
690                 resolve_address (rc->addrcp, GNUNET_YES ); /* Failed to resolve address, try numeric lookup */
691         }
692         else
693         FPRINTF (stdout, _("Peer `%s': %s <unable to resolve address>\n"), GNUNET_i2s (&addrcp->peer), addrcp->transport_name);
694     }
695     GNUNET_free (rc->addrcp);
696     GNUNET_CONTAINER_DLL_remove (rc_head, rc_tail, rc);
697     GNUNET_free (rc);
698     if ((0 == address_resolutions) && (iterate_connections))
699     {
700         if (GNUNET_SCHEDULER_NO_TASK != end)
701         {
702           GNUNET_SCHEDULER_cancel (end);
703           end = GNUNET_SCHEDULER_NO_TASK;
704         }
705         if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
706         {
707                 GNUNET_SCHEDULER_cancel (op_timeout);
708                 op_timeout = GNUNET_SCHEDULER_NO_TASK;
709         }
710         ret = 0;
711         end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
712     }
713   }
714 }
715
716 static void resolve_address (const struct GNUNET_HELLO_Address *address,
717                                                                                                                  int numeric)
718 {
719   struct ResolutionContext *rc;
720
721   rc = GNUNET_malloc(sizeof (struct ResolutionContext));
722   GNUNET_assert (NULL != rc);
723   GNUNET_CONTAINER_DLL_insert (rc_head, rc_tail, rc);
724   address_resolutions ++;
725
726   rc->addrcp = GNUNET_HELLO_address_copy(address);
727   rc->printed = GNUNET_NO;
728   /* Resolve address to string */
729   rc->asc = GNUNET_TRANSPORT_address_to_string (cfg, address, numeric,
730                                       RESOLUTION_TIMEOUT, &process_string,
731                                       rc);
732 }
733
734 /**
735  * Function to call with a binary address
736  *
737  * @param cls closure
738  * @param peer identity of the peer
739  * @param address binary address (NULL on disconnect)
740  */
741 static void
742 process_address (void *cls, const struct GNUNET_PeerIdentity *peer,
743                  const struct GNUNET_HELLO_Address *address)
744 {
745   if (peer == NULL)
746   {
747     /* done */
748     address_resolution_in_progress = GNUNET_NO;
749     pic = NULL;
750     if (GNUNET_SCHEDULER_NO_TASK != end)
751       GNUNET_SCHEDULER_cancel (end);
752     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
753     return;
754   }
755   if (address == NULL)
756   {
757     FPRINTF (stdout, _("Peer `%s' disconnected\n"), GNUNET_i2s (peer));
758     return;
759   }
760
761   if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
762         GNUNET_SCHEDULER_cancel (op_timeout);
763   op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT,
764                                              &operation_timeout, NULL);
765
766   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received address for peer `%s': %s\n",
767                 GNUNET_i2s (peer), address->transport_name);
768   resolve_address (address, numeric);
769 }
770
771 void try_connect_cb (void *cls,
772                      const int result)
773 {
774   static int retries = 0;
775   if (GNUNET_OK == result)
776   {
777       tc_handle = NULL;
778       return;
779   }
780   retries ++;
781   if (retries < 10)
782     tc_handle = GNUNET_TRANSPORT_try_connect (handle, &pid, try_connect_cb, NULL);
783   else
784   {
785     FPRINTF (stderr, "%s", _("Failed to send connect request to transport service\n"));
786     if (GNUNET_SCHEDULER_NO_TASK != end)
787       GNUNET_SCHEDULER_cancel (end);
788     ret = 1;
789     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
790     return;
791   }
792 }
793
794
795 /**
796  * Function called with the result of the check if the 'transport'
797  * service is running.
798  *
799  * @param cls closure with our configuration
800  * @param result GNUNET_YES if transport is running
801  */
802 static void
803 testservice_task (void *cls,
804                   int result)
805 {
806   int counter = 0;
807   ret = 1;
808
809   if (GNUNET_YES != result)
810   {
811     FPRINTF (stderr, 
812              _("Service `%s' is not running\n"), "transport");
813     return;
814   }
815
816   if ( (NULL != cpid) && 
817        (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (cpid, &pid.hashPubKey)))
818   {
819     FPRINTF (stderr, _("Failed to parse peer identity `%s'\n"), cpid);
820     return;
821   }
822
823   counter = benchmark_send + benchmark_receive + iterate_connections +
824             monitor_connections + monitor_connects + try_connect;
825
826   if (1 < counter)
827   {
828     FPRINTF (stderr, _("Multiple operations given. Please choose only one operation: %s, %s, %s, %s, %s, %s\n"),
829              "connect", "benchmark send", "benchmark receive", "information", "monitor", "events");
830     return;
831   }
832   if (0 == counter)
833   {
834     FPRINTF (stderr, _("No operation given. Please choose one operation: %s, %s, %s, %s, %s, %s\n"),
835              "connect", "benchmark send", "benchmark receive", "information", "monitor", "events");
836     return;
837   }
838
839   if (try_connect) /* -C: Connect to peer */
840   {
841     if (NULL == cpid)
842     {
843       FPRINTF (stderr, _("Option `%s' makes no sense without option `%s'.\n"),
844                "-C", "-p");
845       ret = 1;
846       return;
847     }
848     handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL,
849                                        &notify_receive,
850                                        &notify_connect,
851                                        &notify_disconnect);
852     if (NULL == handle)
853     {
854         FPRINTF (stderr, "%s", _("Failed to connect to transport service\n"));
855         ret = 1;
856         return;
857     }
858     tc_handle = GNUNET_TRANSPORT_try_connect (handle, &pid, try_connect_cb, NULL);
859     if (NULL == tc_handle)
860     {
861         FPRINTF (stderr, "%s", _("Failed to send request to transport service\n"));
862         ret = 1;
863         return;
864     }
865     op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT,
866                                                &operation_timeout, NULL);
867
868   }
869   else if (benchmark_send) /* -s: Benchmark sending */
870   {
871     if (NULL == cpid)
872     {
873       FPRINTF (stderr, _("Option `%s' makes no sense without option `%s'.\n"),
874                "-s", "-p");
875       ret = 1;
876       return;
877     }
878     handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL,
879                                        &notify_receive,
880                                        &notify_connect,
881                                        &notify_disconnect);
882     if (NULL == handle)
883     {
884         FPRINTF (stderr, "%s", _("Failed to connect to transport service\n"));
885         ret = 1;
886         return;
887     }
888     tc_handle =  GNUNET_TRANSPORT_try_connect (handle, &pid, try_connect_cb, NULL);
889     if (NULL == tc_handle)
890     {
891         FPRINTF (stderr, "%s", _("Failed to send request to transport service\n"));
892         ret = 1;
893         return;
894     }
895     start_time = GNUNET_TIME_absolute_get ();
896     op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT,
897                                                &operation_timeout, NULL);
898   }
899   else if (benchmark_receive) /* -b: Benchmark receiving */
900   {
901     handle =
902         GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive,
903                                   NULL, NULL);
904     if (NULL == handle)
905     {
906         FPRINTF (stderr, "%s", _("Failed to connect to transport service\n"));
907         ret = 1;
908         return;
909     }
910     if (verbosity > 0)
911       FPRINTF (stdout, "%s", _("Starting to receive benchmark data\n"));
912     start_time = GNUNET_TIME_absolute_get ();
913
914   }
915   else if (iterate_connections) /* -i: List all active addresses once */
916   {
917     peers = GNUNET_CONTAINER_multihashmap_create (20, GNUNET_NO);
918     address_resolution_in_progress = GNUNET_YES;
919     pic = GNUNET_TRANSPORT_peer_get_active_addresses (cfg,
920                                                 (NULL == cpid) ? NULL : &pid,
921                                                 GNUNET_YES,
922                                                 TIMEOUT,
923                                                 &process_address, (void *) cfg);
924     op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT,
925                                                &operation_timeout, NULL);
926   }
927   else if (monitor_connections) /* -m: List all active addresses continously */
928   {
929     peers = GNUNET_CONTAINER_multihashmap_create (20, GNUNET_NO);
930     address_resolution_in_progress = GNUNET_YES;
931     pic = GNUNET_TRANSPORT_peer_get_active_addresses (cfg,
932                                                 (NULL == cpid) ? NULL : &pid,
933                                                 GNUNET_NO,
934                                                 TIMEOUT,
935                                                 &process_address, (void *) cfg);
936   }
937   else if (monitor_connects) /* -e : Monitor (dis)connect events continously */
938   {
939     monitor_connect_counter = 0;
940     handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL,
941                                        &monitor_notify_connect,
942                                        &monitor_notify_disconnect);
943     if (NULL == handle)
944     {
945       FPRINTF (stderr, "%s", _("Failed to connect to transport service\n"));
946       ret = 1;
947       return;
948     }
949     ret = 0;
950   }
951   else
952   {
953     GNUNET_break (0);
954     return;
955   }
956
957   end = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
958                                       &shutdown_task,
959                                       NULL);
960
961 }
962
963
964 /**
965  * Main function that will be run by the scheduler.
966  *
967  * @param cls closure
968  * @param args remaining command-line arguments
969  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
970  * @param mycfg configuration
971  */
972 static void
973 run (void *cls, char *const *args, const char *cfgfile,
974      const struct GNUNET_CONFIGURATION_Handle *mycfg)
975 {
976         cfg = (struct GNUNET_CONFIGURATION_Handle *) mycfg;
977         if (test_configuration)
978   {
979     do_test_configuration (cfg);
980     return;
981   }
982   GNUNET_CLIENT_service_test ("transport", cfg,
983                               GNUNET_TIME_UNIT_SECONDS,
984                               &testservice_task,
985                               (void *) cfg);
986 }
987
988
989 int
990 main (int argc, char *const *argv)
991 {
992   int res;
993   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
994     {'b', "benchmark", NULL,
995      gettext_noop ("measure how fast we are receiving data from all peers (until CTRL-C)"),
996      0, &GNUNET_GETOPT_set_one, &benchmark_receive},
997     {'C', "connect", NULL,
998      gettext_noop ("connect to a peer"),
999      0, &GNUNET_GETOPT_set_one, &try_connect},
1000     {'i', "information", NULL,
1001      gettext_noop ("provide information about all current connections (once)"),
1002      0, &GNUNET_GETOPT_set_one, &iterate_connections},
1003     {'m', "monitor", NULL,
1004      gettext_noop ("provide information about all current connections (continuously)"),
1005      0, &GNUNET_GETOPT_set_one, &monitor_connections},
1006     {'e', "events", NULL,
1007      gettext_noop ("provide information about all connects and disconnect events (continuously)"),
1008      0, &GNUNET_GETOPT_set_one, &monitor_connects},
1009     {'n', "numeric", NULL,
1010      gettext_noop ("do not resolve hostnames"),
1011      0, &GNUNET_GETOPT_set_one, &numeric},
1012      {'p', "peer", "PEER",
1013       gettext_noop ("peer identity"),
1014       1, &GNUNET_GETOPT_set_string, &cpid},
1015     {'s', "send", NULL,
1016      gettext_noop
1017      ("send data for benchmarking to the other peer (until CTRL-C)"),
1018      0, &GNUNET_GETOPT_set_one, &benchmark_send},
1019     {'t', "test", NULL,
1020      gettext_noop ("test transport configuration (involves external server)"),
1021      0, &GNUNET_GETOPT_set_one, &test_configuration},
1022     GNUNET_GETOPT_OPTION_VERBOSE (&verbosity),
1023     GNUNET_GETOPT_OPTION_END
1024   };
1025
1026   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1027     return 2;
1028
1029   res = GNUNET_PROGRAM_run (argc, argv, "gnunet-transport",
1030                               gettext_noop
1031                               ("Direct access to transport service."), options,
1032                               &run, NULL);
1033   GNUNET_free ((void *) argv);
1034   if (GNUNET_OK == res)
1035     return ret;
1036   return 1;
1037 }
1038
1039
1040 /* end of gnunet-transport.c */