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