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