glitch in the license text detected by hyazinthe, thank you!
[oweals/gnunet.git] / src / cadet / test_cadet.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011, 2017 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14 */
15 /**
16  * @file cadet/test_cadet.c
17  * @author Bart Polot
18  * @author Christian Grothoff
19  * @brief Test for the cadet service using mq API.
20  */
21 #include <stdio.h>
22 #include "platform.h"
23 #include "cadet_test_lib.h"
24 #include "gnunet_cadet_service.h"
25 #include "gnunet_statistics_service.h"
26 #include <gauger.h>
27
28
29 /**
30  * Ugly workaround to unify data handlers on incoming and outgoing channels.
31  */
32 struct CadetTestChannelWrapper
33 {
34   /**
35    * Channel pointer.
36    */
37   struct GNUNET_CADET_Channel *ch;
38 };
39
40 /**
41  * How many messages to send by default.
42  */
43 #define TOTAL_PACKETS 500       /* Cannot exceed 64k! */
44
45 /**
46  * How long until we give up on connecting the peers?
47  */
48 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120)
49
50 /**
51  * Time to wait by default  for stuff that should be rather fast.
52  */
53 #define SHORT_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20)
54
55 /**
56  * How fast do we send messages?
57  */
58 #define SEND_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 10)
59
60 /**
61  * DIFFERENT TESTS TO RUN
62  */
63 #define SETUP 0
64 #define FORWARD 1
65 #define KEEPALIVE 2
66 #define SPEED 3
67 #define SPEED_ACK 4
68 #define SPEED_REL 8
69 #define P2P_SIGNAL 10
70
71 /**
72  * Which test are we running?
73  */
74 static int test;
75
76 /**
77  * String with test name
78  */
79 static char *test_name;
80
81 /**
82  * Flag to send traffic leaf->root in speed tests to test BCK_ACK logic.
83  */
84 static int test_backwards = GNUNET_NO;
85
86 /**
87  * How many packets to send.
88  */
89 static unsigned int total_packets;
90
91 /**
92  * Time to wait for fast operations.
93  */
94 static struct GNUNET_TIME_Relative short_time;
95
96 /**
97  * How many events have happened
98  */
99 static int ok;
100
101 /**
102  * Number of events expected to conclude the test successfully.
103  */
104 static int ok_goal;
105
106 /**
107  * Size of each test packet's payload
108  */
109 static size_t size_payload = sizeof (uint32_t);
110
111 /**
112  * Operation to get peer ids.
113  */
114 static struct GNUNET_TESTBED_Operation *t_op[2];
115
116 /**
117  * Peer ids.
118  */
119 static struct GNUNET_PeerIdentity *p_id[2];
120
121 /**
122  * Port ID
123  */
124 static struct GNUNET_HashCode port;
125
126 /**
127  * Peer ids counter.
128  */
129 static unsigned int p_ids;
130
131 /**
132  * Is the setup initialized?
133  */
134 static int initialized;
135
136 /**
137  * Number of payload packes sent.
138  */
139 static int data_sent;
140
141 /**
142  * Number of payload packets received.
143  */
144 static int data_received;
145
146 /**
147  * Number of payload packed acknowledgements sent.
148  */
149 static int ack_sent;
150
151 /**
152  * Number of payload packed explicitly (app level) acknowledged.
153  */
154 static int ack_received;
155
156 /**
157  * Total number of peers asked to run.
158  */
159 static unsigned long long peers_requested;
160
161 /**
162  * Number of currently running peers (should be same as @c peers_requested).
163  */
164 static unsigned long long peers_running;
165
166 /**
167  * Test context (to shut down).
168  */
169 struct GNUNET_CADET_TEST_Context *test_ctx;
170
171 /**
172  * Task called to disconnect peers.
173  */
174 static struct GNUNET_SCHEDULER_Task *disconnect_task;
175
176 /**
177  * Task To perform tests
178  */
179 static struct GNUNET_SCHEDULER_Task *test_task;
180
181 /**
182  * Task runnining #send_next_msg().
183  */
184 static struct GNUNET_SCHEDULER_Task *send_next_msg_task;
185
186 /**
187  * Cadet handle for the root peer
188  */
189 static struct GNUNET_CADET_Handle *h1;
190
191 /**
192  * Cadet handle for the first leaf peer
193  */
194 static struct GNUNET_CADET_Handle *h2;
195
196 /**
197  * Channel handle for the root peer
198  */
199 static struct GNUNET_CADET_Channel *outgoing_ch;
200
201 /**
202  * Channel handle for the dest peer
203  */
204 static struct GNUNET_CADET_Channel *incoming_ch;
205
206 /**
207  * Time we started the data transmission (after channel has been established
208  * and initilized).
209  */
210 static struct GNUNET_TIME_Absolute start_time;
211
212 /**
213  * Peers handle.
214  */
215 static struct GNUNET_TESTBED_Peer **testbed_peers;
216
217 /**
218  * Statistics operation handle.
219  */
220 static struct GNUNET_TESTBED_Operation *stats_op;
221
222 /**
223  * Keepalives sent.
224  */
225 static unsigned int ka_sent;
226
227 /**
228  * Keepalives received.
229  */
230 static unsigned int ka_received;
231
232 /**
233  * How many messages were dropped by CADET because of full buffers?
234  */
235 static unsigned int msg_dropped;
236
237
238 /******************************************************************************/
239
240
241 /******************************************************************************/
242
243
244 /**
245  * Get the channel considered as the "target" or "receiver", depending on
246  * the test type and size.
247  *
248  * @return Channel handle of the target client, either 0 (for backward tests)
249  *         or the last peer in the line (for other tests).
250  */
251 static struct GNUNET_CADET_Channel *
252 get_target_channel ()
253 {
254   if (SPEED == test && GNUNET_YES == test_backwards)
255     return outgoing_ch;
256   else
257     return incoming_ch;
258 }
259
260
261 /**
262  * Show the results of the test (banwidth acheived) and log them to GAUGER
263  */
264 static void
265 show_end_data (void)
266 {
267   static struct GNUNET_TIME_Absolute end_time;
268   static struct GNUNET_TIME_Relative total_time;
269
270   end_time = GNUNET_TIME_absolute_get ();
271   total_time = GNUNET_TIME_absolute_get_difference (start_time, end_time);
272   FPRINTF (stderr,
273            "\nResults of test \"%s\"\n",
274            test_name);
275   FPRINTF (stderr,
276            "Test time %s\n",
277            GNUNET_STRINGS_relative_time_to_string (total_time, GNUNET_YES));
278   FPRINTF (stderr,
279            "Test bandwidth: %f kb/s\n",
280            4 * total_packets * 1.0 / (total_time.rel_value_us / 1000));    // 4bytes * ms
281   FPRINTF (stderr,
282            "Test throughput: %f packets/s\n\n",
283            total_packets * 1000.0 / (total_time.rel_value_us / 1000));     // packets * ms
284   GAUGER ("CADET",
285           test_name,
286           total_packets * 1000.0 / (total_time.rel_value_us / 1000),
287           "packets/s");
288 }
289
290
291 /**
292  * Disconnect from cadet services af all peers, call shutdown.
293  *
294  * @param cls Closure (line number from which termination was requested).
295  * @param tc Task Context.
296  */
297 static void
298 disconnect_cadet_peers (void *cls)
299 {
300   long line = (long) cls;
301
302   disconnect_task = NULL;
303   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
304               "disconnecting cadet service of peers, called from line %ld\n",
305               line);
306   for (unsigned int i = 0; i < 2; i++)
307   {
308     GNUNET_TESTBED_operation_done (t_op[i]);
309   }
310   if (NULL != outgoing_ch)
311   {
312     GNUNET_CADET_channel_destroy (outgoing_ch);
313     outgoing_ch = NULL;
314   }
315   if (NULL != incoming_ch)
316   {
317     GNUNET_CADET_channel_destroy (incoming_ch);
318     incoming_ch = NULL;
319   }
320   GNUNET_CADET_TEST_cleanup (test_ctx);
321   GNUNET_SCHEDULER_shutdown ();
322 }
323
324
325 /**
326  * Shut down peergroup, clean up.
327  *
328  * @param cls Closure (unused).
329  * @param tc Task Context.
330  */
331 static void
332 shutdown_task (void *cls)
333 {
334   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
335               "Ending test.\n");
336   if (NULL != send_next_msg_task)
337   {
338     GNUNET_SCHEDULER_cancel (send_next_msg_task);
339     send_next_msg_task = NULL;
340   }
341   if (NULL != test_task)
342   {
343     GNUNET_SCHEDULER_cancel (test_task);
344     test_task = NULL;
345   }
346   if (NULL != disconnect_task)
347   {
348     GNUNET_SCHEDULER_cancel (disconnect_task);
349     disconnect_task =
350         GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers,
351                                   (void *) __LINE__);
352   }
353 }
354
355
356 /**
357  * Stats callback. Finish the stats testbed operation and when all stats have
358  * been iterated, shutdown the test.
359  *
360  * @param cls Closure (line number from which termination was requested).
361  * @param op the operation that has been finished
362  * @param emsg error message in case the operation has failed; will be NULL if
363  *          operation has executed successfully.
364  */
365 static void
366 stats_cont (void *cls,
367             struct GNUNET_TESTBED_Operation *op,
368             const char *emsg)
369 {
370   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
371               "KA sent: %u, KA received: %u\n",
372               ka_sent,
373               ka_received);
374   if ((KEEPALIVE == test) && ((ka_sent < 2) || (ka_sent > ka_received + 1)))
375   {
376     GNUNET_break (0);
377     ok--;
378   }
379   GNUNET_TESTBED_operation_done (stats_op);
380
381   if (NULL != disconnect_task)
382     GNUNET_SCHEDULER_cancel (disconnect_task);
383   disconnect_task = GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers,
384                                               cls);
385 }
386
387
388 /**
389  * Process statistic values.
390  *
391  * @param cls closure (line number, unused)
392  * @param peer the peer the statistic belong to
393  * @param subsystem name of subsystem that created the statistic
394  * @param name the name of the datum
395  * @param value the current value
396  * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
397  * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
398  */
399 static int
400 stats_iterator (void *cls,
401                 const struct GNUNET_TESTBED_Peer *peer,
402                 const char *subsystem,
403                 const char *name,
404                 uint64_t value,
405                 int is_persistent)
406 {
407   static const char *s_sent = "# keepalives sent";
408   static const char *s_recv = "# keepalives received";
409   static const char *rdrops = "# messages dropped due to full buffer";
410   static const char *cdrops = "# messages dropped due to slow client";
411   uint32_t i;
412
413   i = GNUNET_TESTBED_get_index (peer);
414   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "STATS PEER %u - %s [%s]: %llu\n", i,
415               subsystem, name, (unsigned long long) value);
416   if (0 == strncmp (s_sent, name, strlen (s_sent)) && 0 == i)
417     ka_sent = value;
418   if (0 == strncmp (s_recv, name, strlen (s_recv)) && peers_requested - 1 == i)
419     ka_received = value;
420   if (0 == strncmp (rdrops, name, strlen (rdrops)))
421     msg_dropped += value;
422   if (0 == strncmp (cdrops, name, strlen (cdrops)))
423     msg_dropped += value;
424
425   return GNUNET_OK;
426 }
427
428
429 /**
430  * Task to gather all statistics.
431  *
432  * @param cls Closure (line from which the task was scheduled).
433  */
434 static void
435 gather_stats_and_exit (void *cls)
436 {
437   long l = (long) cls;
438
439   disconnect_task = NULL;
440   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
441               "gathering statistics from line %ld\n",
442               l);
443   if (NULL != outgoing_ch)
444   {
445     GNUNET_CADET_channel_destroy (outgoing_ch);
446     outgoing_ch = NULL;
447   }
448   stats_op = GNUNET_TESTBED_get_statistics (peers_running,
449                                             testbed_peers,
450                                             "cadet",
451                                             NULL,
452                                             &stats_iterator,
453                                             stats_cont,
454                                             cls);
455 }
456
457
458 /**
459  * Abort test: schedule disconnect and shutdown immediately
460  *
461  * @param line Line in the code the abort is requested from (__LINE__).
462  */
463 static void
464 abort_test (long line)
465 {
466   if (NULL != disconnect_task)
467   {
468     GNUNET_SCHEDULER_cancel (disconnect_task);
469     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
470                 "Aborting test from %ld\n",
471                 line);
472     disconnect_task =
473         GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers,
474                                   (void *) line);
475   }
476 }
477
478
479 /**
480  * Send a message on the channel with the appropriate size and payload.
481  *
482  * Update the appropriate *_sent counter.
483  *
484  * @param channel Channel to send the message on.
485  */
486 static void
487 send_test_message (struct GNUNET_CADET_Channel *channel)
488 {
489   struct GNUNET_MQ_Envelope *env;
490   struct GNUNET_MessageHeader *msg;
491   uint32_t *data;
492   int payload;
493   int size;
494
495   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
496               "Sending test message on channel %p\n",
497               channel);
498   size = size_payload;
499   if (GNUNET_NO == initialized)
500   {
501     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending INITIALIZER\n");
502     size += 1000;
503     payload = data_sent;
504     if (SPEED_ACK == test) // FIXME unify SPEED_ACK with an initializer
505         data_sent++;
506   }
507   else if (SPEED == test || SPEED_ACK == test)
508   {
509     if (get_target_channel() == channel)
510     {
511       payload = ack_sent;
512       size += ack_sent;
513       ack_sent++;
514       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
515                   "Sending ACK %u [%d bytes]\n",
516                   payload, size);
517     }
518     else
519     {
520       payload = data_sent;
521       size += data_sent;
522       data_sent++;
523       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
524                   "Sending DATA %u [%d bytes]\n",
525                   data_sent, size);
526     }
527   }
528   else if (FORWARD == test)
529   {
530     payload = ack_sent;
531   }
532   else if (P2P_SIGNAL == test)
533   {
534     payload = data_sent;
535   }
536   else
537   {
538     GNUNET_assert (0);
539   }
540   env = GNUNET_MQ_msg_extra (msg, size, GNUNET_MESSAGE_TYPE_DUMMY);
541
542   data = (uint32_t *) &msg[1];
543   *data = htonl (payload);
544   GNUNET_MQ_send (GNUNET_CADET_get_mq (channel), env);
545 }
546
547
548 /**
549  * Task to request a new data transmission in a SPEED test, without waiting
550  * for previous messages to be sent/arrrive.
551  *
552  * @param cls Closure (unused).
553  */
554 static void
555 send_next_msg (void *cls)
556 {
557   struct GNUNET_CADET_Channel *channel;
558
559   send_next_msg_task = NULL;
560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
561               "Sending next message: %d\n",
562               data_sent);
563
564   channel = GNUNET_YES == test_backwards ? incoming_ch : outgoing_ch;
565   GNUNET_assert (NULL != channel);
566   GNUNET_assert (SPEED == test);
567   send_test_message (channel);
568   if (data_sent < total_packets)
569   {
570     /* SPEED test: Send all messages as soon as possible */
571     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
572                 "Scheduling message %d\n",
573                 data_sent + 1);
574     send_next_msg_task =
575       GNUNET_SCHEDULER_add_delayed (SEND_INTERVAL,
576                                       &send_next_msg,
577                                       NULL);
578   }
579 }
580
581
582 /**
583  * Every few messages cancel the timeout task and re-schedule it again, to
584  * avoid timing out when traffic keeps coming.
585  *
586  * @param line Code line number to log if a timeout occurs.
587  */
588 static void
589 reschedule_timeout_task (long line)
590 {
591   if ((ok % 10) == 0)
592   {
593     if (NULL != disconnect_task)
594     {
595       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
596                   "reschedule timeout every 10 messages\n");
597       GNUNET_SCHEDULER_cancel (disconnect_task);
598       disconnect_task = GNUNET_SCHEDULER_add_delayed (short_time,
599                                                       &gather_stats_and_exit,
600                                                       (void *) line);
601     }
602   }
603 }
604
605
606 /**
607  * Check if payload is sane (size contains payload).
608  *
609  * @param cls should match #ch
610  * @param message The actual message.
611  * @return #GNUNET_OK to keep the channel open,
612  *         #GNUNET_SYSERR to close it (signal serious error).
613  */
614 static int
615 check_data (void *cls,
616             const struct GNUNET_MessageHeader *message)
617 {
618   return GNUNET_OK;             /* all is well-formed */
619 }
620
621
622 /**
623  * Function is called whenever a message is received.
624  *
625  * @param cls closure (set from GNUNET_CADET_connect(), peer number)
626  * @param message the actual message
627  */
628 static void
629 handle_data (void *cls,
630              const struct GNUNET_MessageHeader *message)
631 {
632   struct CadetTestChannelWrapper *ch = cls;
633   struct GNUNET_CADET_Channel *channel = ch->ch;
634   uint32_t *data;
635   uint32_t payload;
636   int *counter;
637
638   ok++;
639   GNUNET_CADET_receive_done (channel);
640   counter = get_target_channel () == channel ? &data_received : &ack_received;
641
642   reschedule_timeout_task ((long) __LINE__);
643
644   if (channel == outgoing_ch)
645   {
646     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
647                 "Root client got a message.\n");
648   }
649   else if (channel == incoming_ch)
650   {
651     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
652                 "Leaf client got a message.\n");
653   }
654   else
655   {
656     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
657                 "Unknown channel %p.\n",
658                 channel);
659     GNUNET_assert (0);
660   }
661
662   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
663               " ok: (%d/%d)\n",
664               ok,
665               ok_goal);
666   data = (uint32_t *) &message[1];
667   payload = ntohl (*data);
668   if (payload == *counter)
669   {
670     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
671                 " payload as expected: %u\n",
672                 payload);
673   }
674   else
675   {
676     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
677                 " payload %u, expected: %u\n",
678                 payload, *counter);
679   }
680
681   if (GNUNET_NO == initialized)
682   {
683     initialized = GNUNET_YES;
684     start_time = GNUNET_TIME_absolute_get ();
685     if (SPEED == test)
686     {
687       GNUNET_assert (incoming_ch == channel);
688       send_next_msg_task = GNUNET_SCHEDULER_add_now (&send_next_msg,
689                                                      NULL);
690       return;
691     }
692   }
693
694   (*counter)++;
695   if (get_target_channel () == channel) /* Got "data" */
696   {
697     GNUNET_log (GNUNET_ERROR_TYPE_INFO, " received data %u\n", data_received);
698     if (SPEED != test || (ok_goal - 2) == ok)
699     {
700       /* Send ACK */
701       send_test_message (channel);
702       return;
703     }
704     else
705     {
706       if (data_received < total_packets)
707         return;
708     }
709   }
710   else /* Got "ack" */
711   {
712     if (SPEED_ACK == test || SPEED == test)
713     {
714       GNUNET_log (GNUNET_ERROR_TYPE_INFO, " received ack %u\n", ack_received);
715       /* Send more data */
716       send_test_message (channel);
717       if (ack_received < total_packets && SPEED != test)
718         return;
719       if (ok == 2 && SPEED == test)
720         return;
721       show_end_data ();
722     }
723     if (test == P2P_SIGNAL)
724     {
725       GNUNET_CADET_channel_destroy (incoming_ch);
726       incoming_ch = NULL;
727     }
728     else
729     {
730       GNUNET_CADET_channel_destroy (outgoing_ch);
731       outgoing_ch = NULL;
732     }
733   }
734 }
735
736
737 /**
738  * Method called whenever a peer connects to a port in MQ-based CADET.
739  *
740  * @param cls Closure from #GNUNET_CADET_open_port (peer # as long).
741  * @param channel New handle to the channel.
742  * @param source Peer that started this channel.
743  * @return Closure for the incoming @a channel. It's given to:
744  *         - The #GNUNET_CADET_DisconnectEventHandler (given to
745  *           #GNUNET_CADET_open_port) when the channel dies.
746  *         - Each the #GNUNET_MQ_MessageCallback handlers for each message
747  *           received on the @a channel.
748  */
749 static void *
750 connect_handler (void *cls,
751                  struct GNUNET_CADET_Channel *channel,
752                  const struct GNUNET_PeerIdentity *source)
753 {
754   struct CadetTestChannelWrapper *ch;
755   long peer = (long) cls;
756
757   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
758               "Incoming channel from %s to %ld: %p\n",
759               GNUNET_i2s (source),
760               peer,
761               channel);
762   ok++;
763   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
764               " ok: %d\n",
765               ok);
766   if (peer == peers_requested - 1)
767   {
768     if (NULL != incoming_ch)
769     {
770       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
771                   "Duplicate incoming channel for client %lu\n",
772                   (long) cls);
773       GNUNET_assert (0);
774     }
775     incoming_ch = channel;
776   }
777   else
778   {
779     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
780                 "Incoming channel for unexpected peer #%lu\n",
781                 (long) cls);
782     GNUNET_assert (0);
783   }
784   if (NULL != disconnect_task)
785   {
786     GNUNET_SCHEDULER_cancel (disconnect_task);
787     disconnect_task = GNUNET_SCHEDULER_add_delayed (short_time,
788                                                     &gather_stats_and_exit,
789                                                     (void *) __LINE__);
790   }
791
792   /* TODO: cannot return channel as-is, in order to unify the data handlers */
793   ch = GNUNET_new (struct CadetTestChannelWrapper);
794   ch->ch = channel;
795
796   return ch;
797 }
798
799
800 /**
801  * Function called whenever an MQ-channel is destroyed, even if the destruction
802  * was requested by #GNUNET_CADET_channel_destroy.
803  * It must NOT call #GNUNET_CADET_channel_destroy on the channel.
804  *
805  * It should clean up any associated state, including cancelling any pending
806  * transmission on this channel.
807  *
808  * @param cls Channel closure (channel wrapper).
809  * @param channel Connection to the other end (henceforth invalid).
810  */
811 static void
812 disconnect_handler (void *cls,
813                     const struct GNUNET_CADET_Channel *channel)
814 {
815   struct CadetTestChannelWrapper *ch_w = cls;
816
817   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
818               "Channel disconnected at %d\n",
819               ok);
820   GNUNET_assert (ch_w->ch == channel);
821   if (channel == incoming_ch)
822   {
823     ok++;
824     incoming_ch = NULL;
825   }
826   else if (outgoing_ch == channel)
827   {
828     if (P2P_SIGNAL == test)
829     {
830       ok++;
831     }
832     outgoing_ch = NULL;
833   }
834   else
835     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
836                 "Unknown channel! %p\n",
837                 channel);
838   if (NULL != disconnect_task)
839   {
840     GNUNET_SCHEDULER_cancel (disconnect_task);
841     disconnect_task =
842         GNUNET_SCHEDULER_add_now (&gather_stats_and_exit,
843                                   (void *) __LINE__);
844   }
845   GNUNET_free (ch_w);
846 }
847
848
849 /**
850  * START THE TESTCASE ITSELF, AS WE ARE CONNECTED TO THE CADET SERVICES.
851  *
852  * Testcase continues when the root receives confirmation of connected peers,
853  * on callback function ch.
854  *
855  * @param cls Closure (unused).
856  */
857 static void
858 start_test (void *cls)
859 {
860   struct GNUNET_MQ_MessageHandler handlers[] = {
861     GNUNET_MQ_hd_var_size (data,
862                            GNUNET_MESSAGE_TYPE_DUMMY,
863                            struct GNUNET_MessageHeader,
864                            NULL),
865     GNUNET_MQ_handler_end ()
866   };
867   struct CadetTestChannelWrapper *ch;
868   enum GNUNET_CADET_ChannelOption flags;
869
870   test_task = NULL;
871   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "start_test\n");
872   if (NULL != disconnect_task)
873   {
874     GNUNET_SCHEDULER_cancel (disconnect_task);
875     disconnect_task = NULL;
876   }
877
878   flags = GNUNET_CADET_OPTION_DEFAULT;
879   if (SPEED_REL == test)
880   {
881     test = SPEED;
882     flags |= GNUNET_CADET_OPTION_RELIABLE;
883   }
884
885   ch = GNUNET_new (struct CadetTestChannelWrapper);
886   outgoing_ch = GNUNET_CADET_channel_create (h1,
887                                              ch,
888                                              p_id[1],
889                                              &port,
890                                              flags,
891                                              NULL,
892                                              &disconnect_handler,
893                                              handlers);
894
895   ch->ch = outgoing_ch;
896
897   disconnect_task = GNUNET_SCHEDULER_add_delayed (short_time,
898                                                   &gather_stats_and_exit,
899                                                   (void *) __LINE__);
900   if (KEEPALIVE == test)
901     return;                     /* Don't send any data. */
902
903
904   data_received = 0;
905   data_sent = 0;
906   ack_received = 0;
907   ack_sent = 0;
908   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
909               "Sending data initializer on channel %p...\n",
910               outgoing_ch);
911   send_test_message (outgoing_ch);
912 }
913
914
915 /**
916  * Callback to be called when the requested peer information is available
917  *
918  * @param cls the closure from GNUNET_TESTBED_peer_get_information()
919  * @param op the operation this callback corresponds to
920  * @param pinfo the result; will be NULL if the operation has failed
921  * @param emsg error message if the operation has failed;
922  *             NULL if the operation is successfull
923  */
924 static void
925 pi_cb (void *cls,
926        struct GNUNET_TESTBED_Operation *op,
927        const struct GNUNET_TESTBED_PeerInformation *pinfo,
928        const char *emsg)
929 {
930   long i = (long) cls;
931
932   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
933               "ID callback for %ld\n",
934               i);
935   if ( (NULL == pinfo) ||
936        (NULL != emsg) )
937   {
938     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
939                 "pi_cb: %s\n",
940                 emsg);
941     abort_test (__LINE__);
942     return;
943   }
944   p_id[i] = pinfo->result.id;
945   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
946               "id: %s\n",
947               GNUNET_i2s (p_id[i]));
948   p_ids++;
949   if (p_ids < 2)
950     return;
951   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
952               "Got all IDs, starting test\n");
953   test_task = GNUNET_SCHEDULER_add_now (&start_test, NULL);
954 }
955
956
957 /**
958  * test main: start test when all peers are connected
959  *
960  * @param cls Closure.
961  * @param ctx Argument to give to GNUNET_CADET_TEST_cleanup on test end.
962  * @param num_peers Number of peers that are running.
963  * @param peers Array of peers.
964  * @param cadets Handle to each of the CADETs of the peers.
965  */
966 static void
967 tmain (void *cls,
968        struct GNUNET_CADET_TEST_Context *ctx,
969        unsigned int num_peers,
970        struct GNUNET_TESTBED_Peer **peers,
971        struct GNUNET_CADET_Handle **cadets)
972 {
973   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "test main\n");
974   ok = 0;
975   test_ctx = ctx;
976   peers_running = num_peers;
977   GNUNET_assert (peers_running == peers_requested);
978   testbed_peers = peers;
979   h1 = cadets[0];
980   h2 = cadets[num_peers - 1];
981   disconnect_task = GNUNET_SCHEDULER_add_delayed (short_time,
982                                                   &disconnect_cadet_peers,
983                                                   (void *) __LINE__);
984   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
985                                  NULL);
986   t_op[0] = GNUNET_TESTBED_peer_get_information (peers[0],
987                                                  GNUNET_TESTBED_PIT_IDENTITY,
988                                                  &pi_cb,
989                                                  (void *) 0L);
990   t_op[1] = GNUNET_TESTBED_peer_get_information (peers[num_peers - 1],
991                                                  GNUNET_TESTBED_PIT_IDENTITY,
992                                                  &pi_cb,
993                                                  (void *) 1L);
994   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "requested peer ids\n");
995 }
996
997
998 /**
999  * Main: start test
1000  */
1001 int
1002 main (int argc, char *argv[])
1003 {
1004   static const struct GNUNET_HashCode *ports[2];
1005   struct GNUNET_MQ_MessageHandler handlers[] = {
1006     GNUNET_MQ_hd_var_size (data,
1007                            GNUNET_MESSAGE_TYPE_DUMMY,
1008                            struct GNUNET_MessageHeader,
1009                            NULL),
1010     GNUNET_MQ_handler_end ()
1011   };
1012   const char *config_file;
1013   char port_id[] = "test port";
1014   struct GNUNET_GETOPT_CommandLineOption options[] = {
1015     GNUNET_GETOPT_option_relative_time ('t',
1016                                         "time",
1017                                         "short_time",
1018                                         gettext_noop ("set short timeout"),
1019                                         &short_time),
1020     GNUNET_GETOPT_option_uint ('m',
1021                                "messages",
1022                                "NUM_MESSAGES",
1023                                gettext_noop ("set number of messages to send"),
1024                                &total_packets),
1025
1026     GNUNET_GETOPT_OPTION_END
1027   };
1028
1029
1030   initialized = GNUNET_NO;
1031   GNUNET_log_setup ("test", "DEBUG", NULL);
1032
1033   total_packets = TOTAL_PACKETS;
1034   short_time = SHORT_TIME;
1035   if (-1 == GNUNET_GETOPT_run (argv[0], options, argc, argv))
1036   {
1037     FPRINTF (stderr, "test failed: problem with CLI parameters\n");
1038     exit (1);
1039   }
1040
1041   config_file = "test_cadet.conf";
1042   GNUNET_CRYPTO_hash (port_id, sizeof (port_id), &port);
1043
1044   /* Find out requested size */
1045   if (strstr (argv[0], "_2_") != NULL)
1046   {
1047     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "DIRECT CONNECTIONs\n");
1048     peers_requested = 2;
1049   }
1050   else if (strstr (argv[0], "_5_") != NULL)
1051   {
1052     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "5 PEER LINE\n");
1053     peers_requested = 5;
1054   }
1055   else
1056   {
1057     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "SIZE UNKNOWN, USING 2\n");
1058     peers_requested = 2;
1059   }
1060
1061   /* Find out requested test */
1062   if (strstr (argv[0], "_forward") != NULL)
1063   {
1064     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "FORWARD\n");
1065     test = FORWARD;
1066     test_name = "unicast";
1067     ok_goal = 4;
1068   }
1069   else if (strstr (argv[0], "_signal") != NULL)
1070   {
1071     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "SIGNAL\n");
1072     test = P2P_SIGNAL;
1073     test_name = "signal";
1074     ok_goal = 4;
1075   }
1076   else if (strstr (argv[0], "_speed_ack") != NULL)
1077   {
1078     /* Test is supposed to generate the following callbacks:
1079      * 1 incoming channel (@dest)
1080      * total_packets received data packet (@dest)
1081      * total_packets received data packet (@orig)
1082      * 1 received channel destroy (@dest)
1083      */
1084     ok_goal = total_packets * 2 + 2;
1085     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "SPEED_ACK\n");
1086     test = SPEED_ACK;
1087     test_name = "speed ack";
1088   }
1089   else if (strstr (argv[0], "_speed") != NULL)
1090   {
1091     /* Test is supposed to generate the following callbacks:
1092      * 1 incoming channel (@dest)
1093      * 1 initial packet (@dest)
1094      * total_packets received data packet (@dest)
1095      * 1 received data packet (@orig)
1096      * 1 received channel destroy (@dest)
1097      */
1098     ok_goal = total_packets + 4;
1099     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "SPEED\n");
1100     if (strstr (argv[0], "_reliable") != NULL)
1101     {
1102       test = SPEED_REL;
1103       test_name = "speed reliable";
1104       config_file = "test_cadet_drop.conf";
1105     }
1106     else
1107     {
1108       test = SPEED;
1109       test_name = "speed";
1110     }
1111   }
1112   else if (strstr (argv[0], "_keepalive") != NULL)
1113   {
1114     test = KEEPALIVE;
1115     /* Test is supposed to generate the following callbacks:
1116      * 1 incoming channel (@dest)
1117      * [wait]
1118      * 1 received channel destroy (@dest)
1119      */
1120     ok_goal = 2;
1121   }
1122   else
1123   {
1124     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "UNKNOWN\n");
1125     test = SETUP;
1126     ok_goal = 0;
1127   }
1128
1129   if (strstr (argv[0], "backwards") != NULL)
1130   {
1131     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "BACKWARDS (LEAF TO ROOT)\n");
1132     test_backwards = GNUNET_YES;
1133     GNUNET_asprintf (&test_name, "backwards %s", test_name);
1134   }
1135
1136   p_ids = 0;
1137   ports[0] = &port;
1138   ports[1] = NULL;
1139   GNUNET_CADET_TEST_ruN ("test_cadet_small",
1140                          config_file,
1141                          peers_requested,
1142                          &tmain,
1143                          NULL,        /* tmain cls */
1144                          &connect_handler,
1145                          NULL,
1146                          &disconnect_handler,
1147                          handlers,
1148                          ports);
1149   if (NULL != strstr (argv[0], "_reliable"))
1150     msg_dropped = 0;            /* dropped should be retransmitted */
1151
1152   if (ok_goal > ok - msg_dropped)
1153   {
1154     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "FAILED! (%d/%d)\n", ok, ok_goal);
1155     return 1;
1156   }
1157   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "success\n");
1158   return 0;
1159 }
1160
1161 /* end of test_cadet.c */