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