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