-indentation
[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, 20)
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  * Which peer should we connect to?
53  */
54 static char *cpid;
55
56 /**
57  * Handle to transport service.
58  */
59 static struct GNUNET_TRANSPORT_Handle *handle;
60
61 /**
62  * Configuration handle
63  */
64 static struct GNUNET_CONFIGURATION_Handle *cfg;
65
66 /**
67  * Try_connect handle
68  */
69 struct GNUNET_TRANSPORT_TryConnectHandle * tc_handle;
70
71 /**
72  * Option -s.
73  */
74 static int benchmark_send;
75
76 /**
77  * Option -b.
78  */
79 static int benchmark_receive;
80
81 /**
82  * Option -l.
83  */
84 static int benchmark_receive;
85
86 /**
87  * Option -i.
88  */
89 static int iterate_connections;
90
91 /**
92  * Option -d.
93  */
94 static int iterate_validation;
95
96 /**
97  * Option -a.
98  */
99 static int iterate_all;
100
101 /**
102  * Option -t.
103  */
104 static int test_configuration;
105
106 /**
107  * Option -c.
108  */
109 static int monitor_connects;
110
111 /**
112  * Option -m.
113  */
114 static int monitor_connections;
115
116 /**
117  * Option -f.
118  */
119 static int monitor_validation;
120
121 /**
122  * Option -C.
123  */
124 static int try_connect;
125
126 /**
127  * Option -D.
128  */
129 static int try_disconnect;
130
131 /**
132  * Option -n.
133  */
134 static int numeric;
135
136 /**
137  * Global return value (0 success).
138  */
139 static int ret;
140
141 /**
142  * Current number of connections in monitor mode
143  */
144 static int monitor_connect_counter;
145
146 /**
147  * Number of bytes of traffic we received so far.
148  */
149 static unsigned long long traffic_received;
150
151 /**
152  * Number of bytes of traffic we sent so far.
153  */
154 static unsigned long long traffic_sent;
155
156 /**
157  * Starting time of transmitting/receiving data.
158  */
159 static struct GNUNET_TIME_Absolute start_time;
160
161 /**
162  * Handle for current transmission request.
163  */
164 static struct GNUNET_TRANSPORT_TransmitHandle *th;
165
166 /**
167  * Map storing information about monitored peers
168  */
169 static struct GNUNET_CONTAINER_MultiPeerMap *monitored_peers;
170
171 /**
172  *
173  */
174 static struct GNUNET_TRANSPORT_PeerMonitoringContext *pic;
175
176 static struct GNUNET_TRANSPORT_ValidationMonitoringContext *vic;
177
178 /**
179  * Identity of the peer we transmit to / connect to.
180  * (equivalent to 'cpid' string).
181  */
182 static struct GNUNET_PeerIdentity pid;
183
184 /**
185  * Task scheduled for cleanup / termination of the process.
186  */
187 static GNUNET_SCHEDULER_TaskIdentifier end;
188
189 /**
190  * Task for operation timeout
191  */
192 static GNUNET_SCHEDULER_TaskIdentifier op_timeout;
193
194 /**
195  * Selected level of verbosity.
196  */
197 static int verbosity;
198
199 /**
200  * Resolver process handle.
201  */
202 struct GNUNET_OS_Process *resolver;
203
204 /**
205  * Number of address resolutions pending
206  */
207 static unsigned int address_resolutions;
208
209 /**
210  * Address resolutions pending in progress
211  */
212 static unsigned int address_resolution_in_progress;
213
214 /**
215  * DLL for NAT Test Contexts: head
216  */
217 struct TestContext *head;
218
219 /**
220  * DLL for NAT Test Contexts: tail
221  */
222 struct TestContext *tail;
223
224 /**
225  * Context for a plugin test.
226  */
227 struct TestContext
228 {
229   /**
230    * Previous in DLL
231    */
232   struct TestContext *prev;
233
234   /**
235    * Next in DLL
236    */
237   struct TestContext *next;
238
239   /**
240    * Handle to the active NAT test.
241    */
242   struct GNUNET_NAT_Test *tst;
243
244   /**
245    * Task identifier for the timeout.
246    */
247   GNUNET_SCHEDULER_TaskIdentifier tsk;
248
249   /**
250    * Name of plugin under test.
251    */
252   char *name;
253
254   /**
255    * Bound port
256    */
257   unsigned long long bnd_port;
258
259   /**
260    * Advertised ports
261    */
262   unsigned long long adv_port;
263
264 };
265
266 enum TestResult
267 {
268   /* NAT returned success */
269   NAT_TEST_SUCCESS = GNUNET_OK,
270
271   /* NAT returned failure  */
272   NAT_TEST_FAIL = GNUNET_NO,
273
274   /* NAT returned failure while running test */
275   NAT_TEST_INTERNAL_FAIL = GNUNET_SYSERR,
276
277   /* We could not start the test */
278   NAT_TEST_FAILED_TO_START = 2,
279
280   /* We had a timeout while running the test */
281   NAT_TEST_TIMEOUT = 3,
282 };
283
284 static struct ValidationResolutionContext *vc_head;
285 static struct ValidationResolutionContext *vc_tail;
286
287 struct ValidationResolutionContext
288 {
289   struct ValidationResolutionContext *next;
290   struct ValidationResolutionContext *prev;
291
292   struct GNUNET_PeerIdentity id;
293   struct GNUNET_HELLO_Address *addrcp;
294   struct GNUNET_TIME_Absolute last_validation;
295   struct GNUNET_TIME_Absolute valid_until;
296   struct GNUNET_TIME_Absolute next_validation;
297   enum GNUNET_TRANSPORT_ValidationState state;
298
299   struct GNUNET_TRANSPORT_AddressToStringContext *asc;
300
301   char *transport;
302   int printed;
303 };
304
305 struct MonitoredPeer
306 {
307   enum GNUNET_TRANSPORT_PeerState state;
308   struct GNUNET_TIME_Absolute state_timeout;
309   struct GNUNET_HELLO_Address *address;
310 };
311
312
313 static int
314 destroy_it (void *cls,
315             const struct GNUNET_PeerIdentity *key,
316             void *value)
317 {
318   struct MonitoredPeer *m = value;
319
320   GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multipeermap_remove (monitored_peers,
321                                                                     key, value));
322   GNUNET_free_non_null (m->address);
323   GNUNET_free (value);
324   return GNUNET_OK;
325 }
326
327
328 /**
329  * Task run in monitor mode when the user presses CTRL-C to abort.
330  * Stops monitoring activity.
331  *
332  * @param cls the 'struct GNUNET_TRANSPORT_PeerIterateContext *'
333  * @param tc scheduler context
334  */
335 static void
336 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
337 {
338   struct GNUNET_TIME_Relative duration;
339   struct ValidationResolutionContext *cur;
340   struct ValidationResolutionContext *next;
341   end = GNUNET_SCHEDULER_NO_TASK;
342   if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
343   {
344     GNUNET_SCHEDULER_cancel (op_timeout);
345     op_timeout = GNUNET_SCHEDULER_NO_TASK;
346   }
347   if (NULL != tc_handle)
348   {
349     GNUNET_TRANSPORT_try_connect_cancel (tc_handle);
350     tc_handle = NULL;
351   }
352   if (NULL != pic)
353   {
354     GNUNET_TRANSPORT_monitor_peers_cancel (pic);
355     pic = NULL;
356   }
357   if (NULL != vic)
358   {
359     GNUNET_TRANSPORT_monitor_validation_entries_cancel (vic);
360     vic = NULL;
361   }
362
363   next = vc_head;
364   for (cur = next; NULL != cur; cur = next)
365   {
366     next = cur->next;
367
368     GNUNET_TRANSPORT_address_to_string_cancel (cur->asc);
369     GNUNET_CONTAINER_DLL_remove (vc_head, vc_tail, cur);
370     GNUNET_free (cur->transport);
371     GNUNET_HELLO_address_free (cur->addrcp);
372     GNUNET_free (cur);
373   }
374
375   if (NULL != th)
376   {
377     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
378     th = NULL;
379   }
380   if (NULL != handle)
381   {
382     GNUNET_TRANSPORT_disconnect (handle);
383     handle = NULL;
384   }
385   if (benchmark_send)
386   {
387     duration = GNUNET_TIME_absolute_get_duration (start_time);
388     FPRINTF (stdout, _("Transmitted %llu bytes/s (%llu bytes in %s)\n"),
389         1000LL * 1000LL * traffic_sent / (1 + duration.rel_value_us),
390         traffic_sent,
391         GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
392   }
393   if (benchmark_receive)
394   {
395     duration = GNUNET_TIME_absolute_get_duration (start_time);
396     FPRINTF (stdout, _("Received %llu bytes/s (%llu bytes in %s)\n"),
397         1000LL * 1000LL * traffic_received / (1 + duration.rel_value_us),
398         traffic_received,
399         GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
400   }
401
402   if (NULL != monitored_peers)
403   {
404     GNUNET_CONTAINER_multipeermap_iterate (monitored_peers, &destroy_it, NULL);
405     GNUNET_CONTAINER_multipeermap_destroy (monitored_peers);
406     monitored_peers = NULL;
407   }
408 }
409
410 static struct PeerResolutionContext *rc_head;
411 static struct PeerResolutionContext *rc_tail;
412
413 struct PeerResolutionContext
414 {
415   struct PeerResolutionContext *next;
416   struct PeerResolutionContext *prev;
417   struct GNUNET_PeerIdentity id;
418   struct GNUNET_HELLO_Address *addrcp;
419   struct GNUNET_TRANSPORT_AddressToStringContext *asc;
420   enum GNUNET_TRANSPORT_PeerState state;
421   struct GNUNET_TIME_Absolute state_timeout;
422   char *transport;
423   int printed;
424 };
425
426
427
428 static void
429 operation_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
430 {
431   struct PeerResolutionContext *cur;
432   struct PeerResolutionContext *next;
433   op_timeout = GNUNET_SCHEDULER_NO_TASK;
434   if ((try_connect) || (benchmark_send) || (benchmark_receive))
435   {
436     FPRINTF (stdout, _("Failed to connect to `%s'\n"), GNUNET_i2s_full (&pid));
437     if (GNUNET_SCHEDULER_NO_TASK != end)
438       GNUNET_SCHEDULER_cancel (end);
439     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL );
440     ret = 1;
441     return;
442   }
443   if (iterate_connections)
444   {
445     next = rc_head;
446     while (NULL != (cur = next))
447     {
448       next = cur->next;
449       FPRINTF (stdout, _("Failed to resolve address for peer `%s'\n"),
450           GNUNET_i2s (&cur->addrcp->peer));
451
452       GNUNET_CONTAINER_DLL_remove(rc_head, rc_tail, cur);
453       GNUNET_TRANSPORT_address_to_string_cancel (cur->asc);
454       GNUNET_free(cur->transport);
455       GNUNET_free(cur->addrcp);
456       GNUNET_free(cur);
457
458     }
459     FPRINTF (stdout, "%s", _("Failed to list connections, timeout occured\n") );
460     if (GNUNET_SCHEDULER_NO_TASK != end)
461       GNUNET_SCHEDULER_cancel (end);
462     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL );
463     ret = 1;
464     return;
465   }
466
467 }
468
469 static void
470 run_nat_test ();
471
472 /**
473  * Display the result of the test.
474  *
475  * @param tc test context
476  * @param result #GNUNET_YES on success
477  */
478 static void
479 display_test_result (struct TestContext *tc, enum TestResult result)
480 {
481   switch (result) {
482     case NAT_TEST_FAIL:
483       FPRINTF (stderr, _("Configuration for plugin `%s' did not work!\n"),
484           tc->name);
485       break;
486     case NAT_TEST_SUCCESS:
487       FPRINTF (stderr, _("Configuration for plugin `%s' did work!\n"),
488           tc->name);
489       break;
490     case NAT_TEST_INTERNAL_FAIL:
491       FPRINTF (stderr, _("Internal NAT error while running test for plugin `%s'\n"),
492           tc->name);
493       break;
494     case NAT_TEST_FAILED_TO_START:
495       FPRINTF (stderr, _("Failed to start NAT test for plugin `%s'\n"),
496           tc->name);
497       break;
498     case NAT_TEST_TIMEOUT:
499       FPRINTF (stderr, _("Timeout while waiting for result of NAT test for plugin `%s'\n"),
500           tc->name);
501       break;
502     default:
503       break;
504   }
505
506   if (GNUNET_YES != result)
507   {
508     FPRINTF (stderr, "Configuration for plugin `%s' did not work!\n", tc->name);
509   }
510   else
511   {
512     FPRINTF (stderr, "Configuration for plugin `%s' is working!\n", tc->name);
513   }
514   if (GNUNET_SCHEDULER_NO_TASK != tc->tsk)
515   {
516     GNUNET_SCHEDULER_cancel (tc->tsk);
517     tc->tsk = GNUNET_SCHEDULER_NO_TASK;
518   }
519   if (NULL != tc->tst)
520   {
521     GNUNET_NAT_test_stop (tc->tst);
522     tc->tst = NULL;
523   }
524
525   GNUNET_CONTAINER_DLL_remove (head, tail, tc);
526   GNUNET_free (tc->name);
527   GNUNET_free (tc);
528
529   if ((NULL == head) && (NULL != resolver))
530   {
531     GNUNET_break(0 == GNUNET_OS_process_kill (resolver, GNUNET_TERM_SIG));
532     GNUNET_OS_process_destroy (resolver);
533     resolver = NULL;
534   }
535   if (NULL != head)
536     run_nat_test ();
537 }
538
539 /**
540  * Function called by NAT to report the outcome of the nat-test.
541  * Clean up and update GUI.
542  *
543  * @param cls test context
544  * @param success currently always #GNUNET_OK
545  * @param emsg error message, NULL on success
546  */
547 static void
548 result_callback (void *cls, enum GNUNET_NAT_FailureCode result)
549 {
550   struct TestContext *tc = cls;
551   display_test_result (tc, result);
552 }
553
554 static void
555 resolve_validation_address (const struct GNUNET_PeerIdentity *id,
556                             const struct GNUNET_HELLO_Address *address,
557                             int numeric,
558                             struct GNUNET_TIME_Absolute last_validation,
559                             struct GNUNET_TIME_Absolute valid_until,
560                             struct GNUNET_TIME_Absolute next_validation,
561                             enum GNUNET_TRANSPORT_ValidationState state);
562
563
564
565 /**
566  * Function to call with a textual representation of an address.  This
567  * function will be called several times with different possible
568  * textual representations, and a last time with @address being NULL
569  * to signal the end of the iteration.  Note that @address NULL
570  * always is the last call, regardless of the value in @a res.
571  *
572  * @param cls closure
573  * @param address NULL on end of iteration,
574  *        otherwise 0-terminated printable UTF-8 string,
575  *        in particular an empty string if @a res is #GNUNET_NO
576  * @param res result of the address to string conversion:
577  *        if #GNUNET_OK: conversion successful
578  *        if #GNUNET_NO: address was invalid (or not supported)
579  *        if #GNUNET_SYSERR: communication error (IPC error)
580  */
581 static void
582 process_validation_string (void *cls,
583                            const char *address,
584                            int res)
585 {
586   struct ValidationResolutionContext *vc = cls;
587   char *s_valid;
588   char *s_last;
589   char *s_next;
590
591   if (NULL != address)
592   {
593     if (GNUNET_SYSERR == res)
594     {
595       FPRINTF (stderr,
596                "Failed to convert address for peer `%s' plugin `%s' length %lu to string \n",
597                GNUNET_i2s (&vc->id),
598                vc->addrcp->transport_name,
599                vc->addrcp->address_length);
600     }
601     if (GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us == vc->valid_until.abs_value_us)
602       s_valid = GNUNET_strdup ("never");
603     else
604       s_valid = GNUNET_strdup (GNUNET_STRINGS_absolute_time_to_string (vc->valid_until));
605
606     if (GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us == vc->last_validation.abs_value_us)
607       s_last = GNUNET_strdup ("never");
608     else
609       s_last = GNUNET_strdup (GNUNET_STRINGS_absolute_time_to_string (vc->last_validation));
610
611     if (GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us == vc->next_validation.abs_value_us)
612       s_next = GNUNET_strdup ("never");
613     else
614       s_next = GNUNET_strdup (GNUNET_STRINGS_absolute_time_to_string (vc->next_validation));
615
616     FPRINTF (stdout,
617              _("Peer `%s' %s %s\n\t%s%s\n\t%s%s\n\t%s%s\n"),
618              GNUNET_i2s (&vc->id),
619              (GNUNET_OK == res) ? address : "<invalid address>",
620              (monitor_validation) ? GNUNET_TRANSPORT_vs2s (vc->state) : "",
621              "Valid until    : ", s_valid,
622              "Last validation: ",s_last,
623              "Next validation: ", s_next);
624     GNUNET_free (s_valid);
625     GNUNET_free (s_last);
626     GNUNET_free (s_next);
627     vc->printed = GNUNET_YES;
628     return;
629   }
630   /* last call, we are done */
631   GNUNET_assert (address_resolutions > 0);
632   address_resolutions--;
633   if ( (GNUNET_SYSERR == res) &&
634        (GNUNET_NO == vc->printed) )
635   {
636     if (numeric == GNUNET_NO)
637     {
638       /* Failed to resolve address, try numeric lookup
639          (note: this should be unnecessary, as
640          transport should fallback to numeric lookup
641          internally if DNS takes too long anyway) */
642       resolve_validation_address (&vc->id,
643                                   vc->addrcp,
644                                   GNUNET_NO,
645                                   vc->last_validation,
646                                   vc->valid_until,
647                                   vc->next_validation,
648                                   vc->state);
649     }
650     else
651     {
652       FPRINTF (stdout,
653                _("Peer `%s' %s `%s' \n"),
654                GNUNET_i2s (&vc->id),
655                "<unable to resolve address>",
656                GNUNET_TRANSPORT_vs2s (vc->state));
657     }
658   }
659   GNUNET_free (vc->transport);
660   GNUNET_free (vc->addrcp);
661   GNUNET_CONTAINER_DLL_remove (vc_head, vc_tail, vc);
662   GNUNET_free (vc);
663   if ((0 == address_resolutions) && (iterate_validation))
664   {
665     if (GNUNET_SCHEDULER_NO_TASK != end)
666     {
667       GNUNET_SCHEDULER_cancel (end);
668       end = GNUNET_SCHEDULER_NO_TASK;
669     }
670     if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
671     {
672       GNUNET_SCHEDULER_cancel (op_timeout);
673       op_timeout = GNUNET_SCHEDULER_NO_TASK;
674     }
675     ret = 0;
676     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
677   }
678 }
679
680
681
682 static void
683 resolve_validation_address (const struct GNUNET_PeerIdentity *id,
684                             const struct GNUNET_HELLO_Address *address,
685                             int numeric,
686                             struct GNUNET_TIME_Absolute last_validation,
687                             struct GNUNET_TIME_Absolute valid_until,
688                             struct GNUNET_TIME_Absolute next_validation,
689                             enum GNUNET_TRANSPORT_ValidationState state)
690 {
691   struct ValidationResolutionContext *vc;
692
693   vc = GNUNET_new (struct ValidationResolutionContext);
694   GNUNET_assert(NULL != vc);
695   GNUNET_CONTAINER_DLL_insert(vc_head, vc_tail, vc);
696   address_resolutions++;
697
698   vc->id = (*id);
699   vc->transport = GNUNET_strdup(address->transport_name);
700   vc->addrcp = GNUNET_HELLO_address_copy (address);
701   vc->printed = GNUNET_NO;
702   vc->state = state;
703   vc->last_validation = last_validation;
704   vc->valid_until = valid_until;
705   vc->next_validation = next_validation;
706
707   /* Resolve address to string */
708   vc->asc = GNUNET_TRANSPORT_address_to_string (cfg,
709                                                 address,
710                                                 numeric,
711                                                 RESOLUTION_TIMEOUT,
712                                                 &process_validation_string, vc);
713 }
714
715
716 static void
717 process_validation_cb (void *cls,
718                        const struct GNUNET_PeerIdentity *peer,
719                        const struct GNUNET_HELLO_Address *address,
720                        struct GNUNET_TIME_Absolute last_validation,
721                        struct GNUNET_TIME_Absolute valid_until,
722                        struct GNUNET_TIME_Absolute next_validation,
723                        enum GNUNET_TRANSPORT_ValidationState state)
724 {
725   if ((NULL == peer) && (NULL == address))
726   {
727     if (monitor_validation)
728     {
729       FPRINTF (stdout,
730                "%s",
731                _("Monitor disconnected from transport service. Reconnecting.\n"));
732       return;
733     }
734
735     /* done */
736     vic = NULL;
737     if (GNUNET_SCHEDULER_NO_TASK != end)
738       GNUNET_SCHEDULER_cancel (end);
739     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL );
740     return;
741   }
742   if ((NULL == peer) || (NULL == address))
743   {
744     /* invalid response */
745     vic = NULL;
746     if (GNUNET_SCHEDULER_NO_TASK != end)
747       GNUNET_SCHEDULER_cancel (end);
748     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL );
749     return;
750   }
751   resolve_validation_address (peer, address,
752      numeric, last_validation,
753      valid_until, next_validation, state);
754 }
755
756
757 static void
758 run_nat_test ()
759 {
760   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
761       "Running test for plugin `%s' using bind port %u and advertised port %u \n",
762       head->name, (uint16_t) head->bnd_port, (uint16_t) head->adv_port);
763
764   head->tst = GNUNET_NAT_test_start (cfg,
765       (0 == strcasecmp (head->name, "udp")) ? GNUNET_NO : GNUNET_YES,
766       (uint16_t) head->bnd_port,
767       (uint16_t) head->adv_port,
768       TIMEOUT,
769       &result_callback, head);
770 }
771
772
773 /**
774  * Test our plugin's configuration (NAT traversal, etc.).
775  *
776  * @param cfg configuration to test
777  */
778 static void
779 do_test_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
780 {
781   char *plugins;
782   char *tok;
783   unsigned long long bnd_port;
784   unsigned long long adv_port;
785   struct TestContext *tc;
786   char *binary;
787
788   if (GNUNET_OK
789       != GNUNET_CONFIGURATION_get_value_string (cfg, "transport", "plugins",
790           &plugins))
791   {
792     FPRINTF (stderr, "%s", _
793     ("No transport plugins configured, peer will never communicate\n") );
794     ret = 4;
795     return;
796   }
797
798   for (tok = strtok (plugins, " "); tok != NULL ; tok = strtok (NULL, " "))
799   {
800     char section[12 + strlen (tok)];
801     GNUNET_snprintf (section, sizeof(section), "transport-%s", tok);
802     if (GNUNET_OK
803         != GNUNET_CONFIGURATION_get_value_number (cfg, section, "PORT",
804             &bnd_port))
805     {
806       FPRINTF (stderr,
807           _("No port configured for plugin `%s', cannot test it\n"), tok);
808       continue;
809     }
810     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, section,
811             "ADVERTISED_PORT", &adv_port))
812       adv_port = bnd_port;
813
814     tc = GNUNET_new (struct TestContext);
815     tc->name = GNUNET_strdup (tok);
816     tc->adv_port = adv_port;
817     tc->bnd_port = bnd_port;
818     GNUNET_CONTAINER_DLL_insert_tail (head, tail, tc);
819   }
820   GNUNET_free(plugins);
821
822   if ((NULL != head) && (NULL == resolver))
823   {
824     binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-resolver");
825     resolver = GNUNET_OS_start_process (GNUNET_YES,
826                                         GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
827                                         NULL, NULL, NULL,
828                                         binary,
829                                         "gnunet-service-resolver", NULL );
830     if (NULL == resolver)
831     {
832       FPRINTF (stderr, _("Failed to start resolver!\n"));
833       return;
834     }
835
836     GNUNET_free(binary);
837     GNUNET_RESOLVER_connect (cfg);
838     run_nat_test ();
839   }
840 }
841
842 /**
843  * Function called to notify a client about the socket
844  * begin ready to queue more data.  @a buf will be
845  * NULL and @a size zero if the socket was closed for
846  * writing in the meantime.
847  *
848  * @param cls closure
849  * @param size number of bytes available in @a buf
850  * @param buf where the callee should write the message
851  * @return number of bytes written to @a buf
852  */
853 static size_t
854 transmit_data (void *cls, size_t size, void *buf)
855 {
856   struct GNUNET_MessageHeader *m = buf;
857
858   if ((NULL == buf) || (0 == size))
859   {
860     th = NULL;
861     return 0;
862   }
863
864   GNUNET_assert(size >= sizeof(struct GNUNET_MessageHeader));
865   GNUNET_assert(size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
866   m->size = ntohs (size);
867   m->type = ntohs (GNUNET_MESSAGE_TYPE_DUMMY);
868   memset (&m[1], 52, size - sizeof(struct GNUNET_MessageHeader));
869   traffic_sent += size;
870   th = GNUNET_TRANSPORT_notify_transmit_ready (handle, &pid,
871                                                BLOCKSIZE * 1024,
872                                                GNUNET_TIME_UNIT_FOREVER_REL,
873                                                &transmit_data, NULL );
874   if (verbosity > 0)
875     FPRINTF (stdout, _("Transmitting %u bytes to %s\n"), (unsigned int) size,
876         GNUNET_i2s (&pid));
877   return size;
878 }
879
880
881 /**
882  * Function called to notify transport users that another
883  * peer connected to us.
884  *
885  * @param cls closure
886  * @param peer the peer that connected
887  */
888 static void
889 notify_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
890 {
891   if (0 != memcmp (&pid, peer, sizeof(struct GNUNET_PeerIdentity)))
892     return;
893   ret = 0;
894   if (try_connect)
895   {
896     /* all done, terminate instantly */
897     FPRINTF (stdout, _("Successfully connected to `%s'\n"),
898         GNUNET_i2s_full (peer));
899     ret = 0;
900
901     if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
902     {
903       GNUNET_SCHEDULER_cancel (op_timeout);
904       op_timeout = GNUNET_SCHEDULER_NO_TASK;
905     }
906
907     if (GNUNET_SCHEDULER_NO_TASK != end)
908       GNUNET_SCHEDULER_cancel (end);
909     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL );
910     return;
911   }
912   if (benchmark_send)
913   {
914     if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
915     {
916       GNUNET_SCHEDULER_cancel (op_timeout);
917       op_timeout = GNUNET_SCHEDULER_NO_TASK;
918     }
919     if (verbosity > 0)
920       FPRINTF (stdout,
921           _("Successfully connected to `%s', starting to send benchmark data in %u Kb blocks\n"),
922           GNUNET_i2s (&pid), BLOCKSIZE);
923     start_time = GNUNET_TIME_absolute_get ();
924     if (NULL == th)
925       th = GNUNET_TRANSPORT_notify_transmit_ready (handle, peer,
926                                                    BLOCKSIZE * 1024,
927                                                    GNUNET_TIME_UNIT_FOREVER_REL,
928                                                    &transmit_data,
929                                                    NULL);
930     else
931       GNUNET_break(0);
932     return;
933   }
934 }
935
936 /**
937  * Function called to notify transport users that another
938  * peer disconnected from us.
939  *
940  * @param cls closure
941  * @param peer the peer that disconnected
942  */
943 static void
944 notify_disconnect (void *cls,
945                    const struct GNUNET_PeerIdentity *peer)
946 {
947   if (0 != memcmp (&pid, peer, sizeof(struct GNUNET_PeerIdentity)))
948     return;
949
950   if (try_disconnect)
951   {
952     /* all done, terminate instantly */
953     FPRINTF (stdout, _("Successfully disconnected from `%s'\n"),
954         GNUNET_i2s_full (peer));
955     ret = 0;
956
957     if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
958     {
959       GNUNET_SCHEDULER_cancel (op_timeout);
960       op_timeout = GNUNET_SCHEDULER_NO_TASK;
961     }
962
963     if (GNUNET_SCHEDULER_NO_TASK != end)
964       GNUNET_SCHEDULER_cancel (end);
965     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL );
966     return;
967   }
968
969   if (NULL != th)
970   {
971     GNUNET_TRANSPORT_notify_transmit_ready_cancel (th);
972     th = NULL;
973   }
974   if (benchmark_send)
975   {
976     FPRINTF (stdout, _("Disconnected from peer `%s' while benchmarking\n"),
977         GNUNET_i2s (&pid));
978     if (GNUNET_SCHEDULER_NO_TASK != end)
979       GNUNET_SCHEDULER_cancel (end);
980     return;
981   }
982 }
983
984 /**
985  * Function called to notify transport users that another
986  * peer connected to us.
987  *
988  * @param cls closure
989  * @param peer the peer that connected
990  */
991 static void
992 monitor_notify_connect (void *cls,
993                         const struct GNUNET_PeerIdentity *peer)
994 {
995   monitor_connect_counter++;
996   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
997   const char *now_str = GNUNET_STRINGS_absolute_time_to_string (now);
998
999   FPRINTF (stdout,
1000            _("%24s: %-17s %4s   (%u connections in total)\n"),
1001            now_str,
1002            _("Connected to"),
1003            GNUNET_i2s (peer),
1004            monitor_connect_counter);
1005 }
1006
1007
1008 /**
1009  * Function called to notify transport users that another
1010  * peer disconnected from us.
1011  *
1012  * @param cls closure
1013  * @param peer the peer that disconnected
1014  */
1015 static void
1016 monitor_notify_disconnect (void *cls,
1017                            const struct GNUNET_PeerIdentity *peer)
1018 {
1019   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1020   const char *now_str = GNUNET_STRINGS_absolute_time_to_string (now);
1021
1022   GNUNET_assert(monitor_connect_counter > 0);
1023   monitor_connect_counter--;
1024
1025   FPRINTF (stdout,
1026            _("%24s: %-17s %4s   (%u connections in total)\n"),
1027            now_str,
1028            _("Disconnected from"),
1029            GNUNET_i2s (peer),
1030            monitor_connect_counter);
1031 }
1032
1033
1034 /**
1035  * Function called by the transport for each received message.
1036  *
1037  * @param cls closure
1038  * @param peer (claimed) identity of the other peer
1039  * @param message the message
1040  */
1041 static void
1042 notify_receive (void *cls,
1043                 const struct GNUNET_PeerIdentity *peer,
1044                 const struct GNUNET_MessageHeader *message)
1045 {
1046   if (benchmark_receive)
1047   {
1048     if (GNUNET_MESSAGE_TYPE_DUMMY != ntohs (message->type))
1049       return;
1050     if (verbosity > 0)
1051       FPRINTF (stdout,
1052                _("Received %u bytes from %s\n"),
1053                (unsigned int) ntohs (message->size),
1054                GNUNET_i2s (peer));
1055
1056     if (traffic_received == 0)
1057       start_time = GNUNET_TIME_absolute_get ();
1058     traffic_received += ntohs (message->size);
1059     return;
1060   }
1061 }
1062
1063
1064 static void
1065 resolve_peer_address (const struct GNUNET_PeerIdentity *id,
1066                       const struct GNUNET_HELLO_Address *address,
1067                       int numeric,
1068                       enum GNUNET_TRANSPORT_PeerState state,
1069                       struct GNUNET_TIME_Absolute state_timeout);
1070
1071
1072 static void
1073 print_info (const struct GNUNET_PeerIdentity *id,
1074             const char *transport,
1075             const char *addr,
1076             enum GNUNET_TRANSPORT_PeerState state,
1077             struct GNUNET_TIME_Absolute state_timeout)
1078 {
1079
1080   if ( ((GNUNET_YES == iterate_connections) && (GNUNET_YES == iterate_all)) ||
1081        (GNUNET_YES == monitor_connections) )
1082   {
1083     FPRINTF (stdout,
1084              _("Peer `%s': %s %s in state `%s' until %s\n"),
1085              GNUNET_i2s (id),
1086              (NULL == transport) ? "<none>" : transport,
1087              (NULL == transport) ? "<none>" : addr,
1088              GNUNET_TRANSPORT_ps2s (state),
1089              GNUNET_STRINGS_absolute_time_to_string (state_timeout));
1090   }
1091   else if ( (GNUNET_YES == iterate_connections) &&
1092              (GNUNET_TRANSPORT_is_connected(state)) )
1093   {
1094     /* Only connected peers, skip state */
1095     FPRINTF (stdout,
1096              _("Peer `%s': %s %s\n"),
1097              GNUNET_i2s (id),
1098              transport,
1099              addr);
1100   }
1101 }
1102
1103
1104 /**
1105  * Function called with a textual representation of an address.  This
1106  * function will be called several times with different possible
1107  * textual representations, and a last time with @address being NULL
1108  * to signal the end of the iteration.  Note that @address NULL
1109  * always is the last call, regardless of the value in @a res.
1110  *
1111  * @param cls closure
1112  * @param address NULL on end of iteration,
1113  *        otherwise 0-terminated printable UTF-8 string,
1114  *        in particular an empty string if @a res is #GNUNET_NO
1115  * @param res result of the address to string conversion:
1116  *        if #GNUNET_OK: conversion successful
1117  *        if #GNUNET_NO: address was invalid (or not supported)
1118  *        if #GNUNET_SYSERR: communication error (IPC error)
1119  */
1120 static void
1121 process_peer_string (void *cls,
1122                      const char *address,
1123                      int res)
1124 {
1125   struct PeerResolutionContext *rc = cls;
1126
1127   if (NULL != address)
1128   {
1129     if (GNUNET_SYSERR == res)
1130     {
1131       FPRINTF (stderr,
1132                "Failed to convert address for peer `%s' plugin `%s' length %lu to string \n",
1133                GNUNET_i2s (&rc->id),
1134                rc->addrcp->transport_name,
1135                rc->addrcp->address_length);
1136       print_info (&rc->id,
1137                   rc->transport,
1138                   NULL,
1139                   rc->state,
1140                   rc->state_timeout);
1141       rc->printed = GNUNET_YES;
1142       return;
1143     }
1144     if (GNUNET_OK == res)
1145     {
1146       print_info (&rc->id,
1147                   rc->transport,
1148                   address,
1149                   rc->state,
1150                   rc->state_timeout);
1151       rc->printed = GNUNET_YES;
1152       return; /* Wait for done call */
1153     }
1154     /* GNUNET_NO == res: ignore, was simply not supported */
1155     return;
1156   }
1157   /* NULL == address, last call, we are done */
1158
1159   GNUNET_assert (address_resolutions > 0);
1160   address_resolutions--;
1161   if (GNUNET_NO == rc->printed)
1162   {
1163     if (numeric == GNUNET_NO)
1164     {
1165       /* Failed to resolve address, try numeric lookup
1166          (note: this should not be needed, as transport
1167          should fallback to numeric conversion if DNS takes
1168          too long) */
1169       resolve_peer_address (&rc->id,
1170                             rc->addrcp,
1171                             GNUNET_YES,
1172                             rc->state,
1173                             rc->state_timeout);
1174     }
1175     else
1176     {
1177       print_info (&rc->id,
1178                   rc->transport,
1179                   NULL,
1180                   rc->state,
1181                   rc->state_timeout);
1182     }
1183   }
1184   GNUNET_free (rc->transport);
1185   GNUNET_free (rc->addrcp);
1186   GNUNET_CONTAINER_DLL_remove (rc_head, rc_tail, rc);
1187   GNUNET_free (rc);
1188   if ((0 == address_resolutions) && (iterate_connections))
1189   {
1190     if (GNUNET_SCHEDULER_NO_TASK != end)
1191     {
1192       GNUNET_SCHEDULER_cancel (end);
1193       end = GNUNET_SCHEDULER_NO_TASK;
1194     }
1195     if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
1196     {
1197       GNUNET_SCHEDULER_cancel (op_timeout);
1198       op_timeout = GNUNET_SCHEDULER_NO_TASK;
1199     }
1200     ret = 0;
1201     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL );
1202   }
1203 }
1204
1205
1206 static void
1207 resolve_peer_address (const struct GNUNET_PeerIdentity *id,
1208                       const struct GNUNET_HELLO_Address *address,
1209                       int numeric,
1210                       enum GNUNET_TRANSPORT_PeerState state,
1211                       struct GNUNET_TIME_Absolute state_timeout)
1212 {
1213   struct PeerResolutionContext *rc;
1214
1215   rc = GNUNET_new (struct PeerResolutionContext);
1216   GNUNET_assert(NULL != rc);
1217   GNUNET_CONTAINER_DLL_insert(rc_head, rc_tail, rc);
1218   address_resolutions++;
1219
1220   rc->id = (*id);
1221   rc->transport = GNUNET_strdup(address->transport_name);
1222   rc->addrcp = GNUNET_HELLO_address_copy (address);
1223   rc->printed = GNUNET_NO;
1224   rc->state = state;
1225   rc->state_timeout = state_timeout;
1226   /* Resolve address to string */
1227   rc->asc = GNUNET_TRANSPORT_address_to_string (cfg,
1228                                                 address,
1229                                                 numeric,
1230                                                 RESOLUTION_TIMEOUT,
1231                                                 &process_peer_string, rc);
1232 }
1233
1234
1235 /**
1236  * Function called with information about a peers during a one shot iteration
1237  *
1238  * @param cls closure
1239  * @param peer identity of the peer, NULL for final callback when operation done
1240  * @param address binary address used to communicate with this peer,
1241  *  NULL on disconnect or when done
1242  * @param state current state this peer is in
1243  * @param state_timeout time out for the current state
1244  */
1245 static void
1246 process_peer_iteration_cb (void *cls,
1247                            const struct GNUNET_PeerIdentity *peer,
1248                            const struct GNUNET_HELLO_Address *address,
1249                            enum GNUNET_TRANSPORT_PeerState state,
1250                            struct GNUNET_TIME_Absolute state_timeout)
1251 {
1252   if (NULL == peer)
1253   {
1254     /* done */
1255     address_resolution_in_progress = GNUNET_NO;
1256     pic = NULL;
1257     if (GNUNET_SCHEDULER_NO_TASK != end)
1258       GNUNET_SCHEDULER_cancel (end);
1259     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL );
1260     return;
1261   }
1262
1263   if ( (GNUNET_NO == iterate_all) &&
1264        (GNUNET_NO == GNUNET_TRANSPORT_is_connected(state)) )
1265       return; /* Display only connected peers */
1266
1267   if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
1268     GNUNET_SCHEDULER_cancel (op_timeout);
1269   op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT,
1270                                              &operation_timeout,
1271                                              NULL);
1272
1273   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1274               "Received address for peer `%s': %s\n",
1275               GNUNET_i2s (peer),
1276               address->transport_name);
1277
1278   if (NULL != address)
1279     resolve_peer_address (peer, address, numeric, state, state_timeout);
1280   else
1281     print_info (peer, NULL, NULL, state, state_timeout);
1282 }
1283
1284
1285 /**
1286  * Function called with information about a peers
1287  *
1288  * @param cls closure
1289  * @param peer identity of the peer, NULL for final callback when operation done
1290  * @param address binary address used to communicate with this peer,
1291  *  NULL on disconnect or when done
1292  * @param state current state this peer is in
1293  * @param state_timeout time out for the current state
1294  *
1295  */
1296 static void
1297 process_peer_monitoring_cb (void *cls,
1298                             const struct GNUNET_PeerIdentity *peer,
1299                             const struct GNUNET_HELLO_Address *address,
1300                             enum GNUNET_TRANSPORT_PeerState state,
1301                             struct GNUNET_TIME_Absolute state_timeout)
1302 {
1303   struct MonitoredPeer *m;
1304
1305   if (NULL == peer)
1306   {
1307     FPRINTF (stdout,
1308              "%s",
1309              _("Monitor disconnected from transport service. Reconnecting.\n"));
1310     return;
1311   }
1312
1313   if (GNUNET_SCHEDULER_NO_TASK != op_timeout)
1314     GNUNET_SCHEDULER_cancel (op_timeout);
1315   op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT,
1316                                              &operation_timeout,
1317                                              NULL);
1318
1319   if (NULL == (m = GNUNET_CONTAINER_multipeermap_get (monitored_peers, peer)))
1320   {
1321     m = GNUNET_new (struct MonitoredPeer);
1322     GNUNET_CONTAINER_multipeermap_put (monitored_peers, peer,
1323         m, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1324   }
1325   else
1326   {
1327     if ( (m->state == state) &&
1328       (m->state_timeout.abs_value_us == state_timeout.abs_value_us) &&
1329       ((NULL == address) && (NULL == m->address)) )
1330     {
1331       return; /* No real change */
1332     }
1333     if ( (m->state == state) && ((NULL != address) && (NULL != m->address)) &&
1334         (0 == GNUNET_HELLO_address_cmp(m->address, address)) )
1335       return; /* No real change */
1336   }
1337
1338   if (NULL != m->address)
1339   {
1340     GNUNET_free (m->address);
1341     m->address = NULL;
1342   }
1343   if (NULL != address)
1344     m->address = GNUNET_HELLO_address_copy (address);
1345   m->state = state;
1346   m->state_timeout = state_timeout;
1347
1348   if (NULL != address)
1349     resolve_peer_address (peer,
1350                           m->address,
1351                           numeric,
1352                           m->state,
1353                           m->state_timeout);
1354   else
1355     print_info (peer,
1356                 NULL,
1357                 NULL,
1358                 m->state,
1359                 m->state_timeout);
1360 }
1361
1362
1363 static void
1364 try_connect_cb (void *cls,
1365                 const int result)
1366 {
1367   static int retries = 0;
1368
1369   if (GNUNET_OK == result)
1370   {
1371     tc_handle = NULL;
1372     return;
1373   }
1374   retries++;
1375   if (retries < 10)
1376     tc_handle = GNUNET_TRANSPORT_try_connect (handle, &pid, try_connect_cb,
1377         NULL );
1378   else
1379   {
1380     FPRINTF (stderr,
1381              "%s",
1382              _("Failed to send connect request to transport service\n") );
1383     if (GNUNET_SCHEDULER_NO_TASK != end)
1384       GNUNET_SCHEDULER_cancel (end);
1385     ret = 1;
1386     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL );
1387     return;
1388   }
1389 }
1390
1391
1392 static void
1393 try_disconnect_cb (void *cls,
1394                    const int result)
1395 {
1396   static int retries = 0;
1397   if (GNUNET_OK == result)
1398   {
1399     tc_handle = NULL;
1400     return;
1401   }
1402   retries++;
1403   if (retries < 10)
1404     tc_handle = GNUNET_TRANSPORT_try_disconnect (handle, &pid, try_disconnect_cb,
1405         NULL );
1406   else
1407   {
1408     FPRINTF (stderr, "%s",
1409         _("Failed to send connect request to transport service\n") );
1410     if (GNUNET_SCHEDULER_NO_TASK != end)
1411       GNUNET_SCHEDULER_cancel (end);
1412     ret = 1;
1413     end = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL );
1414     return;
1415   }
1416 }
1417
1418
1419 /**
1420  * Function called with the result of the check if the 'transport'
1421  * service is running.
1422  *
1423  * @param cls closure with our configuration
1424  * @param result #GNUNET_YES if transport is running
1425  */
1426 static void
1427 testservice_task (void *cls, int result)
1428 {
1429   int counter = 0;
1430   ret = 1;
1431
1432   if (GNUNET_YES != result)
1433   {
1434     FPRINTF (stderr, _("Service `%s' is not running\n"), "transport");
1435     return;
1436   }
1437
1438   if ((NULL != cpid)
1439       && (GNUNET_OK
1440           != GNUNET_CRYPTO_eddsa_public_key_from_string (cpid, strlen (cpid),
1441               &pid.public_key)))
1442   {
1443     FPRINTF (stderr, _("Failed to parse peer identity `%s'\n"), cpid);
1444     return;
1445   }
1446
1447   counter = benchmark_send + benchmark_receive + iterate_connections
1448       + monitor_connections + monitor_connects + try_connect + try_disconnect +
1449       + iterate_validation + monitor_validation;
1450
1451   if (1 < counter)
1452   {
1453     FPRINTF (stderr,
1454         _("Multiple operations given. Please choose only one operation: %s, %s, %s, %s, %s, %s\n"),
1455         "connect", "benchmark send", "benchmark receive", "information",
1456         "monitor", "events");
1457     return;
1458   }
1459   if (0 == counter)
1460   {
1461     FPRINTF (stderr,
1462         _("No operation given. Please choose one operation: %s, %s, %s, %s, %s, %s\n"),
1463         "connect", "benchmark send", "benchmark receive", "information",
1464         "monitor", "events");
1465     return;
1466   }
1467
1468   if (try_connect) /* -C: Connect to peer */
1469   {
1470     if (NULL == cpid)
1471     {
1472       FPRINTF (stderr, _("Option `%s' makes no sense without option `%s'.\n"),
1473           "-C", "-p");
1474       ret = 1;
1475       return;
1476     }
1477     handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive,
1478         &notify_connect, &notify_disconnect);
1479     if (NULL == handle)
1480     {
1481       FPRINTF (stderr, "%s", _("Failed to connect to transport service\n") );
1482       ret = 1;
1483       return;
1484     }
1485     tc_handle = GNUNET_TRANSPORT_try_connect (handle, &pid, try_connect_cb,
1486         NULL );
1487     if (NULL == tc_handle)
1488     {
1489       FPRINTF (stderr, "%s",
1490           _("Failed to send request to transport service\n") );
1491       ret = 1;
1492       return;
1493     }
1494     op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT, &operation_timeout,
1495         NULL );
1496
1497   }
1498   else if (try_disconnect) /* -D: Disconnect from peer */
1499   {
1500     if (NULL == cpid)
1501     {
1502       FPRINTF (stderr, _("Option `%s' makes no sense without option `%s'.\n"),
1503           "-D", "-p");
1504       ret = 1;
1505       return;
1506     }
1507     handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive,
1508         &notify_connect, &notify_disconnect);
1509     if (NULL == handle)
1510     {
1511       FPRINTF (stderr, "%s", _("Failed to connect to transport service\n") );
1512       ret = 1;
1513       return;
1514     }
1515     tc_handle = GNUNET_TRANSPORT_try_disconnect (handle, &pid, try_disconnect_cb,
1516         NULL );
1517     if (NULL == tc_handle)
1518     {
1519       FPRINTF (stderr, "%s",
1520           _("Failed to send request to transport service\n") );
1521       ret = 1;
1522       return;
1523     }
1524     op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT, &operation_timeout,
1525         NULL );
1526
1527   }
1528   else if (benchmark_send) /* -s: Benchmark sending */
1529   {
1530     if (NULL == cpid)
1531     {
1532       FPRINTF (stderr, _("Option `%s' makes no sense without option `%s'.\n"),
1533           "-s", "-p");
1534       ret = 1;
1535       return;
1536     }
1537     handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive,
1538         &notify_connect, &notify_disconnect);
1539     if (NULL == handle)
1540     {
1541       FPRINTF (stderr, "%s", _("Failed to connect to transport service\n") );
1542       ret = 1;
1543       return;
1544     }
1545     tc_handle = GNUNET_TRANSPORT_try_connect (handle, &pid, try_connect_cb,
1546         NULL );
1547     if (NULL == tc_handle)
1548     {
1549       FPRINTF (stderr, "%s",
1550           _("Failed to send request to transport service\n") );
1551       ret = 1;
1552       return;
1553     }
1554     start_time = GNUNET_TIME_absolute_get ();
1555     op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT, &operation_timeout,
1556         NULL );
1557   }
1558   else if (benchmark_receive) /* -b: Benchmark receiving */
1559   {
1560     handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL, &notify_receive, NULL,
1561         NULL );
1562     if (NULL == handle)
1563     {
1564       FPRINTF (stderr, "%s", _("Failed to connect to transport service\n") );
1565       ret = 1;
1566       return;
1567     }
1568     if (verbosity > 0)
1569       FPRINTF (stdout, "%s", _("Starting to receive benchmark data\n") );
1570     start_time = GNUNET_TIME_absolute_get ();
1571
1572   }
1573   else if (iterate_connections) /* -i: List information about peers once */
1574   {
1575     address_resolution_in_progress = GNUNET_YES;
1576     pic = GNUNET_TRANSPORT_monitor_peers (cfg, (NULL == cpid) ? NULL : &pid,
1577         GNUNET_YES, TIMEOUT, &process_peer_iteration_cb, (void *) cfg);
1578     op_timeout = GNUNET_SCHEDULER_add_delayed (OP_TIMEOUT, &operation_timeout,
1579         NULL );
1580   }
1581   else if (monitor_connections) /* -m: List information about peers continuously */
1582   {
1583     monitored_peers = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1584     address_resolution_in_progress = GNUNET_YES;
1585     pic = GNUNET_TRANSPORT_monitor_peers (cfg, (NULL == cpid) ? NULL : &pid,
1586         GNUNET_NO, TIMEOUT, &process_peer_monitoring_cb, (void *) cfg);
1587   }
1588   else if (iterate_validation) /* -d: Print information about validations */
1589   {
1590     vic = GNUNET_TRANSPORT_monitor_validation_entries (cfg,
1591         (NULL == cpid) ? NULL : &pid,
1592         GNUNET_YES, TIMEOUT, &process_validation_cb, (void *) cfg);
1593   }
1594   else if (monitor_validation) /* -f: Print information about validations continuously */
1595   {
1596     vic = GNUNET_TRANSPORT_monitor_validation_entries (cfg,
1597         (NULL == cpid) ? NULL : &pid,
1598         GNUNET_NO, TIMEOUT, &process_validation_cb, (void *) cfg);
1599   }
1600   else if (monitor_connects) /* -e : Monitor (dis)connect events continuously */
1601   {
1602     monitor_connect_counter = 0;
1603     handle = GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL,
1604                                        &monitor_notify_connect,
1605                                        &monitor_notify_disconnect);
1606     if (NULL == handle)
1607     {
1608       FPRINTF (stderr, "%s", _("Failed to connect to transport service\n") );
1609       ret = 1;
1610       return;
1611     }
1612     ret = 0;
1613   }
1614   else
1615   {
1616     GNUNET_break(0);
1617     return;
1618   }
1619
1620   end = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1621       &shutdown_task, NULL );
1622
1623 }
1624
1625 /**
1626  * Main function that will be run by the scheduler.
1627  *
1628  * @param cls closure
1629  * @param args remaining command-line arguments
1630  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1631  * @param mycfg configuration
1632  */
1633 static void
1634 run (void *cls, char * const *args, const char *cfgfile,
1635     const struct GNUNET_CONFIGURATION_Handle *mycfg)
1636 {
1637   cfg = (struct GNUNET_CONFIGURATION_Handle *) mycfg;
1638   if (test_configuration)
1639   {
1640     do_test_configuration (cfg);
1641     return;
1642   }
1643   GNUNET_CLIENT_service_test ("transport", cfg, GNUNET_TIME_UNIT_SECONDS,
1644       &testservice_task, (void *) cfg);
1645 }
1646
1647 int
1648 main (int argc, char * const *argv)
1649 {
1650   int res;
1651   static const struct GNUNET_GETOPT_CommandLineOption options[] =
1652       {
1653           { 'a', "all", NULL,
1654               gettext_noop ("print information for all peers (instead of only connected peers )"),
1655               0, &GNUNET_GETOPT_set_one, &iterate_all },
1656           { 'b', "benchmark", NULL,
1657               gettext_noop ("measure how fast we are receiving data from all peers (until CTRL-C)"),
1658               0, &GNUNET_GETOPT_set_one, &benchmark_receive },
1659           { 'C', "connect",
1660               NULL, gettext_noop ("connect to a peer"), 0,
1661               &GNUNET_GETOPT_set_one, &try_connect },
1662           { 'D', "disconnect",
1663               NULL, gettext_noop ("disconnect to a peer"), 0,
1664               &GNUNET_GETOPT_set_one, &try_disconnect },
1665           { 'd', "validation", NULL,
1666               gettext_noop ("print information for all pending validations "),
1667               0, &GNUNET_GETOPT_set_one, &iterate_validation },
1668           { 'f', "monitorvalidation", NULL,
1669               gettext_noop ("print information for all pending validations continously"),
1670               0, &GNUNET_GETOPT_set_one, &monitor_validation },
1671           { 'i', "information", NULL,
1672               gettext_noop ("provide information about all current connections (once)"),
1673               0, &GNUNET_GETOPT_set_one, &iterate_connections },
1674           { 'm', "monitor", NULL,
1675               gettext_noop ("provide information about all current connections (continuously)"),
1676               0, &GNUNET_GETOPT_set_one, &monitor_connections },
1677           { 'e', "events", NULL,
1678               gettext_noop ("provide information about all connects and disconnect events (continuously)"),
1679               0, &GNUNET_GETOPT_set_one, &monitor_connects }, { 'n', "numeric",
1680               NULL, gettext_noop ("do not resolve hostnames"), 0,
1681               &GNUNET_GETOPT_set_one, &numeric }, { 'p', "peer", "PEER",
1682               gettext_noop ("peer identity"), 1, &GNUNET_GETOPT_set_string,
1683               &cpid }, { 's', "send", NULL, gettext_noop
1684           ("send data for benchmarking to the other peer (until CTRL-C)"), 0,
1685               &GNUNET_GETOPT_set_one, &benchmark_send },
1686           { 't', "test", NULL,
1687               gettext_noop ("test transport configuration (involves external server)"),
1688               0, &GNUNET_GETOPT_set_one, &test_configuration },
1689               GNUNET_GETOPT_OPTION_VERBOSE (&verbosity),
1690               GNUNET_GETOPT_OPTION_END };
1691
1692   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1693     return 2;
1694
1695   res = GNUNET_PROGRAM_run (argc, argv, "gnunet-transport", gettext_noop
1696   ("Direct access to transport service."), options, &run, NULL );
1697   GNUNET_free((void * ) argv);
1698   if (GNUNET_OK == res)
1699     return ret;
1700   return 1;
1701 }
1702
1703 /* end of gnunet-transport.c */