codesonar fixes
[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                            struct GNUNET_TIME_Relative latency, uint32_t distance)
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, peer, latency, distance, NULL);
3122     }
3123
3124   if (iter_ctx->completed == iter_ctx->total)
3125     {
3126       iter_ctx->topology_cb(iter_ctx->cls, NULL, NULL, GNUNET_TIME_relative_get_zero(), 0, NULL);
3127       /* Once all are done, free the iteration context */
3128       GNUNET_free(iter_ctx);
3129     }
3130 }
3131
3132
3133 /**
3134  * Check running topology iteration tasks, if below max start a new one, otherwise
3135  * schedule for some time in the future.
3136  */
3137 static void
3138 schedule_get_topology(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3139 {
3140   struct CoreContext *core_context = cls;
3141   struct TopologyIterateContext *topology_context = (struct TopologyIterateContext *)core_context->iter_context;
3142   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3143     return;
3144
3145   if (topology_context->connected > MAX_OUTSTANDING_CONNECTIONS)
3146     {
3147 #if VERBOSE_TESTING > 2
3148           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3149                       _("Delaying connect, we have too many outstanding connections!\n"));
3150 #endif
3151       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_get_topology, core_context);
3152     }
3153   else
3154     {
3155 #if VERBOSE_TESTING > 2
3156           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3157                       _("Creating connection, outstanding_connections is %d\n"), outstanding_connects);
3158 #endif
3159       topology_context->connected++;
3160       if (GNUNET_OK != GNUNET_CORE_iterate_peers (core_context->daemon->cfg, &internal_topology_callback, core_context))
3161         internal_topology_callback(core_context, NULL, GNUNET_TIME_relative_get_zero(), 0);
3162
3163     }
3164 }
3165
3166 /**
3167  * Iterate over all (running) peers in the peer group, retrieve
3168  * all connections that each currently has.
3169  */
3170 void
3171 GNUNET_TESTING_get_topology (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_NotifyTopology cb, void *cls)
3172 {
3173   struct TopologyIterateContext *topology_context;
3174   struct CoreContext *core_ctx;
3175   unsigned int i;
3176   unsigned int total_count;
3177
3178   /* Allocate a single topology iteration context */
3179   topology_context = GNUNET_malloc(sizeof(struct TopologyIterateContext));
3180   topology_context->topology_cb = cb;
3181   topology_context->cls = cls;
3182   total_count = 0;
3183   for (i = 0; i < pg->total; i++)
3184     {
3185       if (pg->peers[i].daemon->running == GNUNET_YES)
3186         {
3187           /* Allocate one core context per core we need to connect to */
3188           core_ctx = GNUNET_malloc(sizeof(struct CoreContext));
3189           core_ctx->daemon = pg->peers[i].daemon;
3190           /* Set back pointer to topology iteration context */
3191           core_ctx->iter_context = topology_context;
3192           GNUNET_SCHEDULER_add_now(&schedule_get_topology, core_ctx);
3193           total_count++;
3194         }
3195     }
3196   if (total_count == 0)
3197     {
3198       cb(cls, NULL, NULL, GNUNET_TIME_relative_get_zero(), 0, "Cannot iterate over topology, no running peers!");
3199       GNUNET_free(topology_context);
3200     }
3201   else
3202     topology_context->total = total_count;
3203   return;
3204 }
3205
3206 /**
3207  * Callback function to process statistic values.
3208  * This handler is here only really to insert a peer
3209  * identity (or daemon) so the statistics can be uniquely
3210  * tied to a single running peer.
3211  *
3212  * @param cls closure
3213  * @param subsystem name of subsystem that created the statistic
3214  * @param name the name of the datum
3215  * @param value the current value
3216  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
3217  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
3218  */
3219 static int internal_stats_callback (void *cls,
3220                                     const char *subsystem,
3221                                     const char *name,
3222                                     uint64_t value,
3223                                     int is_persistent)
3224 {
3225   struct StatsCoreContext *core_context = cls;
3226   struct StatsIterateContext *stats_context = (struct StatsIterateContext *)core_context->iter_context;
3227
3228   return stats_context->proc(stats_context->cls, &core_context->daemon->id, subsystem, name, value, is_persistent);
3229 }
3230
3231 /**
3232  * Internal continuation call for statistics iteration.
3233  *
3234  * @param cls closure, the CoreContext for this iteration
3235  * @param success whether or not the statistics iterations
3236  *        was canceled or not (we don't care)
3237  */
3238 static void internal_stats_cont (void *cls, int success)
3239 {
3240   struct StatsCoreContext *core_context = cls;
3241   struct StatsIterateContext *stats_context = (struct StatsIterateContext *)core_context->iter_context;
3242
3243   stats_context->connected--;
3244   stats_context->completed++;
3245
3246   if (stats_context->completed == stats_context->total)
3247     {
3248       stats_context->cont(stats_context->cls, GNUNET_YES);
3249       GNUNET_free(stats_context);
3250     }
3251
3252   if (core_context->stats_handle != NULL)
3253     GNUNET_STATISTICS_destroy(core_context->stats_handle, GNUNET_NO);
3254
3255   GNUNET_free(core_context);
3256 }
3257
3258 /**
3259  * Check running topology iteration tasks, if below max start a new one, otherwise
3260  * schedule for some time in the future.
3261  */
3262 static void
3263 schedule_get_statistics(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3264 {
3265   struct StatsCoreContext *core_context = cls;
3266   struct StatsIterateContext *stats_context = (struct StatsIterateContext *)core_context->iter_context;
3267
3268   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3269     return;
3270
3271   if (stats_context->connected > MAX_OUTSTANDING_CONNECTIONS)
3272     {
3273 #if VERBOSE_TESTING > 2
3274           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3275                       _("Delaying connect, we have too many outstanding connections!\n"));
3276 #endif
3277       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_get_statistics, core_context);
3278     }
3279   else
3280     {
3281 #if VERBOSE_TESTING > 2
3282           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3283                       _("Creating connection, outstanding_connections is %d\n"), outstanding_connects);
3284 #endif
3285
3286       stats_context->connected++;
3287       core_context->stats_handle = GNUNET_STATISTICS_create("testing", core_context->daemon->cfg);
3288       if (core_context->stats_handle == NULL)
3289         {
3290           internal_stats_cont (core_context, GNUNET_NO);
3291           return;
3292         }
3293
3294       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);
3295       if (core_context->stats_get_handle == NULL)
3296         internal_stats_cont (core_context, GNUNET_NO);
3297
3298     }
3299 }
3300
3301 struct DuplicateStats
3302 {
3303   /**
3304    * Next item in the list
3305    */
3306   struct DuplicateStats *next;
3307
3308   /**
3309    * Nasty string, concatenation of relevant information.
3310    */
3311   char *unique_string;
3312 };
3313
3314 /**
3315  * Check whether the combination of port/host/unix domain socket
3316  * already exists in the list of peers being checked for statistics.
3317  *
3318  * @param pg the peergroup in question
3319  * @param specific_peer the peer we're concerned with
3320  * @param stats_list the list to return to the caller
3321  *
3322  * @return GNUNET_YES if the statistics instance has been seen already,
3323  *         GNUNET_NO if not (and we may have added it to the list)
3324  */
3325 static int
3326 stats_check_existing(struct GNUNET_TESTING_PeerGroup *pg, struct PeerData *specific_peer, struct DuplicateStats **stats_list)
3327 {
3328   struct DuplicateStats *pos;
3329   char *unix_domain_socket;
3330   unsigned long long port;
3331   char *to_match;
3332   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_yesno(pg->cfg, "testing", "single_statistics_per_host"))
3333     return GNUNET_NO; /* Each peer has its own statistics instance, do nothing! */
3334
3335   pos = *stats_list;
3336   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(specific_peer->cfg, "statistics", "unixpath", &unix_domain_socket))
3337     return GNUNET_NO;
3338
3339   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(specific_peer->cfg, "statistics", "port", &port))
3340     return GNUNET_NO;
3341
3342   if (specific_peer->daemon->hostname != NULL)
3343     GNUNET_asprintf(&to_match, "%s%s%llu", specific_peer->daemon->hostname, unix_domain_socket, port);
3344   else
3345     GNUNET_asprintf(&to_match, "%s%llu", unix_domain_socket, port);
3346
3347   while (pos != NULL)
3348     {
3349       if (0 == strcmp(to_match, pos->unique_string))
3350         {
3351           GNUNET_free (unix_domain_socket);
3352           GNUNET_free (to_match);
3353           return GNUNET_YES;
3354         }
3355       pos = pos->next;
3356     }
3357   pos = GNUNET_malloc(sizeof(struct DuplicateStats));
3358   pos->unique_string = to_match;
3359   pos->next = *stats_list;
3360   *stats_list = pos;
3361   GNUNET_free (unix_domain_socket);
3362   return GNUNET_NO;
3363 }
3364
3365 /**
3366  * Iterate over all (running) peers in the peer group, retrieve
3367  * all statistics from each.
3368  */
3369 void
3370 GNUNET_TESTING_get_statistics (struct GNUNET_TESTING_PeerGroup *pg,
3371                                GNUNET_STATISTICS_Callback cont,
3372                                GNUNET_TESTING_STATISTICS_Iterator proc, void *cls)
3373 {
3374   struct StatsIterateContext *stats_context;
3375   struct StatsCoreContext *core_ctx;
3376   unsigned int i;
3377   unsigned int total_count;
3378   struct DuplicateStats *stats_list;
3379   struct DuplicateStats *pos;
3380   stats_list = NULL;
3381
3382   /* Allocate a single stats iteration context */
3383   stats_context = GNUNET_malloc(sizeof(struct StatsIterateContext));
3384   stats_context->cont = cont;
3385   stats_context->proc = proc;
3386   stats_context->cls = cls;
3387   total_count = 0;
3388
3389   for (i = 0; i < pg->total; i++)
3390     {
3391       if ((pg->peers[i].daemon->running == GNUNET_YES) && (GNUNET_NO == stats_check_existing(pg, &pg->peers[i], &stats_list)))
3392         {
3393           /* Allocate one core context per core we need to connect to */
3394           core_ctx = GNUNET_malloc(sizeof(struct StatsCoreContext));
3395           core_ctx->daemon = pg->peers[i].daemon;
3396           /* Set back pointer to topology iteration context */
3397           core_ctx->iter_context = stats_context;
3398           GNUNET_SCHEDULER_add_now(&schedule_get_statistics, core_ctx);
3399           total_count++;
3400         }
3401     }
3402
3403   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Retrieving stats from %u total instances.\n", total_count);
3404   stats_context->total = total_count;
3405   if (stats_list != NULL)
3406     {
3407       pos = stats_list;
3408       while(pos != NULL)
3409         {
3410           GNUNET_free(pos->unique_string);
3411           stats_list = pos->next;
3412           GNUNET_free(pos);
3413           pos = stats_list->next;
3414         }
3415     }
3416   return;
3417 }
3418
3419 /**
3420  * There are many ways to connect peers that are supported by this function.
3421  * To connect peers in the same topology that was created via the
3422  * GNUNET_TESTING_create_topology, the topology variable must be set to
3423  * GNUNET_TESTING_TOPOLOGY_NONE.  If the topology variable is specified,
3424  * a new instance of that topology will be generated and attempted to be
3425  * connected.  This could result in some connections being impossible,
3426  * because some topologies are non-deterministic.
3427  *
3428  * @param pg the peer group struct representing the running peers
3429  * @param topology which topology to connect the peers in
3430  * @param options options for connecting the topology
3431  * @param option_modifier modifier for options that take a parameter
3432  * @param notify_callback notification to be called once all connections completed
3433  * @param notify_cls closure for notification callback
3434  *
3435  * @return the number of connections that will be attempted, GNUNET_SYSERR on error
3436  */
3437 int
3438 GNUNET_TESTING_connect_topology (struct GNUNET_TESTING_PeerGroup *pg,
3439                                  enum GNUNET_TESTING_Topology topology,
3440                                  enum GNUNET_TESTING_TopologyOption options,
3441                                  double option_modifier,
3442                                  GNUNET_TESTING_NotifyCompletion notify_callback,
3443                                  void *notify_cls)
3444 {
3445   switch (topology)
3446       {
3447       case GNUNET_TESTING_TOPOLOGY_CLIQUE:
3448 #if VERBOSE_TOPOLOGY
3449       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3450                   _("Creating clique CONNECT topology\n"));
3451 #endif
3452         create_clique (pg, &add_actual_connections);
3453         break;
3454       case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
3455 #if VERBOSE_TOPOLOGY
3456       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3457                   _("Creating small world (ring) CONNECT topology\n"));
3458 #endif
3459         create_small_world_ring (pg, &add_actual_connections);
3460         break;
3461       case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
3462 #if VERBOSE_TOPOLOGY
3463       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3464                   _("Creating small world (2d-torus) CONNECT topology\n"));
3465 #endif
3466         create_small_world (pg, &add_actual_connections);
3467         break;
3468       case GNUNET_TESTING_TOPOLOGY_RING:
3469 #if VERBOSE_TOPOLOGY
3470       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3471                   _("Creating ring CONNECT topology\n"));
3472 #endif
3473         create_ring (pg, &add_actual_connections);
3474         break;
3475       case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
3476 #if VERBOSE_TOPOLOGY
3477       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3478                   _("Creating 2d torus CONNECT topology\n"));
3479 #endif
3480         create_2d_torus (pg, &add_actual_connections);
3481         break;
3482       case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
3483 #if VERBOSE_TOPOLOGY
3484       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3485                   _("Creating Erdos-Renyi CONNECT topology\n"));
3486 #endif
3487         create_erdos_renyi (pg, &add_actual_connections);
3488         break;
3489       case GNUNET_TESTING_TOPOLOGY_INTERNAT:
3490 #if VERBOSE_TOPOLOGY
3491       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3492                   _("Creating InterNAT CONNECT topology\n"));
3493 #endif
3494         create_nated_internet (pg, &add_actual_connections);
3495         break;
3496       case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
3497 #if VERBOSE_TOPOLOGY
3498       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3499                   _("Creating Scale Free CONNECT topology\n"));
3500 #endif
3501         create_scale_free (pg, &add_actual_connections);
3502         break;
3503       case GNUNET_TESTING_TOPOLOGY_LINE:
3504 #if VERBOSE_TOPOLOGY
3505       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3506                   _("Creating straight line CONNECT topology\n"));
3507 #endif
3508         create_line (pg, &add_actual_connections);
3509         break;
3510       case GNUNET_TESTING_TOPOLOGY_NONE:
3511 #if VERBOSE_TOPOLOGY
3512         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3513                   _("Creating no CONNECT topology\n"));
3514 #endif
3515         copy_allowed_topology(pg);
3516         break;
3517       default:
3518         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
3519                    _("Unknown topology specification, can't connect peers!\n"));
3520         return GNUNET_SYSERR;
3521       }
3522
3523   switch (options)
3524     {
3525     case GNUNET_TESTING_TOPOLOGY_OPTION_RANDOM:
3526 #if VERBOSE_TOPOLOGY
3527       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3528                   _("Connecting random subset (%'.2f percent) of possible peers\n"), 100 * option_modifier);
3529 #endif
3530       choose_random_connections(pg, option_modifier);
3531       break;
3532     case GNUNET_TESTING_TOPOLOGY_OPTION_MINIMUM:
3533 #if VERBOSE_TOPOLOGY
3534       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3535                   _("Connecting a minimum of %u peers each (if possible)\n"), (unsigned int)option_modifier);
3536 #endif
3537       choose_minimum(pg, (unsigned int)option_modifier);
3538       break;
3539     case GNUNET_TESTING_TOPOLOGY_OPTION_DFS:
3540 #if VERBOSE_TOPOLOGY
3541       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3542                   _("Using DFS to connect a minimum of %u peers each (if possible)\n"), (unsigned int)option_modifier);
3543 #endif
3544       perform_dfs(pg, (int)option_modifier);
3545       break;
3546     case GNUNET_TESTING_TOPOLOGY_OPTION_ADD_CLOSEST:
3547 #if VERBOSE_TOPOLOGY
3548       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3549                   _("Finding additional %u closest peers each (if possible)\n"), (unsigned int)option_modifier);
3550 #endif
3551       add_closest(pg, (unsigned int)option_modifier, &add_actual_connections);
3552       break;
3553     case GNUNET_TESTING_TOPOLOGY_OPTION_NONE:
3554       break;
3555     case GNUNET_TESTING_TOPOLOGY_OPTION_ALL:
3556       break;
3557     default:
3558       break;
3559     }
3560
3561   return connect_topology(pg, notify_callback, notify_cls);
3562 }
3563
3564 /**
3565  * Callback that is called whenever a hostkey is generated
3566  * for a peer.  Call the real callback and decrement the
3567  * starting counter for the peergroup.
3568  *
3569  * @param cls closure
3570  * @param id identifier for the daemon, NULL on error
3571  * @param d handle for the daemon
3572  * @param emsg error message (NULL on success)
3573  */
3574 static void internal_hostkey_callback (void *cls,
3575                                        const struct GNUNET_PeerIdentity *id,
3576                                        struct GNUNET_TESTING_Daemon *d,
3577                                        const char *emsg)
3578 {
3579   struct InternalStartContext *internal_context = cls;
3580   internal_context->peer->pg->starting--;
3581   internal_context->peer->pg->started++;
3582   if (internal_context->hostkey_callback != NULL)
3583     internal_context->hostkey_callback(internal_context->hostkey_cls, id, d, emsg);
3584   else if (internal_context->peer->pg->started == internal_context->peer->pg->total)
3585     {
3586       internal_context->peer->pg->started = 0; /* Internal startup may use this counter! */
3587       GNUNET_TESTING_daemons_continue_startup(internal_context->peer->pg);
3588     }
3589 }
3590
3591 /**
3592  * Callback that is called whenever a peer has finished starting.
3593  * Call the real callback and decrement the starting counter
3594  * for the peergroup.
3595  *
3596  * @param cls closure
3597  * @param id identifier for the daemon, NULL on error
3598  * @param d handle for the daemon
3599  * @param emsg error message (NULL on success)
3600  */
3601 static void internal_startup_callback (void *cls,
3602                                        const struct GNUNET_PeerIdentity *id,
3603                                        const struct GNUNET_CONFIGURATION_Handle *cfg,
3604                                        struct GNUNET_TESTING_Daemon *d,
3605                                        const char *emsg)
3606 {
3607   struct InternalStartContext *internal_context = cls;
3608   internal_context->peer->pg->starting--;
3609   if (internal_context->start_cb != NULL)
3610     internal_context->start_cb(internal_context->start_cb_cls, id, cfg, d, emsg);
3611 }
3612
3613 static void
3614 internal_continue_startup (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
3615 {
3616   struct InternalStartContext *internal_context = cls;
3617
3618   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3619     {
3620       return;
3621     }
3622
3623   if (internal_context->peer->pg->starting < MAX_CONCURRENT_STARTING)
3624     {
3625       internal_context->peer->pg->starting++;
3626       GNUNET_TESTING_daemon_continue_startup (internal_context->peer->daemon);
3627     }
3628   else
3629     {
3630       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &internal_continue_startup, internal_context);
3631     }
3632 }
3633
3634
3635 /**
3636  * Callback for informing us about a successful
3637  * or unsuccessful churn start call.
3638  *
3639  * @param cls a ChurnContext
3640  * @param id the peer identity of the started peer
3641  * @param cfg the handle to the configuration of the peer
3642  * @param d handle to the daemon for the peer
3643  * @param emsg NULL on success, non-NULL on failure
3644  *
3645  */
3646 void
3647 churn_start_callback (void *cls,
3648                       const struct GNUNET_PeerIdentity *id,
3649                       const struct GNUNET_CONFIGURATION_Handle *cfg,
3650                       struct GNUNET_TESTING_Daemon *d,
3651                       const char *emsg)
3652 {
3653   struct ChurnRestartContext *startup_ctx = cls;
3654   struct ChurnContext *churn_ctx = startup_ctx->churn_ctx;
3655
3656   unsigned int total_left;
3657   char *error_message;
3658
3659   error_message = NULL;
3660   if (emsg != NULL)
3661     {
3662       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3663                   "Churn stop callback failed with error `%s'\n",
3664                   emsg);
3665       churn_ctx->num_failed_start++;
3666     }
3667   else
3668     {
3669       churn_ctx->num_to_start--;
3670     }
3671
3672 #if DEBUG_CHURN
3673   GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
3674              "Started peer, %d left.\n",
3675              churn_ctx->num_to_start);
3676 #endif
3677
3678   total_left = (churn_ctx->num_to_stop - churn_ctx->num_failed_stop) + (churn_ctx->num_to_start - churn_ctx->num_failed_start);
3679
3680   if (total_left == 0)
3681   {
3682     if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
3683       GNUNET_asprintf(&error_message,
3684                       "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!",
3685                       churn_ctx->num_failed_start,
3686                       churn_ctx->num_failed_stop);
3687     churn_ctx->cb(churn_ctx->cb_cls, error_message);
3688     GNUNET_free_non_null(error_message);
3689     GNUNET_free(churn_ctx);
3690     GNUNET_free(startup_ctx);
3691   }
3692 }
3693
3694
3695 static void schedule_churn_restart(void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
3696 {
3697   struct PeerRestartContext *peer_restart_ctx = cls;
3698   struct ChurnRestartContext *startup_ctx = peer_restart_ctx->churn_restart_ctx;
3699
3700   if (startup_ctx->outstanding > MAX_CONCURRENT_STARTING)
3701     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_churn_restart, peer_restart_ctx);
3702   else
3703     {
3704       GNUNET_TESTING_daemon_start_stopped(peer_restart_ctx->daemon,
3705                                           startup_ctx->timeout,
3706                                           &churn_start_callback,
3707                                           startup_ctx);
3708       GNUNET_free(peer_restart_ctx);
3709     }
3710 }
3711
3712 static void
3713 internal_start (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
3714 {
3715   struct InternalStartContext *internal_context = cls;
3716
3717   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3718     {
3719       return;
3720     }
3721
3722   if (internal_context->peer->pg->starting < MAX_CONCURRENT_HOSTKEYS)
3723     {
3724       internal_context->peer->pg->starting++;
3725       internal_context->peer->daemon = GNUNET_TESTING_daemon_start (internal_context->peer->cfg,
3726                                                                     internal_context->timeout,
3727                                                                     internal_context->hostname,
3728                                                                     internal_context->username,
3729                                                                     internal_context->sshport,
3730                                                                     &internal_hostkey_callback,
3731                                                                     internal_context,
3732                                                                     &internal_startup_callback,
3733                                                                     internal_context);
3734     }
3735   else
3736     {
3737       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &internal_start, internal_context);
3738     }
3739 }
3740
3741 /**
3742  * Function which continues a peer group starting up
3743  * after successfully generating hostkeys for each peer.
3744  *
3745  * @param pg the peer group to continue starting
3746  *
3747  */
3748 void
3749 GNUNET_TESTING_daemons_continue_startup(struct GNUNET_TESTING_PeerGroup *pg)
3750 {
3751   unsigned int i;
3752
3753   pg->starting = 0;
3754   for (i = 0; i < pg->total; i++)
3755     {
3756       GNUNET_SCHEDULER_add_now (&internal_continue_startup, &pg->peers[i].internal_context);
3757       //GNUNET_TESTING_daemon_continue_startup(pg->peers[i].daemon);
3758     }
3759 }
3760
3761 /**
3762  * Start count gnunet instances with the same set of transports and
3763  * applications.  The port numbers (any option called "PORT") will be
3764  * adjusted to ensure that no two peers running on the same system
3765  * have the same port(s) in their respective configurations.
3766  *
3767  * @param cfg configuration template to use
3768  * @param total number of daemons to start
3769  * @param timeout total time allowed for peers to start
3770  * @param hostkey_callback function to call on each peers hostkey generation
3771  *        if NULL, peers will be started by this call, if non-null,
3772  *        GNUNET_TESTING_daemons_continue_startup must be called after
3773  *        successful hostkey generation
3774  * @param hostkey_cls closure for hostkey callback
3775  * @param cb function to call on each daemon that was started
3776  * @param cb_cls closure for cb
3777  * @param connect_callback function to call each time two hosts are connected
3778  * @param connect_callback_cls closure for connect_callback
3779  * @param hostnames linked list of hosts to use to start peers on (NULL to run on localhost only)
3780  *
3781  * @return NULL on error, otherwise handle to control peer group
3782  */
3783 struct GNUNET_TESTING_PeerGroup *
3784 GNUNET_TESTING_daemons_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
3785                               unsigned int total,
3786                               struct GNUNET_TIME_Relative timeout,
3787                               GNUNET_TESTING_NotifyHostkeyCreated hostkey_callback,
3788                               void *hostkey_cls,
3789                               GNUNET_TESTING_NotifyDaemonRunning cb,
3790                               void *cb_cls,
3791                               GNUNET_TESTING_NotifyConnection
3792                               connect_callback, void *connect_callback_cls,
3793                               const struct GNUNET_TESTING_Host *hostnames)
3794 {
3795   struct GNUNET_TESTING_PeerGroup *pg;
3796   const struct GNUNET_TESTING_Host *hostpos;
3797 #if 0
3798   char *pos;
3799   const char *rpos;
3800   char *start;
3801 #endif
3802   const char *hostname;
3803   const char *username;
3804   char *baseservicehome;
3805   char *newservicehome;
3806   char *tmpdir;
3807   struct GNUNET_CONFIGURATION_Handle *pcfg;
3808   unsigned int off;
3809   unsigned int hostcnt;
3810   uint16_t minport;
3811   uint16_t sshport;
3812   uint32_t upnum;
3813   uint32_t fdnum;
3814
3815   if (0 == total)
3816     {
3817       GNUNET_break (0);
3818       return NULL;
3819     }
3820   upnum = 0;
3821   fdnum = 0;
3822   pg = GNUNET_malloc (sizeof (struct GNUNET_TESTING_PeerGroup));
3823   pg->cfg = cfg;
3824   pg->notify_connection = connect_callback;
3825   pg->notify_connection_cls = connect_callback_cls;
3826   pg->total = total;
3827   pg->max_timeout = GNUNET_TIME_relative_to_absolute(timeout);
3828   pg->peers = GNUNET_malloc (total * sizeof (struct PeerData));
3829   if (NULL != hostnames)
3830     {
3831       off = 0;
3832       hostpos = hostnames;
3833       while (hostpos != NULL)
3834         {
3835           hostpos = hostpos->next;
3836           off++;
3837         }
3838       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
3839       off = 0;
3840
3841       hostpos = hostnames;
3842       while (hostpos != NULL)
3843         {
3844           pg->hosts[off].minport = LOW_PORT;
3845           pg->hosts[off].hostname = GNUNET_strdup(hostpos->hostname);
3846           if (hostpos->username != NULL)
3847             pg->hosts[off].username = GNUNET_strdup(hostpos->username);
3848           pg->hosts[off].sshport = hostpos->port;
3849           hostpos = hostpos->next;
3850           off++;
3851         }
3852
3853       if (off == 0)
3854         {
3855           pg->hosts = NULL;
3856         }
3857       hostcnt = off;
3858       minport = 0;
3859       pg->num_hosts = off;
3860
3861 #if NO_LL
3862       off = 2;
3863       /* skip leading spaces */
3864       while ((0 != *hostnames) && (isspace ( (unsigned char) *hostnames)))
3865         hostnames++;
3866       rpos = hostnames;
3867       while ('\0' != *rpos)
3868         {
3869           if (isspace ( (unsigned char) *rpos))
3870             off++;
3871           rpos++;
3872         }
3873       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
3874       off = 0;
3875       start = GNUNET_strdup (hostnames);
3876       pos = start;
3877       while ('\0' != *pos)
3878         {
3879           if (isspace ( (unsigned char) *pos))
3880             {
3881               *pos = '\0';
3882               if (strlen (start) > 0)
3883                 {
3884                   pg->hosts[off].minport = LOW_PORT;
3885                   pg->hosts[off++].hostname = start;
3886                 }
3887               start = pos + 1;
3888             }
3889           pos++;
3890         }
3891       if (strlen (start) > 0)
3892         {
3893           pg->hosts[off].minport = LOW_PORT;
3894           pg->hosts[off++].hostname = start;
3895         }
3896       if (off == 0)
3897         {
3898           GNUNET_free (start);
3899           GNUNET_free (pg->hosts);
3900           pg->hosts = NULL;
3901         }
3902       hostcnt = off;
3903       minport = 0;              /* make gcc happy */
3904 #endif
3905     }
3906   else
3907     {
3908       hostcnt = 0;
3909       minport = LOW_PORT;
3910     }
3911   for (off = 0; off < total; off++)
3912     {
3913       if (hostcnt > 0)
3914         {
3915           hostname = pg->hosts[off % hostcnt].hostname;
3916           username = pg->hosts[off % hostcnt].username;
3917           sshport = pg->hosts[off % hostcnt].sshport;
3918           pcfg = make_config (cfg, 
3919                               &pg->hosts[off % hostcnt].minport,
3920                               &upnum,
3921                               hostname, &fdnum);
3922         }
3923       else
3924         {
3925           hostname = NULL;
3926           username = NULL;
3927           sshport = 0;
3928           pcfg = make_config (cfg,
3929                               &minport,
3930                               &upnum,
3931                               hostname, &fdnum);
3932         }
3933
3934       if (NULL == pcfg)
3935         {
3936           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3937                       _
3938                       ("Could not create configuration for peer number %u on `%s'!\n"),
3939                       off, hostname == NULL ? "localhost" : hostname);
3940           continue;
3941         }
3942
3943       if (GNUNET_YES ==
3944           GNUNET_CONFIGURATION_get_value_string (pcfg, "PATHS", "SERVICEHOME",
3945                                                  &baseservicehome))
3946         {
3947           GNUNET_asprintf (&newservicehome,
3948                            "%s/%d/", baseservicehome, off);
3949           GNUNET_free (baseservicehome);
3950         }
3951       else
3952         {
3953           tmpdir = getenv ("TMPDIR");
3954           tmpdir = tmpdir ? tmpdir : "/tmp";
3955           GNUNET_asprintf (&newservicehome,
3956                            "%s/%s/%d/",
3957                            tmpdir,
3958                            "gnunet-testing-test-test", off);
3959         }
3960       GNUNET_CONFIGURATION_set_value_string (pcfg,
3961                                              "PATHS",
3962                                              "SERVICEHOME", newservicehome);
3963       GNUNET_free (newservicehome);
3964       pg->peers[off].cfg = pcfg;
3965       pg->peers[off].allowed_peers = GNUNET_CONTAINER_multihashmap_create(total);
3966       pg->peers[off].connect_peers = GNUNET_CONTAINER_multihashmap_create(total);
3967       pg->peers[off].blacklisted_peers = GNUNET_CONTAINER_multihashmap_create(total);
3968       pg->peers[off].pg = pg;
3969
3970       pg->peers[off].internal_context.peer = &pg->peers[off];
3971       pg->peers[off].internal_context.timeout = timeout;
3972       pg->peers[off].internal_context.hostname = hostname;
3973       pg->peers[off].internal_context.username = username;
3974       pg->peers[off].internal_context.sshport = sshport;
3975       pg->peers[off].internal_context.hostkey_callback = hostkey_callback;
3976       pg->peers[off].internal_context.hostkey_cls = hostkey_cls;
3977       pg->peers[off].internal_context.start_cb = cb;
3978       pg->peers[off].internal_context.start_cb_cls = cb_cls;
3979
3980       GNUNET_SCHEDULER_add_now (&internal_start, &pg->peers[off].internal_context);
3981
3982     }
3983   return pg;
3984 }
3985
3986 /*
3987  * Get a daemon by number, so callers don't have to do nasty
3988  * offsetting operation.
3989  */
3990 struct GNUNET_TESTING_Daemon *
3991 GNUNET_TESTING_daemon_get (struct GNUNET_TESTING_PeerGroup *pg, unsigned int position)
3992 {
3993   if (position < pg->total)
3994     return pg->peers[position].daemon;
3995   else
3996     return NULL;
3997 }
3998
3999 /*
4000  * Get a daemon by peer identity, so callers can
4001  * retrieve the daemon without knowing it's offset.
4002  *
4003  * @param pg the peer group to retrieve the daemon from
4004  * @param peer_id the peer identity of the daemon to retrieve
4005  *
4006  * @return the daemon on success, or NULL if no such peer identity is found
4007  */
4008 struct GNUNET_TESTING_Daemon *
4009 GNUNET_TESTING_daemon_get_by_id (struct GNUNET_TESTING_PeerGroup *pg, struct GNUNET_PeerIdentity *peer_id)
4010 {
4011   unsigned int i;
4012
4013   for (i = 0; i < pg->total; i ++)
4014     {
4015       if (0 == memcmp(&pg->peers[i].daemon->id, peer_id, sizeof(struct GNUNET_PeerIdentity)))
4016         return pg->peers[i].daemon;
4017     }
4018
4019   return NULL;
4020 }
4021
4022 /**
4023  * Prototype of a function that will be called when a
4024  * particular operation was completed the testing library.
4025  *
4026  * @param cls closure (a struct RestartContext)
4027  * @param id id of the peer that was restarted
4028  * @param cfg handle to the configuration of the peer
4029  * @param d handle to the daemon that was restarted
4030  * @param emsg NULL on success
4031  */
4032 void restart_callback (void *cls,
4033                        const struct GNUNET_PeerIdentity *id,
4034                        const struct GNUNET_CONFIGURATION_Handle *cfg,
4035                        struct GNUNET_TESTING_Daemon *d,
4036                        const char *emsg)
4037 {
4038   struct RestartContext *restart_context = cls;
4039
4040   if (emsg == NULL)
4041     {
4042       restart_context->peers_restarted++;
4043     }
4044   else
4045     {
4046       restart_context->peers_restart_failed++;
4047     }
4048
4049   if (restart_context->peers_restarted == restart_context->peer_group->total)
4050     {
4051       restart_context->callback(restart_context->callback_cls, NULL);
4052       GNUNET_free(restart_context);
4053     }
4054   else if (restart_context->peers_restart_failed + restart_context->peers_restarted == restart_context->peer_group->total)
4055     {
4056       restart_context->callback(restart_context->callback_cls, "Failed to restart peers!");
4057       GNUNET_free(restart_context);
4058     }
4059
4060 }
4061
4062 /**
4063  * Callback for informing us about a successful
4064  * or unsuccessful churn stop call.
4065  *
4066  * @param cls a ChurnContext
4067  * @param emsg NULL on success, non-NULL on failure
4068  *
4069  */
4070 void
4071 churn_stop_callback (void *cls, const char *emsg)
4072 {
4073   struct ShutdownContext *shutdown_ctx = cls;
4074   struct ChurnContext *churn_ctx = shutdown_ctx->cb_cls;
4075   unsigned int total_left;
4076   char *error_message;
4077
4078   error_message = NULL;
4079   shutdown_ctx->outstanding--;
4080
4081   if (emsg != NULL)
4082     {
4083       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4084                  "Churn stop callback failed with error `%s'\n", emsg);
4085       churn_ctx->num_failed_stop++;
4086     }
4087   else
4088     {
4089       churn_ctx->num_to_stop--;
4090     }
4091
4092 #if DEBUG_CHURN
4093   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4094              "Stopped peer, %d left.\n", 
4095              churn_ctx->num_to_stop);
4096 #endif
4097   total_left = (churn_ctx->num_to_stop - churn_ctx->num_failed_stop) + (churn_ctx->num_to_start - churn_ctx->num_failed_start);
4098
4099   if (total_left == 0)
4100   {
4101     if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
4102       {
4103         GNUNET_asprintf(&error_message, 
4104                         "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!", 
4105                         churn_ctx->num_failed_start, 
4106                         churn_ctx->num_failed_stop);
4107       }
4108     churn_ctx->cb(churn_ctx->cb_cls, error_message);
4109     GNUNET_free_non_null(error_message);
4110     GNUNET_free(churn_ctx);
4111     GNUNET_free(shutdown_ctx);
4112   }
4113 }
4114
4115 /**
4116  * Count the number of running peers.
4117  *
4118  * @param pg handle for the peer group
4119  *
4120  * @return the number of currently running peers in the peer group
4121  */
4122 unsigned int
4123 GNUNET_TESTING_daemons_running (struct GNUNET_TESTING_PeerGroup *pg)
4124 {
4125   unsigned int i;
4126   unsigned int running = 0;
4127   for (i = 0; i < pg->total; i++)
4128   {
4129     if (pg->peers[i].daemon->running == GNUNET_YES)
4130     {
4131       GNUNET_assert(running != -1);
4132       running++;
4133     }
4134   }
4135   return running;
4136 }
4137
4138 /**
4139  * Task to rate limit the number of outstanding peer shutdown
4140  * requests.  This is necessary for making sure we don't do
4141  * too many ssh connections at once, but is generally nicer
4142  * to any system as well (graduated task starts, as opposed
4143  * to calling gnunet-arm N times all at once).
4144  */
4145 static void
4146 schedule_churn_shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
4147 {
4148   struct PeerShutdownContext *peer_shutdown_ctx = cls;
4149   struct ShutdownContext *shutdown_ctx;
4150
4151   GNUNET_assert(peer_shutdown_ctx != NULL);
4152   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
4153   GNUNET_assert(shutdown_ctx != NULL);
4154
4155   if (shutdown_ctx->outstanding > MAX_CONCURRENT_SHUTDOWN)
4156     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_churn_shutdown_task, peer_shutdown_ctx);
4157   else
4158     {
4159       shutdown_ctx->outstanding++;
4160       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon, shutdown_ctx->timeout, shutdown_ctx->cb, shutdown_ctx, GNUNET_NO, GNUNET_YES);
4161       GNUNET_free(peer_shutdown_ctx);
4162     }
4163 }
4164
4165 /**
4166  * Simulate churn by stopping some peers (and possibly
4167  * re-starting others if churn is called multiple times).  This
4168  * function can only be used to create leave-join churn (peers "never"
4169  * leave for good).  First "voff" random peers that are currently
4170  * online will be taken offline; then "von" random peers that are then
4171  * offline will be put back online.  No notifications will be
4172  * generated for any of these operations except for the callback upon
4173  * completion.
4174  *
4175  * @param pg handle for the peer group
4176  * @param voff number of peers that should go offline
4177  * @param von number of peers that should come back online;
4178  *            must be zero on first call (since "testbed_start"
4179  *            always starts all of the peers)
4180  * @param timeout how long to wait for operations to finish before
4181  *        giving up
4182  * @param cb function to call at the end
4183  * @param cb_cls closure for cb
4184  */
4185 void
4186 GNUNET_TESTING_daemons_churn (struct GNUNET_TESTING_PeerGroup *pg,
4187                               unsigned int voff,
4188                               unsigned int von,
4189                               struct GNUNET_TIME_Relative timeout,
4190                               GNUNET_TESTING_NotifyCompletion cb,
4191                               void *cb_cls)
4192 {
4193   struct ChurnContext *churn_ctx;
4194   struct ShutdownContext *shutdown_ctx;
4195   struct PeerShutdownContext *peer_shutdown_ctx;
4196   struct PeerRestartContext *peer_restart_ctx;
4197   struct ChurnRestartContext *churn_startup_ctx;
4198
4199   unsigned int running;
4200   unsigned int stopped;
4201   unsigned int total_running;
4202   unsigned int total_stopped;
4203   unsigned int i;
4204   unsigned int *running_arr;
4205   unsigned int *stopped_arr;
4206   unsigned int *running_permute;
4207   unsigned int *stopped_permute;
4208
4209   running = 0;
4210   stopped = 0;
4211
4212   if ((von == 0) && (voff == 0)) /* No peers at all? */
4213     {
4214       cb(cb_cls, NULL);
4215       return;
4216     }
4217
4218   for (i = 0; i < pg->total; i++)
4219   {
4220     if (pg->peers[i].daemon->running == GNUNET_YES)
4221     {
4222       GNUNET_assert(running != -1);
4223       running++;
4224     }
4225     else
4226     {
4227       GNUNET_assert(stopped != -1);
4228       stopped++;
4229     }
4230   }
4231
4232   if (voff > running)
4233   {
4234     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Trying to stop more peers than are currently running!\n");
4235     cb(cb_cls, "Trying to stop more peers than are currently running!");
4236     return;
4237   }
4238
4239   if (von > stopped)
4240   {
4241     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Trying to start more peers than are currently stopped!\n");
4242     cb(cb_cls, "Trying to start more peers than are currently stopped!");
4243     return;
4244   }
4245
4246   churn_ctx = GNUNET_malloc(sizeof(struct ChurnContext));
4247
4248   running_arr = NULL;
4249   if (running > 0)
4250     running_arr = GNUNET_malloc(running * sizeof(unsigned int));
4251
4252   stopped_arr = NULL;
4253   if (stopped > 0)
4254     stopped_arr = GNUNET_malloc(stopped * sizeof(unsigned int));
4255
4256   running_permute = NULL;
4257   stopped_permute = NULL;
4258
4259   if (running > 0)
4260     running_permute = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_WEAK, running);
4261   if (stopped > 0)
4262     stopped_permute = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_WEAK, stopped);
4263
4264   total_running = running;
4265   total_stopped = stopped;
4266   running = 0;
4267   stopped = 0;
4268
4269   churn_ctx->num_to_start = von;
4270   churn_ctx->num_to_stop = voff;
4271   churn_ctx->cb = cb;
4272   churn_ctx->cb_cls = cb_cls;  
4273
4274   for (i = 0; i < pg->total; i++)
4275   {
4276     if (pg->peers[i].daemon->running == GNUNET_YES)
4277     {
4278       GNUNET_assert((running_arr != NULL) && (total_running > running));
4279       running_arr[running] = i;
4280       running++;
4281     }
4282     else
4283     {
4284       GNUNET_assert((stopped_arr != NULL) && (total_stopped > stopped));
4285       stopped_arr[stopped] = i;
4286       stopped++;
4287     }
4288   }
4289
4290   GNUNET_assert(running >= voff);
4291   if (voff > 0)
4292     {
4293       shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
4294       shutdown_ctx->cb = &churn_stop_callback;
4295       shutdown_ctx->cb_cls = churn_ctx;
4296       shutdown_ctx->total_peers = voff;
4297       shutdown_ctx->timeout = timeout;
4298     }
4299
4300   for (i = 0; i < voff; i++)
4301   {
4302 #if DEBUG_CHURN
4303     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Stopping peer %d!\n", running_permute[i]);
4304 #endif
4305     GNUNET_assert(running_arr != NULL);
4306     peer_shutdown_ctx = GNUNET_malloc(sizeof(struct PeerShutdownContext));
4307     peer_shutdown_ctx->daemon = pg->peers[running_arr[running_permute[i]]].daemon;
4308     peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
4309     GNUNET_SCHEDULER_add_now(&schedule_churn_shutdown_task, peer_shutdown_ctx);
4310
4311     /*
4312     GNUNET_TESTING_daemon_stop (pg->peers[running_arr[running_permute[i]]].daemon,
4313                                 timeout, 
4314                                 &churn_stop_callback, churn_ctx, 
4315                                 GNUNET_NO, GNUNET_YES); */
4316   }
4317
4318   GNUNET_assert(stopped >= von);
4319   if (von > 0)
4320     {
4321       churn_startup_ctx = GNUNET_malloc(sizeof(struct ChurnRestartContext));
4322       churn_startup_ctx->churn_ctx = churn_ctx;
4323       churn_startup_ctx->timeout = timeout;
4324     }
4325   for (i = 0; i < von; i++)
4326     {
4327 #if DEBUG_CHURN
4328       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Starting up peer %d!\n", stopped_permute[i]);
4329 #endif
4330       GNUNET_assert(stopped_arr != NULL);
4331       peer_restart_ctx = GNUNET_malloc(sizeof(struct PeerRestartContext));
4332       peer_restart_ctx->churn_restart_ctx = churn_startup_ctx;
4333       peer_restart_ctx->daemon = pg->peers[stopped_arr[stopped_permute[i]]].daemon;
4334       GNUNET_SCHEDULER_add_now(&schedule_churn_restart, peer_restart_ctx);
4335       /*
4336       GNUNET_TESTING_daemon_start_stopped(pg->peers[stopped_arr[stopped_permute[i]]].daemon, 
4337                                           timeout, &churn_start_callback, churn_ctx);*/
4338   }
4339
4340   GNUNET_free_non_null(running_arr);
4341   GNUNET_free_non_null(stopped_arr);
4342   GNUNET_free_non_null(running_permute);
4343   GNUNET_free_non_null(stopped_permute);
4344 }
4345
4346
4347 /**
4348  * Restart all peers in the given group.
4349  *
4350  * @param pg the handle to the peer group
4351  * @param callback function to call on completion (or failure)
4352  * @param callback_cls closure for the callback function
4353  */
4354 void
4355 GNUNET_TESTING_daemons_restart (struct GNUNET_TESTING_PeerGroup *pg,
4356                                 GNUNET_TESTING_NotifyCompletion callback,
4357                                 void *callback_cls)
4358 {
4359   struct RestartContext *restart_context;
4360   unsigned int off;
4361
4362   if (pg->total > 0)
4363     {
4364       restart_context = GNUNET_malloc(sizeof(struct RestartContext));
4365       restart_context->peer_group = pg;
4366       restart_context->peers_restarted = 0;
4367       restart_context->callback = callback;
4368       restart_context->callback_cls = callback_cls;
4369
4370       for (off = 0; off < pg->total; off++)
4371         {
4372           GNUNET_TESTING_daemon_restart (pg->peers[off].daemon, &restart_callback, restart_context);
4373         }
4374     }
4375 }
4376
4377 /**
4378  * Start or stop an individual peer from the given group.
4379  *
4380  * @param pg handle to the peer group
4381  * @param offset which peer to start or stop
4382  * @param desired_status GNUNET_YES to have it running, GNUNET_NO to stop it
4383  * @param timeout how long to wait for shutdown
4384  * @param cb function to call at the end
4385  * @param cb_cls closure for cb
4386  */
4387 void
4388 GNUNET_TESTING_daemons_vary (struct GNUNET_TESTING_PeerGroup *pg, 
4389                              unsigned int offset,
4390                              int desired_status,
4391                              struct GNUNET_TIME_Relative timeout,
4392                              GNUNET_TESTING_NotifyCompletion cb,
4393                              void *cb_cls)
4394 {
4395   struct ShutdownContext *shutdown_ctx;
4396   struct ChurnRestartContext *startup_ctx;
4397   struct ChurnContext *churn_ctx;
4398
4399   if (GNUNET_NO == desired_status)
4400     {
4401       if (NULL != pg->peers[offset].daemon)
4402         {
4403           shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
4404           churn_ctx = GNUNET_malloc(sizeof(struct ChurnContext));
4405           churn_ctx->num_to_start = 0;
4406           churn_ctx->num_to_stop = 1;
4407           churn_ctx->cb = cb;
4408           churn_ctx->cb_cls = cb_cls;
4409           shutdown_ctx->cb_cls = churn_ctx;
4410           GNUNET_TESTING_daemon_stop(pg->peers[offset].daemon, 
4411                                      timeout, &churn_stop_callback, shutdown_ctx,
4412                                      GNUNET_NO, GNUNET_YES);     
4413         }
4414     }
4415   else if (GNUNET_YES == desired_status)
4416     {
4417       if (NULL == pg->peers[offset].daemon)
4418         {
4419           startup_ctx = GNUNET_malloc(sizeof(struct ChurnRestartContext));
4420           churn_ctx = GNUNET_malloc(sizeof(struct ChurnContext));
4421           churn_ctx->num_to_start = 1;
4422           churn_ctx->num_to_stop = 0;
4423           churn_ctx->cb = cb;
4424           churn_ctx->cb_cls = cb_cls;  
4425           startup_ctx->churn_ctx = churn_ctx;
4426           GNUNET_TESTING_daemon_start_stopped(pg->peers[offset].daemon, 
4427                                               timeout, &churn_start_callback, startup_ctx);
4428         }
4429     }
4430   else
4431     GNUNET_break (0);
4432 }
4433
4434
4435 /**
4436  * Callback for shutting down peers in a peer group.
4437  *
4438  * @param cls closure (struct ShutdownContext)
4439  * @param emsg NULL on success
4440  */
4441 void internal_shutdown_callback (void *cls,
4442                                  const char *emsg)
4443 {
4444   struct ShutdownContext *shutdown_ctx = cls;
4445
4446   shutdown_ctx->outstanding--;
4447   if (emsg == NULL)
4448     {
4449       shutdown_ctx->peers_down++;
4450     }
4451   else
4452     {
4453       shutdown_ctx->peers_failed++;
4454     }
4455
4456   if ((shutdown_ctx->cb != NULL) && (shutdown_ctx->peers_down + shutdown_ctx->peers_failed == shutdown_ctx->total_peers))
4457     {
4458       if (shutdown_ctx->peers_failed > 0)
4459         shutdown_ctx->cb(shutdown_ctx->cb_cls, "Not all peers successfully shut down!");
4460       else
4461         shutdown_ctx->cb(shutdown_ctx->cb_cls, NULL);
4462       GNUNET_free(shutdown_ctx);
4463     }
4464 }
4465
4466
4467 /**
4468  * Task to rate limit the number of outstanding peer shutdown
4469  * requests.  This is necessary for making sure we don't do
4470  * too many ssh connections at once, but is generally nicer
4471  * to any system as well (graduated task starts, as opposed
4472  * to calling gnunet-arm N times all at once).
4473  */
4474 static void
4475 schedule_shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
4476 {
4477   struct PeerShutdownContext *peer_shutdown_ctx = cls;
4478   struct ShutdownContext *shutdown_ctx;
4479
4480   GNUNET_assert(peer_shutdown_ctx != NULL);
4481   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
4482   GNUNET_assert(shutdown_ctx != NULL);
4483
4484   if (shutdown_ctx->outstanding > MAX_CONCURRENT_SHUTDOWN)
4485     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_shutdown_task, peer_shutdown_ctx);
4486   else
4487     {
4488       shutdown_ctx->outstanding++;
4489       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon, shutdown_ctx->timeout, &internal_shutdown_callback, shutdown_ctx, GNUNET_YES, GNUNET_NO);
4490       GNUNET_free(peer_shutdown_ctx);
4491     }
4492 }
4493
4494 /**
4495  * Shutdown all peers started in the given group.
4496  *
4497  * @param pg handle to the peer group
4498  * @param timeout how long to wait for shutdown
4499  * @param cb callback to notify upon success or failure
4500  * @param cb_cls closure for cb
4501  */
4502 void
4503 GNUNET_TESTING_daemons_stop (struct GNUNET_TESTING_PeerGroup *pg, 
4504                              struct GNUNET_TIME_Relative timeout,
4505                              GNUNET_TESTING_NotifyCompletion cb,
4506                              void *cb_cls)
4507 {
4508   unsigned int off;
4509   struct ShutdownContext *shutdown_ctx;
4510   struct PeerShutdownContext *peer_shutdown_ctx;
4511
4512   GNUNET_assert(pg->total > 0);
4513
4514   shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
4515   shutdown_ctx->cb = cb;
4516   shutdown_ctx->cb_cls = cb_cls;
4517   shutdown_ctx->total_peers = pg->total;
4518   shutdown_ctx->timeout = timeout;
4519   /* shtudown_ctx->outstanding = 0; */
4520
4521   for (off = 0; off < pg->total; off++)
4522     {
4523       GNUNET_assert(NULL != pg->peers[off].daemon);
4524       peer_shutdown_ctx = GNUNET_malloc(sizeof(struct PeerShutdownContext));
4525       peer_shutdown_ctx->daemon = pg->peers[off].daemon;
4526       peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
4527       GNUNET_SCHEDULER_add_now(&schedule_shutdown_task, peer_shutdown_ctx);
4528       //GNUNET_TESTING_daemon_stop (pg->peers[off].daemon, timeout, shutdown_cb, shutdown_ctx, GNUNET_YES, GNUNET_NO);
4529       if (NULL != pg->peers[off].cfg)
4530         GNUNET_CONFIGURATION_destroy (pg->peers[off].cfg);
4531       if (pg->peers[off].allowed_peers != NULL)
4532         GNUNET_CONTAINER_multihashmap_destroy(pg->peers[off].allowed_peers);
4533       if (pg->peers[off].connect_peers != NULL)
4534         GNUNET_CONTAINER_multihashmap_destroy(pg->peers[off].connect_peers);
4535       if (pg->peers[off].blacklisted_peers != NULL)
4536         GNUNET_CONTAINER_multihashmap_destroy(pg->peers[off].blacklisted_peers);
4537     }
4538   GNUNET_free (pg->peers);
4539   for (off = 0; off < pg->num_hosts; off++)
4540     {
4541       GNUNET_free (pg->hosts[off].hostname);
4542       GNUNET_free_non_null (pg->hosts[off].username);
4543     }
4544   GNUNET_free_non_null (pg->hosts);
4545   GNUNET_free (pg);
4546 }
4547
4548
4549 /* end of testing_group.c */