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