the big core API/protocol change, breaks all testcases using core, since the code...
[oweals/gnunet.git] / src / testing / testing_group.c
1 /*
2       This file is part of GNUnet
3       (C) 2008, 2009 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 testing/testing_group.c
23  * @brief convenience API for writing testcases for GNUnet
24  * @author Nathan Evans
25  * @author Christian Grothoff
26  *
27  */
28 #include "platform.h"
29 #include "gnunet_arm_service.h"
30 #include "gnunet_testing_lib.h"
31 #include "gnunet_core_service.h"
32
33 #define VERBOSE_TESTING GNUNET_NO
34
35 #define VERBOSE_TOPOLOGY GNUNET_YES
36
37 #define DEBUG_CHURN GNUNET_NO
38
39 /**
40  * Lowest port used for GNUnet testing.  Should be high enough to not
41  * conflict with other applications running on the hosts but be low
42  * enough to not conflict with client-ports (typically starting around
43  * 32k).
44  */
45 #define LOW_PORT 10000
46
47 /**
48  * Highest port used for GNUnet testing.  Should be low enough to not
49  * conflict with the port range for "local" ports (client apps; see
50  * /proc/sys/net/ipv4/ip_local_port_range on Linux for example).
51  */
52 #define HIGH_PORT 56000
53
54 #define MAX_OUTSTANDING_CONNECTIONS 40
55
56 #define MAX_CONCURRENT_HOSTKEYS 10
57
58 #define MAX_CONCURRENT_STARTING 10
59
60 #define MAX_CONCURRENT_SHUTDOWN 10
61
62 #define CONNECT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300)
63
64 #define CONNECT_ATTEMPTS 8
65
66 /**
67  * Prototype of a function called whenever two peers would be connected
68  * in a certain topology.
69  */
70 typedef unsigned int (*GNUNET_TESTING_ConnectionProcessor)(struct GNUNET_TESTING_PeerGroup *pg,
71                                                   unsigned int first,
72                                                   unsigned int second);
73
74
75 /**
76  * Context for handling churning a peer group
77  */
78 struct ChurnContext
79 {
80   /**
81    * Callback used to notify of churning finished
82    */
83   GNUNET_TESTING_NotifyCompletion cb;
84
85   /**
86    * Closure for callback
87    */
88   void *cb_cls;
89
90   /**
91    * Number of peers that still need to be started
92    */
93   unsigned int num_to_start;
94
95   /**
96    * Number of peers that still need to be stopped
97    */
98   unsigned int num_to_stop;
99  
100   /**
101    * Number of peers that failed to start
102    */
103   unsigned int num_failed_start;
104
105   /**
106    * Number of peers that failed to stop
107    */
108   unsigned int num_failed_stop;
109 };
110
111 struct RestartContext
112 {
113   /**
114    * The group of peers being restarted
115    */
116   struct GNUNET_TESTING_PeerGroup *peer_group;
117
118   /**
119    * How many peers have been restarted thus far
120    */
121   unsigned int peers_restarted;
122
123   /**
124    * How many peers got an error when restarting
125    */
126   unsigned int peers_restart_failed;
127
128   /**
129    * The function to call once all peers have been restarted
130    */
131   GNUNET_TESTING_NotifyCompletion callback;
132
133   /**
134    * Closure for callback function
135    */
136   void *callback_cls;
137
138 };
139
140
141 struct ShutdownContext
142 {
143   /**
144    * Total peers to wait for
145    */
146   unsigned int total_peers;
147
148   /**
149    * Number of peers successfully shut down
150    */
151   unsigned int peers_down;
152
153   /**
154    * Number of peers failed to shut down
155    */
156   unsigned int peers_failed;
157
158   /**
159    * Number of peers we have started shutting
160    * down.  If too many, wait on them.
161    */
162   unsigned int outstanding;
163
164   /**
165    * Timeout for shutdown.
166    */
167   struct GNUNET_TIME_Relative timeout;
168
169   /**
170    * Callback to call when all peers either
171    * shutdown or failed to shutdown
172    */
173   GNUNET_TESTING_NotifyCompletion cb;
174
175   /**
176    * Closure for cb
177    */
178   void *cb_cls;
179 };
180
181 /**
182  * Individual shutdown context for a particular peer.
183  */
184 struct PeerShutdownContext
185 {
186   /**
187    * Pointer to the high level shutdown context.
188    */
189   struct ShutdownContext *shutdown_ctx;
190
191   /**
192    * The daemon handle for the peer to shut down.
193    */
194   struct GNUNET_TESTING_Daemon *daemon;
195 };
196
197 /**
198  * Individual shutdown context for a particular peer.
199  */
200 struct PeerRestartContext
201 {
202   /**
203    * Pointer to the high level restart context.
204    */
205   struct ChurnRestartContext *churn_restart_ctx;
206
207   /**
208    * The daemon handle for the peer to shut down.
209    */
210   struct GNUNET_TESTING_Daemon *daemon;
211 };
212
213
214 struct CreateTopologyContext
215 {
216
217   /**
218    * Function to call with number of connections
219    */
220   GNUNET_TESTING_NotifyConnections cont;
221
222   /**
223    * Closure for connection notification
224    */
225   void *cls;
226 };
227
228 #if OLD
229 struct PeerConnection
230 {
231   /*
232    * Linked list
233    */
234   struct PeerConnection *next;
235
236   /*
237    * Pointer to daemon handle
238    */
239   struct GNUNET_TESTING_Daemon *daemon;
240
241 };
242 #endif
243
244 struct InternalStartContext
245 {
246   /**
247    * Pointer to peerdata
248    */
249   struct PeerData *peer;
250
251   /**
252    * Timeout for peer startup
253    */
254   struct GNUNET_TIME_Relative timeout;
255
256   /**
257    * Client callback for hostkey notification
258    */
259   GNUNET_TESTING_NotifyHostkeyCreated hostkey_callback;
260
261   /**
262    * Closure for hostkey_callback
263    */
264   void *hostkey_cls;
265
266   /**
267    * Client callback for peer start notification
268    */
269   GNUNET_TESTING_NotifyDaemonRunning start_cb;
270
271   /**
272    * Closure for cb
273    */
274   void *start_cb_cls;
275
276   /**
277    * Hostname, where to start the peer
278    */
279   const char *hostname;
280
281   /**
282    * Username to use when connecting to the
283    * host via ssh.
284    */
285   const char *username;
286
287   /**
288    * Port to use for ssh.
289    */
290   uint16_t sshport;
291
292 };
293
294 struct ChurnRestartContext
295 {
296   /**
297    * Number of restarts currently in flight.
298    */
299   unsigned int outstanding;
300
301   /**
302    * Handle to the underlying churn context.
303    */
304   struct ChurnContext *churn_ctx;
305
306   /**
307    * How long to allow the operation to take.
308    */
309   struct GNUNET_TIME_Relative timeout;
310 };
311
312 /**
313  * Data we keep per peer.
314  */
315 struct PeerData
316 {
317   /**
318    * (Initial) configuration of the host.
319    * (initial because clients could change
320    *  it and we would not know about those
321    *  updates).
322    */
323   struct GNUNET_CONFIGURATION_Handle *cfg;
324
325   /**
326    * Handle for controlling the daemon.
327    */
328   struct GNUNET_TESTING_Daemon *daemon;
329
330   /**
331    * The peergroup this peer belongs to.
332    */
333   struct GNUNET_TESTING_PeerGroup *pg;
334
335   /**
336    * Hash map of allowed peer connections (F2F created topology)
337    */
338   struct GNUNET_CONTAINER_MultiHashMap *allowed_peers;
339
340   /**
341    * Hash map of blacklisted peers
342    */
343   struct GNUNET_CONTAINER_MultiHashMap *blacklisted_peers;
344
345   /**
346    * Hash map of peer connections
347    */
348   struct GNUNET_CONTAINER_MultiHashMap *connect_peers;
349
350   /**
351    * Temporary hash map of peer connections
352    */
353   struct GNUNET_CONTAINER_MultiHashMap *connect_peers_working_set;
354
355   /**
356    * Temporary variable for topology creation, should be reset before
357    * creating any topology so the count is valid once finished.
358    */
359   int num_connections;
360
361   /**
362    * Context to keep track of peers being started, to
363    * stagger hostkey generation and peer startup.
364    */
365   struct InternalStartContext internal_context;
366 };
367
368
369 /**
370  * Linked list of per-host data.
371  */
372 struct HostData
373 {
374   /**
375    * Name of the host.
376    */
377   char *hostname;
378
379   /**
380    * SSH username to use when connecting to this host.
381    */
382   char *username;
383
384   /**
385    * SSH port to use when connecting to this host.
386    */
387   uint16_t sshport;
388
389   /**
390    * Lowest port that we have not yet used
391    * for GNUnet.
392    */
393   uint16_t minport;
394 };
395
396 struct TopologyIterateContext
397 {
398   /**
399    * Callback for notifying of two connected peers.
400    */
401   GNUNET_TESTING_NotifyTopology topology_cb;
402
403   /**
404    * Closure for topology_cb
405    */
406   void *cls;
407
408   /**
409    * Number of peers currently connected to.
410    */
411   unsigned int connected;
412
413   /**
414    * Number of peers we have finished iterating.
415    */
416   unsigned int completed;
417
418   /**
419    * Number of peers total.
420    */
421   unsigned int total;
422 };
423
424 struct StatsIterateContext
425 {
426   /**
427    * Continuation to call once all stats information has been retrieved.
428    */
429   GNUNET_STATISTICS_Callback cont;
430
431   /**
432    * Proc function to call on each value received.
433    */
434   GNUNET_TESTING_STATISTICS_Iterator proc;
435
436   /**
437    * Closure for topology_cb
438    */
439   void *cls;
440
441   /**
442    * Number of peers currently connected to.
443    */
444   unsigned int connected;
445
446   /**
447    * Number of peers we have finished iterating.
448    */
449   unsigned int completed;
450
451   /**
452    * Number of peers total.
453    */
454   unsigned int total;
455 };
456
457 struct CoreContext
458 {
459   void *iter_context;
460   struct GNUNET_TESTING_Daemon *daemon;
461 };
462
463 struct StatsCoreContext
464 {
465   void *iter_context;
466   struct GNUNET_TESTING_Daemon *daemon;
467   /**
468    * Handle to the statistics service.
469    */
470   struct GNUNET_STATISTICS_Handle *stats_handle;
471
472   /**
473    * Handle for getting statistics.
474    */
475   struct GNUNET_STATISTICS_GetHandle *stats_get_handle;
476 };
477
478 /**
479  * Handle to a group of GNUnet peers.
480  */
481 struct GNUNET_TESTING_PeerGroup
482 {
483   /**
484    * Configuration template.
485    */
486   const struct GNUNET_CONFIGURATION_Handle *cfg;
487
488   /**
489    * Function to call on each started daemon.
490    */
491   //GNUNET_TESTING_NotifyDaemonRunning cb;
492
493   /**
494    * Closure for cb.
495    */
496   //void *cb_cls;
497
498   /*
499    * Function to call on each topology connection created
500    */
501   GNUNET_TESTING_NotifyConnection notify_connection;
502
503   /*
504    * Callback for notify_connection
505    */
506   void *notify_connection_cls;
507
508   /**
509    * Array of information about hosts.
510    */
511   struct HostData *hosts;
512
513   /**
514    * Number of hosts (size of HostData)
515    */
516   unsigned int num_hosts;
517
518   /**
519    * Array of "total" peers.
520    */
521   struct PeerData *peers;
522
523   /**
524    * Number of peers in this group.
525    */
526   unsigned int total;
527
528   /**
529    * At what time should we fail the peer startup process?
530    */
531   struct GNUNET_TIME_Absolute max_timeout;
532
533   /**
534    * How many peers are being started right now?
535    */
536   unsigned int starting;
537
538   /**
539    * How many peers have already been started?
540    */
541   unsigned int started;
542 };
543
544 struct UpdateContext
545 {
546   struct GNUNET_CONFIGURATION_Handle *ret;
547   const struct GNUNET_CONFIGURATION_Handle *orig;
548   const char *hostname;
549   unsigned int nport;
550   unsigned int upnum;
551   unsigned int fdnum;
552 };
553
554 struct ConnectTopologyContext
555 {
556   /**
557    * How many connections are left to create.
558    */
559   unsigned int remaining_connections;
560
561   /**
562    * Handle to group of peers.
563    */
564   struct GNUNET_TESTING_PeerGroup *pg;
565
566   /**
567    * Temp value set for each iteration.
568    */
569   struct PeerData *first;
570
571   /**
572    * Notification that all peers are connected.
573    */
574   GNUNET_TESTING_NotifyCompletion notify_connections_done;
575
576   /**
577    * Closure for notify.
578    */
579   void *notify_cls;
580 };
581
582 struct ConnectContext
583 {
584   /**
585    * Peer to connect second to.
586    */
587   struct GNUNET_TESTING_Daemon *first;
588
589   /**
590    * Peer to connect first to.
591    */
592   struct GNUNET_TESTING_Daemon *second;
593
594   /**
595    * Higher level topology connection context.
596    */
597   struct ConnectTopologyContext *ct_ctx;
598 };
599
600 /**
601  * Convert unique ID to hash code.
602  *
603  * @param uid unique ID to convert
604  * @param hash set to uid (extended with zeros)
605  */
606 static void
607 hash_from_uid (uint32_t uid,
608                GNUNET_HashCode *hash)
609 {
610   memset (hash, 0, sizeof(GNUNET_HashCode));
611   *((uint32_t*)hash) = uid;
612 }
613
614 /**
615  * Convert hash code to unique ID.
616  *
617  * @param uid unique ID to convert
618  * @param hash set to uid (extended with zeros)
619  */
620 static void
621 uid_from_hash (const GNUNET_HashCode *hash, uint32_t *uid)
622 {
623   memcpy (uid, hash, sizeof(uint32_t));
624 }
625
626 /**
627  * Number of connects we are waiting on, allows us to rate limit
628  * connect attempts.
629  */
630 static int outstanding_connects;
631
632 /**
633  * Get a topology from a string input.
634  *
635  * @param topology where to write the retrieved topology
636  * @param topology_string The string to attempt to
637  *        get a configuration value from
638  * @return GNUNET_YES if topology string matched a
639  *         known topology, GNUNET_NO if not
640  */
641 int
642 GNUNET_TESTING_topology_get(enum GNUNET_TESTING_Topology *topology, const char * topology_string)
643 {
644   /**
645    * Strings representing topologies in enum
646    */
647   static const char * topology_strings[] =
648     {
649       /**
650        * A clique (everyone connected to everyone else).
651        */
652       "CLIQUE",
653       
654       /**
655        * Small-world network (2d torus plus random links).
656        */
657       "SMALL_WORLD",
658       
659       /**
660        * Small-world network (ring plus random links).
661        */
662       "SMALL_WORLD_RING",
663       
664       /**
665        * Ring topology.
666        */
667       "RING",
668       
669       /**
670        * 2-d torus.
671        */
672       "2D_TORUS",
673       
674       /**
675        * Random graph.
676        */
677       "ERDOS_RENYI",
678       
679       /**
680        * Certain percentage of peers are unable to communicate directly
681        * replicating NAT conditions
682        */
683       "INTERNAT",
684       
685       /**
686        * Scale free topology.
687        */
688       "SCALE_FREE",
689       
690       /**
691        * Straight line topology.
692        */
693       "LINE",
694       
695       /**
696        * All peers are disconnected.
697        */
698       "NONE",
699
700       NULL
701     };
702
703   int curr = 0;
704   if (topology_string == NULL)
705     return GNUNET_NO;
706   while (topology_strings[curr] != NULL)
707     {
708       if (strcasecmp(topology_strings[curr], topology_string) == 0)
709         {
710           *topology = curr;
711           return GNUNET_YES;
712         }
713       curr++;
714     }
715   *topology = GNUNET_TESTING_TOPOLOGY_NONE;
716   return GNUNET_NO;
717 }
718
719
720 /**
721  * Get connect topology option from string input.
722  *
723  * @param topology_option where to write the retrieved topology
724  * @param topology_string The string to attempt to
725  *        get a configuration value from
726  * @return GNUNET_YES if string matched a known
727  *         topology option, GNUNET_NO if not
728  */
729 int
730 GNUNET_TESTING_topology_option_get (enum GNUNET_TESTING_TopologyOption *topology_option,
731                                     const char * topology_string)
732 {
733   /**
734    * Options for connecting a topology as strings.
735    */
736   static const char * topology_option_strings[] =
737     {
738       /**
739        * Try to connect all peers specified in the topology.
740        */
741       "CONNECT_ALL",
742       
743       /**
744        * Choose a random subset of connections to create.
745        */
746       "CONNECT_RANDOM_SUBSET",
747       
748       /**
749        * Create at least X connections for each peer.
750        */
751       "CONNECT_MINIMUM",
752       
753       /**
754        * Using a depth first search, create one connection
755        * per peer.  If any are missed (graph disconnected)
756        * start over at those peers until all have at least one
757        * connection.
758        */
759       "CONNECT_DFS",
760       
761       /**
762        * Find the N closest peers to each allowed peer in the
763        * topology and make sure a connection to those peers
764        * exists in the connect topology.
765        */
766       "CONNECT_CLOSEST",
767
768       /**
769        * No options specified.
770        */
771       "CONNECT_NONE",
772
773       NULL
774     };
775   int curr = 0;
776
777   if (topology_string == NULL)
778     return GNUNET_NO;
779   while (NULL != topology_option_strings[curr])
780     {
781       if (strcasecmp(topology_option_strings[curr], topology_string) == 0)
782         {
783           *topology_option = curr;
784           return GNUNET_YES;
785         }
786       curr++;
787     } 
788   *topology_option = GNUNET_TESTING_TOPOLOGY_OPTION_NONE;
789   return GNUNET_NO;
790 }
791
792 /**
793  * Function to iterate over options.  Copies
794  * the options to the target configuration,
795  * updating PORT values as needed.
796  *
797  * @param cls closure
798  * @param section name of the section
799  * @param option name of the option
800  * @param value value of the option
801  */
802 static void
803 update_config (void *cls,
804                const char *section, const char *option, const char *value)
805 {
806   struct UpdateContext *ctx = cls;
807   unsigned int ival;
808   char cval[12];
809   char uval[128];
810   char *single_variable;
811   char *per_host_variable;
812   unsigned long long num_per_host;
813
814   if ((0 == strcmp (option, "PORT")) && (1 == sscanf (value, "%u", &ival)))
815     {
816       GNUNET_asprintf(&single_variable, "single_%s_per_host", section);
817       if ((ival != 0) && (GNUNET_YES != GNUNET_CONFIGURATION_get_value_yesno(ctx->orig, "testing", single_variable)))
818         {
819           GNUNET_snprintf (cval, sizeof (cval), "%u", ctx->nport++);
820           value = cval;
821         }
822
823       GNUNET_free(single_variable);
824     }
825
826   if (0 == strcmp (option, "UNIXPATH"))
827     {
828       GNUNET_asprintf(&single_variable, "single_%s_per_host", section);
829       GNUNET_asprintf(&per_host_variable, "num_%s_per_host", section);
830       if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_yesno(ctx->orig, "testing", single_variable))
831         {
832           GNUNET_snprintf (uval,
833                            sizeof (uval),
834                            "/tmp/test-service-%s-%u",
835                            section,
836                            ctx->upnum++);
837           value = uval;
838         }
839       else if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_number(ctx->orig, "testing", per_host_variable, &num_per_host))
840         {
841           GNUNET_snprintf (uval,
842                            sizeof (uval),
843                            "/tmp/test-service-%s-%u",
844                            section,
845                            ctx->fdnum % num_per_host);
846           value = uval;
847         }
848       GNUNET_free(single_variable);
849       GNUNET_free(per_host_variable);
850
851     }
852
853   if ((0 == strcmp (option, "HOSTNAME")) && (ctx->hostname != NULL))
854     {
855       value = ctx->hostname;
856     }
857
858   GNUNET_CONFIGURATION_set_value_string (ctx->ret, section, option, value);
859 }
860
861
862 /**
863  * Create a new configuration using the given configuration
864  * as a template; however, each PORT in the existing cfg
865  * must be renumbered by incrementing "*port".  If we run
866  * out of "*port" numbers, return NULL.
867  *
868  * @param cfg template configuration
869  * @param port port numbers to use, update to reflect
870  *             port numbers that were used
871  * @param upnum number to make unix domain socket names unique
872  * @param hostname hostname of the controlling host, to allow control connections from
873  * @param fdnum number used to offset the unix domain socket for grouped processes
874  *              (such as statistics or peerinfo, which can be shared among others)
875  *
876  * @return new configuration, NULL on error
877  */
878 static struct GNUNET_CONFIGURATION_Handle *
879 make_config (const struct GNUNET_CONFIGURATION_Handle *cfg, 
880              uint16_t * port,
881              uint32_t * upnum,
882              const char *hostname, uint32_t * fdnum)
883 {
884   struct UpdateContext uc;
885   uint16_t orig;
886   char *control_host;
887   char *allowed_hosts;
888
889   orig = *port;
890   uc.nport = *port;
891   uc.upnum = *upnum;
892   uc.fdnum = *fdnum;
893   uc.ret = GNUNET_CONFIGURATION_create ();
894   uc.hostname = hostname;
895   uc.orig = cfg;
896
897   GNUNET_CONFIGURATION_iterate (cfg, &update_config, &uc);
898   if (uc.nport >= HIGH_PORT)
899     {
900       *port = orig;
901       GNUNET_CONFIGURATION_destroy (uc.ret);
902       return NULL;
903     }
904
905   if (GNUNET_CONFIGURATION_get_value_string(cfg, "testing", "control_host", &control_host) == GNUNET_OK)
906     {
907       if (hostname != NULL)
908         GNUNET_asprintf(&allowed_hosts, "%s; 127.0.0.1; %s;", control_host, hostname);
909       else
910         GNUNET_asprintf(&allowed_hosts, "%s; 127.0.0.1;", control_host);
911
912       GNUNET_CONFIGURATION_set_value_string(uc.ret, "core", "ACCEPT_FROM", allowed_hosts);
913       GNUNET_CONFIGURATION_set_value_string(uc.ret, "transport", "ACCEPT_FROM", allowed_hosts);
914       GNUNET_CONFIGURATION_set_value_string(uc.ret, "dht", "ACCEPT_FROM", allowed_hosts);
915       GNUNET_CONFIGURATION_set_value_string(uc.ret, "statistics", "ACCEPT_FROM", allowed_hosts);
916       GNUNET_free_non_null(control_host);
917       GNUNET_free(allowed_hosts);
918     }
919
920
921   /* arm needs to know to allow connections from the host on which it is running,
922    * otherwise gnunet-arm is unable to connect to it in some instances */
923   if (hostname != NULL)
924     {
925       GNUNET_asprintf(&allowed_hosts, "%s; 127.0.0.1;", hostname);
926       GNUNET_CONFIGURATION_set_value_string(uc.ret, "transport-udp", "BINDTO", hostname);
927       GNUNET_CONFIGURATION_set_value_string(uc.ret, "transport-tcp", "BINDTO", hostname);
928       GNUNET_CONFIGURATION_set_value_string(uc.ret, "arm", "ACCEPT_FROM", allowed_hosts);
929       GNUNET_free(allowed_hosts);
930     }
931   else
932     {
933       GNUNET_CONFIGURATION_set_value_string(uc.ret, "transport-tcp", "BINDTO", "127.0.0.1");
934       GNUNET_CONFIGURATION_set_value_string(uc.ret, "transport-udp", "BINDTO", "127.0.0.1");
935     }
936
937   *port = (uint16_t) uc.nport;
938   *upnum = uc.upnum;
939   uc.fdnum++;
940   *fdnum = uc.fdnum;
941   return uc.ret;
942 }
943
944
945 /*
946  * Add entries to the peers connect list
947  *
948  * @param pg the peer group we are working with
949  * @param first index of the first peer
950  * @param second index of the second peer
951  *
952  * @return the number of connections added
953  *         technically should only be 0 or 2
954  *
955  */
956 static unsigned int
957 add_actual_connections(struct GNUNET_TESTING_PeerGroup *pg, unsigned int first, unsigned int second)
958 {
959   int added;
960   int add_first;
961   int add_second;
962
963   GNUNET_HashCode hash_first;
964   GNUNET_HashCode hash_second;
965
966   hash_from_uid(first, &hash_first);
967   hash_from_uid(second, &hash_second);
968
969   add_first = GNUNET_NO;
970   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[first].connect_peers, &hash_second))
971     {
972       add_first = GNUNET_YES;
973     }
974
975   add_second = GNUNET_NO;
976   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[second].connect_peers, &hash_first))
977     {
978       add_second = GNUNET_YES;
979     }
980
981   added = 0;
982   if (add_first)
983     {
984       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[first].connect_peers, &hash_second, pg->peers[second].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
985       pg->peers[first].num_connections++;
986       added++;
987     }
988
989   if (add_second)
990     {
991       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[second].connect_peers, &hash_first, pg->peers[first].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
992       pg->peers[second].num_connections++;
993       added++;
994     }
995
996   return added;
997 }
998
999
1000 /*
1001  * Add entries to the peers allowed connections list
1002  *
1003  * @param pg the peer group we are working with
1004  * @param first index of the first peer
1005  * @param second index of the second peer
1006  *
1007  * @return the number of connections added (can be 0, 1 or 2)
1008  *         technically should only be 0 or 2, but the small price
1009  *         of iterating over the lists (hashmaps in the future)
1010  *         for being sure doesn't bother me!
1011  *
1012  */
1013 static unsigned int
1014 add_allowed_connections(struct GNUNET_TESTING_PeerGroup *pg, unsigned int first, unsigned int second)
1015 {
1016   int added;
1017 #if OLD
1018   struct PeerConnection *first_iter;
1019   struct PeerConnection *second_iter;
1020   struct PeerConnection *new_first;
1021   struct PeerConnection *new_second;
1022 #endif
1023   int add_first;
1024   int add_second;
1025
1026   GNUNET_HashCode hash_first;
1027   GNUNET_HashCode hash_second;
1028
1029   hash_from_uid(first, &hash_first);
1030   hash_from_uid(second, &hash_second);
1031
1032   add_first = GNUNET_NO;
1033   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[first].allowed_peers, &hash_second))
1034     {
1035       add_first = GNUNET_YES;
1036     }
1037
1038   add_second = GNUNET_NO;
1039   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[second].allowed_peers, &hash_first))
1040     {
1041       add_second = GNUNET_YES;
1042     }
1043 #if OLD
1044   first_iter = pg->peers[first].connected_peers;
1045   while (first_iter != NULL)
1046     {
1047       if (first_iter->daemon == pg->peers[second].daemon)
1048         add_first = GNUNET_NO;
1049       first_iter = first_iter->next;
1050     }
1051
1052   second_iter = pg->peers[second].connected_peers;
1053   add_second = GNUNET_YES;
1054   while (second_iter != NULL)
1055     {
1056       if (second_iter->daemon == pg->peers[first].daemon)
1057         add_second = GNUNET_NO;
1058       second_iter = second_iter->next;
1059     }
1060 #endif
1061
1062   added = 0;
1063   if (add_first)
1064     {
1065       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[first].allowed_peers, &hash_second, pg->peers[second].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1066 #if OLD
1067       new_first = GNUNET_malloc(sizeof(struct PeerConnection));
1068       new_first->daemon = pg->peers[second].daemon;
1069       new_first->next = pg->peers[first].connected_peers;
1070       pg->peers[first].connected_peers = new_first;
1071 #endif
1072       pg->peers[first].num_connections++;
1073       added++;
1074     }
1075
1076   if (add_second)
1077     {
1078       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[second].allowed_peers, &hash_first, pg->peers[first].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1079 #if OLD
1080       new_second = GNUNET_malloc(sizeof(struct PeerConnection));
1081       new_second->daemon = pg->peers[first].daemon;
1082       new_second->next = pg->peers[second].connected_peers;
1083       pg->peers[second].connected_peers = new_second;
1084       pg->peers[first].num_connections++;
1085 #endif
1086       pg->peers[second].num_connections++;
1087       added++;
1088     }
1089
1090   return added;
1091 }
1092
1093 /*
1094  * Add entries to the peers blacklisted list
1095  *
1096  * @param pg the peer group we are working with
1097  * @param first index of the first peer
1098  * @param second index of the second peer
1099  *
1100  * @return the number of connections added (can be 0, 1 or 2)
1101  *
1102  */
1103 static unsigned int
1104 blacklist_connections(struct GNUNET_TESTING_PeerGroup *pg, unsigned int first, unsigned int second)
1105 {
1106   int added;
1107   int add_first;
1108   int add_second;
1109   GNUNET_HashCode hash_first;
1110   GNUNET_HashCode hash_second;
1111
1112   hash_from_uid(first, &hash_first);
1113   hash_from_uid(second, &hash_second);
1114
1115   add_first = GNUNET_NO;
1116   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[first].blacklisted_peers, &hash_second))
1117     {
1118       add_first = GNUNET_YES;
1119     }
1120
1121   add_second = GNUNET_NO;
1122   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[second].blacklisted_peers, &hash_first))
1123     {
1124       add_second = GNUNET_YES;
1125     }
1126
1127   added = 0;
1128   if (add_first)
1129     {
1130       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[first].blacklisted_peers, &hash_second, pg->peers[second].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1131       pg->peers[first].num_connections++;
1132       added++;
1133     }
1134
1135   if (add_second)
1136     {
1137       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[second].blacklisted_peers, &hash_first, pg->peers[first].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1138       pg->peers[second].num_connections++;
1139       added++;
1140     }
1141
1142   return added;
1143 }
1144
1145 /*
1146  * Remove entries from the peers blacklisted list
1147  *
1148  * @param pg the peer group we are working with
1149  * @param first index of the first peer
1150  * @param second index of the second peer
1151  *
1152  * @return the number of connections removed (can be 0, 1 or 2)
1153  *
1154  */
1155 static unsigned int
1156 unblacklist_connections(struct GNUNET_TESTING_PeerGroup *pg, unsigned int first, unsigned int second)
1157 {
1158   int removed;
1159   int remove_first;
1160   int remove_second;
1161   GNUNET_HashCode hash_first;
1162   GNUNET_HashCode hash_second;
1163
1164   hash_from_uid(first, &hash_first);
1165   hash_from_uid(second, &hash_second);
1166
1167   remove_first = GNUNET_CONTAINER_multihashmap_contains(pg->peers[first].blacklisted_peers, &hash_second);
1168   remove_second = GNUNET_CONTAINER_multihashmap_contains(pg->peers[second].blacklisted_peers, &hash_first);
1169
1170   removed = 0;
1171   if (remove_first)
1172     {
1173       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(pg->peers[first].blacklisted_peers, &hash_second, pg->peers[second].daemon));
1174       removed++;
1175     }
1176
1177   if (remove_second)
1178     {
1179       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(pg->peers[second].blacklisted_peers, &hash_first, pg->peers[first].daemon));
1180       removed++;
1181     }
1182
1183   return removed;
1184 }
1185
1186 /**
1187  * Scale free network construction as described in:
1188  *
1189  * "Emergence of Scaling in Random Networks." Science 286, 509-512, 1999.
1190  *
1191  * Start with a network of "one" peer, then progressively add
1192  * peers up to the total number.  At each step, iterate over
1193  * all possible peers and connect new peer based on number of
1194  * existing connections of the target peer.
1195  *
1196  * @param pg the peer group we are dealing with
1197  * @param proc the connection processor to use
1198  *
1199  * @return the number of connections created
1200  */
1201 static unsigned int
1202 create_scale_free (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1203 {
1204
1205   unsigned int total_connections;
1206   unsigned int outer_count;
1207   unsigned int i;
1208   unsigned int previous_total_connections;
1209   double random;
1210   double probability;
1211
1212   GNUNET_assert(pg->total > 1);
1213
1214   /* Add a connection between the first two nodes */
1215   total_connections = proc(pg, 0, 1);
1216
1217   for (outer_count = 1; outer_count < pg->total; outer_count++)
1218     {
1219       previous_total_connections = total_connections;
1220       for (i = 0; i < outer_count; i++)
1221         {
1222           probability = pg->peers[i].num_connections / (double)previous_total_connections;
1223           random = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
1224                                                       UINT64_MAX)) / ( (double) UINT64_MAX);
1225 #if VERBOSE_TESTING
1226           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1227                       "Considering connecting peer %d to peer %d\n",
1228                       outer_count, i);
1229 #endif
1230           if (random < probability)
1231             {
1232 #if VERBOSE_TESTING
1233               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1234                           "Connecting peer %d to peer %d\n",
1235                           outer_count, i);
1236 #endif
1237               total_connections += proc(pg, outer_count, i);
1238             }
1239         }
1240     }
1241
1242   return total_connections;
1243 }
1244
1245 /**
1246  * Create a topology given a peer group (set of running peers)
1247  * and a connection processor.
1248  *
1249  * @param pg the peergroup to create the topology on
1250  * @param proc the connection processor to call to actually set
1251  *        up connections between two peers
1252  *
1253  * @return the number of connections that were set up
1254  *
1255  */
1256 static unsigned int
1257 create_small_world_ring(struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1258 {
1259   unsigned int i, j;
1260   int nodeToConnect;
1261   unsigned int natLog;
1262   unsigned int randomPeer;
1263   double random, logNModifier, percentage;
1264   unsigned int smallWorldConnections;
1265   int connsPerPeer;
1266   char *p_string;
1267   int max;
1268   int min;
1269   unsigned int useAnd;
1270   int connect_attempts;
1271
1272   logNModifier = 0.5; /* FIXME: default value? */
1273   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1274                                                          "TESTING",
1275                                                          "LOGNMODIFIER",
1276                                                          &p_string))
1277     {
1278       if (sscanf(p_string, "%lf", &logNModifier) != 1)
1279         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1280                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1281                     p_string,
1282                     "LOGNMODIFIER",
1283                     "TESTING");
1284       GNUNET_free (p_string);
1285     }
1286   percentage = 0.5; /* FIXME: default percentage? */
1287   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1288                                                          "TESTING",
1289                                                          "PERCENTAGE",
1290                                                          &p_string))
1291     {
1292       if (sscanf(p_string, "%lf", &percentage) != 1)
1293         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1294                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1295                     p_string,
1296                     "PERCENTAGE",
1297                     "TESTING");
1298       GNUNET_free (p_string);
1299     }
1300   natLog = log (pg->total);
1301   connsPerPeer = ceil (natLog * logNModifier);
1302
1303   if (connsPerPeer % 2 == 1)
1304     connsPerPeer += 1;
1305
1306   smallWorldConnections = 0;
1307   connect_attempts = 0;
1308   for (i = 0; i < pg->total; i++)
1309     {
1310       useAnd = 0;
1311       max = i + connsPerPeer / 2;
1312       min = i - connsPerPeer / 2;
1313
1314       if (max > pg->total - 1)
1315         {
1316           max = max - pg->total;
1317           useAnd = 1;
1318         }
1319
1320       if (min < 0)
1321         {
1322           min = pg->total - 1 + min;
1323           useAnd = 1;
1324         }
1325
1326       for (j = 0; j < connsPerPeer / 2; j++)
1327         {
1328           random = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
1329                                                       UINT64_MAX) / ( (double) UINT64_MAX));
1330           if (random < percentage)
1331             {
1332               /* Connect to uniformly selected random peer */
1333               randomPeer =
1334                 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1335                                    pg->total);
1336               while ((((randomPeer < max) && (randomPeer > min))
1337                       && (useAnd == 0)) || (((randomPeer > min)
1338                                              || (randomPeer < max))
1339                                             && (useAnd == 1)))
1340                 {
1341                   randomPeer =
1342                       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1343                                                          pg->total);
1344                 }
1345               smallWorldConnections +=
1346                 proc (pg, i, randomPeer);
1347             }
1348           else
1349             {
1350               nodeToConnect = i + j + 1;
1351               if (nodeToConnect > pg->total - 1)
1352                 {
1353                   nodeToConnect = nodeToConnect - pg->total;
1354                 }
1355               connect_attempts +=
1356                 proc (pg, i, nodeToConnect);
1357             }
1358         }
1359
1360     }
1361
1362   connect_attempts += smallWorldConnections;
1363
1364   return connect_attempts;
1365 }
1366
1367 /**
1368  * Create a topology given a peer group (set of running peers)
1369  * and a connection processor.
1370  *
1371  * @param pg the peergroup to create the topology on
1372  * @param proc the connection processor to call to actually set
1373  *        up connections between two peers
1374  *
1375  * @return the number of connections that were set up
1376  *
1377  */
1378 static unsigned int
1379 create_nated_internet (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1380 {
1381   unsigned int outer_count, inner_count;
1382   unsigned int cutoff;
1383   int connect_attempts;
1384   double nat_percentage;
1385   char *p_string;
1386
1387   nat_percentage = 0.6; /* FIXME: default percentage? */
1388   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1389                                                          "TESTING",
1390                                                          "NATPERCENTAGE",
1391                                                          &p_string))
1392     {
1393       if (sscanf(p_string, "%lf", &nat_percentage) != 1)
1394         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1395                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1396                     p_string,
1397                     "NATPERCENTAGE",
1398                     "TESTING");
1399       GNUNET_free (p_string);
1400     }
1401
1402
1403
1404   cutoff = (unsigned int) (nat_percentage * pg->total);
1405
1406   connect_attempts = 0;
1407
1408   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
1409     {
1410       for (inner_count = outer_count + 1; inner_count < pg->total;
1411            inner_count++)
1412         {
1413           if ((outer_count > cutoff) || (inner_count > cutoff))
1414             {
1415 #if VERBOSE_TESTING
1416               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1417                           "Connecting peer %d to peer %d\n",
1418                           outer_count, inner_count);
1419 #endif
1420               connect_attempts += proc(pg, outer_count, inner_count);
1421             }
1422         }
1423     }
1424
1425   return connect_attempts;
1426
1427 }
1428
1429 /**
1430  * Create a topology given a peer group (set of running peers)
1431  * and a connection processor.
1432  *
1433  * @param pg the peergroup to create the topology on
1434  * @param proc the connection processor to call to actually set
1435  *        up connections between two peers
1436  *
1437  * @return the number of connections that were set up
1438  *
1439  */
1440 static unsigned int
1441 create_small_world (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1442 {
1443   unsigned int i, j, k;
1444   unsigned int square;
1445   unsigned int rows;
1446   unsigned int cols;
1447   unsigned int toggle = 1;
1448   unsigned int nodeToConnect;
1449   unsigned int natLog;
1450   unsigned int node1Row;
1451   unsigned int node1Col;
1452   unsigned int node2Row;
1453   unsigned int node2Col;
1454   unsigned int distance;
1455   double probability, random, percentage;
1456   unsigned int smallWorldConnections;
1457   unsigned int small_world_it;
1458   char *p_string;
1459   int connect_attempts;
1460   square = floor (sqrt (pg->total));
1461   rows = square;
1462   cols = square;
1463
1464   percentage = 0.5; /* FIXME: default percentage? */
1465   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1466                                                          "TESTING",
1467                                                          "PERCENTAGE",
1468                                                          &p_string))
1469     {
1470       if (sscanf(p_string, "%lf", &percentage) != 1)
1471         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1472                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1473                     p_string,
1474                     "PERCENTAGE",
1475                     "TESTING");
1476       GNUNET_free (p_string);
1477     }
1478   if (percentage < 0.0)
1479     {
1480       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1481                   _("Invalid value `%s' for option `%s' in section `%s': got %f, needed value greater than 0\n"),
1482                   "PERCENTAGE", "TESTING", percentage);
1483       percentage = 0.5;
1484     }
1485   probability = 0.5; /* FIXME: default percentage? */
1486   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1487                                                          "TESTING",
1488                                                          "PROBABILITY",
1489                                                          &p_string))
1490     {
1491       if (sscanf(p_string, "%lf", &probability) != 1)
1492         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1493                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1494                     p_string,
1495                     "PROBABILITY",
1496                     "TESTING");
1497       GNUNET_free (p_string);
1498     }
1499   if (square * square != pg->total)
1500     {
1501       while (rows * cols < pg->total)
1502         {
1503           if (toggle % 2 == 0)
1504             rows++;
1505           else
1506             cols++;
1507
1508           toggle++;
1509         }
1510     }
1511 #if VERBOSE_TESTING
1512       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1513                   _("Connecting nodes in 2d torus topology: %u rows %u columns\n"),
1514                   rows, cols);
1515 #endif
1516
1517   connect_attempts = 0;
1518   /* Rows and columns are all sorted out, now iterate over all nodes and connect each
1519    * to the node to its right and above.  Once this is over, we'll have our torus!
1520    * Special case for the last node (if the rows and columns are not equal), connect
1521    * to the first in the row to maintain topology.
1522    */
1523   for (i = 0; i < pg->total; i++)
1524     {
1525       /* First connect to the node to the right */
1526       if (((i + 1) % cols != 0) && (i + 1 != pg->total))
1527         nodeToConnect = i + 1;
1528       else if (i + 1 == pg->total)
1529         nodeToConnect = rows * cols - cols;
1530       else
1531         nodeToConnect = i - cols + 1;
1532
1533       connect_attempts += proc (pg, i, nodeToConnect);
1534
1535       if (i < cols)
1536         nodeToConnect = (rows * cols) - cols + i;
1537       else
1538         nodeToConnect = i - cols;
1539
1540       if (nodeToConnect < pg->total)
1541         connect_attempts += proc (pg, i, nodeToConnect);
1542     }
1543   natLog = log (pg->total);
1544 #if VERBOSE_TESTING > 2
1545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1546               _("natural log of %d is %d, will run %d iterations\n"),
1547              pg->total, natLog, (int) (natLog * percentage));
1548   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Total connections added thus far: %u!\n"), connect_attempts);
1549 #endif
1550   smallWorldConnections = 0;
1551   small_world_it = (unsigned int)(natLog * percentage);
1552   if (small_world_it < 1)
1553     small_world_it = 1;
1554   GNUNET_assert(small_world_it > 0 && small_world_it < (unsigned int)-1);
1555   for (i = 0; i < small_world_it; i++)
1556     {
1557       for (j = 0; j < pg->total; j++)
1558         {
1559           /* Determine the row and column of node at position j on the 2d torus */
1560           node1Row = j / cols;
1561           node1Col = j - (node1Row * cols);
1562           for (k = 0; k < pg->total; k++)
1563             {
1564               /* Determine the row and column of node at position k on the 2d torus */
1565               node2Row = k / cols;
1566               node2Col = k - (node2Row * cols);
1567               /* Simple Cartesian distance */
1568               distance = abs (node1Row - node2Row) + abs (node1Col - node2Col);
1569               if (distance > 1)
1570                 {
1571                   /* Calculate probability as 1 over the square of the distance */
1572                   probability = 1.0 / (distance * distance);
1573                   /* Choose a random value between 0 and 1 */
1574                   random = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
1575                                                               UINT64_MAX)) / ( (double) UINT64_MAX);
1576                   /* If random < probability, then connect the two nodes */
1577                   if (random < probability)
1578                     smallWorldConnections += proc (pg, j, k);
1579
1580                 }
1581             }
1582         }
1583     }
1584   connect_attempts += smallWorldConnections;
1585 #if VERBOSE_TESTING > 2
1586           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1587                       _("Total connections added for small world: %d!\n"),
1588                       smallWorldConnections);
1589 #endif
1590   return connect_attempts;
1591 }
1592
1593 /**
1594  * Create a topology given a peer group (set of running peers)
1595  * and a connection processor.
1596  *
1597  * @param pg the peergroup to create the topology on
1598  * @param proc the connection processor to call to actually set
1599  *        up connections between two peers
1600  *
1601  * @return the number of connections that were set up
1602  *
1603  */
1604 static unsigned int
1605 create_erdos_renyi (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1606 {
1607   double temp_rand;
1608   unsigned int outer_count;
1609   unsigned int inner_count;
1610   int connect_attempts;
1611   double probability;
1612   char *p_string;
1613
1614   probability = 0.5; /* FIXME: default percentage? */
1615   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1616                                                          "TESTING",
1617                                                          "PROBABILITY",
1618                                                          &p_string))
1619     {
1620       if (sscanf(p_string, "%lf", &probability) != 1)
1621         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1622                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1623                     p_string,
1624                     "PROBABILITY",
1625                     "TESTING");
1626       GNUNET_free (p_string);
1627     }
1628   connect_attempts = 0;
1629   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
1630     {
1631       for (inner_count = outer_count + 1; inner_count < pg->total;
1632            inner_count++)
1633         {
1634           temp_rand = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
1635                                                          UINT64_MAX)) / ( (double) UINT64_MAX);
1636 #if VERBOSE_TESTING
1637           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1638                       _("rand is %f probability is %f\n"), temp_rand,
1639                       probability);
1640 #endif
1641           if (temp_rand < probability)
1642             {
1643               connect_attempts += proc (pg, outer_count, inner_count);
1644             }
1645         }
1646     }
1647
1648   return connect_attempts;
1649 }
1650
1651 /**
1652  * Create a topology given a peer group (set of running peers)
1653  * and a connection processor.  This particular function creates
1654  * the connections for a 2d-torus, plus additional "closest"
1655  * connections per peer.
1656  *
1657  * @param pg the peergroup to create the topology on
1658  * @param proc the connection processor to call to actually set
1659  *        up connections between two peers
1660  *
1661  * @return the number of connections that were set up
1662  *
1663  */
1664 static unsigned int
1665 create_2d_torus (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1666 {
1667   unsigned int i;
1668   unsigned int square;
1669   unsigned int rows;
1670   unsigned int cols;
1671   unsigned int toggle = 1;
1672   unsigned int nodeToConnect;
1673   int connect_attempts;
1674
1675   connect_attempts = 0;
1676
1677   square = floor (sqrt (pg->total));
1678   rows = square;
1679   cols = square;
1680
1681   if (square * square != pg->total)
1682     {
1683       while (rows * cols < pg->total)
1684         {
1685           if (toggle % 2 == 0)
1686             rows++;
1687           else
1688             cols++;
1689
1690           toggle++;
1691         }
1692     }
1693 #if VERBOSE_TESTING
1694       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1695                   _("Connecting nodes in 2d torus topology: %u rows %u columns\n"),
1696                   rows, cols);
1697 #endif
1698   /* Rows and columns are all sorted out, now iterate over all nodes and connect each
1699    * to the node to its right and above.  Once this is over, we'll have our torus!
1700    * Special case for the last node (if the rows and columns are not equal), connect
1701    * to the first in the row to maintain topology.
1702    */
1703   for (i = 0; i < pg->total; i++)
1704     {
1705       /* First connect to the node to the right */
1706       if (((i + 1) % cols != 0) && (i + 1 != pg->total))
1707         nodeToConnect = i + 1;
1708       else if (i + 1 == pg->total)
1709         nodeToConnect = rows * cols - cols;
1710       else
1711         nodeToConnect = i - cols + 1;
1712 #if VERBOSE_TESTING
1713           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714                       "Connecting peer %d to peer %d\n",
1715                       i, nodeToConnect);
1716 #endif
1717       connect_attempts += proc(pg, i, nodeToConnect);
1718
1719       /* Second connect to the node immediately above */
1720       if (i < cols)
1721         nodeToConnect = (rows * cols) - cols + i;
1722       else
1723         nodeToConnect = i - cols;
1724
1725       if (nodeToConnect < pg->total)
1726         {
1727 #if VERBOSE_TESTING
1728           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1729                       "Connecting peer %d to peer %d\n",
1730                       i, nodeToConnect);
1731 #endif
1732           connect_attempts += proc(pg, i, nodeToConnect);
1733         }
1734
1735     }
1736
1737   return connect_attempts;
1738 }
1739
1740
1741 /**
1742  * Create a topology given a peer group (set of running peers)
1743  * and a connection processor.
1744  *
1745  * @param pg the peergroup to create the topology on
1746  * @param proc the connection processor to call to actually set
1747  *        up connections between two peers
1748  *
1749  * @return the number of connections that were set up
1750  *
1751  */
1752 static unsigned int
1753 create_clique (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1754 {
1755   unsigned int outer_count;
1756   unsigned int inner_count;
1757   int connect_attempts;
1758
1759   connect_attempts = 0;
1760
1761   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
1762     {
1763       for (inner_count = outer_count + 1; inner_count < pg->total;
1764            inner_count++)
1765         {
1766 #if VERBOSE_TESTING
1767           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1768                       "Connecting peer %d to peer %d\n",
1769                       outer_count, inner_count);
1770 #endif
1771           connect_attempts += proc(pg, outer_count, inner_count);
1772         }
1773     }
1774
1775   return connect_attempts;
1776 }
1777
1778 /**
1779  * Create a topology given a peer group (set of running peers)
1780  * and a connection processor.
1781  *
1782  * @param pg the peergroup to create the topology on
1783  * @param proc the connection processor to call to actually set
1784  *        up connections between two peers
1785  *
1786  * @return the number of connections that were set up
1787  *
1788  */
1789 static unsigned int
1790 create_line (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1791 {
1792   unsigned int count;
1793   int connect_attempts;
1794
1795   connect_attempts = 0;
1796
1797   /* Connect each peer to the next highest numbered peer */
1798   for (count = 0; count < pg->total - 1; count++)
1799     {
1800 #if VERBOSE_TESTING
1801           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1802                       "Connecting peer %d to peer %d\n",
1803                       count, count + 1);
1804 #endif
1805       connect_attempts += proc(pg, count, count + 1);
1806     }
1807
1808   return connect_attempts;
1809 }
1810
1811 /**
1812  * Create a topology given a peer group (set of running peers)
1813  * and a connection processor.
1814  *
1815  * @param pg the peergroup to create the topology on
1816  * @param proc the connection processor to call to actually set
1817  *        up connections between two peers
1818  *
1819  * @return the number of connections that were set up
1820  *
1821  */
1822 static unsigned int
1823 create_ring (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1824 {
1825   unsigned int count;
1826   int connect_attempts;
1827
1828   connect_attempts = 0;
1829
1830   /* Connect each peer to the next highest numbered peer */
1831   for (count = 0; count < pg->total - 1; count++)
1832     {
1833 #if VERBOSE_TESTING
1834           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1835                       "Connecting peer %d to peer %d\n",
1836                       count, count + 1);
1837 #endif
1838       connect_attempts += proc(pg, count, count + 1);
1839     }
1840
1841   /* Connect the last peer to the first peer */
1842   connect_attempts += proc(pg, pg->total - 1, 0);
1843
1844   return connect_attempts;
1845 }
1846
1847
1848 /**
1849  * Iterator for writing friends of a peer to a file.
1850  *
1851  * @param cls closure, an open writable file handle
1852  * @param key the key the daemon was stored under
1853  * @param value the GNUNET_TESTING_Daemon that needs to be written.
1854  *
1855  * @return GNUNET_YES to continue iteration
1856  *
1857  * TODO: Could replace friend_file_iterator and blacklist_file_iterator
1858  *       with a single file_iterator that takes a closure which contains
1859  *       the prefix to write before the peer.  Then this could be used
1860  *       for blacklisting multiple transports and writing the friend
1861  *       file.  I'm sure *someone* will complain loudly about other
1862  *       things that negate these functions even existing so no point in
1863  *       "fixing" now.
1864  */
1865 static int
1866 friend_file_iterator (void *cls,
1867                   const GNUNET_HashCode * key,
1868                   void *value)
1869 {
1870   FILE *temp_friend_handle = cls;
1871   struct GNUNET_TESTING_Daemon *peer = value;
1872   struct GNUNET_PeerIdentity *temppeer;
1873   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
1874
1875   temppeer = &peer->id;
1876   GNUNET_CRYPTO_hash_to_enc(&temppeer->hashPubKey, &peer_enc);
1877   fprintf(temp_friend_handle, "%s\n", (char *)&peer_enc);
1878
1879   return GNUNET_YES;
1880 }
1881
1882 struct BlacklistContext
1883 {
1884   /*
1885    * The (open) file handle to write to
1886    */
1887   FILE *temp_file_handle;
1888
1889   /*
1890    * The transport that this peer will be blacklisted on.
1891    */
1892   char *transport;
1893 };
1894
1895 /**
1896  * Iterator for writing blacklist data to appropriate files.
1897  *
1898  * @param cls closure, an open writable file handle
1899  * @param key the key the daemon was stored under
1900  * @param value the GNUNET_TESTING_Daemon that needs to be written.
1901  *
1902  * @return GNUNET_YES to continue iteration
1903  */
1904 static int
1905 blacklist_file_iterator (void *cls,
1906                          const GNUNET_HashCode * key,
1907                          void *value)
1908 {
1909   struct BlacklistContext *blacklist_ctx = cls;
1910   //FILE *temp_blacklist_handle = cls;
1911   struct GNUNET_TESTING_Daemon *peer = value;
1912   struct GNUNET_PeerIdentity *temppeer;
1913   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
1914
1915   temppeer = &peer->id;
1916   GNUNET_CRYPTO_hash_to_enc(&temppeer->hashPubKey, &peer_enc);
1917   fprintf(blacklist_ctx->temp_file_handle, "%s:%s\n", blacklist_ctx->transport, (char *)&peer_enc);
1918
1919   return GNUNET_YES;
1920 }
1921
1922 /*
1923  * Create the friend files based on the PeerConnection's
1924  * of each peer in the peer group, and copy the files
1925  * to the appropriate place
1926  *
1927  * @param pg the peer group we are dealing with
1928  */
1929 static int
1930 create_and_copy_friend_files (struct GNUNET_TESTING_PeerGroup *pg)
1931 {
1932   FILE *temp_friend_handle;
1933   unsigned int pg_iter;
1934   char *temp_service_path;
1935   struct GNUNET_OS_Process **procarr;
1936   char *arg;
1937   char * mytemp;
1938   enum GNUNET_OS_ProcessStatusType type;
1939   unsigned long return_code;
1940   int count;
1941   int ret;
1942   int max_wait = 10;
1943
1944   procarr = GNUNET_malloc(sizeof(struct GNUNET_OS_Process *) * pg->total);
1945   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
1946     {
1947       mytemp = GNUNET_DISK_mktemp("friends");
1948       GNUNET_assert(mytemp != NULL);
1949       temp_friend_handle = fopen (mytemp, "wt");
1950       GNUNET_assert(temp_friend_handle != NULL);
1951       GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].allowed_peers, &friend_file_iterator, temp_friend_handle);
1952       fclose(temp_friend_handle);
1953
1954       if (GNUNET_OK !=
1955           GNUNET_CONFIGURATION_get_value_string(pg->peers[pg_iter].daemon->cfg, "PATHS", "SERVICEHOME", &temp_service_path))
1956         {
1957           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1958                       _("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
1959                       "SERVICEHOME",
1960                       "PATHS");
1961           if (UNLINK (mytemp) != 0)
1962             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", mytemp);
1963           GNUNET_free (mytemp);
1964           break;
1965         }
1966
1967       if (pg->peers[pg_iter].daemon->hostname == NULL) /* Local, just copy the file */
1968         {
1969           GNUNET_asprintf (&arg, "%s/friends", temp_service_path);
1970           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "mv",
1971                                          "mv", mytemp, arg, NULL);
1972 #if VERBOSE_TESTING
1973           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1974                       _("Copying file with command cp %s %s\n"), mytemp, arg);
1975 #endif
1976
1977           GNUNET_free(arg);
1978         }
1979       else /* Remote, scp the file to the correct place */
1980         {
1981           if (NULL != pg->peers[pg_iter].daemon->username)
1982             GNUNET_asprintf (&arg, "%s@%s:%s/friends", pg->peers[pg_iter].daemon->username, pg->peers[pg_iter].daemon->hostname, temp_service_path);
1983           else
1984             GNUNET_asprintf (&arg, "%s:%s/friends", pg->peers[pg_iter].daemon->hostname, temp_service_path);
1985           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "scp",
1986                                          "scp", mytemp, arg, NULL);
1987
1988 #if VERBOSE_TESTING
1989           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1990                       _("Copying file with command scp %s %s\n"), mytemp, arg);
1991 #endif
1992           GNUNET_free(arg);
1993         }
1994       GNUNET_free (temp_service_path);
1995       GNUNET_free (mytemp);
1996     }
1997
1998   count = 0;
1999   ret = GNUNET_SYSERR;
2000   while ((count < max_wait) && (ret != GNUNET_OK))
2001     {
2002       ret = GNUNET_OK;
2003       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2004         {
2005 #if VERBOSE_TESTING
2006           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2007                       _("Checking copy status of file %d\n"), pg_iter);
2008 #endif
2009           if (procarr[pg_iter] != NULL) /* Check for already completed! */
2010             {
2011               if (GNUNET_OS_process_status(procarr[pg_iter], &type, &return_code) != GNUNET_OK)
2012                 {
2013                   ret = GNUNET_SYSERR;
2014                 }
2015               else if ((type != GNUNET_OS_PROCESS_EXITED) || (return_code != 0))
2016                 {
2017                   ret = GNUNET_SYSERR;
2018                 }
2019               else
2020                 {
2021                   GNUNET_OS_process_close (procarr[pg_iter]);
2022                   procarr[pg_iter] = NULL;
2023 #if VERBOSE_TESTING
2024             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2025                       _("File %d copied\n"), pg_iter);
2026 #endif
2027                 }
2028             }
2029         }
2030       count++;
2031       if (ret == GNUNET_SYSERR)
2032         {
2033           /* FIXME: why sleep here? -CG */
2034           sleep(1);
2035         }
2036     }
2037
2038 #if VERBOSE_TESTING
2039     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2040                 _("Finished copying all friend files!\n"));
2041 #endif
2042   GNUNET_free(procarr);
2043   return ret;
2044 }
2045
2046
2047 /*
2048  * Create the blacklist files based on the PeerConnection's
2049  * of each peer in the peer group, and copy the files
2050  * to the appropriate place.
2051  *
2052  * @param pg the peer group we are dealing with
2053  * @param transports space delimited list of transports to blacklist
2054  */
2055 static int
2056 create_and_copy_blacklist_files (struct GNUNET_TESTING_PeerGroup *pg, const char *transports)
2057 {
2058   FILE *temp_file_handle;
2059   static struct BlacklistContext blacklist_ctx;
2060   unsigned int pg_iter;
2061   char *temp_service_path;
2062   struct GNUNET_OS_Process **procarr;
2063   char *arg;
2064   char *mytemp;
2065   enum GNUNET_OS_ProcessStatusType type;
2066   unsigned long return_code;
2067   int count;
2068   int ret;
2069   int max_wait = 10;
2070   int transport_len;
2071   unsigned int i;
2072   char *pos;
2073   char *temp_transports;
2074
2075   procarr = GNUNET_malloc(sizeof(struct GNUNET_OS_Process *) * pg->total);
2076   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2077     {
2078       mytemp = GNUNET_DISK_mktemp("blacklist");
2079       GNUNET_assert(mytemp != NULL);
2080       temp_file_handle = fopen (mytemp, "wt");
2081       GNUNET_assert(temp_file_handle != NULL);
2082       temp_transports = GNUNET_strdup(transports);
2083       blacklist_ctx.temp_file_handle = temp_file_handle;
2084       transport_len = strlen(temp_transports) + 1;
2085       pos = NULL;
2086
2087       for (i = 0; i < transport_len; i++)
2088       {
2089         if ((temp_transports[i] == ' ') && (pos == NULL))
2090           continue; /* At start of string (whitespace) */
2091         else if ((temp_transports[i] == ' ') || (temp_transports[i] == '\0')) /* At end of string */
2092         {
2093           temp_transports[i] = '\0';
2094           blacklist_ctx.transport = pos;
2095           GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].blacklisted_peers, &blacklist_file_iterator, &blacklist_ctx);
2096           pos = NULL;
2097         } /* At beginning of actual string */
2098         else if (pos == NULL)
2099         {
2100           pos = &temp_transports[i];
2101         }
2102       }
2103
2104       GNUNET_free (temp_transports);
2105       fclose(temp_file_handle);
2106
2107       if (GNUNET_OK !=
2108           GNUNET_CONFIGURATION_get_value_string(pg->peers[pg_iter].daemon->cfg, "PATHS", "SERVICEHOME", &temp_service_path))
2109         {
2110           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2111                       _("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
2112                       "SERVICEHOME",
2113                       "PATHS");
2114           if (UNLINK (mytemp) != 0)
2115             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", mytemp);
2116           GNUNET_free (mytemp);
2117           break;
2118         }
2119
2120       if (pg->peers[pg_iter].daemon->hostname == NULL) /* Local, just copy the file */
2121         {
2122           GNUNET_asprintf (&arg, "%s/blacklist", temp_service_path);
2123           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "mv",
2124                                          "mv", mytemp, arg, NULL);
2125 #if VERBOSE_TESTING
2126           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2127                       _("Copying file with command cp %s %s\n"), mytemp, arg);
2128 #endif
2129
2130           GNUNET_free(arg);
2131         }
2132       else /* Remote, scp the file to the correct place */
2133         {
2134           if (NULL != pg->peers[pg_iter].daemon->username)
2135             GNUNET_asprintf (&arg, "%s@%s:%s/blacklist", pg->peers[pg_iter].daemon->username, pg->peers[pg_iter].daemon->hostname, temp_service_path);
2136           else
2137             GNUNET_asprintf (&arg, "%s:%s/blacklist", pg->peers[pg_iter].daemon->hostname, temp_service_path);
2138           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "scp",
2139                                          "scp", mytemp, arg, NULL);
2140
2141 #if VERBOSE_TESTING
2142           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2143                       _("Copying file with command scp %s %s\n"), mytemp, arg);
2144 #endif
2145           GNUNET_free(arg);
2146         }
2147       GNUNET_free (temp_service_path);
2148       GNUNET_free (mytemp);
2149     }
2150
2151   count = 0;
2152   ret = GNUNET_SYSERR;
2153   while ((count < max_wait) && (ret != GNUNET_OK))
2154     {
2155       ret = GNUNET_OK;
2156       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2157         {
2158 #if VERBOSE_TESTING
2159           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2160                       _("Checking copy status of file %d\n"), pg_iter);
2161 #endif
2162           if (procarr[pg_iter] != NULL) /* Check for already completed! */
2163             {
2164               if (GNUNET_OS_process_status(procarr[pg_iter], &type, &return_code) != GNUNET_OK)
2165                 {
2166                   ret = GNUNET_SYSERR;
2167                 }
2168               else if ((type != GNUNET_OS_PROCESS_EXITED) || (return_code != 0))
2169                 {
2170                   ret = GNUNET_SYSERR;
2171                 }
2172               else
2173                 {
2174                   GNUNET_OS_process_close (procarr[pg_iter]);
2175                   procarr[pg_iter] = NULL;
2176 #if VERBOSE_TESTING
2177             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2178                       _("File %d copied\n"), pg_iter);
2179 #endif
2180                 }
2181             }
2182         }
2183       count++;
2184       if (ret == GNUNET_SYSERR)
2185         {
2186           /* FIXME: why sleep here? -CG */
2187           sleep(1);
2188         }
2189     }
2190
2191 #if VERBOSE_TESTING
2192     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2193                 _("Finished copying all blacklist files!\n"));
2194 #endif
2195   GNUNET_free(procarr);
2196   return ret;
2197 }
2198
2199
2200 /**
2201  * Internal notification of a connection, kept so that we can ensure some connections
2202  * happen instead of flooding all testing daemons with requests to connect.
2203  */
2204 static void internal_connect_notify (void *cls,
2205                                      const struct GNUNET_PeerIdentity *first,
2206                                      const struct GNUNET_PeerIdentity *second,
2207                                      uint32_t distance,
2208                                      const struct GNUNET_CONFIGURATION_Handle *first_cfg,
2209                                      const struct GNUNET_CONFIGURATION_Handle *second_cfg,
2210                                      struct GNUNET_TESTING_Daemon *first_daemon,
2211                                      struct GNUNET_TESTING_Daemon *second_daemon,
2212                                      const char *emsg)
2213 {
2214   struct ConnectTopologyContext *ct_ctx = cls;
2215   struct GNUNET_TESTING_PeerGroup *pg = ct_ctx->pg;
2216   outstanding_connects--;
2217   ct_ctx->remaining_connections--;
2218   if (ct_ctx->remaining_connections == 0)
2219     {
2220       if (ct_ctx->notify_connections_done != NULL)
2221         ct_ctx->notify_connections_done(ct_ctx->notify_cls, NULL);
2222       GNUNET_free(ct_ctx);
2223     }
2224
2225   if (pg->notify_connection != NULL)
2226     pg->notify_connection (pg->notify_connection_cls, first, second, distance, first_cfg, second_cfg, first_daemon, second_daemon, emsg);
2227 }
2228
2229
2230 /**
2231  * Either delay a connection (because there are too many outstanding)
2232  * or schedule it for right now.
2233  *
2234  * @param cls a connection context
2235  * @param tc the task runtime context
2236  */
2237 static void schedule_connect(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2238 {
2239   struct ConnectContext *connect_context = cls;
2240
2241   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2242     return;
2243
2244   if (outstanding_connects > MAX_OUTSTANDING_CONNECTIONS)
2245     {
2246 #if VERBOSE_TESTING > 2
2247           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2248                       _("Delaying connect, we have too many outstanding connections!\n"));
2249 #endif
2250       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_connect, connect_context);
2251     }
2252   else
2253     {
2254 #if VERBOSE_TESTING > 2
2255           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2256                       _("Creating connection, outstanding_connections is %d\n"), outstanding_connects);
2257 #endif
2258       outstanding_connects++;
2259       GNUNET_TESTING_daemons_connect (connect_context->first,
2260                                       connect_context->second,
2261                                       CONNECT_TIMEOUT,
2262                                       CONNECT_ATTEMPTS,
2263                                       &internal_connect_notify,
2264                                       connect_context->ct_ctx);
2265       GNUNET_free(connect_context);
2266     }
2267 }
2268
2269
2270 /**
2271  * Iterator for actually scheduling connections to be created
2272  * between two peers.
2273  *
2274  * @param cls closure, a GNUNET_TESTING_Daemon
2275  * @param key the key the second Daemon was stored under
2276  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
2277  *
2278  * @return GNUNET_YES to continue iteration
2279  */
2280 static int
2281 connect_iterator (void *cls,
2282                   const GNUNET_HashCode * key,
2283                   void *value)
2284 {
2285   struct ConnectTopologyContext *ct_ctx = cls;
2286   struct PeerData *first = ct_ctx->first;
2287   struct GNUNET_TESTING_Daemon *second = value;
2288   struct ConnectContext *connect_context;
2289
2290   connect_context = GNUNET_malloc(sizeof(struct ConnectContext));
2291   connect_context->first = first->daemon;
2292   connect_context->second = second;
2293   connect_context->ct_ctx = ct_ctx;
2294   GNUNET_SCHEDULER_add_now(&schedule_connect, connect_context);
2295
2296   return GNUNET_YES;
2297 }
2298
2299
2300 /**
2301  * Iterator for copying all entries in the allowed hashmap to the
2302  * connect hashmap.
2303  *
2304  * @param cls closure, a GNUNET_TESTING_Daemon
2305  * @param key the key the second Daemon was stored under
2306  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
2307  *
2308  * @return GNUNET_YES to continue iteration
2309  */
2310 static int
2311 copy_topology_iterator (void *cls,
2312                   const GNUNET_HashCode * key,
2313                   void *value)
2314 {
2315   struct PeerData *first = cls;
2316
2317   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(first->connect_peers, key, value, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2318
2319   return GNUNET_YES;
2320 }
2321
2322 /**
2323  * Make the peers to connect the same as those that are allowed to be
2324  * connected.
2325  *
2326  * @param pg the peer group
2327  */
2328 static int
2329 copy_allowed_topology (struct GNUNET_TESTING_PeerGroup *pg)
2330 {
2331   unsigned int pg_iter;
2332   int ret;
2333   int total;
2334
2335   total = 0;
2336   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2337     {
2338       ret = GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].allowed_peers, &copy_topology_iterator, &pg->peers[pg_iter]);
2339       if (GNUNET_SYSERR == ret)
2340         return GNUNET_SYSERR;
2341
2342       total = total + ret;
2343     }
2344
2345   return total;
2346 }
2347
2348
2349 /**
2350  * Connect the topology as specified by the PeerConnection's
2351  * of each peer in the peer group
2352  *
2353  * @param pg the peer group we are dealing with
2354  * @return the number of connections that will be attempted
2355  */
2356 static int
2357 connect_topology (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_NotifyCompletion notify_callback, void *notify_cls)
2358 {
2359   unsigned int pg_iter;
2360   int ret;
2361   unsigned int total;
2362   struct ConnectTopologyContext *ct_ctx;
2363 #if OLD
2364   struct PeerConnection *connection_iter;
2365   struct ConnectContext *connect_context;
2366 #endif
2367
2368   total = 0;
2369   ct_ctx = GNUNET_malloc(sizeof(struct ConnectTopologyContext));
2370   ct_ctx->notify_connections_done = notify_callback;
2371   ct_ctx->notify_cls = notify_cls;
2372   ct_ctx->pg = pg;
2373
2374   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2375     {
2376       total += GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers);
2377     }
2378
2379   if (total == 0)
2380     {
2381       GNUNET_free(ct_ctx);
2382       return total;
2383     }
2384   ct_ctx->remaining_connections = total;
2385   total = 0;
2386
2387   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2388     {
2389       ct_ctx->first = &pg->peers[pg_iter];
2390       ret = GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].connect_peers, &connect_iterator, ct_ctx);
2391       GNUNET_assert(GNUNET_SYSERR != ret && ret >= 0);
2392       total = total + ret;
2393
2394 #if OLD
2395       connection_iter = FIXME;
2396       while (connection_iter != NULL)
2397         {
2398           connect_context = GNUNET_malloc(sizeof(struct ConnectContext));
2399           connect_context->pg = pg;
2400           connect_context->first = FIXME;
2401           connect_context->second = connection_iter->daemon;
2402           GNUNET_SCHEDULER_add_now(&schedule_connect, connect_context);
2403           connection_iter = connection_iter->next;
2404         }
2405 #endif
2406     }
2407   return total;
2408 }
2409
2410
2411 /**
2412  * Takes a peer group and creates a topology based on the
2413  * one specified.  Creates a topology means generates friend
2414  * files for the peers so they can only connect to those allowed
2415  * by the topology.  This will only have an effect once peers
2416  * are started if the FRIENDS_ONLY option is set in the base
2417  * config.  Also takes an optional restrict topology which
2418  * disallows connections based on a particular transport
2419  * UNLESS they are specified in the restricted topology.
2420  *
2421  * @param pg the peer group struct representing the running peers
2422  * @param topology which topology to connect the peers in
2423  * @param restrict_topology allow only direct TCP connections in this topology
2424  *                          use GNUNET_TESTING_TOPOLOGY_NONE for no restrictions
2425  * @param restrict_transports space delimited list of transports to blacklist
2426  *                            to create restricted topology
2427  *
2428  * @return the maximum number of connections were all allowed peers
2429  *         connected to each other
2430  */
2431 unsigned int
2432 GNUNET_TESTING_create_topology (struct GNUNET_TESTING_PeerGroup *pg,
2433                                 enum GNUNET_TESTING_Topology topology,
2434                                 enum GNUNET_TESTING_Topology restrict_topology,
2435                                 const char *restrict_transports)
2436 {
2437   int ret;
2438   unsigned int num_connections;
2439   int unblacklisted_connections;
2440
2441   switch (topology)
2442     {
2443     case GNUNET_TESTING_TOPOLOGY_CLIQUE:
2444 #if VERBOSE_TESTING
2445       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2446                   _("Creating clique topology\n"));
2447 #endif
2448       num_connections = create_clique (pg, &add_allowed_connections);
2449       break;
2450     case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
2451 #if VERBOSE_TESTING
2452       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2453                   _("Creating small world (ring) topology\n"));
2454 #endif
2455       num_connections = create_small_world_ring (pg, &add_allowed_connections);
2456       break;
2457     case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
2458 #if VERBOSE_TESTING
2459       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2460                   _("Creating small world (2d-torus) topology\n"));
2461 #endif
2462       num_connections = create_small_world (pg, &add_allowed_connections);
2463       break;
2464     case GNUNET_TESTING_TOPOLOGY_RING:
2465 #if VERBOSE_TESTING
2466       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2467                   _("Creating ring topology\n"));
2468 #endif
2469       num_connections = create_ring (pg, &add_allowed_connections);
2470       break;
2471     case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
2472 #if VERBOSE_TESTING
2473       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2474                   _("Creating 2d torus topology\n"));
2475 #endif
2476       num_connections = create_2d_torus (pg, &add_allowed_connections);
2477       break;
2478     case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
2479 #if VERBOSE_TESTING
2480       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2481                   _("Creating Erdos-Renyi topology\n"));
2482 #endif
2483       num_connections = create_erdos_renyi (pg, &add_allowed_connections);
2484       break;
2485     case GNUNET_TESTING_TOPOLOGY_INTERNAT:
2486 #if VERBOSE_TESTING
2487       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488                   _("Creating InterNAT topology\n"));
2489 #endif
2490       num_connections = create_nated_internet (pg, &add_allowed_connections);
2491       break;
2492     case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
2493 #if VERBOSE_TESTING
2494       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495                   _("Creating Scale Free topology\n"));
2496 #endif
2497       num_connections = create_scale_free (pg, &add_allowed_connections);
2498       break;
2499     case GNUNET_TESTING_TOPOLOGY_LINE:
2500 #if VERBOSE_TESTING
2501       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2502                   _("Creating straight line topology\n"));
2503 #endif
2504       num_connections = create_line (pg, &add_allowed_connections);
2505       break;
2506     case GNUNET_TESTING_TOPOLOGY_NONE:
2507 #if VERBOSE_TESTING
2508       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2509                   _("Creating no allowed topology (all peers can connect at core level)\n"));
2510 #endif
2511       num_connections = 0;
2512       break;
2513     default:
2514       num_connections = 0;
2515       break;
2516     }
2517
2518   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "TESTING", "F2F"))
2519     {
2520       ret = create_and_copy_friend_files(pg);
2521       if (ret != GNUNET_OK)
2522         {
2523 #if VERBOSE_TESTING
2524           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2525                       _("Failed during friend file copying!\n"));
2526 #endif
2527           return GNUNET_SYSERR;
2528         }
2529       else
2530         {
2531 #if VERBOSE_TESTING
2532               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2533                           _("Friend files created/copied successfully!\n"));
2534 #endif
2535         }
2536     }
2537
2538   /* Use the create clique method to initially set all connections as blacklisted. */
2539   if (restrict_topology != GNUNET_TESTING_TOPOLOGY_NONE)
2540     create_clique (pg, &blacklist_connections);
2541
2542   unblacklisted_connections = 0;
2543   /* Un-blacklist connections as per the topology specified */
2544   switch (restrict_topology)
2545     {
2546     case GNUNET_TESTING_TOPOLOGY_CLIQUE:
2547 #if VERBOSE_TESTING
2548       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2549                   _("Blacklisting all but clique topology\n"));
2550 #endif
2551       unblacklisted_connections = create_clique (pg, &unblacklist_connections);
2552       break;
2553     case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
2554 #if VERBOSE_TESTING
2555       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2556                   _("Blacklisting all but small world (ring) topology\n"));
2557 #endif
2558       unblacklisted_connections = create_small_world_ring (pg, &unblacklist_connections);
2559       break;
2560     case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
2561 #if VERBOSE_TESTING
2562       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2563                   _("Blacklisting all but small world (2d-torus) topology\n"));
2564 #endif
2565       unblacklisted_connections = create_small_world (pg, &unblacklist_connections);
2566       break;
2567     case GNUNET_TESTING_TOPOLOGY_RING:
2568 #if VERBOSE_TESTING
2569       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2570                   _("Blacklisting all but ring topology\n"));
2571 #endif
2572       unblacklisted_connections = create_ring (pg, &unblacklist_connections);
2573       break;
2574     case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
2575 #if VERBOSE_TESTING
2576       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2577                   _("Blacklisting all but 2d torus topology\n"));
2578 #endif
2579       unblacklisted_connections = create_2d_torus (pg, &unblacklist_connections);
2580       break;
2581     case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
2582 #if VERBOSE_TESTING
2583       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2584                   _("Blacklisting all but Erdos-Renyi topology\n"));
2585 #endif
2586       unblacklisted_connections = create_erdos_renyi (pg, &unblacklist_connections);
2587       break;
2588     case GNUNET_TESTING_TOPOLOGY_INTERNAT:
2589 #if VERBOSE_TESTING
2590       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2591                   _("Blacklisting all but InterNAT topology\n"));
2592 #endif
2593       unblacklisted_connections = create_nated_internet (pg, &unblacklist_connections);
2594       break;
2595     case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
2596 #if VERBOSE_TESTING
2597       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2598                   _("Blacklisting all but Scale Free topology\n"));
2599 #endif
2600       unblacklisted_connections = create_scale_free (pg, &unblacklist_connections);
2601       break;
2602     case GNUNET_TESTING_TOPOLOGY_LINE:
2603 #if VERBOSE_TESTING
2604       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2605                   _("Blacklisting all but straight line topology\n"));
2606 #endif
2607       unblacklisted_connections = create_line (pg, &unblacklist_connections);
2608       break;
2609     case GNUNET_TESTING_TOPOLOGY_NONE:
2610 #if VERBOSE_TESTING
2611       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2612                   _("Creating no blacklist topology (all peers can connect at transport level)\n"));
2613 #endif
2614     default:
2615       break;
2616     }
2617
2618   if ((unblacklisted_connections > 0) && (restrict_transports != NULL))
2619   {
2620     ret = create_and_copy_blacklist_files(pg, restrict_transports);
2621     if (ret != GNUNET_OK)
2622       {
2623 #if VERBOSE_TESTING
2624         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2625                     _("Failed during blacklist file copying!\n"));
2626 #endif
2627         return 0;
2628       }
2629     else
2630       {
2631 #if VERBOSE_TESTING
2632         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2633                     _("Blacklist files created/copied successfully!\n"));
2634 #endif
2635       }
2636   }
2637   return num_connections;
2638 }
2639
2640 struct RandomContext
2641 {
2642   /**
2643    * The peergroup
2644    */
2645   struct GNUNET_TESTING_PeerGroup *pg;
2646
2647   /**
2648    * uid of the first peer
2649    */
2650   uint32_t first_uid;
2651
2652   /**
2653    * Peer data for first peer.
2654    */
2655   struct PeerData *first;
2656
2657   /**
2658    * Random percentage to use
2659    */
2660   double percentage;
2661 };
2662
2663 struct MinimumContext
2664 {
2665   /**
2666    * The peergroup
2667    */
2668   struct GNUNET_TESTING_PeerGroup *pg;
2669
2670   /**
2671    * uid of the first peer
2672    */
2673   uint32_t first_uid;
2674
2675   /**
2676    * Peer data for first peer.
2677    */
2678   struct PeerData *first;
2679
2680   /**
2681    * Number of conns per peer
2682    */
2683   unsigned int num_to_add;
2684
2685   /**
2686    * Permuted array of all possible connections.  Only add the Nth
2687    * peer if it's in the Nth position.
2688    */
2689   unsigned int *pg_array;
2690
2691   /**
2692    * What number is the current element we are iterating over?
2693    */
2694   unsigned int current;
2695 };
2696
2697 struct DFSContext
2698 {
2699   /**
2700    * The peergroup
2701    */
2702   struct GNUNET_TESTING_PeerGroup *pg;
2703
2704   /**
2705    * uid of the first peer
2706    */
2707   uint32_t first_uid;
2708
2709   /**
2710    * uid of the second peer
2711    */
2712   uint32_t second_uid;
2713
2714   /**
2715    * Peer data for first peer.
2716    */
2717   struct PeerData *first;
2718
2719   /**
2720    * Which peer has been chosen as the one to add?
2721    */
2722   unsigned int chosen;
2723
2724   /**
2725    * What number is the current element we are iterating over?
2726    */
2727   unsigned int current;
2728 };
2729
2730 /**
2731  * Iterator for choosing random peers to connect.
2732  *
2733  * @param cls closure, a RandomContext
2734  * @param key the key the second Daemon was stored under
2735  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
2736  *
2737  * @return GNUNET_YES to continue iteration
2738  */
2739 static int
2740 random_connect_iterator (void *cls,
2741                          const GNUNET_HashCode * key,
2742                          void *value)
2743 {
2744   struct RandomContext *random_ctx = cls;
2745   double random_number;
2746   uint32_t second_pos;
2747   GNUNET_HashCode first_hash;
2748   random_number = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
2749                                                      UINT64_MAX)) / ( (double) UINT64_MAX);
2750   if (random_number < random_ctx->percentage)
2751   {
2752     GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(random_ctx->first->connect_peers_working_set, key, value, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2753   }
2754   /* Now we have considered this particular connection, remove it from the second peer so it's not double counted */
2755   uid_from_hash(key, &second_pos);
2756   hash_from_uid(random_ctx->first_uid, &first_hash);
2757   GNUNET_assert(random_ctx->pg->total > second_pos);
2758   GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(random_ctx->pg->peers[second_pos].connect_peers, &first_hash, random_ctx->first->daemon));
2759
2760   return GNUNET_YES;
2761 }
2762
2763 /**
2764  * Iterator for adding at least X peers to a peers connection set.
2765  *
2766  * @param cls closure, MinimumContext
2767  * @param key the key the second Daemon was stored under
2768  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
2769  *
2770  * @return GNUNET_YES to continue iteration
2771  */
2772 static int
2773 minimum_connect_iterator (void *cls,
2774                   const GNUNET_HashCode * key,
2775                   void *value)
2776 {
2777   struct MinimumContext *min_ctx = cls;
2778   uint32_t second_pos;
2779   GNUNET_HashCode first_hash;
2780   unsigned int i;
2781
2782   if (GNUNET_CONTAINER_multihashmap_size(min_ctx->first->connect_peers_working_set) < min_ctx->num_to_add)
2783   {
2784     for (i = 0; i < min_ctx->num_to_add; i++)
2785     {
2786       if (min_ctx->pg_array[i] == min_ctx->current)
2787       {
2788         GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(min_ctx->first->connect_peers_working_set, key, value, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2789         uid_from_hash(key, &second_pos);
2790         hash_from_uid(min_ctx->first_uid, &first_hash);
2791         GNUNET_assert(min_ctx->pg->total > second_pos);
2792         GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(min_ctx->pg->peers[second_pos].connect_peers_working_set, &first_hash, min_ctx->first->daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2793         /* Now we have added this particular connection, remove it from the second peer's map so it's not double counted */
2794         GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(min_ctx->pg->peers[second_pos].connect_peers, &first_hash, min_ctx->first->daemon));
2795       }
2796     }
2797     min_ctx->current++;
2798     return GNUNET_YES;
2799   }
2800   else
2801     return GNUNET_NO; /* We can stop iterating, we have enough peers! */
2802
2803 }
2804
2805
2806 /**
2807  * Iterator for adding peers to a connection set based on a depth first search.
2808  *
2809  * @param cls closure, MinimumContext
2810  * @param key the key the second daemon was stored under
2811  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
2812  *
2813  * @return GNUNET_YES to continue iteration
2814  */
2815 static int
2816 dfs_connect_iterator (void *cls,
2817                   const GNUNET_HashCode * key,
2818                   void *value)
2819 {
2820   struct DFSContext *dfs_ctx = cls;
2821   GNUNET_HashCode first_hash;
2822
2823   if (dfs_ctx->current == dfs_ctx->chosen)
2824     {
2825       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(dfs_ctx->first->connect_peers_working_set, key, value, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2826       uid_from_hash(key, &dfs_ctx->second_uid);
2827       hash_from_uid(dfs_ctx->first_uid, &first_hash);
2828       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(dfs_ctx->pg->peers[dfs_ctx->second_uid].connect_peers_working_set, &first_hash, dfs_ctx->first->daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2829       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(dfs_ctx->pg->peers[dfs_ctx->second_uid].connect_peers, &first_hash, dfs_ctx->first->daemon));
2830       /* Can't remove second from first yet because we are currently iterating, hence the return value in the DFSContext! */
2831       return GNUNET_NO; /* We have found our peer, don't iterate more */
2832     }
2833
2834   dfs_ctx->current++;
2835   return GNUNET_YES;
2836 }
2837
2838
2839 /**
2840  * From the set of connections possible, choose percentage percent of connections
2841  * to actually connect.
2842  *
2843  * @param pg the peergroup we are dealing with
2844  * @param percentage what percent of total connections to make
2845  */
2846 void
2847 choose_random_connections(struct GNUNET_TESTING_PeerGroup *pg, double percentage)
2848 {
2849   struct RandomContext random_ctx;
2850   uint32_t pg_iter;
2851
2852   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2853     {
2854       random_ctx.first_uid = pg_iter;
2855       random_ctx.first = &pg->peers[pg_iter];
2856       random_ctx.percentage = percentage;
2857       random_ctx.pg = pg;
2858       pg->peers[pg_iter].connect_peers_working_set = GNUNET_CONTAINER_multihashmap_create(pg->total);
2859       GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].connect_peers, &random_connect_iterator, &random_ctx);
2860       /* Now remove the old connections */
2861       GNUNET_CONTAINER_multihashmap_destroy(pg->peers[pg_iter].connect_peers);
2862       /* And replace with the random set */
2863       pg->peers[pg_iter].connect_peers = pg->peers[pg_iter].connect_peers_working_set;
2864     }
2865 }
2866
2867 /**
2868  * From the set of connections possible, choose at least num connections per
2869  * peer.
2870  *
2871  * @param pg the peergroup we are dealing with
2872  * @param num how many connections at least should each peer have (if possible)?
2873  */
2874 static void
2875 choose_minimum(struct GNUNET_TESTING_PeerGroup *pg, unsigned int num)
2876 {
2877   struct MinimumContext minimum_ctx;
2878   uint32_t pg_iter;
2879
2880   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2881    {
2882      pg->peers[pg_iter].connect_peers_working_set = GNUNET_CONTAINER_multihashmap_create(num);
2883    }
2884
2885   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2886     {
2887       minimum_ctx.first_uid = pg_iter;
2888       minimum_ctx.pg_array = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_WEAK, 
2889                                                           GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers));
2890       minimum_ctx.first = &pg->peers[pg_iter];
2891       minimum_ctx.pg = pg;
2892       minimum_ctx.num_to_add = num;
2893       minimum_ctx.current = 0;
2894       GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].connect_peers,
2895                                             &minimum_connect_iterator, 
2896                                             &minimum_ctx);
2897     }
2898
2899   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2900     {
2901       /* Remove the "old" connections */
2902       GNUNET_CONTAINER_multihashmap_destroy(pg->peers[pg_iter].connect_peers);
2903       /* And replace with the working set */
2904       pg->peers[pg_iter].connect_peers = pg->peers[pg_iter].connect_peers_working_set;
2905     }
2906
2907 }
2908
2909
2910 static unsigned int
2911 count_workingset_connections(struct GNUNET_TESTING_PeerGroup *pg)
2912 {
2913   unsigned int count;
2914   unsigned int pg_iter;
2915
2916   count = 0;
2917
2918   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2919     {
2920       count += GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers_working_set);
2921     }
2922
2923   return count;
2924 }
2925
2926
2927 static unsigned int count_allowed_connections(struct GNUNET_TESTING_PeerGroup *pg)
2928 {
2929   unsigned int count;
2930   unsigned int pg_iter;
2931
2932   count = 0;
2933
2934   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2935     {
2936       count += GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers);
2937     }
2938
2939   return count;
2940 }
2941
2942
2943 struct FindClosestContext
2944 {
2945   /**
2946    * The currently known closest peer.
2947    */
2948   struct GNUNET_TESTING_Daemon *closest;
2949
2950   /**
2951    * The info for the peer we are adding connections for.
2952    */
2953   struct PeerData *curr_peer;
2954
2955   /**
2956    * The distance (bits) between the current
2957    * peer and the currently known closest.
2958    */
2959   unsigned int closest_dist;
2960
2961   /**
2962    * The offset of the closest known peer in
2963    * the peer group.
2964    */
2965   unsigned int closest_num;
2966 };
2967
2968 /**
2969  * Iterator over hash map entries of the allowed
2970  * peer connections.  Find the closest, not already
2971  * connected peer and return it.
2972  *
2973  * @param cls closure (struct FindClosestContext)
2974  * @param key current key code (hash of offset in pg)
2975  * @param value value in the hash map - a GNUNET_TESTING_Daemon
2976  * @return GNUNET_YES if we should continue to
2977  *         iterate,
2978  *         GNUNET_NO if not.
2979  */
2980 static
2981 int find_closest_peers (void *cls, const GNUNET_HashCode * key, void *value)
2982 {
2983   struct FindClosestContext *closest_ctx = cls;
2984   struct GNUNET_TESTING_Daemon *daemon = value;
2985
2986   if (((closest_ctx->closest == NULL) ||
2987        (GNUNET_CRYPTO_hash_matching_bits(&daemon->id.hashPubKey, &closest_ctx->curr_peer->daemon->id.hashPubKey) > closest_ctx->closest_dist))
2988       && (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(closest_ctx->curr_peer->connect_peers, key)))
2989     {
2990       closest_ctx->closest_dist = GNUNET_CRYPTO_hash_matching_bits(&daemon->id.hashPubKey, &closest_ctx->curr_peer->daemon->id.hashPubKey);
2991       closest_ctx->closest = daemon;
2992       uid_from_hash(key, &closest_ctx->closest_num);
2993     }
2994   return GNUNET_YES;
2995 }
2996
2997 /**
2998  * From the set of connections possible, choose at num connections per
2999  * peer based on depth which are closest out of those allowed.  Guaranteed
3000  * to add num peers to connect to, provided there are that many peers
3001  * in the underlay topology to connect to.
3002  *
3003  * @param pg the peergroup we are dealing with
3004  * @param num how many connections at least should each peer have (if possible)?
3005  * @param proc processor to actually add the connections
3006  */
3007 void
3008 add_closest (struct GNUNET_TESTING_PeerGroup *pg, unsigned int num, GNUNET_TESTING_ConnectionProcessor proc)
3009 {
3010   struct FindClosestContext closest_ctx;
3011   uint32_t pg_iter;
3012   uint32_t i;
3013
3014   for (i = 0; i < num; i++) /* Each time find a closest peer (from those available) */
3015     {
3016       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3017         {
3018           closest_ctx.curr_peer = &pg->peers[pg_iter];
3019           closest_ctx.closest = NULL;
3020           closest_ctx.closest_dist = 0;
3021           closest_ctx.closest_num = 0;
3022           GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].allowed_peers, &find_closest_peers, &closest_ctx);
3023           if (closest_ctx.closest != NULL)
3024             {
3025               GNUNET_assert(closest_ctx.closest_num < pg->total);
3026               proc(pg, pg_iter, closest_ctx.closest_num);
3027             }
3028         }
3029     }
3030 }
3031
3032 /**
3033  * From the set of connections possible, choose at least num connections per
3034  * peer based on depth first traversal of peer connections.  If DFS leaves
3035  * peers unconnected, ensure those peers get connections.
3036  *
3037  * @param pg the peergroup we are dealing with
3038  * @param num how many connections at least should each peer have (if possible)?
3039  */
3040 void
3041 perform_dfs (struct GNUNET_TESTING_PeerGroup *pg, unsigned int num)
3042 {
3043   struct DFSContext dfs_ctx;
3044   uint32_t pg_iter;
3045   uint32_t dfs_count;
3046   uint32_t starting_peer;
3047   uint32_t least_connections;
3048   GNUNET_HashCode second_hash;
3049
3050   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3051     {
3052       pg->peers[pg_iter].connect_peers_working_set = GNUNET_CONTAINER_multihashmap_create(num);
3053     }
3054
3055   starting_peer = 0;
3056   dfs_count = 0;
3057   while ((count_workingset_connections(pg) < num * pg->total) && (count_allowed_connections(pg) > 0))
3058     {
3059       if (dfs_count % pg->total == 0) /* Restart the DFS at some weakly connected peer */
3060         {
3061           least_connections = -1; /* Set to very high number */
3062           for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3063             {
3064               if (GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers_working_set) < least_connections)
3065                 {
3066                   starting_peer = pg_iter;
3067                   least_connections = GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers_working_set);
3068                 }
3069             }
3070         }
3071
3072       if (GNUNET_CONTAINER_multihashmap_size(pg->peers[starting_peer].connect_peers) == 0)  /* Ensure there is at least one peer left to connect! */
3073         {
3074           dfs_count = 0;
3075           continue;
3076         }
3077
3078       /* Choose a random peer from the chosen peers set of connections to add */
3079       dfs_ctx.chosen = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, GNUNET_CONTAINER_multihashmap_size(pg->peers[starting_peer].connect_peers));
3080       dfs_ctx.first_uid = starting_peer;
3081       dfs_ctx.first = &pg->peers[starting_peer];
3082       dfs_ctx.pg = pg;
3083       dfs_ctx.current = 0;
3084
3085       GNUNET_CONTAINER_multihashmap_iterate(pg->peers[starting_peer].connect_peers, &dfs_connect_iterator, &dfs_ctx);
3086       /* Remove the second from the first, since we will be continuing the search and may encounter the first peer again! */
3087       hash_from_uid(dfs_ctx.second_uid, &second_hash);
3088       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(pg->peers[starting_peer].connect_peers, &second_hash, pg->peers[dfs_ctx.second_uid].daemon));
3089       starting_peer = dfs_ctx.second_uid;
3090     }
3091
3092   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3093     {
3094       /* Remove the "old" connections */
3095       GNUNET_CONTAINER_multihashmap_destroy(pg->peers[pg_iter].connect_peers);
3096       /* And replace with the working set */
3097       pg->peers[pg_iter].connect_peers = pg->peers[pg_iter].connect_peers_working_set;
3098     }
3099 }
3100
3101 /**
3102  * Internal callback for topology information for a particular peer.
3103  */
3104 static void
3105 internal_topology_callback(void *cls,
3106                            const struct GNUNET_PeerIdentity *peer,
3107                            const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3108 {
3109   struct CoreContext *core_ctx = cls;
3110   struct TopologyIterateContext *iter_ctx = core_ctx->iter_context;
3111
3112   if (peer == NULL) /* Either finished, or something went wrong */
3113     {
3114       iter_ctx->completed++;
3115       iter_ctx->connected--;
3116       /* One core context allocated per iteration, must free! */
3117       GNUNET_free(core_ctx);
3118     }
3119   else
3120     {
3121       iter_ctx->topology_cb(iter_ctx->cls, &core_ctx->daemon->id,
3122                             peer, NULL);
3123     }
3124
3125   if (iter_ctx->completed == iter_ctx->total)
3126     {
3127       iter_ctx->topology_cb(iter_ctx->cls, NULL, NULL, 
3128                             NULL);
3129       /* Once all are done, free the iteration context */
3130       GNUNET_free(iter_ctx);
3131     }
3132 }
3133
3134
3135 /**
3136  * Check running topology iteration tasks, if below max start a new one, otherwise
3137  * schedule for some time in the future.
3138  */
3139 static void
3140 schedule_get_topology(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3141 {
3142   struct CoreContext *core_context = cls;
3143   struct TopologyIterateContext *topology_context = (struct TopologyIterateContext *)core_context->iter_context;
3144   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3145     return;
3146
3147   if (topology_context->connected > MAX_OUTSTANDING_CONNECTIONS)
3148     {
3149 #if VERBOSE_TESTING > 2
3150           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3151                       _("Delaying connect, we have too many outstanding connections!\n"));
3152 #endif
3153       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_get_topology, core_context);
3154     }
3155   else
3156     {
3157 #if VERBOSE_TESTING > 2
3158           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3159                       _("Creating connection, outstanding_connections is %d\n"), outstanding_connects);
3160 #endif
3161       topology_context->connected++;
3162       if (GNUNET_OK != GNUNET_CORE_iterate_peers (core_context->daemon->server, &internal_topology_callback, core_context))
3163         internal_topology_callback(core_context, NULL, NULL);
3164
3165     }
3166 }
3167
3168 /**
3169  * Iterate over all (running) peers in the peer group, retrieve
3170  * all connections that each currently has.
3171  */
3172 void
3173 GNUNET_TESTING_get_topology (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_NotifyTopology cb, void *cls)
3174 {
3175   struct TopologyIterateContext *topology_context;
3176   struct CoreContext *core_ctx;
3177   unsigned int i;
3178   unsigned int total_count;
3179
3180   /* Allocate a single topology iteration context */
3181   topology_context = GNUNET_malloc(sizeof(struct TopologyIterateContext));
3182   topology_context->topology_cb = cb;
3183   topology_context->cls = cls;
3184   total_count = 0;
3185   for (i = 0; i < pg->total; i++)
3186     {
3187       if (pg->peers[i].daemon->running == GNUNET_YES)
3188         {
3189           /* Allocate one core context per core we need to connect to */
3190           core_ctx = GNUNET_malloc(sizeof(struct CoreContext));
3191           core_ctx->daemon = pg->peers[i].daemon;
3192           /* Set back pointer to topology iteration context */
3193           core_ctx->iter_context = topology_context;
3194           GNUNET_SCHEDULER_add_now(&schedule_get_topology, core_ctx);
3195           total_count++;
3196         }
3197     }
3198   if (total_count == 0)
3199     {
3200       cb(cls, NULL, NULL, "Cannot iterate over topology, no running peers!");
3201       GNUNET_free(topology_context);
3202     }
3203   else
3204     topology_context->total = total_count;
3205   return;
3206 }
3207
3208 /**
3209  * Callback function to process statistic values.
3210  * This handler is here only really to insert a peer
3211  * identity (or daemon) so the statistics can be uniquely
3212  * tied to a single running peer.
3213  *
3214  * @param cls closure
3215  * @param subsystem name of subsystem that created the statistic
3216  * @param name the name of the datum
3217  * @param value the current value
3218  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
3219  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
3220  */
3221 static int internal_stats_callback (void *cls,
3222                                     const char *subsystem,
3223                                     const char *name,
3224                                     uint64_t value,
3225                                     int is_persistent)
3226 {
3227   struct StatsCoreContext *core_context = cls;
3228   struct StatsIterateContext *stats_context = (struct StatsIterateContext *)core_context->iter_context;
3229
3230   return stats_context->proc(stats_context->cls, &core_context->daemon->id, subsystem, name, value, is_persistent);
3231 }
3232
3233 /**
3234  * Internal continuation call for statistics iteration.
3235  *
3236  * @param cls closure, the CoreContext for this iteration
3237  * @param success whether or not the statistics iterations
3238  *        was canceled or not (we don't care)
3239  */
3240 static void internal_stats_cont (void *cls, int success)
3241 {
3242   struct StatsCoreContext *core_context = cls;
3243   struct StatsIterateContext *stats_context = (struct StatsIterateContext *)core_context->iter_context;
3244
3245   stats_context->connected--;
3246   stats_context->completed++;
3247
3248   if (stats_context->completed == stats_context->total)
3249     {
3250       stats_context->cont(stats_context->cls, GNUNET_YES);
3251       GNUNET_free(stats_context);
3252     }
3253
3254   if (core_context->stats_handle != NULL)
3255     GNUNET_STATISTICS_destroy(core_context->stats_handle, GNUNET_NO);
3256
3257   GNUNET_free(core_context);
3258 }
3259
3260 /**
3261  * Check running topology iteration tasks, if below max start a new one, otherwise
3262  * schedule for some time in the future.
3263  */
3264 static void
3265 schedule_get_statistics(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3266 {
3267   struct StatsCoreContext *core_context = cls;
3268   struct StatsIterateContext *stats_context = (struct StatsIterateContext *)core_context->iter_context;
3269
3270   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3271     return;
3272
3273   if (stats_context->connected > MAX_OUTSTANDING_CONNECTIONS)
3274     {
3275 #if VERBOSE_TESTING > 2
3276           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3277                       _("Delaying connect, we have too many outstanding connections!\n"));
3278 #endif
3279       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_get_statistics, core_context);
3280     }
3281   else
3282     {
3283 #if VERBOSE_TESTING > 2
3284           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3285                       _("Creating connection, outstanding_connections is %d\n"), outstanding_connects);
3286 #endif
3287
3288       stats_context->connected++;
3289       core_context->stats_handle = GNUNET_STATISTICS_create("testing", core_context->daemon->cfg);
3290       if (core_context->stats_handle == NULL)
3291         {
3292           internal_stats_cont (core_context, GNUNET_NO);
3293           return;
3294         }
3295
3296       core_context->stats_get_handle = GNUNET_STATISTICS_get(core_context->stats_handle, NULL, NULL, GNUNET_TIME_relative_get_forever(), &internal_stats_cont, &internal_stats_callback, core_context);
3297       if (core_context->stats_get_handle == NULL)
3298         internal_stats_cont (core_context, GNUNET_NO);
3299
3300     }
3301 }
3302
3303 struct DuplicateStats
3304 {
3305   /**
3306    * Next item in the list
3307    */
3308   struct DuplicateStats *next;
3309
3310   /**
3311    * Nasty string, concatenation of relevant information.
3312    */
3313   char *unique_string;
3314 };
3315
3316 /**
3317  * Check whether the combination of port/host/unix domain socket
3318  * already exists in the list of peers being checked for statistics.
3319  *
3320  * @param pg the peergroup in question
3321  * @param specific_peer the peer we're concerned with
3322  * @param stats_list the list to return to the caller
3323  *
3324  * @return GNUNET_YES if the statistics instance has been seen already,
3325  *         GNUNET_NO if not (and we may have added it to the list)
3326  */
3327 static int
3328 stats_check_existing(struct GNUNET_TESTING_PeerGroup *pg, struct PeerData *specific_peer, struct DuplicateStats **stats_list)
3329 {
3330   struct DuplicateStats *pos;
3331   char *unix_domain_socket;
3332   unsigned long long port;
3333   char *to_match;
3334   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_yesno(pg->cfg, "testing", "single_statistics_per_host"))
3335     return GNUNET_NO; /* Each peer has its own statistics instance, do nothing! */
3336
3337   pos = *stats_list;
3338   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(specific_peer->cfg, "statistics", "unixpath", &unix_domain_socket))
3339     return GNUNET_NO;
3340
3341   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(specific_peer->cfg, "statistics", "port", &port))
3342     return GNUNET_NO;
3343
3344   if (specific_peer->daemon->hostname != NULL)
3345     GNUNET_asprintf(&to_match, "%s%s%llu", specific_peer->daemon->hostname, unix_domain_socket, port);
3346   else
3347     GNUNET_asprintf(&to_match, "%s%llu", unix_domain_socket, port);
3348
3349   while (pos != NULL)
3350     {
3351       if (0 == strcmp(to_match, pos->unique_string))
3352         {
3353           GNUNET_free (unix_domain_socket);
3354           GNUNET_free (to_match);
3355           return GNUNET_YES;
3356         }
3357       pos = pos->next;
3358     }
3359   pos = GNUNET_malloc(sizeof(struct DuplicateStats));
3360   pos->unique_string = to_match;
3361   pos->next = *stats_list;
3362   *stats_list = pos;
3363   GNUNET_free (unix_domain_socket);
3364   return GNUNET_NO;
3365 }
3366
3367 /**
3368  * Iterate over all (running) peers in the peer group, retrieve
3369  * all statistics from each.
3370  */
3371 void
3372 GNUNET_TESTING_get_statistics (struct GNUNET_TESTING_PeerGroup *pg,
3373                                GNUNET_STATISTICS_Callback cont,
3374                                GNUNET_TESTING_STATISTICS_Iterator proc, void *cls)
3375 {
3376   struct StatsIterateContext *stats_context;
3377   struct StatsCoreContext *core_ctx;
3378   unsigned int i;
3379   unsigned int total_count;
3380   struct DuplicateStats *stats_list;
3381   struct DuplicateStats *pos;
3382   stats_list = NULL;
3383
3384   /* Allocate a single stats iteration context */
3385   stats_context = GNUNET_malloc(sizeof(struct StatsIterateContext));
3386   stats_context->cont = cont;
3387   stats_context->proc = proc;
3388   stats_context->cls = cls;
3389   total_count = 0;
3390
3391   for (i = 0; i < pg->total; i++)
3392     {
3393       if ((pg->peers[i].daemon->running == GNUNET_YES) && (GNUNET_NO == stats_check_existing(pg, &pg->peers[i], &stats_list)))
3394         {
3395           /* Allocate one core context per core we need to connect to */
3396           core_ctx = GNUNET_malloc(sizeof(struct StatsCoreContext));
3397           core_ctx->daemon = pg->peers[i].daemon;
3398           /* Set back pointer to topology iteration context */
3399           core_ctx->iter_context = stats_context;
3400           GNUNET_SCHEDULER_add_now(&schedule_get_statistics, core_ctx);
3401           total_count++;
3402         }
3403     }
3404
3405   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Retrieving stats from %u total instances.\n", total_count);
3406   stats_context->total = total_count;
3407   if (stats_list != NULL)
3408     {
3409       pos = stats_list;
3410       while(pos != NULL)
3411         {
3412           GNUNET_free(pos->unique_string);
3413           stats_list = pos->next;
3414           GNUNET_free(pos);
3415           pos = stats_list->next;
3416         }
3417     }
3418   return;
3419 }
3420
3421 /**
3422  * There are many ways to connect peers that are supported by this function.
3423  * To connect peers in the same topology that was created via the
3424  * GNUNET_TESTING_create_topology, the topology variable must be set to
3425  * GNUNET_TESTING_TOPOLOGY_NONE.  If the topology variable is specified,
3426  * a new instance of that topology will be generated and attempted to be
3427  * connected.  This could result in some connections being impossible,
3428  * because some topologies are non-deterministic.
3429  *
3430  * @param pg the peer group struct representing the running peers
3431  * @param topology which topology to connect the peers in
3432  * @param options options for connecting the topology
3433  * @param option_modifier modifier for options that take a parameter
3434  * @param notify_callback notification to be called once all connections completed
3435  * @param notify_cls closure for notification callback
3436  *
3437  * @return the number of connections that will be attempted, GNUNET_SYSERR on error
3438  */
3439 int
3440 GNUNET_TESTING_connect_topology (struct GNUNET_TESTING_PeerGroup *pg,
3441                                  enum GNUNET_TESTING_Topology topology,
3442                                  enum GNUNET_TESTING_TopologyOption options,
3443                                  double option_modifier,
3444                                  GNUNET_TESTING_NotifyCompletion notify_callback,
3445                                  void *notify_cls)
3446 {
3447   switch (topology)
3448       {
3449       case GNUNET_TESTING_TOPOLOGY_CLIQUE:
3450 #if VERBOSE_TOPOLOGY
3451       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3452                   _("Creating clique CONNECT topology\n"));
3453 #endif
3454         create_clique (pg, &add_actual_connections);
3455         break;
3456       case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
3457 #if VERBOSE_TOPOLOGY
3458       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3459                   _("Creating small world (ring) CONNECT topology\n"));
3460 #endif
3461         create_small_world_ring (pg, &add_actual_connections);
3462         break;
3463       case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
3464 #if VERBOSE_TOPOLOGY
3465       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3466                   _("Creating small world (2d-torus) CONNECT topology\n"));
3467 #endif
3468         create_small_world (pg, &add_actual_connections);
3469         break;
3470       case GNUNET_TESTING_TOPOLOGY_RING:
3471 #if VERBOSE_TOPOLOGY
3472       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3473                   _("Creating ring CONNECT topology\n"));
3474 #endif
3475         create_ring (pg, &add_actual_connections);
3476         break;
3477       case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
3478 #if VERBOSE_TOPOLOGY
3479       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3480                   _("Creating 2d torus CONNECT topology\n"));
3481 #endif
3482         create_2d_torus (pg, &add_actual_connections);
3483         break;
3484       case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
3485 #if VERBOSE_TOPOLOGY
3486       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3487                   _("Creating Erdos-Renyi CONNECT topology\n"));
3488 #endif
3489         create_erdos_renyi (pg, &add_actual_connections);
3490         break;
3491       case GNUNET_TESTING_TOPOLOGY_INTERNAT:
3492 #if VERBOSE_TOPOLOGY
3493       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3494                   _("Creating InterNAT CONNECT topology\n"));
3495 #endif
3496         create_nated_internet (pg, &add_actual_connections);
3497         break;
3498       case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
3499 #if VERBOSE_TOPOLOGY
3500       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3501                   _("Creating Scale Free CONNECT topology\n"));
3502 #endif
3503         create_scale_free (pg, &add_actual_connections);
3504         break;
3505       case GNUNET_TESTING_TOPOLOGY_LINE:
3506 #if VERBOSE_TOPOLOGY
3507       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3508                   _("Creating straight line CONNECT topology\n"));
3509 #endif
3510         create_line (pg, &add_actual_connections);
3511         break;
3512       case GNUNET_TESTING_TOPOLOGY_NONE:
3513 #if VERBOSE_TOPOLOGY
3514         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3515                   _("Creating no CONNECT topology\n"));
3516 #endif
3517         copy_allowed_topology(pg);
3518         break;
3519       default:
3520         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
3521                    _("Unknown topology specification, can't connect peers!\n"));
3522         return GNUNET_SYSERR;
3523       }
3524
3525   switch (options)
3526     {
3527     case GNUNET_TESTING_TOPOLOGY_OPTION_RANDOM:
3528 #if VERBOSE_TOPOLOGY
3529       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3530                   _("Connecting random subset (%'.2f percent) of possible peers\n"), 100 * option_modifier);
3531 #endif
3532       choose_random_connections(pg, option_modifier);
3533       break;
3534     case GNUNET_TESTING_TOPOLOGY_OPTION_MINIMUM:
3535 #if VERBOSE_TOPOLOGY
3536       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3537                   _("Connecting a minimum of %u peers each (if possible)\n"), (unsigned int)option_modifier);
3538 #endif
3539       choose_minimum(pg, (unsigned int)option_modifier);
3540       break;
3541     case GNUNET_TESTING_TOPOLOGY_OPTION_DFS:
3542 #if VERBOSE_TOPOLOGY
3543       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3544                   _("Using DFS to connect a minimum of %u peers each (if possible)\n"), (unsigned int)option_modifier);
3545 #endif
3546       perform_dfs(pg, (int)option_modifier);
3547       break;
3548     case GNUNET_TESTING_TOPOLOGY_OPTION_ADD_CLOSEST:
3549 #if VERBOSE_TOPOLOGY
3550       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3551                   _("Finding additional %u closest peers each (if possible)\n"), (unsigned int)option_modifier);
3552 #endif
3553       add_closest(pg, (unsigned int)option_modifier, &add_actual_connections);
3554       break;
3555     case GNUNET_TESTING_TOPOLOGY_OPTION_NONE:
3556       break;
3557     case GNUNET_TESTING_TOPOLOGY_OPTION_ALL:
3558       break;
3559     default:
3560       break;
3561     }
3562
3563   return connect_topology(pg, notify_callback, notify_cls);
3564 }
3565
3566 /**
3567  * Callback that is called whenever a hostkey is generated
3568  * for a peer.  Call the real callback and decrement the
3569  * starting counter for the peergroup.
3570  *
3571  * @param cls closure
3572  * @param id identifier for the daemon, NULL on error
3573  * @param d handle for the daemon
3574  * @param emsg error message (NULL on success)
3575  */
3576 static void internal_hostkey_callback (void *cls,
3577                                        const struct GNUNET_PeerIdentity *id,
3578                                        struct GNUNET_TESTING_Daemon *d,
3579                                        const char *emsg)
3580 {
3581   struct InternalStartContext *internal_context = cls;
3582   internal_context->peer->pg->starting--;
3583   internal_context->peer->pg->started++;
3584   if (internal_context->hostkey_callback != NULL)
3585     internal_context->hostkey_callback(internal_context->hostkey_cls, id, d, emsg);
3586   else if (internal_context->peer->pg->started == internal_context->peer->pg->total)
3587     {
3588       internal_context->peer->pg->started = 0; /* Internal startup may use this counter! */
3589       GNUNET_TESTING_daemons_continue_startup(internal_context->peer->pg);
3590     }
3591 }
3592
3593 /**
3594  * Callback that is called whenever a peer has finished starting.
3595  * Call the real callback and decrement the starting counter
3596  * for the peergroup.
3597  *
3598  * @param cls closure
3599  * @param id identifier for the daemon, NULL on error
3600  * @param d handle for the daemon
3601  * @param emsg error message (NULL on success)
3602  */
3603 static void internal_startup_callback (void *cls,
3604                                        const struct GNUNET_PeerIdentity *id,
3605                                        const struct GNUNET_CONFIGURATION_Handle *cfg,
3606                                        struct GNUNET_TESTING_Daemon *d,
3607                                        const char *emsg)
3608 {
3609   struct InternalStartContext *internal_context = cls;
3610   internal_context->peer->pg->starting--;
3611   if (internal_context->start_cb != NULL)
3612     internal_context->start_cb(internal_context->start_cb_cls, id, cfg, d, emsg);
3613 }
3614
3615 static void
3616 internal_continue_startup (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
3617 {
3618   struct InternalStartContext *internal_context = cls;
3619
3620   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3621     {
3622       return;
3623     }
3624
3625   if (internal_context->peer->pg->starting < MAX_CONCURRENT_STARTING)
3626     {
3627       internal_context->peer->pg->starting++;
3628       GNUNET_TESTING_daemon_continue_startup (internal_context->peer->daemon);
3629     }
3630   else
3631     {
3632       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &internal_continue_startup, internal_context);
3633     }
3634 }
3635
3636
3637 /**
3638  * Callback for informing us about a successful
3639  * or unsuccessful churn start call.
3640  *
3641  * @param cls a ChurnContext
3642  * @param id the peer identity of the started peer
3643  * @param cfg the handle to the configuration of the peer
3644  * @param d handle to the daemon for the peer
3645  * @param emsg NULL on success, non-NULL on failure
3646  *
3647  */
3648 void
3649 churn_start_callback (void *cls,
3650                       const struct GNUNET_PeerIdentity *id,
3651                       const struct GNUNET_CONFIGURATION_Handle *cfg,
3652                       struct GNUNET_TESTING_Daemon *d,
3653                       const char *emsg)
3654 {
3655   struct ChurnRestartContext *startup_ctx = cls;
3656   struct ChurnContext *churn_ctx = startup_ctx->churn_ctx;
3657
3658   unsigned int total_left;
3659   char *error_message;
3660
3661   error_message = NULL;
3662   if (emsg != NULL)
3663     {
3664       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3665                   "Churn stop callback failed with error `%s'\n",
3666                   emsg);
3667       churn_ctx->num_failed_start++;
3668     }
3669   else
3670     {
3671       churn_ctx->num_to_start--;
3672     }
3673
3674 #if DEBUG_CHURN
3675   GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
3676              "Started peer, %d left.\n",
3677              churn_ctx->num_to_start);
3678 #endif
3679
3680   total_left = (churn_ctx->num_to_stop - churn_ctx->num_failed_stop) + (churn_ctx->num_to_start - churn_ctx->num_failed_start);
3681
3682   if (total_left == 0)
3683   {
3684     if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
3685       GNUNET_asprintf(&error_message,
3686                       "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!",
3687                       churn_ctx->num_failed_start,
3688                       churn_ctx->num_failed_stop);
3689     churn_ctx->cb(churn_ctx->cb_cls, error_message);
3690     GNUNET_free_non_null(error_message);
3691     GNUNET_free(churn_ctx);
3692     GNUNET_free(startup_ctx);
3693   }
3694 }
3695
3696
3697 static void schedule_churn_restart(void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
3698 {
3699   struct PeerRestartContext *peer_restart_ctx = cls;
3700   struct ChurnRestartContext *startup_ctx = peer_restart_ctx->churn_restart_ctx;
3701
3702   if (startup_ctx->outstanding > MAX_CONCURRENT_STARTING)
3703     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_churn_restart, peer_restart_ctx);
3704   else
3705     {
3706       GNUNET_TESTING_daemon_start_stopped(peer_restart_ctx->daemon,
3707                                           startup_ctx->timeout,
3708                                           &churn_start_callback,
3709                                           startup_ctx);
3710       GNUNET_free(peer_restart_ctx);
3711     }
3712 }
3713
3714 static void
3715 internal_start (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
3716 {
3717   struct InternalStartContext *internal_context = cls;
3718
3719   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3720     {
3721       return;
3722     }
3723
3724   if (internal_context->peer->pg->starting < MAX_CONCURRENT_HOSTKEYS)
3725     {
3726       internal_context->peer->pg->starting++;
3727       internal_context->peer->daemon = GNUNET_TESTING_daemon_start (internal_context->peer->cfg,
3728                                                                     internal_context->timeout,
3729                                                                     internal_context->hostname,
3730                                                                     internal_context->username,
3731                                                                     internal_context->sshport,
3732                                                                     &internal_hostkey_callback,
3733                                                                     internal_context,
3734                                                                     &internal_startup_callback,
3735                                                                     internal_context);
3736     }
3737   else
3738     {
3739       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &internal_start, internal_context);
3740     }
3741 }
3742
3743 /**
3744  * Function which continues a peer group starting up
3745  * after successfully generating hostkeys for each peer.
3746  *
3747  * @param pg the peer group to continue starting
3748  *
3749  */
3750 void
3751 GNUNET_TESTING_daemons_continue_startup(struct GNUNET_TESTING_PeerGroup *pg)
3752 {
3753   unsigned int i;
3754
3755   pg->starting = 0;
3756   for (i = 0; i < pg->total; i++)
3757     {
3758       GNUNET_SCHEDULER_add_now (&internal_continue_startup, &pg->peers[i].internal_context);
3759       //GNUNET_TESTING_daemon_continue_startup(pg->peers[i].daemon);
3760     }
3761 }
3762
3763 /**
3764  * Start count gnunet instances with the same set of transports and
3765  * applications.  The port numbers (any option called "PORT") will be
3766  * adjusted to ensure that no two peers running on the same system
3767  * have the same port(s) in their respective configurations.
3768  *
3769  * @param cfg configuration template to use
3770  * @param total number of daemons to start
3771  * @param timeout total time allowed for peers to start
3772  * @param hostkey_callback function to call on each peers hostkey generation
3773  *        if NULL, peers will be started by this call, if non-null,
3774  *        GNUNET_TESTING_daemons_continue_startup must be called after
3775  *        successful hostkey generation
3776  * @param hostkey_cls closure for hostkey callback
3777  * @param cb function to call on each daemon that was started
3778  * @param cb_cls closure for cb
3779  * @param connect_callback function to call each time two hosts are connected
3780  * @param connect_callback_cls closure for connect_callback
3781  * @param hostnames linked list of hosts to use to start peers on (NULL to run on localhost only)
3782  *
3783  * @return NULL on error, otherwise handle to control peer group
3784  */
3785 struct GNUNET_TESTING_PeerGroup *
3786 GNUNET_TESTING_daemons_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
3787                               unsigned int total,
3788                               struct GNUNET_TIME_Relative timeout,
3789                               GNUNET_TESTING_NotifyHostkeyCreated hostkey_callback,
3790                               void *hostkey_cls,
3791                               GNUNET_TESTING_NotifyDaemonRunning cb,
3792                               void *cb_cls,
3793                               GNUNET_TESTING_NotifyConnection
3794                               connect_callback, void *connect_callback_cls,
3795                               const struct GNUNET_TESTING_Host *hostnames)
3796 {
3797   struct GNUNET_TESTING_PeerGroup *pg;
3798   const struct GNUNET_TESTING_Host *hostpos;
3799 #if 0
3800   char *pos;
3801   const char *rpos;
3802   char *start;
3803 #endif
3804   const char *hostname;
3805   const char *username;
3806   char *baseservicehome;
3807   char *newservicehome;
3808   char *tmpdir;
3809   struct GNUNET_CONFIGURATION_Handle *pcfg;
3810   unsigned int off;
3811   unsigned int hostcnt;
3812   uint16_t minport;
3813   uint16_t sshport;
3814   uint32_t upnum;
3815   uint32_t fdnum;
3816
3817   if (0 == total)
3818     {
3819       GNUNET_break (0);
3820       return NULL;
3821     }
3822   upnum = 0;
3823   fdnum = 0;
3824   pg = GNUNET_malloc (sizeof (struct GNUNET_TESTING_PeerGroup));
3825   pg->cfg = cfg;
3826   pg->notify_connection = connect_callback;
3827   pg->notify_connection_cls = connect_callback_cls;
3828   pg->total = total;
3829   pg->max_timeout = GNUNET_TIME_relative_to_absolute(timeout);
3830   pg->peers = GNUNET_malloc (total * sizeof (struct PeerData));
3831   if (NULL != hostnames)
3832     {
3833       off = 0;
3834       hostpos = hostnames;
3835       while (hostpos != NULL)
3836         {
3837           hostpos = hostpos->next;
3838           off++;
3839         }
3840       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
3841       off = 0;
3842
3843       hostpos = hostnames;
3844       while (hostpos != NULL)
3845         {
3846           pg->hosts[off].minport = LOW_PORT;
3847           pg->hosts[off].hostname = GNUNET_strdup(hostpos->hostname);
3848           if (hostpos->username != NULL)
3849             pg->hosts[off].username = GNUNET_strdup(hostpos->username);
3850           pg->hosts[off].sshport = hostpos->port;
3851           hostpos = hostpos->next;
3852           off++;
3853         }
3854
3855       if (off == 0)
3856         {
3857           pg->hosts = NULL;
3858         }
3859       hostcnt = off;
3860       minport = 0;
3861       pg->num_hosts = off;
3862
3863 #if NO_LL
3864       off = 2;
3865       /* skip leading spaces */
3866       while ((0 != *hostnames) && (isspace ( (unsigned char) *hostnames)))
3867         hostnames++;
3868       rpos = hostnames;
3869       while ('\0' != *rpos)
3870         {
3871           if (isspace ( (unsigned char) *rpos))
3872             off++;
3873           rpos++;
3874         }
3875       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
3876       off = 0;
3877       start = GNUNET_strdup (hostnames);
3878       pos = start;
3879       while ('\0' != *pos)
3880         {
3881           if (isspace ( (unsigned char) *pos))
3882             {
3883               *pos = '\0';
3884               if (strlen (start) > 0)
3885                 {
3886                   pg->hosts[off].minport = LOW_PORT;
3887                   pg->hosts[off++].hostname = start;
3888                 }
3889               start = pos + 1;
3890             }
3891           pos++;
3892         }
3893       if (strlen (start) > 0)
3894         {
3895           pg->hosts[off].minport = LOW_PORT;
3896           pg->hosts[off++].hostname = start;
3897         }
3898       if (off == 0)
3899         {
3900           GNUNET_free (start);
3901           GNUNET_free (pg->hosts);
3902           pg->hosts = NULL;
3903         }
3904       hostcnt = off;
3905       minport = 0;              /* make gcc happy */
3906 #endif
3907     }
3908   else
3909     {
3910       hostcnt = 0;
3911       minport = LOW_PORT;
3912     }
3913   for (off = 0; off < total; off++)
3914     {
3915       if (hostcnt > 0)
3916         {
3917           hostname = pg->hosts[off % hostcnt].hostname;
3918           username = pg->hosts[off % hostcnt].username;
3919           sshport = pg->hosts[off % hostcnt].sshport;
3920           pcfg = make_config (cfg, 
3921                               &pg->hosts[off % hostcnt].minport,
3922                               &upnum,
3923                               hostname, &fdnum);
3924         }
3925       else
3926         {
3927           hostname = NULL;
3928           username = NULL;
3929           sshport = 0;
3930           pcfg = make_config (cfg,
3931                               &minport,
3932                               &upnum,
3933                               hostname, &fdnum);
3934         }
3935
3936       if (NULL == pcfg)
3937         {
3938           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3939                       _
3940                       ("Could not create configuration for peer number %u on `%s'!\n"),
3941                       off, hostname == NULL ? "localhost" : hostname);
3942           continue;
3943         }
3944
3945       if (GNUNET_YES ==
3946           GNUNET_CONFIGURATION_get_value_string (pcfg, "PATHS", "SERVICEHOME",
3947                                                  &baseservicehome))
3948         {
3949           GNUNET_asprintf (&newservicehome,
3950                            "%s/%d/", baseservicehome, off);
3951           GNUNET_free (baseservicehome);
3952         }
3953       else
3954         {
3955           tmpdir = getenv ("TMPDIR");
3956           tmpdir = tmpdir ? tmpdir : "/tmp";
3957           GNUNET_asprintf (&newservicehome,
3958                            "%s/%s/%d/",
3959                            tmpdir,
3960                            "gnunet-testing-test-test", off);
3961         }
3962       GNUNET_CONFIGURATION_set_value_string (pcfg,
3963                                              "PATHS",
3964                                              "SERVICEHOME", newservicehome);
3965       GNUNET_free (newservicehome);
3966       pg->peers[off].cfg = pcfg;
3967       pg->peers[off].allowed_peers = GNUNET_CONTAINER_multihashmap_create(total);
3968       pg->peers[off].connect_peers = GNUNET_CONTAINER_multihashmap_create(total);
3969       pg->peers[off].blacklisted_peers = GNUNET_CONTAINER_multihashmap_create(total);
3970       pg->peers[off].pg = pg;
3971
3972       pg->peers[off].internal_context.peer = &pg->peers[off];
3973       pg->peers[off].internal_context.timeout = timeout;
3974       pg->peers[off].internal_context.hostname = hostname;
3975       pg->peers[off].internal_context.username = username;
3976       pg->peers[off].internal_context.sshport = sshport;
3977       pg->peers[off].internal_context.hostkey_callback = hostkey_callback;
3978       pg->peers[off].internal_context.hostkey_cls = hostkey_cls;
3979       pg->peers[off].internal_context.start_cb = cb;
3980       pg->peers[off].internal_context.start_cb_cls = cb_cls;
3981
3982       GNUNET_SCHEDULER_add_now (&internal_start, &pg->peers[off].internal_context);
3983
3984     }
3985   return pg;
3986 }
3987
3988 /*
3989  * Get a daemon by number, so callers don't have to do nasty
3990  * offsetting operation.
3991  */
3992 struct GNUNET_TESTING_Daemon *
3993 GNUNET_TESTING_daemon_get (struct GNUNET_TESTING_PeerGroup *pg, unsigned int position)
3994 {
3995   if (position < pg->total)
3996     return pg->peers[position].daemon;
3997   else
3998     return NULL;
3999 }
4000
4001 /*
4002  * Get a daemon by peer identity, so callers can
4003  * retrieve the daemon without knowing it's offset.
4004  *
4005  * @param pg the peer group to retrieve the daemon from
4006  * @param peer_id the peer identity of the daemon to retrieve
4007  *
4008  * @return the daemon on success, or NULL if no such peer identity is found
4009  */
4010 struct GNUNET_TESTING_Daemon *
4011 GNUNET_TESTING_daemon_get_by_id (struct GNUNET_TESTING_PeerGroup *pg, struct GNUNET_PeerIdentity *peer_id)
4012 {
4013   unsigned int i;
4014
4015   for (i = 0; i < pg->total; i ++)
4016     {
4017       if (0 == memcmp(&pg->peers[i].daemon->id, peer_id, sizeof(struct GNUNET_PeerIdentity)))
4018         return pg->peers[i].daemon;
4019     }
4020
4021   return NULL;
4022 }
4023
4024 /**
4025  * Prototype of a function that will be called when a
4026  * particular operation was completed the testing library.
4027  *
4028  * @param cls closure (a struct RestartContext)
4029  * @param id id of the peer that was restarted
4030  * @param cfg handle to the configuration of the peer
4031  * @param d handle to the daemon that was restarted
4032  * @param emsg NULL on success
4033  */
4034 void restart_callback (void *cls,
4035                        const struct GNUNET_PeerIdentity *id,
4036                        const struct GNUNET_CONFIGURATION_Handle *cfg,
4037                        struct GNUNET_TESTING_Daemon *d,
4038                        const char *emsg)
4039 {
4040   struct RestartContext *restart_context = cls;
4041
4042   if (emsg == NULL)
4043     {
4044       restart_context->peers_restarted++;
4045     }
4046   else
4047     {
4048       restart_context->peers_restart_failed++;
4049     }
4050
4051   if (restart_context->peers_restarted == restart_context->peer_group->total)
4052     {
4053       restart_context->callback(restart_context->callback_cls, NULL);
4054       GNUNET_free(restart_context);
4055     }
4056   else if (restart_context->peers_restart_failed + restart_context->peers_restarted == restart_context->peer_group->total)
4057     {
4058       restart_context->callback(restart_context->callback_cls, "Failed to restart peers!");
4059       GNUNET_free(restart_context);
4060     }
4061
4062 }
4063
4064 /**
4065  * Callback for informing us about a successful
4066  * or unsuccessful churn stop call.
4067  *
4068  * @param cls a ChurnContext
4069  * @param emsg NULL on success, non-NULL on failure
4070  *
4071  */
4072 void
4073 churn_stop_callback (void *cls, const char *emsg)
4074 {
4075   struct ShutdownContext *shutdown_ctx = cls;
4076   struct ChurnContext *churn_ctx = shutdown_ctx->cb_cls;
4077   unsigned int total_left;
4078   char *error_message;
4079
4080   error_message = NULL;
4081   shutdown_ctx->outstanding--;
4082
4083   if (emsg != NULL)
4084     {
4085       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4086                  "Churn stop callback failed with error `%s'\n", emsg);
4087       churn_ctx->num_failed_stop++;
4088     }
4089   else
4090     {
4091       churn_ctx->num_to_stop--;
4092     }
4093
4094 #if DEBUG_CHURN
4095   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4096              "Stopped peer, %d left.\n", 
4097              churn_ctx->num_to_stop);
4098 #endif
4099   total_left = (churn_ctx->num_to_stop - churn_ctx->num_failed_stop) + (churn_ctx->num_to_start - churn_ctx->num_failed_start);
4100
4101   if (total_left == 0)
4102   {
4103     if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
4104       {
4105         GNUNET_asprintf(&error_message, 
4106                         "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!", 
4107                         churn_ctx->num_failed_start, 
4108                         churn_ctx->num_failed_stop);
4109       }
4110     churn_ctx->cb(churn_ctx->cb_cls, error_message);
4111     GNUNET_free_non_null(error_message);
4112     GNUNET_free(churn_ctx);
4113     GNUNET_free(shutdown_ctx);
4114   }
4115 }
4116
4117 /**
4118  * Count the number of running peers.
4119  *
4120  * @param pg handle for the peer group
4121  *
4122  * @return the number of currently running peers in the peer group
4123  */
4124 unsigned int
4125 GNUNET_TESTING_daemons_running (struct GNUNET_TESTING_PeerGroup *pg)
4126 {
4127   unsigned int i;
4128   unsigned int running = 0;
4129   for (i = 0; i < pg->total; i++)
4130   {
4131     if (pg->peers[i].daemon->running == GNUNET_YES)
4132     {
4133       GNUNET_assert(running != -1);
4134       running++;
4135     }
4136   }
4137   return running;
4138 }
4139
4140 /**
4141  * Task to rate limit the number of outstanding peer shutdown
4142  * requests.  This is necessary for making sure we don't do
4143  * too many ssh connections at once, but is generally nicer
4144  * to any system as well (graduated task starts, as opposed
4145  * to calling gnunet-arm N times all at once).
4146  */
4147 static void
4148 schedule_churn_shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
4149 {
4150   struct PeerShutdownContext *peer_shutdown_ctx = cls;
4151   struct ShutdownContext *shutdown_ctx;
4152
4153   GNUNET_assert(peer_shutdown_ctx != NULL);
4154   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
4155   GNUNET_assert(shutdown_ctx != NULL);
4156
4157   if (shutdown_ctx->outstanding > MAX_CONCURRENT_SHUTDOWN)
4158     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_churn_shutdown_task, peer_shutdown_ctx);
4159   else
4160     {
4161       shutdown_ctx->outstanding++;
4162       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon, shutdown_ctx->timeout, shutdown_ctx->cb, shutdown_ctx, GNUNET_NO, GNUNET_YES);
4163       GNUNET_free(peer_shutdown_ctx);
4164     }
4165 }
4166
4167 /**
4168  * Simulate churn by stopping some peers (and possibly
4169  * re-starting others if churn is called multiple times).  This
4170  * function can only be used to create leave-join churn (peers "never"
4171  * leave for good).  First "voff" random peers that are currently
4172  * online will be taken offline; then "von" random peers that are then
4173  * offline will be put back online.  No notifications will be
4174  * generated for any of these operations except for the callback upon
4175  * completion.
4176  *
4177  * @param pg handle for the peer group
4178  * @param voff number of peers that should go offline
4179  * @param von number of peers that should come back online;
4180  *            must be zero on first call (since "testbed_start"
4181  *            always starts all of the peers)
4182  * @param timeout how long to wait for operations to finish before
4183  *        giving up
4184  * @param cb function to call at the end
4185  * @param cb_cls closure for cb
4186  */
4187 void
4188 GNUNET_TESTING_daemons_churn (struct GNUNET_TESTING_PeerGroup *pg,
4189                               unsigned int voff,
4190                               unsigned int von,
4191                               struct GNUNET_TIME_Relative timeout,
4192                               GNUNET_TESTING_NotifyCompletion cb,
4193                               void *cb_cls)
4194 {
4195   struct ChurnContext *churn_ctx;
4196   struct ShutdownContext *shutdown_ctx;
4197   struct PeerShutdownContext *peer_shutdown_ctx;
4198   struct PeerRestartContext *peer_restart_ctx;
4199   struct ChurnRestartContext *churn_startup_ctx;
4200
4201   unsigned int running;
4202   unsigned int stopped;
4203   unsigned int total_running;
4204   unsigned int total_stopped;
4205   unsigned int i;
4206   unsigned int *running_arr;
4207   unsigned int *stopped_arr;
4208   unsigned int *running_permute;
4209   unsigned int *stopped_permute;
4210
4211   running = 0;
4212   stopped = 0;
4213
4214   if ((von == 0) && (voff == 0)) /* No peers at all? */
4215     {
4216       cb(cb_cls, NULL);
4217       return;
4218     }
4219
4220   for (i = 0; i < pg->total; i++)
4221   {
4222     if (pg->peers[i].daemon->running == GNUNET_YES)
4223     {
4224       GNUNET_assert(running != -1);
4225       running++;
4226     }
4227     else
4228     {
4229       GNUNET_assert(stopped != -1);
4230       stopped++;
4231     }
4232   }
4233
4234   if (voff > running)
4235   {
4236     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Trying to stop more peers than are currently running!\n");
4237     cb(cb_cls, "Trying to stop more peers than are currently running!");
4238     return;
4239   }
4240
4241   if (von > stopped)
4242   {
4243     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Trying to start more peers than are currently stopped!\n");
4244     cb(cb_cls, "Trying to start more peers than are currently stopped!");
4245     return;
4246   }
4247
4248   churn_ctx = GNUNET_malloc(sizeof(struct ChurnContext));
4249
4250   running_arr = NULL;
4251   if (running > 0)
4252     running_arr = GNUNET_malloc(running * sizeof(unsigned int));
4253
4254   stopped_arr = NULL;
4255   if (stopped > 0)
4256     stopped_arr = GNUNET_malloc(stopped * sizeof(unsigned int));
4257
4258   running_permute = NULL;
4259   stopped_permute = NULL;
4260
4261   if (running > 0)
4262     running_permute = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_WEAK, running);
4263   if (stopped > 0)
4264     stopped_permute = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_WEAK, stopped);
4265
4266   total_running = running;
4267   total_stopped = stopped;
4268   running = 0;
4269   stopped = 0;
4270
4271   churn_ctx->num_to_start = von;
4272   churn_ctx->num_to_stop = voff;
4273   churn_ctx->cb = cb;
4274   churn_ctx->cb_cls = cb_cls;  
4275
4276   for (i = 0; i < pg->total; i++)
4277   {
4278     if (pg->peers[i].daemon->running == GNUNET_YES)
4279     {
4280       GNUNET_assert((running_arr != NULL) && (total_running > running));
4281       running_arr[running] = i;
4282       running++;
4283     }
4284     else
4285     {
4286       GNUNET_assert((stopped_arr != NULL) && (total_stopped > stopped));
4287       stopped_arr[stopped] = i;
4288       stopped++;
4289     }
4290   }
4291
4292   GNUNET_assert(running >= voff);
4293   if (voff > 0)
4294     {
4295       shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
4296       shutdown_ctx->cb = &churn_stop_callback;
4297       shutdown_ctx->cb_cls = churn_ctx;
4298       shutdown_ctx->total_peers = voff;
4299       shutdown_ctx->timeout = timeout;
4300     }
4301
4302   for (i = 0; i < voff; i++)
4303   {
4304 #if DEBUG_CHURN
4305     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Stopping peer %d!\n", running_permute[i]);
4306 #endif
4307     GNUNET_assert(running_arr != NULL);
4308     peer_shutdown_ctx = GNUNET_malloc(sizeof(struct PeerShutdownContext));
4309     peer_shutdown_ctx->daemon = pg->peers[running_arr[running_permute[i]]].daemon;
4310     peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
4311     GNUNET_SCHEDULER_add_now(&schedule_churn_shutdown_task, peer_shutdown_ctx);
4312
4313     /*
4314     GNUNET_TESTING_daemon_stop (pg->peers[running_arr[running_permute[i]]].daemon,
4315                                 timeout, 
4316                                 &churn_stop_callback, churn_ctx, 
4317                                 GNUNET_NO, GNUNET_YES); */
4318   }
4319
4320   GNUNET_assert(stopped >= von);
4321   if (von > 0)
4322     {
4323       churn_startup_ctx = GNUNET_malloc(sizeof(struct ChurnRestartContext));
4324       churn_startup_ctx->churn_ctx = churn_ctx;
4325       churn_startup_ctx->timeout = timeout;
4326     }
4327   for (i = 0; i < von; i++)
4328     {
4329 #if DEBUG_CHURN
4330       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Starting up peer %d!\n", stopped_permute[i]);
4331 #endif
4332       GNUNET_assert(stopped_arr != NULL);
4333       peer_restart_ctx = GNUNET_malloc(sizeof(struct PeerRestartContext));
4334       peer_restart_ctx->churn_restart_ctx = churn_startup_ctx;
4335       peer_restart_ctx->daemon = pg->peers[stopped_arr[stopped_permute[i]]].daemon;
4336       GNUNET_SCHEDULER_add_now(&schedule_churn_restart, peer_restart_ctx);
4337       /*
4338       GNUNET_TESTING_daemon_start_stopped(pg->peers[stopped_arr[stopped_permute[i]]].daemon, 
4339                                           timeout, &churn_start_callback, churn_ctx);*/
4340   }
4341
4342   GNUNET_free_non_null(running_arr);
4343   GNUNET_free_non_null(stopped_arr);
4344   GNUNET_free_non_null(running_permute);
4345   GNUNET_free_non_null(stopped_permute);
4346 }
4347
4348
4349 /**
4350  * Restart all peers in the given group.
4351  *
4352  * @param pg the handle to the peer group
4353  * @param callback function to call on completion (or failure)
4354  * @param callback_cls closure for the callback function
4355  */
4356 void
4357 GNUNET_TESTING_daemons_restart (struct GNUNET_TESTING_PeerGroup *pg,
4358                                 GNUNET_TESTING_NotifyCompletion callback,
4359                                 void *callback_cls)
4360 {
4361   struct RestartContext *restart_context;
4362   unsigned int off;
4363
4364   if (pg->total > 0)
4365     {
4366       restart_context = GNUNET_malloc(sizeof(struct RestartContext));
4367       restart_context->peer_group = pg;
4368       restart_context->peers_restarted = 0;
4369       restart_context->callback = callback;
4370       restart_context->callback_cls = callback_cls;
4371
4372       for (off = 0; off < pg->total; off++)
4373         {
4374           GNUNET_TESTING_daemon_restart (pg->peers[off].daemon, &restart_callback, restart_context);
4375         }
4376     }
4377 }
4378
4379 /**
4380  * Start or stop an individual peer from the given group.
4381  *
4382  * @param pg handle to the peer group
4383  * @param offset which peer to start or stop
4384  * @param desired_status GNUNET_YES to have it running, GNUNET_NO to stop it
4385  * @param timeout how long to wait for shutdown
4386  * @param cb function to call at the end
4387  * @param cb_cls closure for cb
4388  */
4389 void
4390 GNUNET_TESTING_daemons_vary (struct GNUNET_TESTING_PeerGroup *pg, 
4391                              unsigned int offset,
4392                              int desired_status,
4393                              struct GNUNET_TIME_Relative timeout,
4394                              GNUNET_TESTING_NotifyCompletion cb,
4395                              void *cb_cls)
4396 {
4397   struct ShutdownContext *shutdown_ctx;
4398   struct ChurnRestartContext *startup_ctx;
4399   struct ChurnContext *churn_ctx;
4400
4401   if (GNUNET_NO == desired_status)
4402     {
4403       if (NULL != pg->peers[offset].daemon)
4404         {
4405           shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
4406           churn_ctx = GNUNET_malloc(sizeof(struct ChurnContext));
4407           churn_ctx->num_to_start = 0;
4408           churn_ctx->num_to_stop = 1;
4409           churn_ctx->cb = cb;
4410           churn_ctx->cb_cls = cb_cls;
4411           shutdown_ctx->cb_cls = churn_ctx;
4412           GNUNET_TESTING_daemon_stop(pg->peers[offset].daemon, 
4413                                      timeout, &churn_stop_callback, shutdown_ctx,
4414                                      GNUNET_NO, GNUNET_YES);     
4415         }
4416     }
4417   else if (GNUNET_YES == desired_status)
4418     {
4419       if (NULL == pg->peers[offset].daemon)
4420         {
4421           startup_ctx = GNUNET_malloc(sizeof(struct ChurnRestartContext));
4422           churn_ctx = GNUNET_malloc(sizeof(struct ChurnContext));
4423           churn_ctx->num_to_start = 1;
4424           churn_ctx->num_to_stop = 0;
4425           churn_ctx->cb = cb;
4426           churn_ctx->cb_cls = cb_cls;  
4427           startup_ctx->churn_ctx = churn_ctx;
4428           GNUNET_TESTING_daemon_start_stopped(pg->peers[offset].daemon, 
4429                                               timeout, &churn_start_callback, startup_ctx);
4430         }
4431     }
4432   else
4433     GNUNET_break (0);
4434 }
4435
4436
4437 /**
4438  * Callback for shutting down peers in a peer group.
4439  *
4440  * @param cls closure (struct ShutdownContext)
4441  * @param emsg NULL on success
4442  */
4443 void internal_shutdown_callback (void *cls,
4444                                  const char *emsg)
4445 {
4446   struct ShutdownContext *shutdown_ctx = cls;
4447
4448   shutdown_ctx->outstanding--;
4449   if (emsg == NULL)
4450     {
4451       shutdown_ctx->peers_down++;
4452     }
4453   else
4454     {
4455       shutdown_ctx->peers_failed++;
4456     }
4457
4458   if ((shutdown_ctx->cb != NULL) && (shutdown_ctx->peers_down + shutdown_ctx->peers_failed == shutdown_ctx->total_peers))
4459     {
4460       if (shutdown_ctx->peers_failed > 0)
4461         shutdown_ctx->cb(shutdown_ctx->cb_cls, "Not all peers successfully shut down!");
4462       else
4463         shutdown_ctx->cb(shutdown_ctx->cb_cls, NULL);
4464       GNUNET_free(shutdown_ctx);
4465     }
4466 }
4467
4468
4469 /**
4470  * Task to rate limit the number of outstanding peer shutdown
4471  * requests.  This is necessary for making sure we don't do
4472  * too many ssh connections at once, but is generally nicer
4473  * to any system as well (graduated task starts, as opposed
4474  * to calling gnunet-arm N times all at once).
4475  */
4476 static void
4477 schedule_shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
4478 {
4479   struct PeerShutdownContext *peer_shutdown_ctx = cls;
4480   struct ShutdownContext *shutdown_ctx;
4481
4482   GNUNET_assert(peer_shutdown_ctx != NULL);
4483   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
4484   GNUNET_assert(shutdown_ctx != NULL);
4485
4486   if (shutdown_ctx->outstanding > MAX_CONCURRENT_SHUTDOWN)
4487     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_shutdown_task, peer_shutdown_ctx);
4488   else
4489     {
4490       shutdown_ctx->outstanding++;
4491       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon, shutdown_ctx->timeout, &internal_shutdown_callback, shutdown_ctx, GNUNET_YES, GNUNET_NO);
4492       GNUNET_free(peer_shutdown_ctx);
4493     }
4494 }
4495
4496 /**
4497  * Shutdown all peers started in the given group.
4498  *
4499  * @param pg handle to the peer group
4500  * @param timeout how long to wait for shutdown
4501  * @param cb callback to notify upon success or failure
4502  * @param cb_cls closure for cb
4503  */
4504 void
4505 GNUNET_TESTING_daemons_stop (struct GNUNET_TESTING_PeerGroup *pg, 
4506                              struct GNUNET_TIME_Relative timeout,
4507                              GNUNET_TESTING_NotifyCompletion cb,
4508                              void *cb_cls)
4509 {
4510   unsigned int off;
4511   struct ShutdownContext *shutdown_ctx;
4512   struct PeerShutdownContext *peer_shutdown_ctx;
4513
4514   GNUNET_assert(pg->total > 0);
4515
4516   shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
4517   shutdown_ctx->cb = cb;
4518   shutdown_ctx->cb_cls = cb_cls;
4519   shutdown_ctx->total_peers = pg->total;
4520   shutdown_ctx->timeout = timeout;
4521   /* shtudown_ctx->outstanding = 0; */
4522
4523   for (off = 0; off < pg->total; off++)
4524     {
4525       GNUNET_assert(NULL != pg->peers[off].daemon);
4526       peer_shutdown_ctx = GNUNET_malloc(sizeof(struct PeerShutdownContext));
4527       peer_shutdown_ctx->daemon = pg->peers[off].daemon;
4528       peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
4529       GNUNET_SCHEDULER_add_now(&schedule_shutdown_task, peer_shutdown_ctx);
4530       //GNUNET_TESTING_daemon_stop (pg->peers[off].daemon, timeout, shutdown_cb, shutdown_ctx, GNUNET_YES, GNUNET_NO);
4531       if (NULL != pg->peers[off].cfg)
4532         GNUNET_CONFIGURATION_destroy (pg->peers[off].cfg);
4533       if (pg->peers[off].allowed_peers != NULL)
4534         GNUNET_CONTAINER_multihashmap_destroy(pg->peers[off].allowed_peers);
4535       if (pg->peers[off].connect_peers != NULL)
4536         GNUNET_CONTAINER_multihashmap_destroy(pg->peers[off].connect_peers);
4537       if (pg->peers[off].blacklisted_peers != NULL)
4538         GNUNET_CONTAINER_multihashmap_destroy(pg->peers[off].blacklisted_peers);
4539     }
4540   GNUNET_free (pg->peers);
4541   for (off = 0; off < pg->num_hosts; off++)
4542     {
4543       GNUNET_free (pg->hosts[off].hostname);
4544       GNUNET_free_non_null (pg->hosts[off].username);
4545     }
4546   GNUNET_free_non_null (pg->hosts);
4547   GNUNET_free (pg);
4548 }
4549
4550
4551 /* end of testing_group.c */