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