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