docu
[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              1000 * traffic_sent / (1 + duration.rel_value), 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              1000 * traffic_received / (1 + duration.rel_value),
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  * @param ats performance data
519  * @param ats_count number of entries in ats (excluding 0-termination)
520  */
521 static void
522 notify_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
523                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
524 {
525   if (0 != memcmp (&pid, peer, sizeof (struct GNUNET_PeerIdentity)))
526     return;
527   ret = 0;
528   if (try_connect)
529   {
530       /* all done, terminate instantly */
531       FPRINTF (stdout, _("Successfully connected to `%s'\n"), GNUNET_h2s_full (&peer->hashPubKey));
532       ret = 0;
533
534       if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
535       {
536         GNUNET_SCHEDULER_cancel (op_timeout);
537         op_timeout = GNUNET_SCHEDULER_NO_TASK;
538       }
539
540       if (GNUNET_SCHEDULER_NO_TASK != end)
541         GNUNET_SCHEDULER_cancel (end);
542       end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
543       return;
544   }
545   if (benchmark_send)
546   {
547     if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
548     {
549       GNUNET_SCHEDULER_cancel (op_timeout);
550       op_timeout = GNUNET_SCHEDULER_NO_TASK;
551     }
552     if (verbosity > 0)
553       FPRINTF (stdout, _("Successfully connected to `%s', starting to send benchmark data in %u Kb blocks\n"),
554           GNUNET_i2s (&pid), BLOCKSIZE);
555     start_time = GNUNET_TIME_absolute_get ();
556     if (NULL == th)
557       th = GNUNET_TRANSPORT_notify_transmit_ready (handle, peer,
558                                                    BLOCKSIZE * 1024, 0,
559                                                    GNUNET_TIME_UNIT_FOREVER_REL,
560                                                    &transmit_data, NULL);
561     else
562       GNUNET_break (0);
563     return;
564   }
565 }
566
567
568 /**
569  * Function called to notify transport users that another
570  * peer disconnected from us.
571  *
572  * @param cls closure
573  * @param peer the peer that disconnected
574  */
575 static void
576 notify_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
577 {
578   if (0 != memcmp (&pid, peer, sizeof (struct GNUNET_PeerIdentity)))
579     return;
580
581   if (NULL != th)
582   {
583     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
584     th = NULL;
585   }
586   if (benchmark_send)
587   {
588       FPRINTF (stdout, _("Disconnected from peer `%s' while benchmarking\n"), GNUNET_i2s (&pid));
589       if (GNUNET_SCHEDULER_NO_TASK != end)
590         GNUNET_SCHEDULER_cancel (end);
591       return;
592   }
593 }
594
595 /**
596  * Function called to notify transport users that another
597  * peer connected to us.
598  *
599  * @param cls closure
600  * @param peer the peer that connected
601  * @param ats performance data
602  * @param ats_count number of entries in ats (excluding 0-termination)
603  */
604 static void
605 monitor_notify_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
606                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
607 {
608   monitor_connect_counter ++;
609   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
610   const char *now_str = GNUNET_STRINGS_absolute_time_to_string (now);
611
612   FPRINTF (stdout, _("%24s: %-17s %4s   (%u connections in total)\n"),
613            now_str,
614            _("Connected to"),
615            GNUNET_i2s (peer),
616            monitor_connect_counter);
617 }
618
619
620 /**
621  * Function called to notify transport users that another
622  * peer disconnected from us.
623  *
624  * @param cls closure
625  * @param peer the peer that disconnected
626  */
627 static void
628 monitor_notify_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
629 {
630   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
631   const char *now_str = GNUNET_STRINGS_absolute_time_to_string (now);
632
633   GNUNET_assert (monitor_connect_counter > 0);
634   monitor_connect_counter --;
635
636   FPRINTF (stdout, _("%24s: %-17s %4s   (%u connections in total)\n"),
637            now_str,
638            _("Disconnected from"),
639            GNUNET_i2s (peer),
640            monitor_connect_counter);
641 }
642
643
644
645 /**
646  * Function called by the transport for each received message.
647  *
648  * @param cls closure
649  * @param peer (claimed) identity of the other peer
650  * @param message the message
651  * @param ats performance data
652  * @param ats_count number of entries in ats
653  */
654 static void
655 notify_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
656                 const struct GNUNET_MessageHeader *message,
657                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count)
658 {
659   if (benchmark_receive)
660   {
661     if (GNUNET_MESSAGE_TYPE_DUMMY != ntohs (message->type))
662       return;
663     if (verbosity > 0)
664       FPRINTF (stdout, _("Received %u bytes from %s\n"),
665                (unsigned int) ntohs (message->size), GNUNET_i2s (peer));
666
667     if (traffic_received == 0)
668       start_time = GNUNET_TIME_absolute_get ();
669     traffic_received += ntohs (message->size);
670     return;
671   }
672 }
673
674
675 static void resolve_address (const struct GNUNET_HELLO_Address *address,
676                                                                                                                  int numeric);
677
678
679 static void
680 process_string (void *cls, const char *address)
681 {
682   struct ResolutionContext *rc = cls;
683   struct GNUNET_HELLO_Address *addrcp = rc->addrcp;
684
685   if (address != NULL)
686   {
687     FPRINTF (stdout, _("Peer `%s': %s %s\n"), GNUNET_i2s (&addrcp->peer), addrcp->transport_name, address);
688     rc->printed = GNUNET_YES;
689   }
690   else
691   {
692     /* done */
693     GNUNET_assert (address_resolutions > 0);
694     address_resolutions --;
695     if (GNUNET_NO == rc->printed)
696     {
697         if (numeric == GNUNET_NO)
698         {
699                 resolve_address (rc->addrcp, GNUNET_YES ); /* Failed to resolve address, try numeric lookup */
700         }
701         else
702         FPRINTF (stdout, _("Peer `%s': %s <unable to resolve address>\n"), GNUNET_i2s (&addrcp->peer), addrcp->transport_name);
703     }
704     GNUNET_free (rc->addrcp);
705     GNUNET_CONTAINER_DLL_remove (rc_head, rc_tail, rc);
706     GNUNET_free (rc);
707     if ((0 == address_resolutions) && (iterate_connections))
708     {
709         if (GNUNET_SCHEDULER_NO_TASK != end)
710         {
711           GNUNET_SCHEDULER_cancel (end);
712           end = GNUNET_SCHEDULER_NO_TASK;
713         }
714         if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
715         {
716                 GNUNET_SCHEDULER_cancel (op_timeout);
717                 op_timeout = GNUNET_SCHEDULER_NO_TASK;
718         }
719         ret = 0;
720         end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
721     }
722   }
723 }
724
725 static void resolve_address (const struct GNUNET_HELLO_Address *address,
726                                                                                                                  int numeric)
727 {
728   struct ResolutionContext *rc;
729
730   rc = GNUNET_malloc(sizeof (struct ResolutionContext));
731   GNUNET_assert (NULL != rc);
732   GNUNET_CONTAINER_DLL_insert (rc_head, rc_tail, rc);
733   address_resolutions ++;
734
735   rc->addrcp = GNUNET_HELLO_address_copy(address);
736   rc->printed = GNUNET_NO;
737   /* Resolve address to string */
738   rc->asc = GNUNET_TRANSPORT_address_to_string (cfg, address, numeric,
739                                       RESOLUTION_TIMEOUT, &process_string,
740                                       rc);
741 }
742
743 /**
744  * Function to call with a binary address
745  *
746  * @param cls closure
747  * @param peer identity of the peer
748  * @param address binary address (NULL on disconnect)
749  */
750 static void
751 process_address (void *cls, const struct GNUNET_PeerIdentity *peer,
752                  const struct GNUNET_HELLO_Address *address)
753 {
754   if (peer == NULL)
755   {
756     /* done */
757     address_resolution_in_progress = GNUNET_NO;
758     pic = NULL;
759     if (GNUNET_SCHEDULER_NO_TASK != end)
760       GNUNET_SCHEDULER_cancel (end);
761     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
762     return;
763   }
764   if (address == NULL)
765   {
766     FPRINTF (stdout, _("Peer `%s' disconnected\n"), GNUNET_i2s (peer));
767     return;
768   }
769
770   if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
771         GNUNET_SCHEDULER_cancel (op_timeout);
772   op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT,
773                                              &operation_timeout, NULL);
774
775   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received address for peer `%s': %s\n",
776                 GNUNET_i2s (peer), address->transport_name);
777   resolve_address (address, numeric);
778 }
779
780 void try_connect_cb (void *cls,
781                      const int result)
782 {
783   static int retries = 0;
784   if (GNUNET_OK == result)
785   {
786       tc_handle = NULL;
787       return;
788   }
789   retries ++;
790   if (retries < 10)
791     tc_handle = GNUNET_TRANSPORT_try_connect (handle, &pid, try_connect_cb, NULL);
792   else
793   {
794     FPRINTF (stderr, "%s", _("Failed to send connect request to transport service\n"));
795     if (GNUNET_SCHEDULER_NO_TASK != end)
796       GNUNET_SCHEDULER_cancel (end);
797     ret = 1;
798     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
799     return;
800   }
801 }
802
803
804 static void
805 testservice_task (void *cls,
806                   const struct GNUNET_SCHEDULER_TaskContext *tc)
807 {
808   int counter = 0;
809   ret = 1;
810
811   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
812   {
813       FPRINTF (stderr, _("Service `%s' is not running\n"), "transport");
814       return;
815   }
816
817   if ((NULL != cpid) && (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 cfg 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
983   GNUNET_CLIENT_service_test ("transport", cfg,
984       GNUNET_TIME_UNIT_SECONDS,
985       &testservice_task,
986       (void *) cfg);
987 }
988
989
990 int
991 main (int argc, char *const *argv)
992 {
993   int res;
994   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
995     {'b', "benchmark", NULL,
996      gettext_noop ("measure how fast we are receiving data from all peers (until CTRL-C)"),
997      0, &GNUNET_GETOPT_set_one, &benchmark_receive},
998     {'C', "connect", NULL,
999      gettext_noop ("connect to a peer"),
1000      0, &GNUNET_GETOPT_set_one, &try_connect},
1001     {'i', "information", NULL,
1002      gettext_noop ("provide information about all current connections (once)"),
1003      0, &GNUNET_GETOPT_set_one, &iterate_connections},
1004     {'m', "monitor", NULL,
1005      gettext_noop ("provide information about all current connections (continuously)"),
1006      0, &GNUNET_GETOPT_set_one, &monitor_connections},
1007     {'e', "events", NULL,
1008      gettext_noop ("provide information about all connects and disconnect events (continuously)"),
1009      0, &GNUNET_GETOPT_set_one, &monitor_connects},
1010     {'n', "numeric", NULL,
1011      gettext_noop ("do not resolve hostnames"),
1012      0, &GNUNET_GETOPT_set_one, &numeric},
1013      {'p', "peer", "PEER",
1014       gettext_noop ("peer identity"),
1015       1, &GNUNET_GETOPT_set_string, &cpid},
1016     {'s', "send", NULL,
1017      gettext_noop
1018      ("send data for benchmarking to the other peer (until CTRL-C)"),
1019      0, &GNUNET_GETOPT_set_one, &benchmark_send},
1020     {'t', "test", NULL,
1021      gettext_noop ("test transport configuration (involves external server)"),
1022      0, &GNUNET_GETOPT_set_one, &test_configuration},
1023     GNUNET_GETOPT_OPTION_VERBOSE (&verbosity),
1024     GNUNET_GETOPT_OPTION_END
1025   };
1026
1027   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1028     return 2;
1029
1030   res = GNUNET_PROGRAM_run (argc, argv, "gnunet-transport",
1031                               gettext_noop
1032                               ("Direct access to transport service."), options,
1033                               &run, NULL);
1034   GNUNET_free ((void *) argv);
1035   if (GNUNET_OK == res)
1036     return ret;
1037   return 1;
1038 }
1039
1040
1041 /* end of gnunet-transport.c */