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