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