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