assertions that Nate should agree with
[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_NO);
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   reset_meter (conn_meter);
2379   free_meter (conn_meter);
2380   return connect_attempts;
2381 }
2382
2383 #if !OLD
2384 /**
2385  * Iterator over hash map entries.
2386  *
2387  * @param cls closure the peer group
2388  * @param key the key stored in the hashmap is the
2389  *            index of the peer to connect to
2390  * @param value value in the hash map, handle to the peer daemon
2391  * @return GNUNET_YES if we should continue to
2392  *         iterate,
2393  *         GNUNET_NO if not.
2394  */
2395 static int
2396 unblacklist_iterator (void *cls,
2397     const GNUNET_HashCode * key,
2398     void *value)
2399   {
2400     struct UnblacklistContext *un_ctx = cls;
2401     uint32_t second_pos;
2402
2403     uid_from_hash (key, &second_pos);
2404
2405     unblacklist_connections(un_ctx->pg, un_ctx->first_uid, second_pos);
2406
2407     return GNUNET_YES;
2408   }
2409 #endif
2410
2411 /**
2412  * Create a blacklist topology based on the allowed topology
2413  * which disallows any connections not in the allowed topology
2414  * at the transport level.
2415  *
2416  * @param pg the peergroup to create the topology on
2417  * @param proc the connection processor to call to allow
2418  *        up connections between two peers
2419  *
2420  * @return the number of connections that were set up
2421  *
2422  */
2423 static unsigned int
2424 copy_allowed(struct GNUNET_TESTING_PeerGroup *pg,
2425              GNUNET_TESTING_ConnectionProcessor proc)
2426 {
2427   struct UnblacklistContext un_ctx;
2428   unsigned int count;
2429   unsigned int total;
2430   struct PeerConnection *iter;
2431
2432   un_ctx.pg = pg;
2433   total = 0;
2434   for (count = 0; count < pg->total - 1; count++)
2435     {
2436       un_ctx.first_uid = count;
2437 #if OLD
2438       iter = pg->peers[count].allowed_peers_head;
2439       while (iter != NULL)
2440         {
2441           remove_connections (pg, count, iter->index, BLACKLIST, GNUNET_YES);
2442           //unblacklist_connections(pg, count, iter->index);
2443           iter = iter->next;
2444         }
2445 #else
2446       total += GNUNET_CONTAINER_multihashmap_iterate(pg->peers[count].allowed_peers, &unblacklist_iterator, &un_ctx);
2447 #endif
2448     }
2449   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Unblacklisted %u peers\n", total);
2450   return total;
2451 }
2452
2453 /**
2454  * Create a topology given a peer group (set of running peers)
2455  * and a connection processor.
2456  *
2457  * @param pg the peergroup to create the topology on
2458  * @param proc the connection processor to call to actually set
2459  *        up connections between two peers
2460  * @param list which list should be modified
2461  *
2462  * @return the number of connections that were set up
2463  *
2464  */
2465 static unsigned int
2466 create_line(struct GNUNET_TESTING_PeerGroup *pg,
2467             GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
2468 {
2469   unsigned int count;
2470   int connect_attempts;
2471
2472   connect_attempts = 0;
2473
2474   /* Connect each peer to the next highest numbered peer */
2475   for (count = 0; count < pg->total - 1; count++)
2476     {
2477 #if VERBOSE_TESTING
2478       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2479           "Connecting peer %d to peer %d\n", count, count + 1);
2480 #endif
2481       connect_attempts += proc (pg, count, count + 1, list, GNUNET_YES);
2482     }
2483
2484   return connect_attempts;
2485 }
2486
2487 /**
2488  * Create a topology given a peer group (set of running peers)
2489  * and a connection processor.
2490  *
2491  * @param pg the peergroup to create the topology on
2492  * @param filename the file to read topology information from
2493  * @param proc the connection processor to call to actually set
2494  *        up connections between two peers
2495  * @param list the peer list to use
2496  *
2497  * @return the number of connections that were set up
2498  *
2499  */
2500 static unsigned int
2501 create_from_file(struct GNUNET_TESTING_PeerGroup *pg, char *filename,
2502                  GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
2503 {
2504   int connect_attempts;
2505   unsigned int first_peer_index;
2506   unsigned int second_peer_index;
2507   connect_attempts = 0;
2508   struct stat frstat;
2509   int count;
2510   char *data;
2511   char *buf;
2512   unsigned int total_peers;
2513
2514   enum States curr_state;
2515
2516   if (GNUNET_OK != GNUNET_DISK_file_test (filename))
2517     GNUNET_DISK_fn_write (filename, NULL, 0, GNUNET_DISK_PERM_USER_READ);
2518
2519   if ((0 != STAT (filename, &frstat)) || (frstat.st_size == 0))
2520     {
2521       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2522                   "Could not open file `%s' specified for topology!", filename);
2523       return connect_attempts;
2524     }
2525
2526   data = GNUNET_malloc_large (frstat.st_size);
2527   GNUNET_assert(data != NULL);
2528   if (frstat.st_size != GNUNET_DISK_fn_read (filename, data, frstat.st_size))
2529     {
2530       GNUNET_log (
2531                   GNUNET_ERROR_TYPE_ERROR,
2532                   "Could not read file %s specified for host list, ending test!",
2533                   filename);
2534       GNUNET_free (data);
2535       return connect_attempts;
2536     }
2537
2538   buf = data;
2539   count = 0;
2540   first_peer_index = 0;
2541   /* First line should contain a single integer, specifying the number of peers */
2542   /* Each subsequent line should contain this format PEER_INDEX:OTHER_PEER_INDEX[,...] */
2543   curr_state = NUM_PEERS;
2544   while (count < frstat.st_size - 1)
2545     {
2546       if ((buf[count] == '\n') || (buf[count] == ' '))
2547         {
2548           count++;
2549           continue;
2550         }
2551
2552       switch (curr_state)
2553         {
2554       case NUM_PEERS:
2555         errno = 0;
2556         total_peers = strtoul(&buf[count], NULL, 10);
2557         if (errno != 0)
2558           {
2559             GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2560                         "Failed to read number of peers from topology file!\n");
2561             GNUNET_free_non_null(data);
2562             return connect_attempts;
2563           }
2564         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2565                     "Read %u total peers in topology\n", total_peers);
2566         GNUNET_assert(total_peers == pg->total);
2567         curr_state = PEER_INDEX;
2568         while ((buf[count] != '\n') && (count < frstat.st_size - 1))
2569           count++;
2570         count++;
2571         break;
2572       case PEER_INDEX:
2573         errno = 0;
2574         first_peer_index = strtoul(&buf[count], NULL, 10);
2575         if (errno != 0)
2576           {
2577             GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2578                         "Failed to read peer index from topology file!\n");
2579             GNUNET_free_non_null(data);
2580             return connect_attempts;
2581           }
2582         while ((buf[count] != ':') && (count < frstat.st_size - 1))
2583           count++;
2584         count++;
2585         curr_state = OTHER_PEER_INDEX;
2586         break;
2587       case COLON:
2588         if (1 == sscanf (&buf[count], ":"))
2589           curr_state = OTHER_PEER_INDEX;
2590         count++;
2591         break;
2592       case OTHER_PEER_INDEX:
2593         errno = 0;
2594         second_peer_index = strtoul(&buf[count], NULL, 10);
2595         if (errno != 0)
2596           {
2597             GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2598                         "Failed to peer index from topology file!\n");
2599             GNUNET_free_non_null(data);
2600             return connect_attempts;
2601           }
2602         /* Assume file is written with first peer 1, but array index is 0 */
2603         connect_attempts += proc (pg, first_peer_index - 1, second_peer_index
2604                                   - 1, list, GNUNET_YES);
2605         while ((buf[count] != '\n') && (buf[count] != ',') && (count
2606             < frstat.st_size - 1))
2607           count++;
2608         if (buf[count] == '\n')
2609           {
2610             curr_state = PEER_INDEX;
2611           }
2612         else if (buf[count] != ',')
2613           {
2614             curr_state = OTHER_PEER_INDEX;
2615           }
2616         count++;
2617         break;
2618       default:
2619         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2620                     "Found bad data in topology file while in state %d!\n",
2621                     curr_state);
2622         GNUNET_break(0);
2623         return connect_attempts;
2624         }
2625
2626     }
2627   return connect_attempts;
2628 }
2629
2630 /**
2631  * Create a topology given a peer group (set of running peers)
2632  * and a connection processor.
2633  *
2634  * @param pg the peergroup to create the topology on
2635  * @param proc the connection processor to call to actually set
2636  *        up connections between two peers
2637  * @param list the peer list to use
2638  *
2639  * @return the number of connections that were set up
2640  *
2641  */
2642 static unsigned int
2643 create_ring(struct GNUNET_TESTING_PeerGroup *pg,
2644             GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
2645 {
2646   unsigned int count;
2647   int connect_attempts;
2648
2649   connect_attempts = 0;
2650
2651   /* Connect each peer to the next highest numbered peer */
2652   for (count = 0; count < pg->total - 1; count++)
2653     {
2654 #if VERBOSE_TESTING
2655       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2656           "Connecting peer %d to peer %d\n", count, count + 1);
2657 #endif
2658       connect_attempts += proc (pg, count, count + 1, list, GNUNET_YES);
2659     }
2660
2661   /* Connect the last peer to the first peer */
2662   connect_attempts += proc (pg, pg->total - 1, 0, list, GNUNET_YES);
2663
2664   return connect_attempts;
2665 }
2666
2667 #if !OLD
2668 /**
2669  * Iterator for writing friends of a peer to a file.
2670  *
2671  * @param cls closure, an open writable file handle
2672  * @param key the key the daemon was stored under
2673  * @param value the GNUNET_TESTING_Daemon that needs to be written.
2674  *
2675  * @return GNUNET_YES to continue iteration
2676  *
2677  * TODO: Could replace friend_file_iterator and blacklist_file_iterator
2678  *       with a single file_iterator that takes a closure which contains
2679  *       the prefix to write before the peer.  Then this could be used
2680  *       for blacklisting multiple transports and writing the friend
2681  *       file.  I'm sure *someone* will complain loudly about other
2682  *       things that negate these functions even existing so no point in
2683  *       "fixing" now.
2684  */
2685 static int
2686 friend_file_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2687   {
2688     FILE *temp_friend_handle = cls;
2689     struct GNUNET_TESTING_Daemon *peer = value;
2690     struct GNUNET_PeerIdentity *temppeer;
2691     struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2692
2693     temppeer = &peer->id;
2694     GNUNET_CRYPTO_hash_to_enc (&temppeer->hashPubKey, &peer_enc);
2695     fprintf (temp_friend_handle, "%s\n", (char *) &peer_enc);
2696
2697     return GNUNET_YES;
2698   }
2699
2700 struct BlacklistContext
2701   {
2702     /*
2703      * The (open) file handle to write to
2704      */
2705     FILE *temp_file_handle;
2706
2707     /*
2708      * The transport that this peer will be blacklisted on.
2709      */
2710     char *transport;
2711   };
2712
2713 /**
2714  * Iterator for writing blacklist data to appropriate files.
2715  *
2716  * @param cls closure, an open writable file handle
2717  * @param key the key the daemon was stored under
2718  * @param value the GNUNET_TESTING_Daemon that needs to be written.
2719  *
2720  * @return GNUNET_YES to continue iteration
2721  */
2722 static int
2723 blacklist_file_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2724   {
2725     struct BlacklistContext *blacklist_ctx = cls;
2726     struct GNUNET_TESTING_Daemon *peer = value;
2727     struct GNUNET_PeerIdentity *temppeer;
2728     struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2729
2730     temppeer = &peer->id;
2731     GNUNET_CRYPTO_hash_to_enc (&temppeer->hashPubKey, &peer_enc);
2732     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Writing entry %s:%s to file\n", blacklist_ctx->transport, (char *) &peer_enc);
2733     fprintf (blacklist_ctx->temp_file_handle, "%s:%s\n",
2734         blacklist_ctx->transport, (char *) &peer_enc);
2735
2736     return GNUNET_YES;
2737   }
2738 #endif
2739
2740 /*
2741  * Create the friend files based on the PeerConnection's
2742  * of each peer in the peer group, and copy the files
2743  * to the appropriate place
2744  *
2745  * @param pg the peer group we are dealing with
2746  */
2747 static int
2748 create_and_copy_friend_files(struct GNUNET_TESTING_PeerGroup *pg)
2749 {
2750   FILE *temp_friend_handle;
2751   unsigned int pg_iter;
2752   char *temp_service_path;
2753   struct GNUNET_OS_Process **procarr;
2754   char *arg;
2755   char *mytemp;
2756 #if NOT_STUPID
2757   enum GNUNET_OS_ProcessStatusType type;
2758   unsigned long return_code;
2759   int count;
2760   int max_wait = 10;
2761 #endif
2762   int ret;
2763
2764   ret = GNUNET_OK;
2765 #if OLD
2766   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2767   struct PeerConnection *conn_iter;
2768 #endif
2769   procarr = GNUNET_malloc (sizeof (struct GNUNET_OS_Process *) * pg->total);
2770   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2771     {
2772       mytemp = GNUNET_DISK_mktemp ("friends");
2773       GNUNET_assert (mytemp != NULL);
2774       temp_friend_handle = fopen (mytemp, "wt");
2775       GNUNET_assert (temp_friend_handle != NULL);
2776 #if OLD
2777       conn_iter = pg->peers[pg_iter].allowed_peers_head;
2778       while (conn_iter != NULL)
2779         {
2780           GNUNET_CRYPTO_hash_to_enc (
2781                                      &pg->peers[conn_iter->index].daemon->id.hashPubKey,
2782                                      &peer_enc);
2783           fprintf (temp_friend_handle, "%s\n", (char *) &peer_enc);
2784           conn_iter = conn_iter->next;
2785         }
2786 #else
2787       GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].allowed_peers,
2788           &friend_file_iterator,
2789           temp_friend_handle);
2790 #endif
2791       fclose (temp_friend_handle);
2792
2793       if (GNUNET_OK
2794           != GNUNET_CONFIGURATION_get_value_string (
2795                                                     pg->peers[pg_iter]. daemon->cfg,
2796                                                     "PATHS", "SERVICEHOME",
2797                                                     &temp_service_path))
2798         {
2799           GNUNET_log (
2800                       GNUNET_ERROR_TYPE_WARNING,
2801                       _
2802                       ("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
2803                       "SERVICEHOME", "PATHS");
2804           if (UNLINK (mytemp) != 0)
2805             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
2806                 mytemp);
2807           GNUNET_free (mytemp);
2808           break;
2809         }
2810
2811       if (pg->peers[pg_iter].daemon->hostname == NULL) /* Local, just copy the file */
2812         {
2813           GNUNET_asprintf (&arg, "%s/friends", temp_service_path);
2814           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "mv", "mv",
2815                                                       mytemp, arg, NULL);
2816           GNUNET_assert(procarr[pg_iter] != NULL);
2817 #if VERBOSE_TESTING
2818           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2819               _("Copying file with command cp %s %s\n"), mytemp, arg);
2820 #endif
2821           ret = GNUNET_OS_process_wait (procarr[pg_iter]); /* FIXME: schedule this, throttle! */
2822           GNUNET_OS_process_close (procarr[pg_iter]);
2823           GNUNET_free (arg);
2824         }
2825       else /* Remote, scp the file to the correct place */
2826         {
2827           if (NULL != pg->peers[pg_iter].daemon->username)
2828             GNUNET_asprintf (&arg, "%s@%s:%s/friends",
2829                              pg->peers[pg_iter].daemon->username,
2830                              pg->peers[pg_iter].daemon->hostname,
2831                              temp_service_path);
2832           else
2833             GNUNET_asprintf (&arg, "%s:%s/friends",
2834                              pg->peers[pg_iter].daemon->hostname,
2835                              temp_service_path);
2836           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "scp", "scp",
2837                                                       mytemp, arg, NULL);
2838           GNUNET_assert(procarr[pg_iter] != NULL);
2839           ret = GNUNET_OS_process_wait (procarr[pg_iter]); /* FIXME: schedule this, throttle! */
2840           GNUNET_OS_process_close (procarr[pg_iter]);
2841           if (ret != GNUNET_OK)
2842             return ret;
2843           procarr[pg_iter] = NULL;
2844 #if VERBOSE_TESTING
2845           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2846               _("Copying file with command scp %s %s\n"), mytemp,
2847               arg);
2848 #endif
2849           GNUNET_free (arg);
2850         }
2851       GNUNET_free (temp_service_path);
2852       GNUNET_free (mytemp);
2853     }
2854
2855 #if NOT_STUPID
2856   count = 0;
2857   ret = GNUNET_SYSERR;
2858   while ((count < max_wait) && (ret != GNUNET_OK))
2859     {
2860       ret = GNUNET_OK;
2861       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2862         {
2863 #if VERBOSE_TESTING
2864           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2865               _("Checking copy status of file %d\n"), pg_iter);
2866 #endif
2867           if (procarr[pg_iter] != NULL) /* Check for already completed! */
2868             {
2869               if (GNUNET_OS_process_status
2870                   (procarr[pg_iter], &type, &return_code) != GNUNET_OK)
2871                 {
2872                   ret = GNUNET_SYSERR;
2873                 }
2874               else if ((type != GNUNET_OS_PROCESS_EXITED)
2875                   || (return_code != 0))
2876                 {
2877                   ret = GNUNET_SYSERR;
2878                 }
2879               else
2880                 {
2881                   GNUNET_OS_process_close (procarr[pg_iter]);
2882                   procarr[pg_iter] = NULL;
2883 #if VERBOSE_TESTING
2884                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2885                       _("File %d copied\n"), pg_iter);
2886 #endif
2887                 }
2888             }
2889         }
2890       count++;
2891       if (ret == GNUNET_SYSERR)
2892         {
2893           /* FIXME: why sleep here? -CG */
2894           sleep (1);
2895         }
2896     }
2897
2898 #if VERBOSE_TESTING
2899   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2900       _("Finished copying all friend files!\n"));
2901 #endif
2902 #endif
2903   GNUNET_free (procarr);
2904   return ret;
2905 }
2906
2907 /*
2908  * Create the blacklist files based on the PeerConnection's
2909  * of each peer in the peer group, and copy the files
2910  * to the appropriate place.
2911  *
2912  * @param pg the peer group we are dealing with
2913  * @param transports space delimited list of transports to blacklist
2914  */
2915 static int
2916 create_and_copy_blacklist_files(struct GNUNET_TESTING_PeerGroup *pg,
2917                                 const char *transports)
2918 {
2919   FILE *temp_file_handle;
2920   unsigned int pg_iter;
2921   char *temp_service_path;
2922   struct GNUNET_OS_Process **procarr;
2923   char *arg;
2924   char *mytemp;
2925   enum GNUNET_OS_ProcessStatusType type;
2926   unsigned long return_code;
2927   int count;
2928   int ret;
2929   int max_wait = 10;
2930   int transport_len;
2931   unsigned int i;
2932   char *pos;
2933   char *temp_transports;
2934   int entry_count;
2935 #if OLD
2936   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2937   struct PeerConnection *conn_iter;
2938 #else
2939   static struct BlacklistContext blacklist_ctx;
2940 #endif
2941
2942   procarr = GNUNET_malloc (sizeof (struct GNUNET_OS_Process *) * pg->total);
2943   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2944     {
2945       mytemp = GNUNET_DISK_mktemp ("blacklist");
2946       GNUNET_assert (mytemp != NULL);
2947       temp_file_handle = fopen (mytemp, "wt");
2948       GNUNET_assert (temp_file_handle != NULL);
2949       temp_transports = GNUNET_strdup (transports);
2950 #if !OLD
2951       blacklist_ctx.temp_file_handle = temp_file_handle;
2952 #endif
2953       transport_len = strlen (temp_transports) + 1;
2954       pos = NULL;
2955
2956       for (i = 0; i < transport_len; i++)
2957         {
2958           if ((temp_transports[i] == ' ') && (pos == NULL))
2959             continue; /* At start of string (whitespace) */
2960           else if ((temp_transports[i] == ' ') || (temp_transports[i] == '\0')) /* At end of string */
2961             {
2962               temp_transports[i] = '\0';
2963 #if OLD
2964               conn_iter = pg->peers[pg_iter].blacklisted_peers_head;
2965               while (conn_iter != NULL)
2966                 {
2967                   GNUNET_CRYPTO_hash_to_enc (
2968                                              &pg->peers[conn_iter->index].daemon->id.hashPubKey,
2969                                              &peer_enc);
2970                   fprintf (temp_file_handle, "%s:%s\n", pos, (char *) &peer_enc);
2971                   conn_iter = conn_iter->next;
2972                   entry_count++;
2973                 }
2974 #else
2975               blacklist_ctx.transport = pos;
2976               entry_count = GNUNET_CONTAINER_multihashmap_iterate (pg->
2977                   peers
2978                   [pg_iter].blacklisted_peers,
2979                   &blacklist_file_iterator,
2980                   &blacklist_ctx);
2981 #endif
2982               pos = NULL;
2983             } /* At beginning of actual string */
2984           else if (pos == NULL)
2985             {
2986               pos = &temp_transports[i];
2987             }
2988         }
2989
2990       GNUNET_free (temp_transports);
2991       fclose (temp_file_handle);
2992
2993       if (GNUNET_OK
2994           != GNUNET_CONFIGURATION_get_value_string (
2995                                                     pg->peers[pg_iter]. daemon->cfg,
2996                                                     "PATHS", "SERVICEHOME",
2997                                                     &temp_service_path))
2998         {
2999           GNUNET_log (
3000                       GNUNET_ERROR_TYPE_WARNING,
3001                       _
3002                       ("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
3003                       "SERVICEHOME", "PATHS");
3004           if (UNLINK (mytemp) != 0)
3005             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
3006                 mytemp);
3007           GNUNET_free (mytemp);
3008           break;
3009         }
3010
3011       if (pg->peers[pg_iter].daemon->hostname == NULL) /* Local, just copy the file */
3012         {
3013           GNUNET_asprintf (&arg, "%s/blacklist", temp_service_path);
3014           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "mv", "mv",
3015                                                       mytemp, arg, NULL);
3016 #if VERBOSE_TESTING
3017           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3018               _("Copying file with command cp %s %s\n"), mytemp, arg);
3019 #endif
3020
3021           GNUNET_free (arg);
3022         }
3023       else /* Remote, scp the file to the correct place */
3024         {
3025           if (NULL != pg->peers[pg_iter].daemon->username)
3026             GNUNET_asprintf (&arg, "%s@%s:%s/blacklist",
3027                              pg->peers[pg_iter].daemon->username,
3028                              pg->peers[pg_iter].daemon->hostname,
3029                              temp_service_path);
3030           else
3031             GNUNET_asprintf (&arg, "%s:%s/blacklist",
3032                              pg->peers[pg_iter].daemon->hostname,
3033                              temp_service_path);
3034           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "scp", "scp",
3035                                                       mytemp, arg, NULL);
3036           GNUNET_assert(procarr[pg_iter] != NULL);
3037           GNUNET_OS_process_wait (procarr[pg_iter]); /* FIXME: add scheduled blacklist file copy that parallelizes file copying! */
3038
3039 #if VERBOSE_TESTING
3040           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3041               _("Copying file with command scp %s %s\n"), mytemp,
3042               arg);
3043 #endif
3044           GNUNET_free (arg);
3045         }
3046       GNUNET_free (temp_service_path);
3047       GNUNET_free (mytemp);
3048     }
3049
3050   count = 0;
3051   ret = GNUNET_SYSERR;
3052   while ((count < max_wait) && (ret != GNUNET_OK))
3053     {
3054       ret = GNUNET_OK;
3055       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3056         {
3057 #if VERBOSE_TESTING
3058           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3059               _("Checking copy status of file %d\n"), pg_iter);
3060 #endif
3061           if (procarr[pg_iter] != NULL) /* Check for already completed! */
3062             {
3063               if (GNUNET_OS_process_status (procarr[pg_iter], &type,
3064                                             &return_code) != GNUNET_OK)
3065                 {
3066                   ret = GNUNET_SYSERR;
3067                 }
3068               else if ((type != GNUNET_OS_PROCESS_EXITED) || (return_code != 0))
3069                 {
3070                   ret = GNUNET_SYSERR;
3071                 }
3072               else
3073                 {
3074                   GNUNET_OS_process_close (procarr[pg_iter]);
3075                   procarr[pg_iter] = NULL;
3076 #if VERBOSE_TESTING
3077                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3078                       _("File %d copied\n"), pg_iter);
3079 #endif
3080                 }
3081             }
3082         }
3083       count++;
3084       if (ret == GNUNET_SYSERR)
3085         {
3086           /* FIXME: why sleep here? -CG */
3087           sleep (1);
3088         }
3089     }
3090
3091 #if VERBOSE_TESTING
3092   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3093       _("Finished copying all blacklist files!\n"));
3094 #endif
3095   GNUNET_free (procarr);
3096   return ret;
3097 }
3098
3099 /* Forward Declaration */
3100 static void
3101 schedule_connect(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
3102
3103 /**
3104  * Choose a random peer's next connection to create, and
3105  * call schedule_connect to set up the connect task.
3106  *
3107  * @param ct_ctx the overall connection context
3108  */
3109 static void
3110 preschedule_connect(struct GNUNET_TESTING_PeerGroup *pg)
3111 {
3112   struct ConnectTopologyContext *ct_ctx = &pg->ct_ctx;
3113   struct PeerConnection *connection_iter;
3114   struct ConnectContext *connect_context;
3115   uint32_t random_peer;
3116
3117   if (ct_ctx->remaining_connections == 0)
3118     return;
3119   random_peer
3120       = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, pg->total);
3121   while (pg->peers[random_peer].connect_peers_head == NULL)
3122     random_peer = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3123                                             pg->total);
3124
3125   connection_iter = pg->peers[random_peer].connect_peers_head;
3126   connect_context = GNUNET_malloc (sizeof (struct ConnectContext));
3127   connect_context->first_index = random_peer;
3128   connect_context->second_index = connection_iter->index;
3129   connect_context->ct_ctx = ct_ctx;
3130   GNUNET_SCHEDULER_add_now (&schedule_connect, connect_context);
3131   GNUNET_CONTAINER_DLL_remove(pg->peers[random_peer].connect_peers_head, pg->peers[random_peer].connect_peers_tail, connection_iter);
3132   GNUNET_free(connection_iter);
3133   ct_ctx->remaining_connections--;
3134 }
3135
3136 #if USE_SEND_HELLOS
3137 /* Forward declaration */
3138 static void schedule_send_hellos (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
3139
3140 /**
3141  * Close connections and free the hello context.
3142  *
3143  * @param cls the 'struct SendHelloContext *'
3144  * @param tc scheduler context
3145  */
3146 static void
3147 free_hello_context (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3148   {
3149     struct SendHelloContext *send_hello_context = cls;
3150     if (send_hello_context->peer->daemon->server != NULL)
3151       {
3152         GNUNET_CORE_disconnect(send_hello_context->peer->daemon->server);
3153         send_hello_context->peer->daemon->server = NULL;
3154       }
3155     if (send_hello_context->peer->daemon->th != NULL)
3156       {
3157         GNUNET_TRANSPORT_disconnect(send_hello_context->peer->daemon->th);
3158         send_hello_context->peer->daemon->th = NULL;
3159       }
3160     if (send_hello_context->core_connect_task != GNUNET_SCHEDULER_NO_TASK)
3161       {
3162         GNUNET_SCHEDULER_cancel(send_hello_context->core_connect_task);
3163         send_hello_context->core_connect_task = GNUNET_SCHEDULER_NO_TASK;
3164       }
3165     send_hello_context->pg->outstanding_connects--;
3166     GNUNET_free(send_hello_context);
3167   }
3168
3169 /**
3170  * For peers that haven't yet connected, notify
3171  * the caller that they have failed (timeout).
3172  *
3173  * @param cls the 'struct SendHelloContext *'
3174  * @param tc scheduler context
3175  */
3176 static void
3177 notify_remaining_connections_failed (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3178   {
3179     struct SendHelloContext *send_hello_context = cls;
3180     struct GNUNET_TESTING_PeerGroup *pg = send_hello_context->pg;
3181     struct PeerConnection *connection;
3182
3183     GNUNET_CORE_disconnect(send_hello_context->peer->daemon->server);
3184     send_hello_context->peer->daemon->server = NULL;
3185
3186     connection = send_hello_context->peer->connect_peers_head;
3187
3188     while (connection != NULL)
3189       {
3190         if (pg->notify_connection != NULL)
3191           {
3192             pg->notify_connection(pg->notify_connection_cls,
3193                 &send_hello_context->peer->daemon->id,
3194                 &pg->peers[connection->index].daemon->id,
3195                 0, /* FIXME */
3196                 send_hello_context->peer->daemon->cfg,
3197                 pg->peers[connection->index].daemon->cfg,
3198                 send_hello_context->peer->daemon,
3199                 pg->peers[connection->index].daemon,
3200                 "Peers failed to connect (timeout)");
3201           }
3202         GNUNET_CONTAINER_DLL_remove(send_hello_context->peer->connect_peers_head, send_hello_context->peer->connect_peers_tail, connection);
3203         GNUNET_free(connection);
3204         connection = connection->next;
3205       }
3206     GNUNET_SCHEDULER_add_now(&free_hello_context, send_hello_context);
3207 #if BAD
3208     other_peer = &pg->peers[connection->index];
3209 #endif
3210   }
3211
3212 /**
3213  * For peers that haven't yet connected, send
3214  * CORE connect requests.
3215  *
3216  * @param cls the 'struct SendHelloContext *'
3217  * @param tc scheduler context
3218  */
3219 static void
3220 send_core_connect_requests (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3221   {
3222     struct SendHelloContext *send_hello_context = cls;
3223     struct PeerConnection *conn;
3224     GNUNET_assert(send_hello_context->peer->daemon->server != NULL);
3225
3226     send_hello_context->core_connect_task = GNUNET_SCHEDULER_NO_TASK;
3227
3228     send_hello_context->connect_attempts++;
3229     if (send_hello_context->connect_attempts < send_hello_context->pg->ct_ctx.connect_attempts)
3230       {
3231         conn = send_hello_context->peer->connect_peers_head;
3232         while (conn != NULL)
3233           {
3234             GNUNET_CORE_peer_request_connect(send_hello_context->peer->daemon->server,
3235                 GNUNET_TIME_relative_get_forever(),
3236                 &send_hello_context->pg->peers[conn->index].daemon->id,
3237                 NULL,
3238                 NULL);
3239             conn = conn->next;
3240           }
3241         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) ,
3242             &send_core_connect_requests,
3243             send_hello_context);
3244       }
3245     else
3246       {
3247         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Timeout before all connections created, marking rest as failed!\n");
3248         GNUNET_SCHEDULER_add_now(&notify_remaining_connections_failed, send_hello_context);
3249       }
3250
3251   }
3252
3253 /**
3254  * Success, connection is up.  Signal client our success.
3255  *
3256  * @param cls our "struct SendHelloContext"
3257  * @param peer identity of the peer that has connected
3258  * @param atsi performance information
3259  *
3260  * FIXME: remove peers from BOTH lists, call notify twice, should
3261  * double the speed of connections as long as the list iteration
3262  * doesn't take too long!
3263  */
3264 static void
3265 core_connect_notify (void *cls,
3266     const struct GNUNET_PeerIdentity *peer,
3267     const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3268   {
3269     struct SendHelloContext *send_hello_context = cls;
3270     struct PeerConnection *connection;
3271     struct GNUNET_TESTING_PeerGroup *pg = send_hello_context->pg;
3272 #if BAD
3273     struct PeerData *other_peer;
3274 #endif
3275 #if DEBUG_TESTING
3276     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3277         "Connected peer %s to peer %s\n",
3278         ctx->d1->shortname, GNUNET_i2s(peer));
3279 #endif
3280
3281     if (0 == memcmp(&send_hello_context->peer->daemon->id, peer, sizeof(struct GNUNET_PeerIdentity)))
3282     return;
3283
3284     connection = send_hello_context->peer->connect_peers_head;
3285 #if BAD
3286     other_peer = NULL;
3287 #endif
3288
3289     while ((connection != NULL) &&
3290         (0 != memcmp(&pg->peers[connection->index].daemon->id, peer, sizeof(struct GNUNET_PeerIdentity))))
3291       {
3292         connection = connection->next;
3293       }
3294
3295     if (connection == NULL)
3296       {
3297         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);
3298       }
3299     else
3300       {
3301 #if BAD
3302         other_peer = &pg->peers[connection->index];
3303 #endif
3304         if (pg->notify_connection != NULL)
3305           {
3306             pg->notify_connection(pg->notify_connection_cls,
3307                 &send_hello_context->peer->daemon->id,
3308                 peer,
3309                 0, /* FIXME */
3310                 send_hello_context->peer->daemon->cfg,
3311                 pg->peers[connection->index].daemon->cfg,
3312                 send_hello_context->peer->daemon,
3313                 pg->peers[connection->index].daemon,
3314                 NULL);
3315           }
3316         GNUNET_CONTAINER_DLL_remove(send_hello_context->peer->connect_peers_head, send_hello_context->peer->connect_peers_tail, connection);
3317         GNUNET_free(connection);
3318       }
3319
3320 #if BAD
3321     /* Notify of reverse connection and remove from other peers list of outstanding */
3322     if (other_peer != NULL)
3323       {
3324         connection = other_peer->connect_peers_head;
3325         while ((connection != NULL) &&
3326             (0 != memcmp(&send_hello_context->peer->daemon->id, &pg->peers[connection->index].daemon->id, sizeof(struct GNUNET_PeerIdentity))))
3327           {
3328             connection = connection->next;
3329           }
3330         if (connection != NULL)
3331           {
3332             if (pg->notify_connection != NULL)
3333               {
3334                 pg->notify_connection(pg->notify_connection_cls,
3335                     peer,
3336                     &send_hello_context->peer->daemon->id,
3337                     0, /* FIXME */
3338                     pg->peers[connection->index].daemon->cfg,
3339                     send_hello_context->peer->daemon->cfg,
3340                     pg->peers[connection->index].daemon,
3341                     send_hello_context->peer->daemon,
3342                     NULL);
3343               }
3344
3345             GNUNET_CONTAINER_DLL_remove(other_peer->connect_peers_head, other_peer->connect_peers_tail, connection);
3346             GNUNET_free(connection);
3347           }
3348       }
3349 #endif
3350
3351     if (send_hello_context->peer->connect_peers_head == NULL)
3352       {
3353         GNUNET_SCHEDULER_add_now(&free_hello_context, send_hello_context);
3354       }
3355   }
3356
3357 /**
3358  * Notify of a successful connection to the core service.
3359  *
3360  * @param cls a struct SendHelloContext *
3361  * @param server handle to the core service
3362  * @param my_identity the peer identity of this peer
3363  * @param publicKey the public key of the peer
3364  */
3365 void
3366 core_init (void *cls,
3367     struct GNUNET_CORE_Handle * server,
3368     const struct GNUNET_PeerIdentity *
3369     my_identity,
3370     const struct
3371     GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
3372     publicKey)
3373   {
3374     struct SendHelloContext *send_hello_context = cls;
3375     send_hello_context->core_ready = GNUNET_YES;
3376   }
3377
3378 /**
3379  * Function called once a hello has been sent
3380  * to the transport, move on to the next one
3381  * or go away forever.
3382  *
3383  * @param cls the 'struct SendHelloContext *'
3384  * @param tc scheduler context
3385  */
3386 static void
3387 hello_sent_callback (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3388   {
3389     struct SendHelloContext *send_hello_context = cls;
3390     //unsigned int pg_iter;
3391     if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3392       {
3393         GNUNET_free(send_hello_context);
3394         return;
3395       }
3396
3397     send_hello_context->pg->remaining_hellos--;
3398 #if DEBUG_TESTING
3399     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sent HELLO, have %d remaining!\n", send_hello_context->pg->remaining_hellos);
3400 #endif
3401     if (send_hello_context->peer_pos == NULL) /* All HELLOs (for this peer!) have been transmitted! */
3402       {
3403 #if DEBUG_TESTING
3404         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "All hellos for this peer sent, disconnecting transport!\n");
3405 #endif
3406         GNUNET_assert(send_hello_context->peer->daemon->th != NULL);
3407         GNUNET_TRANSPORT_disconnect(send_hello_context->peer->daemon->th);
3408         send_hello_context->peer->daemon->th = NULL;
3409
3410         /*if (send_hello_context->pg->remaining_hellos == 0)
3411          {
3412          for (pg_iter = 0; pg_iter < send_hello_context->pg->max_outstanding_connections; pg_iter++)
3413          {
3414          preschedule_connect(&send_hello_context->pg->ct_ctx);
3415          }
3416          }
3417          */
3418         GNUNET_assert (send_hello_context->peer->daemon->server == NULL);
3419         send_hello_context->peer->daemon->server = GNUNET_CORE_connect(send_hello_context->peer->cfg,
3420             1,
3421             send_hello_context,
3422             &core_init,
3423             &core_connect_notify,
3424             NULL,
3425             NULL,
3426             NULL, GNUNET_NO,
3427             NULL, GNUNET_NO,
3428             no_handlers);
3429
3430         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),
3431             &send_core_connect_requests,
3432             send_hello_context);
3433       }
3434     else
3435     GNUNET_SCHEDULER_add_now(&schedule_send_hellos, send_hello_context);
3436   }
3437
3438 /**
3439  * Connect to a peer, give it all the HELLO's of those peers
3440  * we will later ask it to connect to.
3441  *
3442  * @param ct_ctx the overall connection context
3443  */
3444 static void schedule_send_hellos (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3445   {
3446     struct SendHelloContext *send_hello_context = cls;
3447     struct GNUNET_TESTING_PeerGroup *pg = send_hello_context->pg;
3448
3449     if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3450       {
3451         GNUNET_free(send_hello_context);
3452         return;
3453       }
3454
3455     GNUNET_assert(send_hello_context->peer_pos != NULL); /* All of the HELLO sends to be scheduled have been scheduled! */
3456
3457     if (((send_hello_context->peer->daemon->th == NULL) &&
3458             (pg->outstanding_connects > pg->max_outstanding_connections)) ||
3459         (pg->stop_connects == GNUNET_YES))
3460       {
3461 #if VERBOSE_TESTING > 2
3462         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3463             _
3464             ("Delaying connect, we have too many outstanding connections!\n"));
3465 #endif
3466         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3467             (GNUNET_TIME_UNIT_MILLISECONDS, 100),
3468             &schedule_send_hellos, send_hello_context);
3469       }
3470     else
3471       {
3472 #if VERBOSE_TESTING > 2
3473         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3474             _("Creating connection, outstanding_connections is %d\n"),
3475             outstanding_connects);
3476 #endif
3477         if (send_hello_context->peer->daemon->th == NULL)
3478           {
3479             pg->outstanding_connects++; /* Actual TRANSPORT, CORE connections! */
3480             send_hello_context->peer->daemon->th
3481                 = GNUNET_TRANSPORT_connect (send_hello_context->peer->cfg, NULL,
3482                                             send_hello_context, NULL, NULL, NULL);
3483           }
3484 #if DEBUG_TESTING
3485         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3486             _("Offering Hello of peer %s to peer %s\n"),
3487             send_hello_context->peer->daemon->shortname, pg->peers[send_hello_context->peer_pos->index].daemon->shortname);
3488 #endif
3489         GNUNET_TRANSPORT_offer_hello(send_hello_context->peer->daemon->th,
3490             (const struct GNUNET_MessageHeader *)pg->peers[send_hello_context->peer_pos->index].daemon->hello,
3491             &hello_sent_callback,
3492             send_hello_context);
3493         send_hello_context->peer_pos = send_hello_context->peer_pos->next;
3494         GNUNET_assert(send_hello_context->peer->daemon->th != NULL);
3495       }
3496   }
3497 #endif
3498
3499 /**
3500  * Internal notification of a connection, kept so that we can ensure some connections
3501  * happen instead of flooding all testing daemons with requests to connect.
3502  */
3503 static void
3504 internal_connect_notify(void *cls, const struct GNUNET_PeerIdentity *first,
3505                         const struct GNUNET_PeerIdentity *second,
3506                         uint32_t distance,
3507                         const struct GNUNET_CONFIGURATION_Handle *first_cfg,
3508                         const struct GNUNET_CONFIGURATION_Handle *second_cfg,
3509                         struct GNUNET_TESTING_Daemon *first_daemon,
3510                         struct GNUNET_TESTING_Daemon *second_daemon,
3511                         const char *emsg)
3512 {
3513   struct ConnectContext *connect_ctx = cls;
3514   struct ConnectTopologyContext *ct_ctx = connect_ctx->ct_ctx;
3515   struct GNUNET_TESTING_PeerGroup *pg = ct_ctx->pg;
3516   struct PeerConnection *connection;
3517
3518   GNUNET_assert (0 < pg->outstanding_connects);
3519   pg->outstanding_connects--;
3520
3521   /*
3522    * Check whether the inverse connection has been scheduled yet,
3523    * if not, we can remove it from the other peers list and avoid
3524    * even trying to connect them again!
3525    */
3526   connection = pg->peers[connect_ctx->second_index].connect_peers_head;
3527 #if BAD
3528   other_peer = NULL;
3529 #endif
3530
3531   while ((connection != NULL) && (0
3532       != memcmp (first, &pg->peers[connection->index].daemon->id,
3533                  sizeof(struct GNUNET_PeerIdentity))))
3534     {
3535       connection = connection->next;
3536     }
3537
3538   if (connection != NULL) /* Can safely remove! */
3539     {
3540       GNUNET_assert (0 < ct_ctx->remaining_connections);
3541       ct_ctx->remaining_connections--;
3542       if (pg->notify_connection != NULL) /* Notify of reverse connection */
3543         pg->notify_connection (pg->notify_connection_cls, second, first,
3544                                distance, second_cfg, first_cfg, second_daemon,
3545                                first_daemon, emsg);
3546
3547       GNUNET_CONTAINER_DLL_remove(pg->peers[connect_ctx->second_index].connect_peers_head, pg->peers[connect_ctx->second_index].connect_peers_tail, connection);
3548       GNUNET_free(connection);
3549     }
3550
3551   if (ct_ctx->remaining_connections == 0)
3552     {
3553       if (ct_ctx->notify_connections_done != NULL)
3554         {
3555           ct_ctx->notify_connections_done (ct_ctx->notify_cls, NULL);
3556           ct_ctx->notify_connections_done = NULL;
3557         }
3558     }
3559   else
3560     preschedule_connect (pg);
3561
3562   if (pg->notify_connection != NULL)
3563     pg->notify_connection (pg->notify_connection_cls, first, second, distance,
3564                            first_cfg, second_cfg, first_daemon, second_daemon,
3565                            emsg);
3566
3567   GNUNET_free(connect_ctx);
3568 }
3569
3570 /**
3571  * Either delay a connection (because there are too many outstanding)
3572  * or schedule it for right now.
3573  *
3574  * @param cls a connection context
3575  * @param tc the task runtime context
3576  */
3577 static void
3578 schedule_connect(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3579 {
3580   struct ConnectContext *connect_context = cls;
3581   struct GNUNET_TESTING_PeerGroup *pg = connect_context->ct_ctx->pg;
3582
3583   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3584     return;
3585
3586   if ((pg->outstanding_connects > pg->max_outstanding_connections)
3587       || (pg->stop_connects == GNUNET_YES))
3588     {
3589 #if VERBOSE_TESTING
3590       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3591           _
3592           ("Delaying connect, we have too many outstanding connections!\n"));
3593 #endif
3594       GNUNET_SCHEDULER_add_delayed (
3595                                     GNUNET_TIME_relative_multiply (
3596                                                                    GNUNET_TIME_UNIT_MILLISECONDS,
3597                                                                    100),
3598                                     &schedule_connect, connect_context);
3599     }
3600   else
3601     {
3602 #if VERBOSE_TESTING
3603       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3604           _("Creating connection, outstanding_connections is %d (max %d)\n"),
3605           pg->outstanding_connects, pg->max_outstanding_connections);
3606 #endif
3607       pg->outstanding_connects++;
3608       pg->total_connects_scheduled++;
3609       GNUNET_TESTING_daemons_connect (
3610                                       pg->peers[connect_context->first_index].daemon,
3611                                       pg->peers[connect_context->second_index].daemon,
3612                                       connect_context->ct_ctx->connect_timeout,
3613                                       connect_context->ct_ctx->connect_attempts,
3614 #if USE_SEND_HELLOS
3615                                       GNUNET_NO,
3616 #else
3617                                       GNUNET_YES,
3618 #endif
3619                                       &internal_connect_notify, connect_context); /* FIXME: free connect context! */
3620     }
3621 }
3622
3623 #if !OLD
3624 /**
3625  * Iterator for actually scheduling connections to be created
3626  * between two peers.
3627  *
3628  * @param cls closure, a GNUNET_TESTING_Daemon
3629  * @param key the key the second Daemon was stored under
3630  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
3631  *
3632  * @return GNUNET_YES to continue iteration
3633  */
3634 static int
3635 connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
3636   {
3637     struct ConnectTopologyContext *ct_ctx = cls;
3638     struct PeerData *first = ct_ctx->first;
3639     struct GNUNET_TESTING_Daemon *second = value;
3640     struct ConnectContext *connect_context;
3641
3642     connect_context = GNUNET_malloc (sizeof (struct ConnectContext));
3643     connect_context->first = first->daemon;
3644     connect_context->second = second;
3645     connect_context->ct_ctx = ct_ctx;
3646     GNUNET_SCHEDULER_add_now (&schedule_connect, connect_context);
3647
3648     return GNUNET_YES;
3649   }
3650 #endif
3651
3652 #if !OLD
3653 /**
3654  * Iterator for copying all entries in the allowed hashmap to the
3655  * connect hashmap.
3656  *
3657  * @param cls closure, a GNUNET_TESTING_Daemon
3658  * @param key the key the second Daemon was stored under
3659  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
3660  *
3661  * @return GNUNET_YES to continue iteration
3662  */
3663 static int
3664 copy_topology_iterator (void *cls, const GNUNET_HashCode * key, void *value)
3665   {
3666     struct PeerData *first = cls;
3667
3668     GNUNET_assert (GNUNET_OK ==
3669         GNUNET_CONTAINER_multihashmap_put (first->connect_peers, key,
3670             value,
3671             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3672
3673     return GNUNET_YES;
3674   }
3675 #endif
3676
3677 /**
3678  * Make the peers to connect the same as those that are allowed to be
3679  * connected.
3680  *
3681  * @param pg the peer group
3682  */
3683 static int
3684 copy_allowed_topology(struct GNUNET_TESTING_PeerGroup *pg)
3685 {
3686   unsigned int pg_iter;
3687   int ret;
3688   int total;
3689 #if OLD
3690   struct PeerConnection *iter;
3691 #endif
3692   total = 0;
3693   ret = 0;
3694   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3695     {
3696 #if OLD
3697       iter = pg->peers[pg_iter].allowed_peers_head;
3698       while (iter != NULL)
3699         {
3700           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3701                       "Creating connection between %d and %d\n", pg_iter,
3702                       iter->index);
3703           total += add_connections (pg, pg_iter, iter->index, CONNECT,
3704                                     GNUNET_YES);
3705           //total += add_actual_connections(pg, pg_iter, iter->index);
3706           iter = iter->next;
3707         }
3708 #else
3709       ret =
3710       GNUNET_CONTAINER_multihashmap_iterate (pg->
3711           peers[pg_iter].allowed_peers,
3712           &copy_topology_iterator,
3713           &pg->peers[pg_iter]);
3714 #endif
3715       if (GNUNET_SYSERR == ret)
3716         return GNUNET_SYSERR;
3717
3718       total = total + ret;
3719     }
3720
3721   return total;
3722 }
3723
3724 /**
3725  * Connect the topology as specified by the PeerConnection's
3726  * of each peer in the peer group
3727  *
3728  * @param pg the peer group we are dealing with
3729  * @param connect_timeout how long try connecting two peers
3730  * @param connect_attempts how many times (max) to attempt
3731  * @param notify_callback callback to notify when finished
3732  * @param notify_cls closure for notify callback
3733  *
3734  * @return the number of connections that will be attempted
3735  */
3736 static int
3737 connect_topology(struct GNUNET_TESTING_PeerGroup *pg,
3738                  struct GNUNET_TIME_Relative connect_timeout,
3739                  unsigned int connect_attempts,
3740                  GNUNET_TESTING_NotifyCompletion notify_callback,
3741                  void *notify_cls)
3742 {
3743   unsigned int pg_iter;
3744   unsigned int total;
3745
3746 #if OLD
3747   struct PeerConnection *connection_iter;
3748 #endif
3749 #if USE_SEND_HELLOS
3750   struct SendHelloContext *send_hello_context;
3751 #endif
3752
3753   total = 0;
3754   pg->ct_ctx.notify_connections_done = notify_callback;
3755   pg->ct_ctx.notify_cls = notify_cls;
3756   pg->ct_ctx.pg = pg;
3757
3758   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3759     {
3760 #if OLD
3761       connection_iter = pg->peers[pg_iter].connect_peers_head;
3762       while (connection_iter != NULL)
3763         {
3764           connection_iter = connection_iter->next;
3765           total++;
3766         }
3767 #else
3768       total +=
3769       GNUNET_CONTAINER_multihashmap_size (pg->peers[pg_iter].connect_peers);
3770 #endif
3771     }
3772
3773   if (total == 0)
3774     return total;
3775
3776   pg->ct_ctx.connect_timeout = connect_timeout;
3777   pg->ct_ctx.connect_attempts = connect_attempts;
3778   pg->ct_ctx.remaining_connections = total;
3779
3780 #if USE_SEND_HELLOS
3781   /* First give all peers the HELLO's of other peers (connect to first peer's transport service, give HELLO's of other peers, continue...) */
3782   pg->remaining_hellos = total;
3783   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3784     {
3785       send_hello_context = GNUNET_malloc(sizeof(struct SendHelloContext));
3786       send_hello_context->peer = &pg->peers[pg_iter];
3787       send_hello_context->peer_pos = pg->peers[pg_iter].connect_peers_head;
3788       send_hello_context->pg = pg;
3789       GNUNET_SCHEDULER_add_now(&schedule_send_hellos, send_hello_context);
3790     }
3791 #else
3792   for (pg_iter = 0; pg_iter < pg->max_outstanding_connections; pg_iter++)
3793     {
3794       preschedule_connect (pg);
3795     }
3796 #endif
3797   return total;
3798
3799 }
3800
3801 /**
3802  * Takes a peer group and creates a topology based on the
3803  * one specified.  Creates a topology means generates friend
3804  * files for the peers so they can only connect to those allowed
3805  * by the topology.  This will only have an effect once peers
3806  * are started if the FRIENDS_ONLY option is set in the base
3807  * config.  Also takes an optional restrict topology which
3808  * disallows connections based on particular transports
3809  * UNLESS they are specified in the restricted topology.
3810  *
3811  * @param pg the peer group struct representing the running peers
3812  * @param topology which topology to connect the peers in
3813  * @param restrict_topology disallow restrict_transports transport
3814  *                          connections to peers NOT in this topology
3815  *                          use GNUNET_TESTING_TOPOLOGY_NONE for no restrictions
3816  * @param restrict_transports space delimited list of transports to blacklist
3817  *                            to create restricted topology
3818  *
3819  * @return the maximum number of connections were all allowed peers
3820  *         connected to each other
3821  */
3822 unsigned int
3823 GNUNET_TESTING_create_topology(struct GNUNET_TESTING_PeerGroup *pg,
3824                                enum GNUNET_TESTING_Topology topology,
3825                                enum GNUNET_TESTING_Topology restrict_topology,
3826                                const char *restrict_transports)
3827 {
3828   int ret;
3829
3830   unsigned int num_connections;
3831   int unblacklisted_connections;
3832   char *filename;
3833   struct PeerConnection *conn_iter;
3834   struct PeerConnection *temp_conn;
3835   unsigned int off;
3836
3837 #if !OLD
3838   unsigned int i;
3839   for (i = 0; i < pg->total; i++)
3840     {
3841       pg->peers[i].allowed_peers =
3842       GNUNET_CONTAINER_multihashmap_create (100);
3843       pg->peers[i].connect_peers =
3844       GNUNET_CONTAINER_multihashmap_create (100);
3845       pg->peers[i].blacklisted_peers =
3846       GNUNET_CONTAINER_multihashmap_create (100);
3847       pg->peers[i].pg = pg;
3848     }
3849 #endif
3850
3851   switch (topology)
3852     {
3853   case GNUNET_TESTING_TOPOLOGY_CLIQUE:
3854 #if VERBOSE_TESTING
3855     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating clique topology\n"));
3856 #endif
3857     num_connections = create_clique (pg, &add_connections, ALLOWED, GNUNET_NO);
3858     break;
3859   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
3860 #if VERBOSE_TESTING
3861     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3862         _("Creating small world (ring) topology\n"));
3863 #endif
3864     num_connections = create_small_world_ring (pg, &add_connections, ALLOWED);
3865     break;
3866   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
3867 #if VERBOSE_TESTING
3868     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3869         _("Creating small world (2d-torus) topology\n"));
3870 #endif
3871     num_connections = create_small_world (pg, &add_connections, ALLOWED);
3872     break;
3873   case GNUNET_TESTING_TOPOLOGY_RING:
3874 #if VERBOSE_TESTING
3875     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating ring topology\n"));
3876 #endif
3877     num_connections = create_ring (pg, &add_connections, ALLOWED);
3878     break;
3879   case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
3880 #if VERBOSE_TESTING
3881     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating 2d torus topology\n"));
3882 #endif
3883     num_connections = create_2d_torus (pg, &add_connections, ALLOWED);
3884     break;
3885   case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
3886 #if VERBOSE_TESTING
3887     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3888         _("Creating Erdos-Renyi topology\n"));
3889 #endif
3890     num_connections = create_erdos_renyi (pg, &add_connections, ALLOWED);
3891     break;
3892   case GNUNET_TESTING_TOPOLOGY_INTERNAT:
3893 #if VERBOSE_TESTING
3894     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating InterNAT topology\n"));
3895 #endif
3896     num_connections = create_nated_internet (pg, &add_connections, ALLOWED);
3897     break;
3898   case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
3899 #if VERBOSE_TESTING
3900     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3901         _("Creating Scale Free topology\n"));
3902 #endif
3903     num_connections = create_scale_free (pg, &add_connections, ALLOWED);
3904     break;
3905   case GNUNET_TESTING_TOPOLOGY_LINE:
3906 #if VERBOSE_TESTING
3907     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3908         _("Creating straight line topology\n"));
3909 #endif
3910     num_connections = create_line (pg, &add_connections, ALLOWED);
3911     break;
3912   case GNUNET_TESTING_TOPOLOGY_FROM_FILE:
3913 #if VERBOSE_TESTING
3914     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3915         _("Creating topology from file!\n"));
3916 #endif
3917     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (pg->cfg, "testing",
3918                                                             "topology_file",
3919                                                             &filename))
3920       num_connections = create_from_file (pg, filename, &add_connections,
3921                                           ALLOWED);
3922     else
3923       {
3924         GNUNET_log (
3925                     GNUNET_ERROR_TYPE_WARNING,
3926                     "Missing configuration option TESTING:TOPOLOGY_FILE for creating topology from file!\n");
3927         num_connections = 0;
3928       }
3929     break;
3930   case GNUNET_TESTING_TOPOLOGY_NONE:
3931 #if VERBOSE_TESTING
3932     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3933         _
3934         ("Creating no allowed topology (all peers can connect at core level)\n"));
3935 #endif
3936     num_connections = pg->total * pg->total; /* Clique is allowed! */
3937     break;
3938   default:
3939     num_connections = 0;
3940     break;
3941     }
3942
3943   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "TESTING",
3944                                                           "F2F"))
3945     {
3946       ret = create_and_copy_friend_files (pg);
3947       if (ret != GNUNET_OK)
3948         {
3949 #if VERBOSE_TESTING
3950           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3951               _("Failed during friend file copying!\n"));
3952 #endif
3953           return GNUNET_SYSERR;
3954         }
3955       else
3956         {
3957 #if VERBOSE_TESTING
3958           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3959               _("Friend files created/copied successfully!\n"));
3960 #endif
3961         }
3962     }
3963
3964   /* Use the create clique method to initially set all connections as blacklisted. */
3965   if ((restrict_topology != GNUNET_TESTING_TOPOLOGY_NONE) && (restrict_topology
3966       != GNUNET_TESTING_TOPOLOGY_FROM_FILE))
3967     create_clique (pg, &add_connections, BLACKLIST, GNUNET_NO);
3968   else
3969     return num_connections;
3970
3971   unblacklisted_connections = 0;
3972   /* Un-blacklist connections as per the topology specified */
3973   switch (restrict_topology)
3974     {
3975   case GNUNET_TESTING_TOPOLOGY_CLIQUE:
3976 #if VERBOSE_TESTING
3977     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3978         _("Blacklisting all but clique topology\n"));
3979 #endif
3980     unblacklisted_connections = create_clique (pg, &remove_connections,
3981                                                BLACKLIST, GNUNET_NO);
3982     break;
3983   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
3984 #if VERBOSE_TESTING
3985     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3986         _("Blacklisting all but small world (ring) topology\n"));
3987 #endif
3988     unblacklisted_connections = create_small_world_ring (pg,
3989                                                          &remove_connections,
3990                                                          BLACKLIST);
3991     break;
3992   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
3993 #if VERBOSE_TESTING
3994     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3995         _
3996         ("Blacklisting all but small world (2d-torus) topology\n"));
3997 #endif
3998     unblacklisted_connections = create_small_world (pg, &remove_connections,
3999                                                     BLACKLIST);
4000     break;
4001   case GNUNET_TESTING_TOPOLOGY_RING:
4002 #if VERBOSE_TESTING
4003     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4004         _("Blacklisting all but ring topology\n"));
4005 #endif
4006     unblacklisted_connections
4007         = create_ring (pg, &remove_connections, BLACKLIST);
4008     break;
4009   case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
4010 #if VERBOSE_TESTING
4011     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4012         _("Blacklisting all but 2d torus topology\n"));
4013 #endif
4014     unblacklisted_connections = create_2d_torus (pg, &remove_connections,
4015                                                  BLACKLIST);
4016     break;
4017   case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
4018 #if VERBOSE_TESTING
4019     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4020         _("Blacklisting all but Erdos-Renyi topology\n"));
4021 #endif
4022     unblacklisted_connections = create_erdos_renyi (pg, &remove_connections,
4023                                                     BLACKLIST);
4024     break;
4025   case GNUNET_TESTING_TOPOLOGY_INTERNAT:
4026 #if VERBOSE_TESTING
4027     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4028         _("Blacklisting all but InterNAT topology\n"));
4029 #endif
4030
4031 #if TOPOLOGY_HACK
4032     for (off = 0; off < pg->total; off++)
4033       {
4034         conn_iter = pg->peers[off].allowed_peers_head;
4035         while (conn_iter != NULL)
4036           {
4037             temp_conn = conn_iter->next;
4038             GNUNET_free(conn_iter);
4039             conn_iter = temp_conn;
4040           }
4041         pg->peers[off].allowed_peers_head = NULL;
4042         pg->peers[off].allowed_peers_tail = NULL;
4043
4044         conn_iter = pg->peers[off].connect_peers_head;
4045         while (conn_iter != NULL)
4046           {
4047             temp_conn = conn_iter->next;
4048             GNUNET_free(conn_iter);
4049             conn_iter = temp_conn;
4050           }
4051         pg->peers[off].connect_peers_head = NULL;
4052         pg->peers[off].connect_peers_tail = NULL;
4053       }
4054     unblacklisted_connections
4055         = create_nated_internet_copy (pg, &remove_connections, BLACKLIST);
4056 #else
4057     unblacklisted_connections =
4058     create_nated_internet (pg, &remove_connections, BLACKLIST);
4059 #endif
4060
4061     break;
4062   case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
4063 #if VERBOSE_TESTING
4064     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4065         _("Blacklisting all but Scale Free topology\n"));
4066 #endif
4067     unblacklisted_connections = create_scale_free (pg, &remove_connections,
4068                                                    BLACKLIST);
4069     break;
4070   case GNUNET_TESTING_TOPOLOGY_LINE:
4071 #if VERBOSE_TESTING
4072     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4073         _("Blacklisting all but straight line topology\n"));
4074 #endif
4075     unblacklisted_connections
4076         = create_line (pg, &remove_connections, BLACKLIST);
4077     break;
4078   case GNUNET_TESTING_TOPOLOGY_NONE: /* Fall through */
4079   case GNUNET_TESTING_TOPOLOGY_FROM_FILE:
4080 #if VERBOSE_TESTING
4081     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4082         _
4083         ("Creating no blacklist topology (all peers can connect at transport level)\n"));
4084 #endif
4085     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _
4086     ("Creating blacklist topology from allowed\n"));
4087     unblacklisted_connections = copy_allowed (pg, &remove_connections);
4088   default:
4089     break;
4090     }
4091
4092   if ((unblacklisted_connections > 0) && (restrict_transports != NULL))
4093     {
4094       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Creating blacklist with `%s'\n",
4095                   restrict_transports);
4096       ret = create_and_copy_blacklist_files (pg, restrict_transports);
4097       if (ret != GNUNET_OK)
4098         {
4099 #if VERBOSE_TESTING
4100           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4101               _("Failed during blacklist file copying!\n"));
4102 #endif
4103           return 0;
4104         }
4105       else
4106         {
4107 #if VERBOSE_TESTING
4108           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4109               _("Blacklist files created/copied successfully!\n"));
4110 #endif
4111         }
4112     }
4113   return num_connections;
4114 }
4115
4116 #if !OLD
4117 /**
4118  * Iterator for choosing random peers to connect.
4119  *
4120  * @param cls closure, a RandomContext
4121  * @param key the key the second Daemon was stored under
4122  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
4123  *
4124  * @return GNUNET_YES to continue iteration
4125  */
4126 static int
4127 random_connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
4128   {
4129     struct RandomContext *random_ctx = cls;
4130     double random_number;
4131     uint32_t second_pos;
4132     GNUNET_HashCode first_hash;
4133     random_number =
4134     ((double)
4135         GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
4136             UINT64_MAX)) / ((double) UINT64_MAX);
4137     if (random_number < random_ctx->percentage)
4138       {
4139         GNUNET_assert (GNUNET_OK ==
4140             GNUNET_CONTAINER_multihashmap_put (random_ctx->
4141                 first->connect_peers_working_set,
4142                 key, value,
4143                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4144       }
4145
4146     /* Now we have considered this particular connection, remove it from the second peer so it's not double counted */
4147     uid_from_hash (key, &second_pos);
4148     hash_from_uid (random_ctx->first_uid, &first_hash);
4149     GNUNET_assert (random_ctx->pg->total > second_pos);
4150     GNUNET_assert (GNUNET_YES ==
4151         GNUNET_CONTAINER_multihashmap_remove (random_ctx->
4152             pg->peers
4153             [second_pos].connect_peers,
4154             &first_hash,
4155             random_ctx->
4156             first->daemon));
4157
4158     return GNUNET_YES;
4159   }
4160
4161 /**
4162  * Iterator for adding at least X peers to a peers connection set.
4163  *
4164  * @param cls closure, MinimumContext
4165  * @param key the key the second Daemon was stored under
4166  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
4167  *
4168  * @return GNUNET_YES to continue iteration
4169  */
4170 static int
4171 minimum_connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
4172   {
4173     struct MinimumContext *min_ctx = cls;
4174     uint32_t second_pos;
4175     GNUNET_HashCode first_hash;
4176     unsigned int i;
4177
4178     if (GNUNET_CONTAINER_multihashmap_size
4179         (min_ctx->first->connect_peers_working_set) < min_ctx->num_to_add)
4180       {
4181         for (i = 0; i < min_ctx->num_to_add; i++)
4182           {
4183             if (min_ctx->pg_array[i] == min_ctx->current)
4184               {
4185                 GNUNET_assert (GNUNET_OK ==
4186                     GNUNET_CONTAINER_multihashmap_put
4187                     (min_ctx->first->connect_peers_working_set, key,
4188                         value,
4189                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4190                 uid_from_hash (key, &second_pos);
4191                 hash_from_uid (min_ctx->first_uid, &first_hash);
4192                 GNUNET_assert (min_ctx->pg->total > second_pos);
4193                 GNUNET_assert (GNUNET_OK ==
4194                     GNUNET_CONTAINER_multihashmap_put (min_ctx->
4195                         pg->peers
4196                         [second_pos].connect_peers_working_set,
4197                         &first_hash,
4198                         min_ctx->first->
4199                         daemon,
4200                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4201                 /* Now we have added this particular connection, remove it from the second peer's map so it's not double counted */
4202                 GNUNET_assert (GNUNET_YES ==
4203                     GNUNET_CONTAINER_multihashmap_remove
4204                     (min_ctx->pg->peers[second_pos].connect_peers,
4205                         &first_hash, min_ctx->first->daemon));
4206               }
4207           }
4208         min_ctx->current++;
4209         return GNUNET_YES;
4210       }
4211     else
4212     return GNUNET_NO; /* We can stop iterating, we have enough peers! */
4213
4214   }
4215
4216 /**
4217  * Iterator for adding peers to a connection set based on a depth first search.
4218  *
4219  * @param cls closure, MinimumContext
4220  * @param key the key the second daemon was stored under
4221  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
4222  *
4223  * @return GNUNET_YES to continue iteration
4224  */
4225 static int
4226 dfs_connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
4227   {
4228     struct DFSContext *dfs_ctx = cls;
4229     GNUNET_HashCode first_hash;
4230
4231     if (dfs_ctx->current == dfs_ctx->chosen)
4232       {
4233         GNUNET_assert (GNUNET_OK ==
4234             GNUNET_CONTAINER_multihashmap_put (dfs_ctx->
4235                 first->connect_peers_working_set,
4236                 key, value,
4237                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4238         uid_from_hash (key, &dfs_ctx->second_uid);
4239         hash_from_uid (dfs_ctx->first_uid, &first_hash);
4240         GNUNET_assert (GNUNET_OK ==
4241             GNUNET_CONTAINER_multihashmap_put (dfs_ctx->
4242                 pg->peers
4243                 [dfs_ctx->second_uid].connect_peers_working_set,
4244                 &first_hash,
4245                 dfs_ctx->
4246                 first->daemon,
4247                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4248         GNUNET_assert (GNUNET_YES ==
4249             GNUNET_CONTAINER_multihashmap_remove (dfs_ctx->
4250                 pg->peers
4251                 [dfs_ctx->second_uid].connect_peers,
4252                 &first_hash,
4253                 dfs_ctx->
4254                 first->daemon));
4255         /* Can't remove second from first yet because we are currently iterating, hence the return value in the DFSContext! */
4256         return GNUNET_NO; /* We have found our peer, don't iterate more */
4257       }
4258
4259     dfs_ctx->current++;
4260     return GNUNET_YES;
4261   }
4262 #endif
4263
4264 /**
4265  * From the set of connections possible, choose percentage percent of connections
4266  * to actually connect.
4267  *
4268  * @param pg the peergroup we are dealing with
4269  * @param percentage what percent of total connections to make
4270  */
4271 void
4272 choose_random_connections(struct GNUNET_TESTING_PeerGroup *pg,
4273                           double percentage)
4274 {
4275   struct RandomContext random_ctx;
4276   uint32_t pg_iter;
4277 #if OLD
4278   struct PeerConnection *temp_peers;
4279   struct PeerConnection *conn_iter;
4280   double random_number;
4281 #endif
4282
4283   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4284     {
4285       random_ctx.first_uid = pg_iter;
4286       random_ctx.first = &pg->peers[pg_iter];
4287       random_ctx.percentage = percentage;
4288       random_ctx.pg = pg;
4289 #if OLD
4290       temp_peers = NULL;
4291       conn_iter = pg->peers[pg_iter].connect_peers_head;
4292       while (conn_iter != NULL)
4293         {
4294           random_number
4295               = ((double) GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
4296                                                     UINT64_MAX))
4297                   / ((double) UINT64_MAX);
4298           if (random_number < percentage)
4299             {
4300               add_connections (pg, pg_iter, conn_iter->index, WORKING_SET,
4301                                GNUNET_YES);
4302             }
4303           conn_iter = conn_iter->next;
4304         }
4305 #else
4306       pg->peers[pg_iter].connect_peers_working_set =
4307       GNUNET_CONTAINER_multihashmap_create (pg->total);
4308       GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].connect_peers,
4309           &random_connect_iterator,
4310           &random_ctx);
4311       /* Now remove the old connections */
4312       GNUNET_CONTAINER_multihashmap_destroy (pg->
4313           peers[pg_iter].connect_peers);
4314       /* And replace with the random set */
4315       pg->peers[pg_iter].connect_peers =
4316       pg->peers[pg_iter].connect_peers_working_set;
4317 #endif
4318     }
4319
4320   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4321     {
4322       conn_iter = pg->peers[pg_iter].connect_peers_head;
4323       while (pg->peers[pg_iter].connect_peers_head != NULL)
4324         remove_connections (pg, pg_iter,
4325                             pg->peers[pg_iter].connect_peers_head->index,
4326                             CONNECT, GNUNET_YES);
4327
4328       pg->peers[pg_iter].connect_peers_head
4329           = pg->peers[pg_iter].connect_peers_working_set_head;
4330       pg->peers[pg_iter].connect_peers_tail
4331           = pg->peers[pg_iter].connect_peers_working_set_tail;
4332       pg->peers[pg_iter].connect_peers_working_set_head = NULL;
4333       pg->peers[pg_iter].connect_peers_working_set_tail = NULL;
4334     }
4335 }
4336
4337 /**
4338  * Count the number of connections in a linked list of connections.
4339  *
4340  * @param conn_list the connection list to get the count of
4341  *
4342  * @return the number of elements in the list
4343  */
4344 static unsigned int
4345 count_connections(struct PeerConnection *conn_list)
4346 {
4347   struct PeerConnection *iter;
4348   unsigned int count;
4349   count = 0;
4350   iter = conn_list;
4351   while (iter != NULL)
4352     {
4353       iter = iter->next;
4354       count++;
4355     }
4356   return count;
4357 }
4358
4359 static unsigned int
4360 count_workingset_connections(struct GNUNET_TESTING_PeerGroup *pg)
4361 {
4362   unsigned int count;
4363   unsigned int pg_iter;
4364 #if OLD
4365   struct PeerConnection *conn_iter;
4366 #endif
4367   count = 0;
4368
4369   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4370     {
4371 #if OLD
4372       conn_iter = pg->peers[pg_iter].connect_peers_working_set_head;
4373       while (conn_iter != NULL)
4374         {
4375           count++;
4376           conn_iter = conn_iter->next;
4377         }
4378 #else
4379       count +=
4380       GNUNET_CONTAINER_multihashmap_size (pg->
4381           peers
4382           [pg_iter].connect_peers_working_set);
4383 #endif
4384     }
4385
4386   return count;
4387 }
4388
4389 static unsigned int
4390 count_allowed_connections(struct GNUNET_TESTING_PeerGroup *pg)
4391 {
4392   unsigned int count;
4393   unsigned int pg_iter;
4394 #if OLD
4395   struct PeerConnection *conn_iter;
4396 #endif
4397
4398   count = 0;
4399   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4400     {
4401 #if OLD
4402       conn_iter = pg->peers[pg_iter].allowed_peers_head;
4403       while (conn_iter != NULL)
4404         {
4405           count++;
4406           conn_iter = conn_iter->next;
4407         }
4408 #else
4409       count +=
4410       GNUNET_CONTAINER_multihashmap_size (pg->
4411           peers
4412           [pg_iter].allowed_peers);
4413 #endif
4414     }
4415
4416   return count;
4417 }
4418
4419 /**
4420  * From the set of connections possible, choose at least num connections per
4421  * peer.
4422  *
4423  * @param pg the peergroup we are dealing with
4424  * @param num how many connections at least should each peer have (if possible)?
4425  */
4426 static void
4427 choose_minimum(struct GNUNET_TESTING_PeerGroup *pg, unsigned int num)
4428 {
4429 #if !OLD
4430   struct MinimumContext minimum_ctx;
4431 #else
4432   struct PeerConnection *conn_iter;
4433   unsigned int temp_list_size;
4434   unsigned int i;
4435   unsigned int count;
4436   uint32_t random; /* Random list entry to connect peer to */
4437 #endif
4438   uint32_t pg_iter;
4439
4440 #if OLD
4441   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4442     {
4443       temp_list_size
4444           = count_connections (pg->peers[pg_iter].connect_peers_head);
4445       if (temp_list_size == 0)
4446         {
4447           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4448                       "Peer %d has 0 connections!?!?\n", pg_iter);
4449           break;
4450         }
4451       for (i = 0; i < num; i++)
4452         {
4453           random = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4454                                              temp_list_size);
4455           conn_iter = pg->peers[pg_iter].connect_peers_head;
4456           for (count = 0; count < random; count++)
4457             conn_iter = conn_iter->next;
4458           /* We now have a random connection, connect it! */
4459           GNUNET_assert(conn_iter != NULL);
4460           add_connections (pg, pg_iter, conn_iter->index, WORKING_SET,
4461                            GNUNET_YES);
4462         }
4463     }
4464 #else
4465   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4466     {
4467       pg->peers[pg_iter].connect_peers_working_set =
4468       GNUNET_CONTAINER_multihashmap_create (num);
4469     }
4470
4471   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4472     {
4473       minimum_ctx.first_uid = pg_iter;
4474       minimum_ctx.pg_array =
4475       GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
4476           GNUNET_CONTAINER_multihashmap_size
4477           (pg->peers[pg_iter].connect_peers));
4478       minimum_ctx.first = &pg->peers[pg_iter];
4479       minimum_ctx.pg = pg;
4480       minimum_ctx.num_to_add = num;
4481       minimum_ctx.current = 0;
4482       GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].connect_peers,
4483           &minimum_connect_iterator,
4484           &minimum_ctx);
4485     }
4486
4487   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4488     {
4489       /* Remove the "old" connections */
4490       GNUNET_CONTAINER_multihashmap_destroy (pg->
4491           peers[pg_iter].connect_peers);
4492       /* And replace with the working set */
4493       pg->peers[pg_iter].connect_peers =
4494       pg->peers[pg_iter].connect_peers_working_set;
4495     }
4496 #endif
4497   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4498     {
4499       while (pg->peers[pg_iter].connect_peers_head != NULL)
4500         {
4501           conn_iter = pg->peers[pg_iter].connect_peers_head;
4502           GNUNET_CONTAINER_DLL_remove(pg->peers[pg_iter].connect_peers_head,
4503               pg->peers[pg_iter].connect_peers_tail,
4504               conn_iter);
4505           GNUNET_free(conn_iter);
4506           /*remove_connections(pg, pg_iter, pg->peers[pg_iter].connect_peers_head->index, CONNECT, GNUNET_YES);*/
4507         }
4508
4509       pg->peers[pg_iter].connect_peers_head
4510           = pg->peers[pg_iter].connect_peers_working_set_head;
4511       pg->peers[pg_iter].connect_peers_tail
4512           = pg->peers[pg_iter].connect_peers_working_set_tail;
4513       pg->peers[pg_iter].connect_peers_working_set_head = NULL;
4514       pg->peers[pg_iter].connect_peers_working_set_tail = NULL;
4515     }
4516 }
4517
4518 #if !OLD
4519 struct FindClosestContext
4520   {
4521     /**
4522      * The currently known closest peer.
4523      */
4524     struct GNUNET_TESTING_Daemon *closest;
4525
4526     /**
4527      * The info for the peer we are adding connections for.
4528      */
4529     struct PeerData *curr_peer;
4530
4531     /**
4532      * The distance (bits) between the current
4533      * peer and the currently known closest.
4534      */
4535     unsigned int closest_dist;
4536
4537     /**
4538      * The offset of the closest known peer in
4539      * the peer group.
4540      */
4541     unsigned int closest_num;
4542   };
4543
4544 /**
4545  * Iterator over hash map entries of the allowed
4546  * peer connections.  Find the closest, not already
4547  * connected peer and return it.
4548  *
4549  * @param cls closure (struct FindClosestContext)
4550  * @param key current key code (hash of offset in pg)
4551  * @param value value in the hash map - a GNUNET_TESTING_Daemon
4552  * @return GNUNET_YES if we should continue to
4553  *         iterate,
4554  *         GNUNET_NO if not.
4555  */
4556 static int
4557 find_closest_peers (void *cls, const GNUNET_HashCode * key, void *value)
4558   {
4559     struct FindClosestContext *closest_ctx = cls;
4560     struct GNUNET_TESTING_Daemon *daemon = value;
4561
4562     if (((closest_ctx->closest == NULL) ||
4563             (GNUNET_CRYPTO_hash_matching_bits
4564                 (&daemon->id.hashPubKey,
4565                     &closest_ctx->curr_peer->daemon->id.hashPubKey) >
4566                 closest_ctx->closest_dist))
4567         && (GNUNET_YES !=
4568             GNUNET_CONTAINER_multihashmap_contains (closest_ctx->
4569                 curr_peer->connect_peers,
4570                 key)))
4571       {
4572         closest_ctx->closest_dist =
4573         GNUNET_CRYPTO_hash_matching_bits (&daemon->id.hashPubKey,
4574             &closest_ctx->curr_peer->daemon->
4575             id.hashPubKey);
4576         closest_ctx->closest = daemon;
4577         uid_from_hash (key, &closest_ctx->closest_num);
4578       }
4579     return GNUNET_YES;
4580   }
4581
4582 /**
4583  * From the set of connections possible, choose at num connections per
4584  * peer based on depth which are closest out of those allowed.  Guaranteed
4585  * to add num peers to connect to, provided there are that many peers
4586  * in the underlay topology to connect to.
4587  *
4588  * @param pg the peergroup we are dealing with
4589  * @param num how many connections at least should each peer have (if possible)?
4590  * @param proc processor to actually add the connections
4591  * @param list the peer list to use
4592  */
4593 void
4594 add_closest (struct GNUNET_TESTING_PeerGroup *pg, unsigned int num,
4595     GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
4596   {
4597 #if OLD
4598
4599 #else
4600     struct FindClosestContext closest_ctx;
4601 #endif
4602     uint32_t pg_iter;
4603     uint32_t i;
4604
4605     for (i = 0; i < num; i++) /* Each time find a closest peer (from those available) */
4606       {
4607         for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4608           {
4609             closest_ctx.curr_peer = &pg->peers[pg_iter];
4610             closest_ctx.closest = NULL;
4611             closest_ctx.closest_dist = 0;
4612             closest_ctx.closest_num = 0;
4613             GNUNET_CONTAINER_multihashmap_iterate (pg->
4614                 peers[pg_iter].allowed_peers,
4615                 &find_closest_peers,
4616                 &closest_ctx);
4617             if (closest_ctx.closest != NULL)
4618               {
4619                 GNUNET_assert (closest_ctx.closest_num < pg->total);
4620                 proc (pg, pg_iter, closest_ctx.closest_num, list);
4621               }
4622           }
4623       }
4624   }
4625 #endif
4626
4627 /**
4628  * From the set of connections possible, choose at least num connections per
4629  * peer based on depth first traversal of peer connections.  If DFS leaves
4630  * peers unconnected, ensure those peers get connections.
4631  *
4632  * @param pg the peergroup we are dealing with
4633  * @param num how many connections at least should each peer have (if possible)?
4634  */
4635 void
4636 perform_dfs(struct GNUNET_TESTING_PeerGroup *pg, unsigned int num)
4637 {
4638   uint32_t pg_iter;
4639   uint32_t dfs_count;
4640   uint32_t starting_peer;
4641   uint32_t least_connections;
4642   uint32_t random_connection;
4643 #if OLD
4644   unsigned int temp_count;
4645   struct PeerConnection *peer_iter;
4646 #else
4647   struct DFSContext dfs_ctx;
4648   GNUNET_HashCode second_hash;
4649 #endif
4650
4651 #if OLD
4652   starting_peer = 0;
4653   dfs_count = 0;
4654   while ((count_workingset_connections (pg) < num * pg->total)
4655       && (count_allowed_connections (pg) > 0))
4656     {
4657       if (dfs_count % pg->total == 0) /* Restart the DFS at some weakly connected peer */
4658         {
4659           least_connections = -1; /* Set to very high number */
4660           for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4661             {
4662               temp_count
4663                   = count_connections (
4664                                        pg->peers[pg_iter].connect_peers_working_set_head);
4665               if (temp_count < least_connections)
4666                 {
4667                   starting_peer = pg_iter;
4668                   least_connections = temp_count;
4669                 }
4670             }
4671         }
4672
4673       temp_count
4674           = count_connections (pg->peers[starting_peer].connect_peers_head);
4675       if (temp_count == 0)
4676         continue; /* FIXME: infinite loop? */
4677
4678       random_connection = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4679                                                     temp_count);
4680       temp_count = 0;
4681       peer_iter = pg->peers[starting_peer].connect_peers_head;
4682       while (temp_count < random_connection)
4683         {
4684           peer_iter = peer_iter->next;
4685           temp_count++;
4686         }
4687       GNUNET_assert(peer_iter != NULL);
4688       add_connections (pg, starting_peer, peer_iter->index, WORKING_SET,
4689                        GNUNET_NO);
4690       remove_connections (pg, starting_peer, peer_iter->index, CONNECT,
4691                           GNUNET_YES);
4692       starting_peer = peer_iter->index;
4693       dfs_count++;
4694     }
4695
4696 #else
4697   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4698     {
4699       pg->peers[pg_iter].connect_peers_working_set =
4700       GNUNET_CONTAINER_multihashmap_create (num);
4701     }
4702
4703   starting_peer = 0;
4704   dfs_count = 0;
4705   while ((count_workingset_connections (pg) < num * pg->total)
4706       && (count_allowed_connections (pg) > 0))
4707     {
4708       if (dfs_count % pg->total == 0) /* Restart the DFS at some weakly connected peer */
4709         {
4710           least_connections = -1; /* Set to very high number */
4711           for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4712             {
4713               if (GNUNET_CONTAINER_multihashmap_size
4714                   (pg->peers[pg_iter].connect_peers_working_set) <
4715                   least_connections)
4716                 {
4717                   starting_peer = pg_iter;
4718                   least_connections =
4719                   GNUNET_CONTAINER_multihashmap_size (pg->
4720                       peers
4721                       [pg_iter].connect_peers_working_set);
4722                 }
4723             }
4724         }
4725
4726       if (GNUNET_CONTAINER_multihashmap_size (pg->peers[starting_peer].connect_peers) == 0) /* Ensure there is at least one peer left to connect! */
4727         {
4728           dfs_count = 0;
4729           continue;
4730         }
4731
4732       /* Choose a random peer from the chosen peers set of connections to add */
4733       dfs_ctx.chosen =
4734       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4735           GNUNET_CONTAINER_multihashmap_size
4736           (pg->peers[starting_peer].connect_peers));
4737       dfs_ctx.first_uid = starting_peer;
4738       dfs_ctx.first = &pg->peers[starting_peer];
4739       dfs_ctx.pg = pg;
4740       dfs_ctx.current = 0;
4741
4742       GNUNET_CONTAINER_multihashmap_iterate (pg->
4743           peers
4744           [starting_peer].connect_peers,
4745           &dfs_connect_iterator, &dfs_ctx);
4746       /* Remove the second from the first, since we will be continuing the search and may encounter the first peer again! */
4747       hash_from_uid (dfs_ctx.second_uid, &second_hash);
4748       GNUNET_assert (GNUNET_YES ==
4749           GNUNET_CONTAINER_multihashmap_remove (pg->peers
4750               [starting_peer].connect_peers,
4751               &second_hash,
4752               pg->
4753               peers
4754               [dfs_ctx.second_uid].daemon));
4755       starting_peer = dfs_ctx.second_uid;
4756     }
4757
4758   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4759     {
4760       /* Remove the "old" connections */
4761       GNUNET_CONTAINER_multihashmap_destroy (pg->
4762           peers[pg_iter].connect_peers);
4763       /* And replace with the working set */
4764       pg->peers[pg_iter].connect_peers =
4765       pg->peers[pg_iter].connect_peers_working_set;
4766     }
4767 #endif
4768 }
4769
4770 /**
4771  * Internal callback for topology information for a particular peer.
4772  */
4773 static void
4774 internal_topology_callback(void *cls, const struct GNUNET_PeerIdentity *peer,
4775                            const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4776 {
4777   struct CoreContext *core_ctx = cls;
4778   struct TopologyIterateContext *iter_ctx = core_ctx->iter_context;
4779
4780   if (peer == NULL) /* Either finished, or something went wrong */
4781     {
4782       iter_ctx->completed++;
4783       iter_ctx->connected--;
4784       /* One core context allocated per iteration, must free! */
4785       GNUNET_free (core_ctx);
4786     }
4787   else
4788     {
4789       iter_ctx->topology_cb (iter_ctx->cls, &core_ctx->daemon->id, peer, NULL);
4790     }
4791
4792   if (iter_ctx->completed == iter_ctx->total)
4793     {
4794       iter_ctx->topology_cb (iter_ctx->cls, NULL, NULL, NULL);
4795       /* Once all are done, free the iteration context */
4796       GNUNET_free (iter_ctx);
4797     }
4798 }
4799
4800 /**
4801  * Check running topology iteration tasks, if below max start a new one, otherwise
4802  * schedule for some time in the future.
4803  */
4804 static void
4805 schedule_get_topology(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4806 {
4807   struct CoreContext *core_context = cls;
4808   struct TopologyIterateContext *topology_context =
4809       (struct TopologyIterateContext *) core_context->iter_context;
4810   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4811     return;
4812
4813   if (topology_context->connected
4814       > topology_context->pg->max_outstanding_connections)
4815     {
4816 #if VERBOSE_TESTING > 2
4817       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4818           _
4819           ("Delaying connect, we have too many outstanding connections!\n"));
4820 #endif
4821       GNUNET_SCHEDULER_add_delayed (
4822                                     GNUNET_TIME_relative_multiply (
4823                                                                    GNUNET_TIME_UNIT_MILLISECONDS,
4824                                                                    100),
4825                                     &schedule_get_topology, core_context);
4826     }
4827   else
4828     {
4829 #if VERBOSE_TESTING > 2
4830       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4831           _("Creating connection, outstanding_connections is %d\n"),
4832           outstanding_connects);
4833 #endif
4834       topology_context->connected++;
4835
4836       if (GNUNET_OK != GNUNET_CORE_iterate_peers (core_context->daemon->cfg,
4837                                                   &internal_topology_callback,
4838                                                   core_context))
4839         {
4840           GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Topology iteration failed.\n");
4841           internal_topology_callback (core_context, NULL, NULL);
4842         }
4843     }
4844 }
4845
4846 /**
4847  * Iterate over all (running) peers in the peer group, retrieve
4848  * all connections that each currently has.
4849  */
4850 void
4851 GNUNET_TESTING_get_topology(struct GNUNET_TESTING_PeerGroup *pg,
4852                             GNUNET_TESTING_NotifyTopology cb, void *cls)
4853 {
4854   struct TopologyIterateContext *topology_context;
4855   struct CoreContext *core_ctx;
4856   unsigned int i;
4857   unsigned int total_count;
4858
4859   /* Allocate a single topology iteration context */
4860   topology_context = GNUNET_malloc (sizeof (struct TopologyIterateContext));
4861   topology_context->topology_cb = cb;
4862   topology_context->cls = cls;
4863   topology_context->pg = pg;
4864   total_count = 0;
4865   for (i = 0; i < pg->total; i++)
4866     {
4867       if (pg->peers[i].daemon->running == GNUNET_YES)
4868         {
4869           /* Allocate one core context per core we need to connect to */
4870           core_ctx = GNUNET_malloc (sizeof (struct CoreContext));
4871           core_ctx->daemon = pg->peers[i].daemon;
4872           /* Set back pointer to topology iteration context */
4873           core_ctx->iter_context = topology_context;
4874           GNUNET_SCHEDULER_add_now (&schedule_get_topology, core_ctx);
4875           total_count++;
4876         }
4877     }
4878   if (total_count == 0)
4879     {
4880       cb (cls, NULL, NULL, "Cannot iterate over topology, no running peers!");
4881       GNUNET_free (topology_context);
4882     }
4883   else
4884     topology_context->total = total_count;
4885   return;
4886 }
4887
4888 /**
4889  * Callback function to process statistic values.
4890  * This handler is here only really to insert a peer
4891  * identity (or daemon) so the statistics can be uniquely
4892  * tied to a single running peer.
4893  *
4894  * @param cls closure
4895  * @param subsystem name of subsystem that created the statistic
4896  * @param name the name of the datum
4897  * @param value the current value
4898  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
4899  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
4900  */
4901 static int
4902 internal_stats_callback(void *cls, const char *subsystem, const char *name,
4903                         uint64_t value, int is_persistent)
4904 {
4905   struct StatsCoreContext *core_context = cls;
4906   struct StatsIterateContext *stats_context =
4907       (struct StatsIterateContext *) core_context->iter_context;
4908
4909   return stats_context->proc (stats_context->cls, &core_context->daemon->id,
4910                               subsystem, name, value, is_persistent);
4911 }
4912
4913 /**
4914  * Internal continuation call for statistics iteration.
4915  *
4916  * @param cls closure, the CoreContext for this iteration
4917  * @param success whether or not the statistics iterations
4918  *        was canceled or not (we don't care)
4919  */
4920 static void
4921 internal_stats_cont(void *cls, int success)
4922 {
4923   struct StatsCoreContext *core_context = cls;
4924   struct StatsIterateContext *stats_context =
4925       (struct StatsIterateContext *) core_context->iter_context;
4926
4927   stats_context->connected--;
4928   stats_context->completed++;
4929
4930   if (stats_context->completed == stats_context->total)
4931     {
4932       stats_context->cont (stats_context->cls, GNUNET_YES);
4933       GNUNET_free (stats_context);
4934     }
4935
4936   if (core_context->stats_handle != NULL)
4937     GNUNET_STATISTICS_destroy (core_context->stats_handle, GNUNET_NO);
4938
4939   GNUNET_free (core_context);
4940 }
4941
4942 /**
4943  * Check running topology iteration tasks, if below max start a new one, otherwise
4944  * schedule for some time in the future.
4945  */
4946 static void
4947 schedule_get_statistics(void *cls,
4948                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4949 {
4950   struct StatsCoreContext *core_context = cls;
4951   struct StatsIterateContext *stats_context =
4952       (struct StatsIterateContext *) core_context->iter_context;
4953
4954   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4955     return;
4956
4957   if (stats_context->connected > stats_context->pg->max_outstanding_connections)
4958     {
4959 #if VERBOSE_TESTING > 2
4960       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4961           _
4962           ("Delaying connect, we have too many outstanding connections!\n"));
4963 #endif
4964       GNUNET_SCHEDULER_add_delayed (
4965                                     GNUNET_TIME_relative_multiply (
4966                                                                    GNUNET_TIME_UNIT_MILLISECONDS,
4967                                                                    100),
4968                                     &schedule_get_statistics, core_context);
4969     }
4970   else
4971     {
4972 #if VERBOSE_TESTING > 2
4973       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4974           _("Creating connection, outstanding_connections is %d\n"),
4975           outstanding_connects);
4976 #endif
4977
4978       stats_context->connected++;
4979       core_context->stats_handle
4980           = GNUNET_STATISTICS_create ("testing", core_context->daemon->cfg);
4981       if (core_context->stats_handle == NULL)
4982         {
4983           internal_stats_cont (core_context, GNUNET_NO);
4984           return;
4985         }
4986
4987       core_context->stats_get_handle
4988           = GNUNET_STATISTICS_get (core_context->stats_handle, NULL, NULL,
4989                                    GNUNET_TIME_relative_get_forever (),
4990                                    &internal_stats_cont,
4991                                    &internal_stats_callback, core_context);
4992       if (core_context->stats_get_handle == NULL)
4993         internal_stats_cont (core_context, GNUNET_NO);
4994
4995     }
4996 }
4997
4998 struct DuplicateStats
4999 {
5000   /**
5001    * Next item in the list
5002    */
5003   struct DuplicateStats *next;
5004
5005   /**
5006    * Nasty string, concatenation of relevant information.
5007    */
5008   char *unique_string;
5009 };
5010
5011 /**
5012  * Check whether the combination of port/host/unix domain socket
5013  * already exists in the list of peers being checked for statistics.
5014  *
5015  * @param pg the peergroup in question
5016  * @param specific_peer the peer we're concerned with
5017  * @param stats_list the list to return to the caller
5018  *
5019  * @return GNUNET_YES if the statistics instance has been seen already,
5020  *         GNUNET_NO if not (and we may have added it to the list)
5021  */
5022 static int
5023 stats_check_existing(struct GNUNET_TESTING_PeerGroup *pg,
5024                      struct PeerData *specific_peer,
5025                      struct DuplicateStats **stats_list)
5026 {
5027   struct DuplicateStats *pos;
5028   char *unix_domain_socket;
5029   unsigned long long port;
5030   char *to_match;
5031   if (GNUNET_YES
5032       != GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "testing",
5033                                                "single_statistics_per_host"))
5034     return GNUNET_NO; /* Each peer has its own statistics instance, do nothing! */
5035
5036   pos = *stats_list;
5037   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (specific_peer->cfg,
5038                                                           "statistics",
5039                                                           "unixpath",
5040                                                           &unix_domain_socket))
5041     return GNUNET_NO;
5042
5043   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (specific_peer->cfg,
5044                                                           "statistics", "port",
5045                                                           &port))
5046     {
5047       GNUNET_free(unix_domain_socket);
5048       return GNUNET_NO;
5049     }
5050
5051   if (specific_peer->daemon->hostname != NULL)
5052     GNUNET_asprintf (&to_match, "%s%s%llu", specific_peer->daemon->hostname,
5053                      unix_domain_socket, port);
5054   else
5055     GNUNET_asprintf (&to_match, "%s%llu", unix_domain_socket, port);
5056
5057   while (pos != NULL)
5058     {
5059       if (0 == strcmp (to_match, pos->unique_string))
5060         {
5061           GNUNET_free (unix_domain_socket);
5062           GNUNET_free (to_match);
5063           return GNUNET_YES;
5064         }
5065       pos = pos->next;
5066     }
5067   pos = GNUNET_malloc (sizeof (struct DuplicateStats));
5068   pos->unique_string = to_match;
5069   pos->next = *stats_list;
5070   *stats_list = pos;
5071   GNUNET_free (unix_domain_socket);
5072   return GNUNET_NO;
5073 }
5074
5075 /**
5076  * Iterate over all (running) peers in the peer group, retrieve
5077  * all statistics from each.
5078  */
5079 void
5080 GNUNET_TESTING_get_statistics(struct GNUNET_TESTING_PeerGroup *pg,
5081                               GNUNET_STATISTICS_Callback cont,
5082                               GNUNET_TESTING_STATISTICS_Iterator proc,
5083                               void *cls)
5084 {
5085   struct StatsIterateContext *stats_context;
5086   struct StatsCoreContext *core_ctx;
5087   unsigned int i;
5088   unsigned int total_count;
5089   struct DuplicateStats *stats_list;
5090   struct DuplicateStats *pos;
5091   stats_list = NULL;
5092
5093   /* Allocate a single stats iteration context */
5094   stats_context = GNUNET_malloc (sizeof (struct StatsIterateContext));
5095   stats_context->cont = cont;
5096   stats_context->proc = proc;
5097   stats_context->cls = cls;
5098   stats_context->pg = pg;
5099   total_count = 0;
5100
5101   for (i = 0; i < pg->total; i++)
5102     {
5103       if ((pg->peers[i].daemon->running == GNUNET_YES) && (GNUNET_NO
5104           == stats_check_existing (pg, &pg->peers[i], &stats_list)))
5105         {
5106           /* Allocate one core context per core we need to connect to */
5107           core_ctx = GNUNET_malloc (sizeof (struct StatsCoreContext));
5108           core_ctx->daemon = pg->peers[i].daemon;
5109           /* Set back pointer to topology iteration context */
5110           core_ctx->iter_context = stats_context;
5111           GNUNET_SCHEDULER_add_now (&schedule_get_statistics, core_ctx);
5112           total_count++;
5113         }
5114     }
5115
5116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5117               "Retrieving stats from %u total instances.\n", total_count);
5118   stats_context->total = total_count;
5119   if (stats_list != NULL)
5120     {
5121       pos = stats_list;
5122       while (pos != NULL)
5123         {
5124           GNUNET_free (pos->unique_string);
5125           stats_list = pos->next;
5126           GNUNET_free (pos);
5127           pos = stats_list->next;
5128         }
5129     }
5130   return;
5131 }
5132
5133 /**
5134  * Stop the connection process temporarily.
5135  *
5136  * @param pg the peer group to stop connecting
5137  */
5138 void
5139 GNUNET_TESTING_stop_connections(struct GNUNET_TESTING_PeerGroup *pg)
5140 {
5141   pg->stop_connects = GNUNET_YES;
5142 }
5143
5144 /**
5145  * Resume the connection process temporarily.
5146  *
5147  * @param pg the peer group to resume connecting
5148  */
5149 void
5150 GNUNET_TESTING_resume_connections(struct GNUNET_TESTING_PeerGroup *pg)
5151 {
5152   pg->stop_connects = GNUNET_NO;
5153 }
5154
5155 /**
5156  * There are many ways to connect peers that are supported by this function.
5157  * To connect peers in the same topology that was created via the
5158  * GNUNET_TESTING_create_topology, the topology variable must be set to
5159  * GNUNET_TESTING_TOPOLOGY_NONE.  If the topology variable is specified,
5160  * a new instance of that topology will be generated and attempted to be
5161  * connected.  This could result in some connections being impossible,
5162  * because some topologies are non-deterministic.
5163  *
5164  * @param pg the peer group struct representing the running peers
5165  * @param topology which topology to connect the peers in
5166  * @param options options for connecting the topology
5167  * @param option_modifier modifier for options that take a parameter
5168  * @param connect_timeout how long to wait before giving up on connecting
5169  *                        two peers
5170  * @param connect_attempts how many times to attempt to connect two peers
5171  *                         over the connect_timeout duration
5172  * @param notify_callback notification to be called once all connections completed
5173  * @param notify_cls closure for notification callback
5174  *
5175  * @return the number of connections that will be attempted, GNUNET_SYSERR on error
5176  */
5177 int
5178 GNUNET_TESTING_connect_topology(
5179                                 struct GNUNET_TESTING_PeerGroup *pg,
5180                                 enum GNUNET_TESTING_Topology topology,
5181                                 enum GNUNET_TESTING_TopologyOption options,
5182                                 double option_modifier,
5183                                 struct GNUNET_TIME_Relative connect_timeout,
5184                                 unsigned int connect_attempts,
5185                                 GNUNET_TESTING_NotifyCompletion notify_callback,
5186                                 void *notify_cls)
5187 {
5188   switch (topology)
5189     {
5190   case GNUNET_TESTING_TOPOLOGY_CLIQUE:
5191 #if VERBOSE_TOPOLOGY
5192     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5193                 _("Creating clique CONNECT topology\n"));
5194 #endif
5195     create_clique (pg, &add_connections, CONNECT, GNUNET_NO);
5196     break;
5197   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
5198 #if VERBOSE_TOPOLOGY
5199     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5200                 _("Creating small world (ring) CONNECT topology\n"));
5201 #endif
5202     create_small_world_ring (pg, &add_connections, CONNECT);
5203     break;
5204   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
5205 #if VERBOSE_TOPOLOGY
5206     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5207                 _("Creating small world (2d-torus) CONNECT topology\n"));
5208 #endif
5209     create_small_world (pg, &add_connections, CONNECT);
5210     break;
5211   case GNUNET_TESTING_TOPOLOGY_RING:
5212 #if VERBOSE_TOPOLOGY
5213     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating ring CONNECT topology\n"));
5214 #endif
5215     create_ring (pg, &add_connections, CONNECT);
5216     break;
5217   case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
5218 #if VERBOSE_TOPOLOGY
5219     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5220                 _("Creating 2d torus CONNECT topology\n"));
5221 #endif
5222     create_2d_torus (pg, &add_connections, CONNECT);
5223     break;
5224   case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
5225 #if VERBOSE_TOPOLOGY
5226     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5227                 _("Creating Erdos-Renyi CONNECT topology\n"));
5228 #endif
5229     create_erdos_renyi (pg, &add_connections, CONNECT);
5230     break;
5231   case GNUNET_TESTING_TOPOLOGY_INTERNAT:
5232 #if VERBOSE_TOPOLOGY
5233     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5234                 _("Creating InterNAT CONNECT topology\n"));
5235 #endif
5236     create_nated_internet (pg, &add_connections, CONNECT);
5237     break;
5238   case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
5239 #if VERBOSE_TOPOLOGY
5240     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5241                 _("Creating Scale Free CONNECT topology\n"));
5242 #endif
5243     create_scale_free (pg, &add_connections, CONNECT);
5244     break;
5245   case GNUNET_TESTING_TOPOLOGY_LINE:
5246 #if VERBOSE_TOPOLOGY
5247     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5248                 _("Creating straight line CONNECT topology\n"));
5249 #endif
5250     create_line (pg, &add_connections, CONNECT);
5251     break;
5252   case GNUNET_TESTING_TOPOLOGY_NONE:
5253 #if VERBOSE_TOPOLOGY
5254     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating no CONNECT topology\n"));
5255 #endif
5256     copy_allowed_topology (pg);
5257     break;
5258   default:
5259     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _
5260     ("Unknown topology specification, can't connect peers!\n"));
5261     return GNUNET_SYSERR;
5262     }
5263
5264   switch (options)
5265     {
5266   case GNUNET_TESTING_TOPOLOGY_OPTION_RANDOM:
5267 #if VERBOSE_TOPOLOGY
5268     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _
5269     ("Connecting random subset (%'.2f percent) of possible peers\n"), 100
5270         * option_modifier);
5271 #endif
5272     choose_random_connections (pg, option_modifier);
5273     break;
5274   case GNUNET_TESTING_TOPOLOGY_OPTION_MINIMUM:
5275 #if VERBOSE_TOPOLOGY
5276     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5277                 _("Connecting a minimum of %u peers each (if possible)\n"),
5278                 (unsigned int) option_modifier);
5279 #endif
5280     choose_minimum (pg, (unsigned int) option_modifier);
5281     break;
5282   case GNUNET_TESTING_TOPOLOGY_OPTION_DFS:
5283 #if VERBOSE_TOPOLOGY
5284     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _
5285     ("Using DFS to connect a minimum of %u peers each (if possible)\n"),
5286                 (unsigned int) option_modifier);
5287 #endif
5288 #if FIXME
5289     perform_dfs (pg, (int) option_modifier);
5290 #endif
5291     break;
5292   case GNUNET_TESTING_TOPOLOGY_OPTION_ADD_CLOSEST:
5293 #if VERBOSE_TOPOLOGY
5294     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _
5295     ("Finding additional %u closest peers each (if possible)\n"),
5296                 (unsigned int) option_modifier);
5297 #endif
5298 #if FIXME
5299     add_closest (pg, (unsigned int) option_modifier,
5300         &add_connections, CONNECT);
5301 #endif
5302     break;
5303   case GNUNET_TESTING_TOPOLOGY_OPTION_NONE:
5304     break;
5305   case GNUNET_TESTING_TOPOLOGY_OPTION_ALL:
5306     break;
5307   default:
5308     break;
5309     }
5310
5311   return connect_topology (pg, connect_timeout, connect_attempts,
5312                            notify_callback, notify_cls);
5313 }
5314
5315 /**
5316  * Lookup and return the number of SSH connections to a host.
5317  *
5318  * @param hostname the hostname to lookup in the list
5319  * @param pg the peergroup that the host belongs to
5320  *
5321  * @return the number of current ssh connections to the host
5322  */
5323 static unsigned int
5324 count_outstanding_at_host(const char *hostname,
5325                           struct GNUNET_TESTING_PeerGroup *pg)
5326 {
5327   struct OutstandingSSH *pos;
5328   pos = pg->ssh_head;
5329   while ((pos != NULL) && (strcmp (pos->hostname, hostname) != 0))
5330     pos = pos->next;
5331   GNUNET_assert(pos != NULL);
5332   return pos->outstanding;
5333 }
5334
5335 /**
5336  * Increment the number of SSH connections to a host by one.
5337  *
5338  * @param hostname the hostname to lookup in the list
5339  * @param pg the peergroup that the host belongs to
5340  *
5341  */
5342 static void
5343 increment_outstanding_at_host(const char *hostname,
5344                               struct GNUNET_TESTING_PeerGroup *pg)
5345 {
5346   struct OutstandingSSH *pos;
5347   pos = pg->ssh_head;
5348   while ((pos != NULL) && (strcmp (pos->hostname, hostname) != 0))
5349     pos = pos->next;
5350   GNUNET_assert(pos != NULL);
5351   pos->outstanding++;
5352 }
5353
5354 /**
5355  * Decrement the number of SSH connections to a host by one.
5356  *
5357  * @param hostname the hostname to lookup in the list
5358  * @param pg the peergroup that the host belongs to
5359  *
5360  */
5361 static void
5362 decrement_outstanding_at_host(const char *hostname,
5363                               struct GNUNET_TESTING_PeerGroup *pg)
5364 {
5365   struct OutstandingSSH *pos;
5366   pos = pg->ssh_head;
5367   while ((pos != NULL) && (strcmp (pos->hostname, hostname) != 0))
5368     pos = pos->next;
5369   GNUNET_assert(pos != NULL);
5370   pos->outstanding--;
5371 }
5372
5373 /**
5374  * Callback that is called whenever a hostkey is generated
5375  * for a peer.  Call the real callback and decrement the
5376  * starting counter for the peergroup.
5377  *
5378  * @param cls closure
5379  * @param id identifier for the daemon, NULL on error
5380  * @param d handle for the daemon
5381  * @param emsg error message (NULL on success)
5382  */
5383 static void
5384 internal_hostkey_callback(void *cls, const struct GNUNET_PeerIdentity *id,
5385                           struct GNUNET_TESTING_Daemon *d, const char *emsg)
5386 {
5387   struct InternalStartContext *internal_context = cls;
5388   internal_context->peer->pg->starting--;
5389   internal_context->peer->pg->started++;
5390   if (internal_context->hostname != NULL)
5391     decrement_outstanding_at_host (internal_context->hostname,
5392                                    internal_context->peer->pg);
5393   if (internal_context->hostkey_callback != NULL)
5394     internal_context->hostkey_callback (internal_context->hostkey_cls, id, d,
5395                                         emsg);
5396   else if (internal_context->peer->pg->started
5397       == internal_context->peer->pg->total)
5398     {
5399       internal_context->peer->pg->started = 0; /* Internal startup may use this counter! */
5400       GNUNET_TESTING_daemons_continue_startup (internal_context->peer->pg);
5401     }
5402 }
5403
5404 /**
5405  * Callback that is called whenever a peer has finished starting.
5406  * Call the real callback and decrement the starting counter
5407  * for the peergroup.
5408  *
5409  * @param cls closure
5410  * @param id identifier for the daemon, NULL on error
5411  * @param cfg config
5412  * @param d handle for the daemon
5413  * @param emsg error message (NULL on success)
5414  */
5415 static void
5416 internal_startup_callback(void *cls, const struct GNUNET_PeerIdentity *id,
5417                           const struct GNUNET_CONFIGURATION_Handle *cfg,
5418                           struct GNUNET_TESTING_Daemon *d, const char *emsg)
5419 {
5420   struct InternalStartContext *internal_context = cls;
5421   internal_context->peer->pg->starting--;
5422   if (internal_context->hostname != NULL)
5423     decrement_outstanding_at_host (internal_context->hostname,
5424                                    internal_context->peer->pg);
5425   if (internal_context->start_cb != NULL)
5426     internal_context->start_cb (internal_context->start_cb_cls, id, cfg, d,
5427                                 emsg);
5428 }
5429
5430 static void
5431 internal_continue_startup(void *cls,
5432                           const struct GNUNET_SCHEDULER_TaskContext *tc)
5433 {
5434   struct InternalStartContext *internal_context = cls;
5435
5436   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
5437     {
5438       return;
5439     }
5440
5441   if ((internal_context->peer->pg->starting
5442       < internal_context->peer->pg->max_concurrent_ssh)
5443       || ((internal_context->hostname != NULL)
5444           && (count_outstanding_at_host (internal_context->hostname,
5445                                          internal_context->peer->pg)
5446               < internal_context->peer->pg->max_concurrent_ssh)))
5447     {
5448       if (internal_context->hostname != NULL)
5449         increment_outstanding_at_host (internal_context->hostname,
5450                                        internal_context->peer->pg);
5451       internal_context->peer->pg->starting++;
5452       GNUNET_TESTING_daemon_continue_startup (internal_context->peer->daemon);
5453     }
5454   else
5455     {
5456       GNUNET_SCHEDULER_add_delayed (
5457                                     GNUNET_TIME_relative_multiply (
5458                                                                    GNUNET_TIME_UNIT_MILLISECONDS,
5459                                                                    100),
5460                                     &internal_continue_startup,
5461                                     internal_context);
5462     }
5463 }
5464
5465 /**
5466  * Callback for informing us about a successful
5467  * or unsuccessful churn start call.
5468  *
5469  * @param cls a ChurnContext
5470  * @param id the peer identity of the started peer
5471  * @param cfg the handle to the configuration of the peer
5472  * @param d handle to the daemon for the peer
5473  * @param emsg NULL on success, non-NULL on failure
5474  *
5475  */
5476 void
5477 churn_start_callback(void *cls, const struct GNUNET_PeerIdentity *id,
5478                      const struct GNUNET_CONFIGURATION_Handle *cfg,
5479                      struct GNUNET_TESTING_Daemon *d, const char *emsg)
5480 {
5481   struct ChurnRestartContext *startup_ctx = cls;
5482   struct ChurnContext *churn_ctx = startup_ctx->churn_ctx;
5483
5484   unsigned int total_left;
5485   char *error_message;
5486
5487   error_message = NULL;
5488   if (emsg != NULL)
5489     {
5490       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5491                   "Churn stop callback failed with error `%s'\n", emsg);
5492       churn_ctx->num_failed_start++;
5493     }
5494   else
5495     {
5496       churn_ctx->num_to_start--;
5497     }
5498
5499 #if DEBUG_CHURN
5500   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5501       "Started peer, %d left.\n", churn_ctx->num_to_start);
5502 #endif
5503
5504   total_left = (churn_ctx->num_to_stop - churn_ctx->num_failed_stop)
5505       + (churn_ctx->num_to_start - churn_ctx->num_failed_start);
5506
5507   if (total_left == 0)
5508     {
5509       if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
5510         GNUNET_asprintf (
5511                          &error_message,
5512                          "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!",
5513                          churn_ctx->num_failed_start,
5514                          churn_ctx->num_failed_stop);
5515       churn_ctx->cb (churn_ctx->cb_cls, error_message);
5516       GNUNET_free_non_null (error_message);
5517       GNUNET_free (churn_ctx);
5518       GNUNET_free (startup_ctx);
5519     }
5520 }
5521
5522 static void
5523 schedule_churn_restart(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5524 {
5525   struct PeerRestartContext *peer_restart_ctx = cls;
5526   struct ChurnRestartContext *startup_ctx = peer_restart_ctx->churn_restart_ctx;
5527
5528   if (startup_ctx->outstanding > startup_ctx->pg->max_concurrent_ssh)
5529     GNUNET_SCHEDULER_add_delayed (
5530                                   GNUNET_TIME_relative_multiply (
5531                                                                  GNUNET_TIME_UNIT_MILLISECONDS,
5532                                                                  100),
5533                                   &schedule_churn_restart, peer_restart_ctx);
5534   else
5535     {
5536       GNUNET_TESTING_daemon_start_stopped (peer_restart_ctx->daemon,
5537                                            startup_ctx->timeout,
5538                                            &churn_start_callback, startup_ctx);
5539       GNUNET_free (peer_restart_ctx);
5540     }
5541 }
5542
5543
5544 static void
5545 internal_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5546 {
5547   struct InternalStartContext *internal_context = cls;
5548
5549   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
5550     {
5551       return;
5552     }
5553
5554   if ((internal_context->peer->pg->starting
5555       < internal_context->peer->pg->max_concurrent_ssh)
5556       || ((internal_context->hostname != NULL)
5557           && (count_outstanding_at_host (internal_context->hostname,
5558                                          internal_context->peer->pg)
5559               < internal_context->peer->pg->max_concurrent_ssh)))
5560     {
5561       if (internal_context->hostname != NULL)
5562         increment_outstanding_at_host (internal_context->hostname,
5563                                        internal_context->peer->pg);
5564       internal_context->peer->pg->starting++;
5565       internal_context->peer->daemon
5566           = GNUNET_TESTING_daemon_start (internal_context->peer->cfg,
5567                                          internal_context->timeout,
5568                                          GNUNET_NO,
5569                                          internal_context->hostname,
5570                                          internal_context->username,
5571                                          internal_context->sshport,
5572                                          internal_context->hostkey,
5573                                          &internal_hostkey_callback,
5574                                          internal_context,
5575                                          &internal_startup_callback,
5576                                          internal_context);
5577     }
5578   else
5579     {
5580       GNUNET_SCHEDULER_add_delayed (
5581                                     GNUNET_TIME_relative_multiply (
5582                                                                    GNUNET_TIME_UNIT_MILLISECONDS,
5583                                                                    100),
5584                                     &internal_start, internal_context);
5585     }
5586 }
5587 #if USE_START_HELPER
5588
5589 struct PeerStartHelperContext
5590 {
5591   struct GNUNET_TESTING_PeerGroup *pg;
5592
5593   struct HostData *host;
5594
5595   struct GNUNET_OS_Process *proc;
5596 };
5597
5598 static void
5599 check_peers_started (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5600 {
5601   struct PeerStartHelperContext *helper = cls;
5602   enum GNUNET_OS_ProcessStatusType type;
5603   unsigned long code;
5604   unsigned int i;
5605   GNUNET_TESTING_NotifyDaemonRunning cb;
5606
5607   if (GNUNET_NO == GNUNET_OS_process_status (helper->proc, &type, &code)) /* Still running, wait some more! */
5608   {
5609     GNUNET_SCHEDULER_add_delayed(GNUNET_CONSTANTS_EXEC_WAIT, &check_peers_started, helper);
5610     return;
5611   }
5612
5613   helper->pg->starting--;
5614   if (helper->pg->starting == 0) /* All peers have finished starting! */
5615     {
5616       /* Call the peer started callback for each peer, set proper FSM state (?) */
5617       for (i = 0; i < helper->pg->total; i++)
5618         {
5619           cb = helper->pg->peers[i].daemon->cb;
5620           helper->pg->peers[i].daemon->cb = NULL;
5621           helper->pg->peers[i].daemon->running = GNUNET_YES;
5622           helper->pg->peers[i].daemon->phase = SP_START_DONE;
5623           if (NULL != cb)
5624           {
5625             if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
5626               cb (helper->pg->peers[i].daemon->cb_cls,
5627                   &helper->pg->peers[i].daemon->id,
5628                   helper->pg->peers[i].daemon->cfg, helper->pg->peers[i].daemon,
5629                   "Failed to execute peerStartHelper.pl, or return code bad!");
5630             else
5631               cb (helper->pg->peers[i].daemon->cb_cls,
5632                   &helper->pg->peers[i].daemon->id,
5633                   helper->pg->peers[i].daemon->cfg, helper->pg->peers[i].daemon,
5634                   NULL);
5635
5636           }
5637
5638         }
5639     }
5640   GNUNET_OS_process_close(helper->proc);
5641 }
5642
5643 static void
5644 start_peer_helper (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5645 {
5646   struct PeerStartHelperContext *helper = cls;
5647   char *baseservicehome;
5648   char *tempdir;
5649   char *arg;
5650   /* ssh user@host peerStartHelper /path/to/basedirectory */
5651   GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (helper->pg->cfg, "PATHS", "SERVICEHOME",
5652                                                                     &baseservicehome));
5653   GNUNET_asprintf(&tempdir, "%s/%s/", baseservicehome, helper->host->hostname);
5654   if (NULL != helper->host->username)
5655     GNUNET_asprintf (&arg, "%s@%s", helper->host->username, helper->host->hostname);
5656   else
5657     GNUNET_asprintf (&arg, "%s", helper->host->hostname);
5658
5659   /* FIXME: Doesn't support ssh_port option! */
5660   helper->proc = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh", arg,
5661                                   "peerStartHelper.pl", tempdir,  NULL);
5662   GNUNET_assert(helper->proc != NULL);
5663   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "starting peers with cmd ssh %s %s %s\n", arg, "peerStartHelper.pl", tempdir);
5664   GNUNET_SCHEDULER_add_now (&check_peers_started, helper);
5665   GNUNET_free (tempdir);
5666   GNUNET_free (baseservicehome);
5667   GNUNET_free (arg);
5668 }
5669 #endif
5670
5671 /**
5672  * Function which continues a peer group starting up
5673  * after successfully generating hostkeys for each peer.
5674  *
5675  * @param pg the peer group to continue starting
5676  *
5677  */
5678 void
5679 GNUNET_TESTING_daemons_continue_startup(struct GNUNET_TESTING_PeerGroup *pg)
5680 {
5681   unsigned int i;
5682
5683 #if USE_START_HELPER
5684   if ((pg->num_hosts > 0) && (pg->hostkey_data != NULL))
5685     {
5686       struct PeerStartHelperContext *helper;
5687       pg->starting = pg->num_hosts;
5688       for (i = 0; i < pg->num_hosts; i++)
5689         {
5690           helper = GNUNET_malloc(sizeof(struct PeerStartHelperContext));
5691           helper->pg = pg;
5692           helper->host = &pg->hosts[i];
5693           GNUNET_SCHEDULER_add_now(&start_peer_helper, helper);
5694         }
5695     }
5696   else
5697     {
5698       pg->starting = 0;
5699       for (i = 0; i < pg->total; i++)
5700         {
5701           GNUNET_SCHEDULER_add_now (&internal_continue_startup,
5702                                     &pg->peers[i].internal_context);
5703         }
5704     }
5705 #else
5706   pg->starting = 0;
5707   for (i = 0; i < pg->total; i++)
5708     {
5709       GNUNET_SCHEDULER_add_now (&internal_continue_startup,
5710                                 &pg->peers[i].internal_context);
5711     }
5712 #endif
5713 }
5714
5715 #if USE_START_HELPER
5716 static void
5717 call_hostkey_callbacks (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5718 {
5719   struct GNUNET_TESTING_PeerGroup *pg = cls;
5720   unsigned int i;
5721   for (i = 0; i < pg->total; i++)
5722     {
5723       if (pg->peers[i].internal_context.hostkey_callback != NULL)
5724         pg->peers[i].internal_context.hostkey_callback (pg->peers[i].internal_context.hostkey_cls,
5725                                                            &pg->peers[i].daemon->id,
5726                                                            pg->peers[i].daemon,
5727                                                            NULL);
5728     }
5729
5730   if (pg->peers[0].internal_context.hostkey_callback == NULL)
5731     GNUNET_TESTING_daemons_continue_startup (pg);
5732 }
5733 #endif
5734
5735 /**
5736  * Start count gnunet instances with the same set of transports and
5737  * applications.  The port numbers (any option called "PORT") will be
5738  * adjusted to ensure that no two peers running on the same system
5739  * have the same port(s) in their respective configurations.
5740  *
5741  * @param cfg configuration template to use
5742  * @param total number of daemons to start
5743  * @param max_concurrent_connections for testing, how many peers can
5744  *                                   we connect to simultaneously
5745  * @param max_concurrent_ssh when starting with ssh, how many ssh
5746  *        connections will we allow at once (based on remote hosts allowed!)
5747  * @param timeout total time allowed for peers to start
5748  * @param hostkey_callback function to call on each peers hostkey generation
5749  *        if NULL, peers will be started by this call, if non-null,
5750  *        GNUNET_TESTING_daemons_continue_startup must be called after
5751  *        successful hostkey generation
5752  * @param hostkey_cls closure for hostkey callback
5753  * @param cb function to call on each daemon that was started
5754  * @param cb_cls closure for cb
5755  * @param connect_callback function to call each time two hosts are connected
5756  * @param connect_callback_cls closure for connect_callback
5757  * @param hostnames linked list of host structs to use to start peers on
5758  *                  (NULL to run on localhost only)
5759  *
5760  * @return NULL on error, otherwise handle to control peer group
5761  */
5762 struct GNUNET_TESTING_PeerGroup *
5763 GNUNET_TESTING_daemons_start(const struct GNUNET_CONFIGURATION_Handle *cfg,
5764                              unsigned int total,
5765                              unsigned int max_concurrent_connections,
5766                              unsigned int max_concurrent_ssh,
5767                              struct GNUNET_TIME_Relative timeout,
5768                              GNUNET_TESTING_NotifyHostkeyCreated hostkey_callback,
5769                              void *hostkey_cls,
5770                              GNUNET_TESTING_NotifyDaemonRunning cb,
5771                              void *cb_cls,
5772                              GNUNET_TESTING_NotifyConnection connect_callback,
5773                              void *connect_callback_cls,
5774                              const struct GNUNET_TESTING_Host *hostnames)
5775 {
5776   struct GNUNET_TESTING_PeerGroup *pg;
5777   const struct GNUNET_TESTING_Host *hostpos;
5778   const char *hostname;
5779   const char *username;
5780   char *baseservicehome;
5781   char *newservicehome;
5782   char *tmpdir;
5783   char *hostkeys_file;
5784   char *arg;
5785   char *ssh_port_str;
5786   struct GNUNET_DISK_FileHandle *fd;
5787   struct GNUNET_CONFIGURATION_Handle *pcfg;
5788   unsigned int off;
5789   struct OutstandingSSH *ssh_entry;
5790   unsigned int hostcnt;
5791   unsigned int i;
5792   uint16_t minport;
5793   uint16_t sshport;
5794   uint32_t upnum;
5795   uint32_t fdnum;
5796   uint64_t fs;
5797   uint64_t total_hostkeys;
5798   struct GNUNET_OS_Process *proc;
5799
5800   username = NULL;
5801   if (0 == total)
5802     {
5803       GNUNET_break (0);
5804       return NULL;
5805     }
5806
5807   upnum = 0;
5808   fdnum = 0;
5809   pg = GNUNET_malloc (sizeof (struct GNUNET_TESTING_PeerGroup));
5810   pg->cfg = cfg;
5811   pg->notify_connection = connect_callback;
5812   pg->notify_connection_cls = connect_callback_cls;
5813   pg->total = total;
5814   pg->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
5815   pg->peers = GNUNET_malloc (total * sizeof (struct PeerData));
5816   pg->max_outstanding_connections = max_concurrent_connections;
5817   pg->max_concurrent_ssh = max_concurrent_ssh;
5818   if (NULL != hostnames)
5819     {
5820       off = 0;
5821       hostpos = hostnames;
5822       while (hostpos != NULL)
5823         {
5824           hostpos = hostpos->next;
5825           off++;
5826         }
5827       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
5828       off = 0;
5829
5830       hostpos = hostnames;
5831       while (hostpos != NULL)
5832         {
5833           pg->hosts[off].minport = LOW_PORT;
5834           pg->hosts[off].hostname = GNUNET_strdup (hostpos->hostname);
5835           if (hostpos->username != NULL)
5836             pg->hosts[off].username = GNUNET_strdup (hostpos->username);
5837           pg->hosts[off].sshport = hostpos->port;
5838           hostpos = hostpos->next;
5839           off++;
5840         }
5841
5842       if (off == 0)
5843         {
5844           pg->hosts = NULL;
5845         }
5846       hostcnt = off;
5847       minport = 0;
5848       pg->num_hosts = off;
5849     }
5850   else
5851     {
5852       hostcnt = 0;
5853       minport = LOW_PORT;
5854     }
5855
5856   /* Create the servicehome directory for each remote peer */
5857   GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS", "SERVICEHOME",
5858                                                                     &baseservicehome));
5859   for (i = 0; i < pg->num_hosts; i++)
5860     {
5861       ssh_entry = GNUNET_malloc(sizeof(struct OutstandingSSH));
5862       ssh_entry->hostname = pg->hosts[i].hostname; /* Don't free! */
5863       GNUNET_CONTAINER_DLL_insert(pg->ssh_head, pg->ssh_tail, ssh_entry);
5864       GNUNET_asprintf(&tmpdir, "%s/%s", baseservicehome, pg->hosts[i].hostname);
5865       if (NULL != pg->hosts[i].username)
5866         GNUNET_asprintf (&arg, "%s@%s", pg->hosts[i].username,
5867                          pg->hosts[i].hostname);
5868       else
5869         GNUNET_asprintf (&arg, "%s", pg->hosts[i].hostname);
5870       if (pg->hosts[i].sshport != 0)
5871         {
5872           GNUNET_asprintf (&ssh_port_str, "%d", pg->hosts[i].sshport);
5873           proc = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh", "-P",
5874                                           ssh_port_str,
5875 #if !DEBUG_TESTING
5876                                           "-q",
5877 #endif
5878                                           arg, "mkdir -p", tmpdir,
5879                                           NULL);
5880         }
5881       else
5882         proc = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh", arg,
5883                                         "mkdir -p", tmpdir, NULL);
5884       GNUNET_assert(proc != NULL);
5885       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5886                   "Creating remote dir with command ssh %s %s %s\n", arg,
5887                   " mkdir -p ", tmpdir);
5888       GNUNET_free(tmpdir);
5889       GNUNET_free(arg);
5890       GNUNET_OS_process_wait (proc);
5891       GNUNET_OS_process_close(proc);
5892     }
5893   GNUNET_free(baseservicehome);
5894
5895   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (cfg, "TESTING",
5896                                                            "HOSTKEYSFILE",
5897                                                            &hostkeys_file))
5898     {
5899       if (GNUNET_YES != GNUNET_DISK_file_test (hostkeys_file))
5900         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Couldn't read hostkeys file!\n");
5901       else
5902         {
5903           /* Check hostkey file size, read entire thing into memory */
5904           fd = GNUNET_DISK_file_open (hostkeys_file, GNUNET_DISK_OPEN_READ,
5905                                       GNUNET_DISK_PERM_NONE);
5906           if (NULL == fd)
5907             {
5908               GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", hostkeys_file);
5909               return NULL;
5910             }
5911
5912           if (GNUNET_YES != GNUNET_DISK_file_size (hostkeys_file, &fs,
5913                                                    GNUNET_YES))
5914             fs = 0;
5915
5916           GNUNET_log (
5917                       GNUNET_ERROR_TYPE_DEBUG,
5918                       "Found file size %llu for hostkeys, expect hostkeys to be size %d\n",
5919                       fs, HOSTKEYFILESIZE);
5920
5921           if (fs % HOSTKEYFILESIZE != 0)
5922             {
5923               GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5924                           "File size %llu seems incorrect for hostkeys...\n",
5925                           fs);
5926             }
5927           else
5928             {
5929               total_hostkeys = fs / HOSTKEYFILESIZE;
5930               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5931                           "Will read %llu hostkeys from file\n", total_hostkeys);
5932               pg->hostkey_data = GNUNET_malloc_large (fs);
5933               GNUNET_assert (fs == GNUNET_DISK_file_read (fd, pg->hostkey_data, fs));
5934               GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fd));
5935             }
5936         }
5937       GNUNET_free(hostkeys_file);
5938     }
5939
5940   for (off = 0; off < total; off++)
5941     {
5942       if (hostcnt > 0)
5943         {
5944           hostname = pg->hosts[off % hostcnt].hostname;
5945           username = pg->hosts[off % hostcnt].username;
5946           sshport = pg->hosts[off % hostcnt].sshport;
5947           pcfg = make_config (cfg, off, &pg->hosts[off % hostcnt].minport,
5948                               &upnum, hostname, &fdnum);
5949         }
5950       else
5951         {
5952           hostname = NULL;
5953           username = NULL;
5954           sshport = 0;
5955           pcfg = make_config (cfg, off, &minport, &upnum, hostname, &fdnum);
5956         }
5957
5958       if (NULL == pcfg)
5959         {
5960           GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _
5961           ("Could not create configuration for peer number %u on `%s'!\n"),
5962                       off, hostname == NULL ? "localhost" : hostname);
5963           continue;
5964         }
5965
5966       if (GNUNET_YES
5967           == GNUNET_CONFIGURATION_get_value_string (pcfg, "PATHS",
5968                                                     "SERVICEHOME",
5969                                                     &baseservicehome))
5970         {
5971           if (hostname != NULL)
5972             GNUNET_asprintf (&newservicehome, "%s/%s/%d/", baseservicehome, hostname, off);
5973           else
5974             GNUNET_asprintf (&newservicehome, "%s/%d/", baseservicehome, off);
5975 #if !USE_START_HELPER
5976           GNUNET_free (baseservicehome);
5977 #endif
5978         }
5979       else
5980         {
5981           tmpdir = getenv ("TMPDIR");
5982           tmpdir = tmpdir ? tmpdir : "/tmp";
5983           if (hostname != NULL)
5984             GNUNET_asprintf (&newservicehome, "%s/%s/%s/%d/", tmpdir, hostname,
5985                              "gnunet-testing-test-test", off);
5986           else
5987             GNUNET_asprintf (&newservicehome, "%s/%s/%d/", tmpdir,
5988                              "gnunet-testing-test-test", off);
5989         }
5990       GNUNET_CONFIGURATION_set_value_string (pcfg, "PATHS", "SERVICEHOME",
5991                                              newservicehome);
5992       GNUNET_free (newservicehome);
5993       pg->peers[off].cfg = pcfg;
5994       pg->peers[off].pg = pg;
5995       pg->peers[off].internal_context.peer = &pg->peers[off];
5996       pg->peers[off].internal_context.timeout = timeout;
5997       pg->peers[off].internal_context.hostname = hostname;
5998       pg->peers[off].internal_context.username = username;
5999       pg->peers[off].internal_context.sshport = sshport;
6000       if (pg->hostkey_data != NULL)
6001         pg->peers[off].internal_context.hostkey = &pg->hostkey_data[off
6002             * HOSTKEYFILESIZE];
6003       pg->peers[off].internal_context.hostkey_callback = hostkey_callback;
6004       pg->peers[off].internal_context.hostkey_cls = hostkey_cls;
6005       pg->peers[off].internal_context.start_cb = cb;
6006       pg->peers[off].internal_context.start_cb_cls = cb_cls;
6007 #if !USE_START_HELPER
6008       GNUNET_SCHEDULER_add_now (&internal_start,
6009                                 &pg->peers[off].internal_context);
6010 #else
6011       if ((pg->hostkey_data != NULL) && (hostcnt > 0))
6012         {
6013           pg->peers[off].daemon = GNUNET_TESTING_daemon_start (pcfg,
6014                                        timeout,
6015                                        GNUNET_YES,
6016                                        hostname,
6017                                        username,
6018                                        sshport,
6019                                        pg->peers[off].internal_context.hostkey,
6020                                        &internal_hostkey_callback,
6021                                        &pg->peers[off].internal_context,
6022                                        &internal_startup_callback,
6023                                        &pg->peers[off].internal_context);
6024           /**
6025            * At this point, given that we had a hostkeyfile,
6026            * we can call the hostkey callback!
6027            * But first, we should copy (rsync) all of the configs
6028            * and hostkeys to the remote peers.  Then let topology
6029            * creation happen, then call the peer start helper processes,
6030            * then set pg->whatever_phase for each peer and let them
6031            * enter the fsm to get the HELLO's for peers and start connecting.
6032            */
6033         }
6034       else
6035         {
6036           GNUNET_SCHEDULER_add_now (&internal_start,
6037                                     &pg->peers[off].internal_context);
6038         }
6039
6040 #endif
6041     }
6042
6043 #if USE_START_HELPER /* Now the peergroup has been set up, hostkeys and configs written to files. */
6044   if ((pg->hostkey_data != NULL) && (hostcnt > 0))
6045     {
6046       for (off = 0; off < hostcnt; off++)
6047         {
6048           GNUNET_asprintf(&newservicehome, "%s/%s/", baseservicehome, pg->hosts[off].hostname);
6049
6050           if (NULL != username)
6051             GNUNET_asprintf (&arg, "%s@%s:%s/%s", username, pg->hosts[off].hostname, baseservicehome, pg->hosts[off].hostname);
6052           else
6053             GNUNET_asprintf (&arg, "%s:%s/%s", pg->hosts[off].hostname, baseservicehome, pg->hosts[off].hostname);
6054
6055           /* FIXME: Doesn't support ssh_port option! */
6056           proc = GNUNET_OS_start_process (NULL, NULL, "rsync", "rsync", "-r", newservicehome, arg, NULL);
6057
6058           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "copying directory with command rsync -r %s %s\n", newservicehome, arg);
6059
6060           GNUNET_free (arg);
6061           if (NULL == proc)
6062             {
6063               GNUNET_log (
6064                           GNUNET_ERROR_TYPE_ERROR,
6065                           _
6066                           ("Could not start `%s' process to copy configuration directory.\n"),
6067                           "scp");
6068               GNUNET_assert(0);
6069             }
6070           GNUNET_OS_process_wait (proc);
6071           GNUNET_OS_process_close (proc);
6072         }
6073       /* Now all the configuration files and hostkeys are copied to the remote host.  Call the hostkey callback for each peer! */
6074       GNUNET_SCHEDULER_add_now(&call_hostkey_callbacks, pg);
6075     }
6076   GNUNET_free (baseservicehome);
6077 #endif
6078   return pg;
6079 }
6080
6081 /*
6082  * Get a daemon by number, so callers don't have to do nasty
6083  * offsetting operation.
6084  */
6085 struct GNUNET_TESTING_Daemon *
6086 GNUNET_TESTING_daemon_get(struct GNUNET_TESTING_PeerGroup *pg,
6087                           unsigned int position)
6088 {
6089   if (position < pg->total)
6090     return pg->peers[position].daemon;
6091   else
6092     return NULL;
6093 }
6094
6095 /*
6096  * Get a daemon by peer identity, so callers can
6097  * retrieve the daemon without knowing it's offset.
6098  *
6099  * @param pg the peer group to retrieve the daemon from
6100  * @param peer_id the peer identity of the daemon to retrieve
6101  *
6102  * @return the daemon on success, or NULL if no such peer identity is found
6103  */
6104 struct GNUNET_TESTING_Daemon *
6105 GNUNET_TESTING_daemon_get_by_id(struct GNUNET_TESTING_PeerGroup *pg,
6106                                 struct GNUNET_PeerIdentity *peer_id)
6107 {
6108   unsigned int i;
6109
6110   for (i = 0; i < pg->total; i++)
6111     {
6112       if (0 == memcmp (&pg->peers[i].daemon->id, peer_id,
6113                        sizeof(struct GNUNET_PeerIdentity)))
6114         return pg->peers[i].daemon;
6115     }
6116
6117   return NULL;
6118 }
6119
6120 /**
6121  * Prototype of a function that will be called when a
6122  * particular operation was completed the testing library.
6123  *
6124  * @param cls closure (a struct RestartContext)
6125  * @param id id of the peer that was restarted
6126  * @param cfg handle to the configuration of the peer
6127  * @param d handle to the daemon that was restarted
6128  * @param emsg NULL on success
6129  */
6130 void
6131 restart_callback(void *cls, const struct GNUNET_PeerIdentity *id,
6132                  const struct GNUNET_CONFIGURATION_Handle *cfg,
6133                  struct GNUNET_TESTING_Daemon *d, const char *emsg)
6134 {
6135   struct RestartContext *restart_context = cls;
6136
6137   if (emsg == NULL)
6138     {
6139       restart_context->peers_restarted++;
6140     }
6141   else
6142     {
6143       restart_context->peers_restart_failed++;
6144     }
6145
6146   if (restart_context->peers_restarted == restart_context->peer_group->total)
6147     {
6148       restart_context->callback (restart_context->callback_cls, NULL);
6149       GNUNET_free (restart_context);
6150     }
6151   else if (restart_context->peers_restart_failed
6152       + restart_context->peers_restarted == restart_context->peer_group->total)
6153     {
6154       restart_context->callback (restart_context->callback_cls,
6155                                  "Failed to restart peers!");
6156       GNUNET_free (restart_context);
6157     }
6158
6159 }
6160
6161 /**
6162  * Callback for informing us about a successful
6163  * or unsuccessful churn stop call.
6164  *
6165  * @param cls a ChurnContext
6166  * @param emsg NULL on success, non-NULL on failure
6167  *
6168  */
6169 void
6170 churn_stop_callback(void *cls, const char *emsg)
6171 {
6172   struct ShutdownContext *shutdown_ctx = cls;
6173   struct ChurnContext *churn_ctx = shutdown_ctx->cb_cls;
6174   unsigned int total_left;
6175   char *error_message;
6176
6177   error_message = NULL;
6178   shutdown_ctx->outstanding--;
6179
6180   if (emsg != NULL)
6181     {
6182       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6183                   "Churn stop callback failed with error `%s'\n", emsg);
6184       churn_ctx->num_failed_stop++;
6185     }
6186   else
6187     {
6188       churn_ctx->num_to_stop--;
6189     }
6190
6191 #if DEBUG_CHURN
6192   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6193       "Stopped peer, %d left.\n", churn_ctx->num_to_stop);
6194 #endif
6195   total_left = (churn_ctx->num_to_stop - churn_ctx->num_failed_stop)
6196       + (churn_ctx->num_to_start - churn_ctx->num_failed_start);
6197
6198   if (total_left == 0)
6199     {
6200       if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
6201         {
6202           GNUNET_asprintf (
6203                            &error_message,
6204                            "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!",
6205                            churn_ctx->num_failed_start,
6206                            churn_ctx->num_failed_stop);
6207         }
6208       churn_ctx->cb (churn_ctx->cb_cls, error_message);
6209       GNUNET_free_non_null (error_message);
6210       GNUNET_free (churn_ctx);
6211       GNUNET_free (shutdown_ctx);
6212     }
6213 }
6214
6215 /**
6216  * Count the number of running peers.
6217  *
6218  * @param pg handle for the peer group
6219  *
6220  * @return the number of currently running peers in the peer group
6221  */
6222 unsigned int
6223 GNUNET_TESTING_daemons_running(struct GNUNET_TESTING_PeerGroup *pg)
6224 {
6225   unsigned int i;
6226   unsigned int running = 0;
6227   for (i = 0; i < pg->total; i++)
6228     {
6229       if (pg->peers[i].daemon->running == GNUNET_YES)
6230         {
6231           GNUNET_assert (running != -1);
6232           running++;
6233         }
6234     }
6235   return running;
6236 }
6237
6238 /**
6239  * Task to rate limit the number of outstanding peer shutdown
6240  * requests.  This is necessary for making sure we don't do
6241  * too many ssh connections at once, but is generally nicer
6242  * to any system as well (graduated task starts, as opposed
6243  * to calling gnunet-arm N times all at once).
6244  */
6245 static void
6246 schedule_churn_shutdown_task(void *cls,
6247                              const struct GNUNET_SCHEDULER_TaskContext *tc)
6248 {
6249   struct PeerShutdownContext *peer_shutdown_ctx = cls;
6250   struct ShutdownContext *shutdown_ctx;
6251   struct ChurnContext *churn_ctx;
6252   GNUNET_assert (peer_shutdown_ctx != NULL);
6253   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
6254   GNUNET_assert (shutdown_ctx != NULL);
6255   churn_ctx = (struct ChurnContext *) shutdown_ctx->cb_cls;
6256   if (shutdown_ctx->outstanding > churn_ctx->pg->max_concurrent_ssh)
6257     GNUNET_SCHEDULER_add_delayed (
6258                                   GNUNET_TIME_relative_multiply (
6259                                                                  GNUNET_TIME_UNIT_MILLISECONDS,
6260                                                                  100),
6261                                   &schedule_churn_shutdown_task,
6262                                   peer_shutdown_ctx);
6263   else
6264     {
6265       shutdown_ctx->outstanding++;
6266       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon,
6267                                   shutdown_ctx->timeout, shutdown_ctx->cb,
6268                                   shutdown_ctx, GNUNET_NO, GNUNET_YES);
6269       GNUNET_free (peer_shutdown_ctx);
6270     }
6271 }
6272
6273 /**
6274  * Simulate churn by stopping some peers (and possibly
6275  * re-starting others if churn is called multiple times).  This
6276  * function can only be used to create leave-join churn (peers "never"
6277  * leave for good).  First "voff" random peers that are currently
6278  * online will be taken offline; then "von" random peers that are then
6279  * offline will be put back online.  No notifications will be
6280  * generated for any of these operations except for the callback upon
6281  * completion.
6282  *
6283  * @param pg handle for the peer group
6284  * @param voff number of peers that should go offline
6285  * @param von number of peers that should come back online;
6286  *            must be zero on first call (since "testbed_start"
6287  *            always starts all of the peers)
6288  * @param timeout how long to wait for operations to finish before
6289  *        giving up
6290  * @param cb function to call at the end
6291  * @param cb_cls closure for cb
6292  */
6293 void
6294 GNUNET_TESTING_daemons_churn(struct GNUNET_TESTING_PeerGroup *pg,
6295                              unsigned int voff, unsigned int von,
6296                              struct GNUNET_TIME_Relative timeout,
6297                              GNUNET_TESTING_NotifyCompletion cb, void *cb_cls)
6298 {
6299   struct ChurnContext *churn_ctx;
6300   struct ShutdownContext *shutdown_ctx;
6301   struct PeerShutdownContext *peer_shutdown_ctx;
6302   struct PeerRestartContext *peer_restart_ctx;
6303   struct ChurnRestartContext *churn_startup_ctx;
6304
6305   unsigned int running;
6306   unsigned int stopped;
6307   unsigned int total_running;
6308   unsigned int total_stopped;
6309   unsigned int i;
6310   unsigned int *running_arr;
6311   unsigned int *stopped_arr;
6312   unsigned int *running_permute;
6313   unsigned int *stopped_permute;
6314
6315   shutdown_ctx = NULL;
6316   peer_shutdown_ctx = NULL;
6317   peer_restart_ctx = NULL;
6318   churn_startup_ctx = NULL;
6319
6320   running = 0;
6321   stopped = 0;
6322
6323   if ((von == 0) && (voff == 0)) /* No peers at all? */
6324     {
6325       cb (cb_cls, NULL);
6326       return;
6327     }
6328
6329   for (i = 0; i < pg->total; i++)
6330     {
6331       if (pg->peers[i].daemon->running == GNUNET_YES)
6332         {
6333           GNUNET_assert (running != -1);
6334           running++;
6335         }
6336       else
6337         {
6338           GNUNET_assert (stopped != -1);
6339           stopped++;
6340         }
6341     }
6342
6343   if (voff > running)
6344     {
6345       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6346                   "Trying to stop more peers than are currently running!\n");
6347       cb (cb_cls, "Trying to stop more peers than are currently running!");
6348       return;
6349     }
6350
6351   if (von > stopped)
6352     {
6353       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6354                   "Trying to start more peers than are currently stopped!\n");
6355       cb (cb_cls, "Trying to start more peers than are currently stopped!");
6356       return;
6357     }
6358
6359   churn_ctx = GNUNET_malloc (sizeof (struct ChurnContext));
6360
6361   running_arr = NULL;
6362   if (running > 0)
6363     running_arr = GNUNET_malloc (running * sizeof (unsigned int));
6364
6365   stopped_arr = NULL;
6366   if (stopped > 0)
6367     stopped_arr = GNUNET_malloc (stopped * sizeof (unsigned int));
6368
6369   running_permute = NULL;
6370   stopped_permute = NULL;
6371
6372   if (running > 0)
6373     running_permute = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
6374                                                     running);
6375   if (stopped > 0)
6376     stopped_permute = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
6377                                                     stopped);
6378
6379   total_running = running;
6380   total_stopped = stopped;
6381   running = 0;
6382   stopped = 0;
6383
6384   churn_ctx->num_to_start = von;
6385   churn_ctx->num_to_stop = voff;
6386   churn_ctx->cb = cb;
6387   churn_ctx->cb_cls = cb_cls;
6388   churn_ctx->pg = pg;
6389
6390   for (i = 0; i < pg->total; i++)
6391     {
6392       if (pg->peers[i].daemon->running == GNUNET_YES)
6393         {
6394           GNUNET_assert ((running_arr != NULL) && (total_running > running));
6395           running_arr[running] = i;
6396           running++;
6397         }
6398       else
6399         {
6400           GNUNET_assert ((stopped_arr != NULL) && (total_stopped > stopped));
6401           stopped_arr[stopped] = i;
6402           stopped++;
6403         }
6404     }
6405
6406   GNUNET_assert (running >= voff);
6407   if (voff > 0)
6408     {
6409       shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
6410       shutdown_ctx->cb = &churn_stop_callback;
6411       shutdown_ctx->cb_cls = churn_ctx;
6412       shutdown_ctx->total_peers = voff;
6413       shutdown_ctx->timeout = timeout;
6414     }
6415
6416   for (i = 0; i < voff; i++)
6417     {
6418 #if DEBUG_CHURN
6419       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Stopping peer %d!\n",
6420           running_permute[i]);
6421 #endif
6422       GNUNET_assert (running_arr != NULL);
6423       peer_shutdown_ctx = GNUNET_malloc (sizeof (struct PeerShutdownContext));
6424       peer_shutdown_ctx->daemon
6425           = pg->peers[running_arr[running_permute[i]]].daemon;
6426       peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
6427       GNUNET_SCHEDULER_add_now (&schedule_churn_shutdown_task,
6428                                 peer_shutdown_ctx);
6429
6430       /*
6431        GNUNET_TESTING_daemon_stop (pg->peers[running_arr[running_permute[i]]].daemon,
6432        timeout,
6433        &churn_stop_callback, churn_ctx,
6434        GNUNET_NO, GNUNET_YES); */
6435     }
6436
6437   GNUNET_assert (stopped >= von);
6438   if (von > 0)
6439     {
6440       churn_startup_ctx = GNUNET_malloc (sizeof (struct ChurnRestartContext));
6441       churn_startup_ctx->churn_ctx = churn_ctx;
6442       churn_startup_ctx->timeout = timeout;
6443       churn_startup_ctx->pg = pg;
6444     }
6445   for (i = 0; i < von; i++)
6446     {
6447 #if DEBUG_CHURN
6448       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Starting up peer %d!\n",
6449           stopped_permute[i]);
6450 #endif
6451       GNUNET_assert (stopped_arr != NULL);
6452       peer_restart_ctx = GNUNET_malloc (sizeof (struct PeerRestartContext));
6453       peer_restart_ctx->churn_restart_ctx = churn_startup_ctx;
6454       peer_restart_ctx->daemon
6455           = pg->peers[stopped_arr[stopped_permute[i]]].daemon;
6456       GNUNET_SCHEDULER_add_now (&schedule_churn_restart, peer_restart_ctx);
6457       /*
6458        GNUNET_TESTING_daemon_start_stopped(pg->peers[stopped_arr[stopped_permute[i]]].daemon,
6459        timeout, &churn_start_callback, churn_ctx); */
6460     }
6461
6462   GNUNET_free_non_null (running_arr);
6463   GNUNET_free_non_null (stopped_arr);
6464   GNUNET_free_non_null (running_permute);
6465   GNUNET_free_non_null (stopped_permute);
6466 }
6467
6468 /**
6469  * Restart all peers in the given group.
6470  *
6471  * @param pg the handle to the peer group
6472  * @param callback function to call on completion (or failure)
6473  * @param callback_cls closure for the callback function
6474  */
6475 void
6476 GNUNET_TESTING_daemons_restart(struct GNUNET_TESTING_PeerGroup *pg,
6477                                GNUNET_TESTING_NotifyCompletion callback,
6478                                void *callback_cls)
6479 {
6480   struct RestartContext *restart_context;
6481   unsigned int off;
6482
6483   if (pg->total > 0)
6484     {
6485       restart_context = GNUNET_malloc (sizeof (struct RestartContext));
6486       restart_context->peer_group = pg;
6487       restart_context->peers_restarted = 0;
6488       restart_context->callback = callback;
6489       restart_context->callback_cls = callback_cls;
6490
6491       for (off = 0; off < pg->total; off++)
6492         {
6493           GNUNET_TESTING_daemon_restart (pg->peers[off].daemon,
6494                                          &restart_callback, restart_context);
6495         }
6496     }
6497 }
6498
6499 /**
6500  * Start or stop an individual peer from the given group.
6501  *
6502  * @param pg handle to the peer group
6503  * @param offset which peer to start or stop
6504  * @param desired_status GNUNET_YES to have it running, GNUNET_NO to stop it
6505  * @param timeout how long to wait for shutdown
6506  * @param cb function to call at the end
6507  * @param cb_cls closure for cb
6508  */
6509 void
6510 GNUNET_TESTING_daemons_vary(struct GNUNET_TESTING_PeerGroup *pg,
6511                             unsigned int offset, int desired_status,
6512                             struct GNUNET_TIME_Relative timeout,
6513                             GNUNET_TESTING_NotifyCompletion cb, void *cb_cls)
6514 {
6515   struct ShutdownContext *shutdown_ctx;
6516   struct ChurnRestartContext *startup_ctx;
6517   struct ChurnContext *churn_ctx;
6518
6519   if (GNUNET_NO == desired_status)
6520     {
6521       if (NULL != pg->peers[offset].daemon)
6522         {
6523           shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
6524           churn_ctx = GNUNET_malloc (sizeof (struct ChurnContext));
6525           churn_ctx->num_to_start = 0;
6526           churn_ctx->num_to_stop = 1;
6527           churn_ctx->cb = cb;
6528           churn_ctx->cb_cls = cb_cls;
6529           shutdown_ctx->cb_cls = churn_ctx;
6530           GNUNET_TESTING_daemon_stop (pg->peers[offset].daemon, timeout,
6531                                       &churn_stop_callback, shutdown_ctx,
6532                                       GNUNET_NO, GNUNET_YES);
6533         }
6534     }
6535   else if (GNUNET_YES == desired_status)
6536     {
6537       if (NULL == pg->peers[offset].daemon)
6538         {
6539           startup_ctx = GNUNET_malloc (sizeof (struct ChurnRestartContext));
6540           churn_ctx = GNUNET_malloc (sizeof (struct ChurnContext));
6541           churn_ctx->num_to_start = 1;
6542           churn_ctx->num_to_stop = 0;
6543           churn_ctx->cb = cb;
6544           churn_ctx->cb_cls = cb_cls;
6545           startup_ctx->churn_ctx = churn_ctx;
6546           GNUNET_TESTING_daemon_start_stopped (pg->peers[offset].daemon,
6547                                                timeout, &churn_start_callback,
6548                                                startup_ctx);
6549         }
6550     }
6551   else
6552     GNUNET_break (0);
6553 }
6554
6555 /**
6556  * Callback for shutting down peers in a peer group.
6557  *
6558  * @param cls closure (struct ShutdownContext)
6559  * @param emsg NULL on success
6560  */
6561 void
6562 internal_shutdown_callback(void *cls, const char *emsg)
6563 {
6564   struct PeerShutdownContext *peer_shutdown_ctx = cls;
6565   struct ShutdownContext *shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
6566   unsigned int off;
6567   struct OutstandingSSH *ssh_pos;
6568
6569   shutdown_ctx->outstanding--;
6570   if (peer_shutdown_ctx->daemon->hostname != NULL)
6571     decrement_outstanding_at_host (peer_shutdown_ctx->daemon->hostname,
6572                                    shutdown_ctx->pg);
6573
6574   if (emsg == NULL)
6575     {
6576       shutdown_ctx->peers_down++;
6577     }
6578   else
6579     {
6580       shutdown_ctx->peers_failed++;
6581     }
6582
6583   if ((shutdown_ctx->cb != NULL) && (shutdown_ctx->peers_down
6584       + shutdown_ctx->peers_failed == shutdown_ctx->total_peers))
6585     {
6586       if (shutdown_ctx->peers_failed > 0)
6587         shutdown_ctx->cb (shutdown_ctx->cb_cls,
6588                           "Not all peers successfully shut down!");
6589       else
6590         shutdown_ctx->cb (shutdown_ctx->cb_cls, NULL);
6591
6592       GNUNET_free (shutdown_ctx->pg->peers);
6593       GNUNET_free_non_null(shutdown_ctx->pg->hostkey_data);
6594       for (off = 0; off < shutdown_ctx->pg->num_hosts; off++)
6595         {
6596           GNUNET_free (shutdown_ctx->pg->hosts[off].hostname);
6597           GNUNET_free_non_null (shutdown_ctx->pg->hosts[off].username);
6598         }
6599       GNUNET_free_non_null (shutdown_ctx->pg->hosts);
6600       while (NULL != (ssh_pos = shutdown_ctx->pg->ssh_head))
6601         {
6602           GNUNET_CONTAINER_DLL_remove(shutdown_ctx->pg->ssh_head, shutdown_ctx->pg->ssh_tail, ssh_pos);
6603           GNUNET_free(ssh_pos);
6604         }
6605       GNUNET_free (shutdown_ctx->pg);
6606       GNUNET_free (shutdown_ctx);
6607     }
6608   GNUNET_free(peer_shutdown_ctx);
6609 }
6610
6611 /**
6612  * Task to rate limit the number of outstanding peer shutdown
6613  * requests.  This is necessary for making sure we don't do
6614  * too many ssh connections at once, but is generally nicer
6615  * to any system as well (graduated task starts, as opposed
6616  * to calling gnunet-arm N times all at once).
6617  */
6618 static void
6619 schedule_shutdown_task(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6620 {
6621   struct PeerShutdownContext *peer_shutdown_ctx = cls;
6622   struct ShutdownContext *shutdown_ctx;
6623
6624   GNUNET_assert (peer_shutdown_ctx != NULL);
6625   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
6626   GNUNET_assert (shutdown_ctx != NULL);
6627
6628   if ((shutdown_ctx->outstanding < shutdown_ctx->pg->max_concurrent_ssh)
6629       || ((peer_shutdown_ctx->daemon->hostname != NULL)
6630           && (count_outstanding_at_host (peer_shutdown_ctx->daemon->hostname,
6631                                          shutdown_ctx->pg)
6632               < shutdown_ctx->pg->max_concurrent_ssh)))
6633     {
6634       if (peer_shutdown_ctx->daemon->hostname != NULL)
6635         increment_outstanding_at_host (peer_shutdown_ctx->daemon->hostname,
6636                                        shutdown_ctx->pg);
6637       shutdown_ctx->outstanding++;
6638       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon,
6639                                   shutdown_ctx->timeout,
6640                                   &internal_shutdown_callback, peer_shutdown_ctx,
6641                                   GNUNET_YES, GNUNET_NO);
6642     }
6643   else
6644     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
6645                                                                  100),
6646                                   &schedule_shutdown_task, peer_shutdown_ctx);
6647
6648 }
6649
6650 /**
6651  * Shutdown all peers started in the given group.
6652  *
6653  * @param pg handle to the peer group
6654  * @param timeout how long to wait for shutdown
6655  * @param cb callback to notify upon success or failure
6656  * @param cb_cls closure for cb
6657  */
6658 void
6659 GNUNET_TESTING_daemons_stop(struct GNUNET_TESTING_PeerGroup *pg,
6660                             struct GNUNET_TIME_Relative timeout,
6661                             GNUNET_TESTING_NotifyCompletion cb, void *cb_cls)
6662 {
6663   unsigned int off;
6664   struct ShutdownContext *shutdown_ctx;
6665   struct PeerShutdownContext *peer_shutdown_ctx;
6666 #if OLD
6667   struct PeerConnection *conn_iter;
6668   struct PeerConnection *temp_conn;
6669 #endif
6670
6671   GNUNET_assert (pg->total > 0);
6672
6673   shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
6674   shutdown_ctx->cb = cb;
6675   shutdown_ctx->cb_cls = cb_cls;
6676   shutdown_ctx->total_peers = pg->total;
6677   shutdown_ctx->timeout = timeout;
6678   shutdown_ctx->pg = pg;
6679   /* shtudown_ctx->outstanding = 0; */
6680
6681   for (off = 0; off < pg->total; off++)
6682     {
6683       GNUNET_assert (NULL != pg->peers[off].daemon);
6684       peer_shutdown_ctx = GNUNET_malloc (sizeof (struct PeerShutdownContext));
6685       peer_shutdown_ctx->daemon = pg->peers[off].daemon;
6686       peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
6687       GNUNET_SCHEDULER_add_now (&schedule_shutdown_task, peer_shutdown_ctx);
6688
6689       if (NULL != pg->peers[off].cfg)
6690       {
6691         GNUNET_CONFIGURATION_destroy (pg->peers[off].cfg);
6692         pg->peers[off].cfg = NULL;
6693       }
6694 #if OLD
6695       conn_iter = pg->peers[off].allowed_peers_head;
6696       while (conn_iter != NULL)
6697         {
6698           temp_conn = conn_iter->next;
6699           GNUNET_free(conn_iter);
6700           conn_iter = temp_conn;
6701         }
6702
6703       conn_iter = pg->peers[off].connect_peers_head;
6704       while (conn_iter != NULL)
6705         {
6706           temp_conn = conn_iter->next;
6707           GNUNET_free(conn_iter);
6708           conn_iter = temp_conn;
6709         }
6710
6711       conn_iter = pg->peers[off].blacklisted_peers_head;
6712       while (conn_iter != NULL)
6713         {
6714           temp_conn = conn_iter->next;
6715           GNUNET_free(conn_iter);
6716           conn_iter = temp_conn;
6717         }
6718
6719       conn_iter = pg->peers[off].connect_peers_working_set_head;
6720       while (conn_iter != NULL)
6721         {
6722           temp_conn = conn_iter->next;
6723           GNUNET_free(conn_iter);
6724           conn_iter = temp_conn;
6725         }
6726 #else
6727       if (pg->peers[off].allowed_peers != NULL)
6728       GNUNET_CONTAINER_multihashmap_destroy (pg->peers[off].allowed_peers);
6729       if (pg->peers[off].connect_peers != NULL)
6730       GNUNET_CONTAINER_multihashmap_destroy (pg->peers[off].connect_peers);
6731       if (pg->peers[off].blacklisted_peers != NULL)
6732       GNUNET_CONTAINER_multihashmap_destroy (pg->
6733           peers[off].blacklisted_peers);
6734 #endif
6735     }
6736 }
6737
6738 /* end of testing_group.c */