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