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