-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 #include "platform.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_arm_service.h"
30 #include "gnunet_testing_lib.h"
31 #include "gnunet_core_service.h"
32
33 #define USE_START_HELPER GNUNET_YES
34
35 #define OLD 1
36
37 /* Before connecting peers, send all of the HELLOs */
38 #define USE_SEND_HELLOS GNUNET_NO
39
40 #define TOPOLOGY_HACK GNUNET_YES
41
42
43 /**
44  * Lowest port used for GNUnet testing.  Should be high enough to not
45  * conflict with other applications running on the hosts but be low
46  * enough to not conflict with client-ports (typically starting around
47  * 32k).
48  */
49 #define LOW_PORT 12000
50
51 /**
52  * Highest port used for GNUnet testing.  Should be low enough to not
53  * conflict with the port range for "local" ports (client apps; see
54  * /proc/sys/net/ipv4/ip_local_port_range on Linux for example).
55  */
56 #define HIGH_PORT 56000
57
58 /* Maximum time to delay connect attempt */
59 #define MAX_CONNECT_DELAY 300
60
61 /**
62  * Which list of peers do we need to modify?
63  */
64 enum PeerLists
65 {
66   /** Modify allowed peers */
67   ALLOWED,
68
69   /** Modify connect peers */
70   CONNECT,
71
72   /** Modify blacklist peers */
73   BLACKLIST,
74
75   /** Modify workingset peers */
76   WORKING_SET
77 };
78
79 /**
80  * Prototype of a function called whenever two peers would be connected
81  * in a certain topology.
82  */
83 typedef unsigned int (*GNUNET_TESTING_ConnectionProcessor) (struct
84                                                             GNUNET_TESTING_PeerGroup
85                                                             * pg,
86                                                             unsigned int first,
87                                                             unsigned int second,
88                                                             enum PeerLists list,
89                                                             unsigned int check);
90
91 /**
92  * Context for handling churning a peer group
93  */
94 struct ChurnContext
95 {
96   /**
97    * The peergroup we are dealing with.
98    */
99   struct GNUNET_TESTING_PeerGroup *pg;
100
101   /**
102    * Name of the service to churn on/off, NULL
103    * to churn entire peer.
104    */
105   char *service;
106
107   /**
108    * Callback used to notify of churning finished
109    */
110   GNUNET_TESTING_NotifyCompletion cb;
111
112   /**
113    * Closure for callback
114    */
115   void *cb_cls;
116
117   /**
118    * Number of peers that still need to be started
119    */
120   unsigned int num_to_start;
121
122   /**
123    * Number of peers that still need to be stopped
124    */
125   unsigned int num_to_stop;
126
127   /**
128    * Number of peers that failed to start
129    */
130   unsigned int num_failed_start;
131
132   /**
133    * Number of peers that failed to stop
134    */
135   unsigned int num_failed_stop;
136 };
137
138 struct RestartContext
139 {
140   /**
141    * The group of peers being restarted
142    */
143   struct GNUNET_TESTING_PeerGroup *peer_group;
144
145   /**
146    * How many peers have been restarted thus far
147    */
148   unsigned int peers_restarted;
149
150   /**
151    * How many peers got an error when restarting
152    */
153   unsigned int peers_restart_failed;
154
155   /**
156    * The function to call once all peers have been restarted
157    */
158   GNUNET_TESTING_NotifyCompletion callback;
159
160   /**
161    * Closure for callback function
162    */
163   void *callback_cls;
164
165 };
166
167 struct SendHelloContext
168 {
169   /**
170    * Global handle to the peer group.
171    */
172   struct GNUNET_TESTING_PeerGroup *pg;
173
174   /**
175    * The data about this specific peer.
176    */
177   struct PeerData *peer;
178
179   /**
180    * The next HELLO that needs sent to this peer.
181    */
182   struct PeerConnection *peer_pos;
183
184   /**
185    * Are we connected to CORE yet?
186    */
187   unsigned int core_ready;
188
189   /**
190    * How many attempts should we make for failed connections?
191    */
192   unsigned int connect_attempts;
193
194   /**
195    * Task for scheduling core connect requests to be sent.
196    */
197   GNUNET_SCHEDULER_TaskIdentifier core_connect_task;
198 };
199
200 struct ShutdownContext
201 {
202   struct GNUNET_TESTING_PeerGroup *pg;
203   /**
204    * Total peers to wait for
205    */
206   unsigned int total_peers;
207
208   /**
209    * Number of peers successfully shut down
210    */
211   unsigned int peers_down;
212
213   /**
214    * Number of peers failed to shut down
215    */
216   unsigned int peers_failed;
217
218   /**
219    * Number of peers we have started shutting
220    * down.  If too many, wait on them.
221    */
222   unsigned int outstanding;
223
224   /**
225    * Timeout for shutdown.
226    */
227   struct GNUNET_TIME_Relative timeout;
228
229   /**
230    * Callback to call when all peers either
231    * shutdown or failed to shutdown
232    */
233   GNUNET_TESTING_NotifyCompletion cb;
234
235   /**
236    * Closure for cb
237    */
238   void *cb_cls;
239
240   /**
241    * Should we delete all of the files from the peers?
242    */
243   int delete_files;
244 };
245
246 /**
247  * Individual shutdown context for a particular peer.
248  */
249 struct PeerShutdownContext
250 {
251   /**
252    * Pointer to the high level shutdown context.
253    */
254   struct ShutdownContext *shutdown_ctx;
255
256   /**
257    * The daemon handle for the peer to shut down.
258    */
259   struct GNUNET_TESTING_Daemon *daemon;
260 };
261
262 /**
263  * Individual shutdown context for a particular peer.
264  */
265 struct PeerRestartContext
266 {
267   /**
268    * Pointer to the high level restart context.
269    */
270   struct ChurnRestartContext *churn_restart_ctx;
271
272   /**
273    * The daemon handle for the peer to shut down.
274    */
275   struct GNUNET_TESTING_Daemon *daemon;
276 };
277
278 struct ServiceStartContext
279 {
280   struct GNUNET_TESTING_PeerGroup *pg;
281   unsigned int remaining;
282   GNUNET_TESTING_NotifyCompletion cb;
283   unsigned int outstanding;
284   char *service;
285   struct GNUNET_TIME_Relative timeout;
286   void *cb_cls;
287 };
288
289 /**
290  * Individual shutdown context for a particular peer.
291  */
292 struct PeerServiceStartContext
293 {
294   /**
295    * Pointer to the high level start context.
296    */
297   struct ServiceStartContext *start_ctx;
298
299   /**
300    * The daemon handle for the peer to start the service on.
301    */
302   struct GNUNET_TESTING_Daemon *daemon;
303 };
304
305 struct CreateTopologyContext
306 {
307
308   /**
309    * Function to call with number of connections
310    */
311   GNUNET_TESTING_NotifyConnections cont;
312
313   /**
314    * Closure for connection notification
315    */
316   void *cls;
317 };
318
319 enum States
320 {
321   /** Waiting to read number of peers */
322   NUM_PEERS,
323
324   /** Should find next peer index */
325   PEER_INDEX,
326
327   /** Should find colon */
328   COLON,
329
330   /** Should read other peer index, space, or endline */
331   OTHER_PEER_INDEX
332 };
333
334 #if OLD
335 struct PeerConnection
336 {
337   /**
338    * Doubly Linked list
339    */
340   struct PeerConnection *prev;
341
342   /*
343    * Doubly Linked list
344    */
345   struct PeerConnection *next;
346
347   /*
348    * Index of daemon in pg->peers
349    */
350   uint32_t index;
351
352 };
353 #endif
354
355 struct InternalStartContext
356 {
357   /**
358    * Pointer to peerdata
359    */
360   struct PeerData *peer;
361
362   /**
363    * Timeout for peer startup
364    */
365   struct GNUNET_TIME_Relative timeout;
366
367   /**
368    * Client callback for hostkey notification
369    */
370   GNUNET_TESTING_NotifyHostkeyCreated hostkey_callback;
371
372   /**
373    * Closure for hostkey_callback
374    */
375   void *hostkey_cls;
376
377   /**
378    * Client callback for peer start notification
379    */
380   GNUNET_TESTING_NotifyDaemonRunning start_cb;
381
382   /**
383    * Closure for cb
384    */
385   void *start_cb_cls;
386
387   /**
388    * Hostname, where to start the peer
389    */
390   const char *hostname;
391
392   /**
393    * Username to use when connecting to the
394    * host via ssh.
395    */
396   const char *username;
397
398   /**
399    * Pointer to starting memory location of a hostkey
400    */
401   const char *hostkey;
402
403   /**
404    * Port to use for ssh.
405    */
406   uint16_t sshport;
407
408 };
409
410 struct ChurnRestartContext
411 {
412   /**
413    * PeerGroup that we are working with.
414    */
415   struct GNUNET_TESTING_PeerGroup *pg;
416
417   /**
418    * Number of restarts currently in flight.
419    */
420   unsigned int outstanding;
421
422   /**
423    * Handle to the underlying churn context.
424    */
425   struct ChurnContext *churn_ctx;
426
427   /**
428    * How long to allow the operation to take.
429    */
430   struct GNUNET_TIME_Relative timeout;
431 };
432
433 struct OutstandingSSH
434 {
435   struct OutstandingSSH *next;
436
437   struct OutstandingSSH *prev;
438
439   /**
440    * Number of current ssh connections.
441    */
442   uint32_t outstanding;
443
444   /**
445    * The hostname of this peer.
446    */
447   const char *hostname;
448 };
449
450 /**
451  * Data we keep per peer.
452  */
453 struct PeerData
454 {
455   /**
456    * (Initial) configuration of the host.
457    * (initial because clients could change
458    *  it and we would not know about those
459    *  updates).
460    */
461   struct GNUNET_CONFIGURATION_Handle *cfg;
462
463   /**
464    * Handle for controlling the daemon.
465    */
466   struct GNUNET_TESTING_Daemon *daemon;
467
468   /**
469    * The peergroup this peer belongs to.
470    */
471   struct GNUNET_TESTING_PeerGroup *pg;
472
473 #if OLD
474   /**
475    * Linked list of allowed peer connections.
476    */
477   struct PeerConnection *allowed_peers_head;
478
479   /**
480    * Linked list of allowed peer connections.
481    */
482   struct PeerConnection *allowed_peers_tail;
483
484   /**
485    * Linked list of blacklisted peer connections.
486    */
487   struct PeerConnection *blacklisted_peers_head;
488
489   /**
490    * Linked list of blacklisted peer connections.
491    */
492   struct PeerConnection *blacklisted_peers_tail;
493
494   /**
495    * Linked list of connect peer connections.
496    */
497   struct PeerConnection *connect_peers_head;
498
499   /**
500    * Linked list of connect peer connections.
501    */
502   struct PeerConnection *connect_peers_tail;
503
504   /**
505    * Linked list of connect peer connections.
506    */
507   struct PeerConnection *connect_peers_working_set_head;
508
509   /**
510    * Linked list of connect peer connections.
511    */
512   struct PeerConnection *connect_peers_working_set_tail;
513
514 #else
515   /**
516    * Hash map of allowed peer connections (F2F created topology)
517    */
518   struct GNUNET_CONTAINER_MultiHashMap *allowed_peers;
519
520   /**
521    * Hash map of blacklisted peers
522    */
523   struct GNUNET_CONTAINER_MultiHashMap *blacklisted_peers;
524
525   /**
526    * Hash map of peer connections
527    */
528   struct GNUNET_CONTAINER_MultiHashMap *connect_peers;
529
530   /**
531    * Temporary hash map of peer connections
532    */
533   struct GNUNET_CONTAINER_MultiHashMap *connect_peers_working_set;
534 #endif
535
536   /**
537    * Temporary variable for topology creation, should be reset before
538    * creating any topology so the count is valid once finished.
539    */
540   int num_connections;
541
542   /**
543    * Context to keep track of peers being started, to
544    * stagger hostkey generation and peer startup.
545    */
546   struct InternalStartContext internal_context;
547
548   /**
549    * Task ID for the queued internal_continue_startup task
550    */
551   GNUNET_SCHEDULER_TaskIdentifier startup_task;
552
553 };
554
555 /**
556  * Linked list of per-host data.
557  */
558 struct HostData
559 {
560   /**
561    * Name of the host.
562    */
563   char *hostname;
564
565   /**
566    * SSH username to use when connecting to this host.
567    */
568   char *username;
569
570   /**
571    * SSH port to use when connecting to this host.
572    */
573   uint16_t sshport;
574
575   /**
576    * Lowest port that we have not yet used
577    * for GNUnet.
578    */
579   uint16_t minport;
580 };
581
582 struct TopologyIterateContext
583 {
584   /**
585    * The peergroup we are working with.
586    */
587   struct GNUNET_TESTING_PeerGroup *pg;
588
589   /**
590    * Callback for notifying of two connected peers.
591    */
592   GNUNET_TESTING_NotifyTopology topology_cb;
593
594   /**
595    * Closure for topology_cb
596    */
597   void *cls;
598
599   /**
600    * Number of peers currently connected to.
601    */
602   unsigned int connected;
603
604   /**
605    * Number of peers we have finished iterating.
606    */
607   unsigned int completed;
608
609   /**
610    * Number of peers total.
611    */
612   unsigned int total;
613 };
614
615 struct StatsIterateContext
616 {
617   /**
618    * The peergroup that we are dealing with.
619    */
620   struct GNUNET_TESTING_PeerGroup *pg;
621
622   /**
623    * Continuation to call once all stats information has been retrieved.
624    */
625   GNUNET_STATISTICS_Callback cont;
626
627   /**
628    * Proc function to call on each value received.
629    */
630   GNUNET_TESTING_STATISTICS_Iterator proc;
631
632   /**
633    * Closure for topology_cb
634    */
635   void *cls;
636
637   /**
638    * Number of peers currently connected to.
639    */
640   unsigned int connected;
641
642   /**
643    * Number of peers we have finished iterating.
644    */
645   unsigned int completed;
646
647   /**
648    * Number of peers total.
649    */
650   unsigned int total;
651 };
652
653 struct CoreContext
654 {
655   void *iter_context;
656   struct GNUNET_TESTING_Daemon *daemon;
657 };
658
659 struct StatsCoreContext
660 {
661   void *iter_context;
662   struct GNUNET_TESTING_Daemon *daemon;
663   /**
664    * Handle to the statistics service.
665    */
666   struct GNUNET_STATISTICS_Handle *stats_handle;
667
668   /**
669    * Handle for getting statistics.
670    */
671   struct GNUNET_STATISTICS_GetHandle *stats_get_handle;
672 };
673
674 struct ConnectTopologyContext
675 {
676   /**
677    * How many connections are left to create.
678    */
679   unsigned int remaining_connections;
680
681   /**
682    * Handle to group of peers.
683    */
684   struct GNUNET_TESTING_PeerGroup *pg;
685
686   /**
687    * How long to try this connection before timing out.
688    */
689   struct GNUNET_TIME_Relative connect_timeout;
690
691   /**
692    * How many times to retry connecting the two peers.
693    */
694   unsigned int connect_attempts;
695
696   /**
697    * Temp value set for each iteration.
698    */
699   //struct PeerData *first;
700
701   /**
702    * Notification that all peers are connected.
703    */
704   GNUNET_TESTING_NotifyCompletion notify_connections_done;
705
706   /**
707    * Closure for notify.
708    */
709   void *notify_cls;
710 };
711
712 struct ConnectContext;
713
714 /**
715  * Handle to a group of GNUnet peers.
716  */
717 struct GNUNET_TESTING_PeerGroup
718 {
719   /**
720    * Configuration template.
721    */
722   const struct GNUNET_CONFIGURATION_Handle *cfg;
723
724   struct ConnectContext *cc_head;
725
726   struct ConnectContext *cc_tail;
727
728   /**
729    * Function to call on each started daemon.
730    */
731   //GNUNET_TESTING_NotifyDaemonRunning cb;
732
733   /**
734    * Closure for cb.
735    */
736   //void *cb_cls;
737
738   /*
739    * Function to call on each topology connection created
740    */
741   GNUNET_TESTING_NotifyConnection notify_connection;
742
743   /*
744    * Callback for notify_connection
745    */
746   void *notify_connection_cls;
747
748   /**
749    * Array of information about hosts.
750    */
751   struct HostData *hosts;
752
753   /**
754    * Number of hosts (size of HostData)
755    */
756   unsigned int num_hosts;
757
758   /**
759    * Array of "total" peers.
760    */
761   struct PeerData *peers;
762
763   /**
764    * Number of peers in this group.
765    */
766   unsigned int total;
767
768   /**
769    * At what time should we fail the peer startup process?
770    */
771   struct GNUNET_TIME_Absolute max_timeout;
772
773   /**
774    * How many peers are being started right now?
775    */
776   unsigned int starting;
777
778   /**
779    * How many peers have already been started?
780    */
781   unsigned int started;
782
783   /**
784    * Number of possible connections to peers
785    * at a time.
786    */
787   unsigned int max_outstanding_connections;
788
789   /**
790    * Number of ssh connections to peers (max).
791    */
792   unsigned int max_concurrent_ssh;
793
794   /**
795    * Number of connects we are waiting on, allows us to rate limit
796    * connect attempts.
797    */
798   unsigned int outstanding_connects;
799
800   /**
801    * Number of HELLOs we have yet to send.
802    */
803   unsigned int remaining_hellos;
804
805   /**
806    * How many connects have already been scheduled?
807    */
808   unsigned int total_connects_scheduled;
809
810   /**
811    * Hostkeys loaded from a file.
812    */
813   char *hostkey_data;
814
815   /**
816    * Head of DLL to keep track of the number of outstanding
817    * ssh connections per peer.
818    */
819   struct OutstandingSSH *ssh_head;
820
821   /**
822    * Tail of DLL to keep track of the number of outstanding
823    * ssh connections per peer.
824    */
825   struct OutstandingSSH *ssh_tail;
826
827   /**
828    * Stop scheduling peers connecting.
829    */
830   unsigned int stop_connects;
831
832   /**
833    * Connection context for peer group.
834    */
835   struct ConnectTopologyContext ct_ctx;
836 };
837
838 struct UpdateContext
839 {
840   /**
841    * The altered configuration.
842    */
843   struct GNUNET_CONFIGURATION_Handle *ret;
844
845   /**
846    * The original configuration to alter.
847    */
848   const struct GNUNET_CONFIGURATION_Handle *orig;
849
850   /**
851    * The hostname that this peer will run on.
852    */
853   const char *hostname;
854
855   /**
856    * The next possible port to assign.
857    */
858   unsigned int nport;
859
860   /**
861    * Unique number for unix domain sockets.
862    */
863   unsigned int upnum;
864
865   /**
866    * Unique number for this peer/host to offset
867    * things that are grouped by host.
868    */
869   unsigned int fdnum;
870 };
871
872 struct ConnectContext
873 {
874
875   struct ConnectContext *next;
876
877   struct ConnectContext *prev;
878
879   /**
880    * Index of peer to connect second to.
881    */
882   uint32_t first_index;
883
884   /**
885    * Index of peer to connect first to.
886    */
887   uint32_t second_index;
888
889   /**
890    * Task associated with the attempt to connect.
891    */
892   GNUNET_SCHEDULER_TaskIdentifier task;
893
894   /**
895    * Context in 'testing.c', to cancel connection attempt.
896    */
897   struct GNUNET_TESTING_ConnectContext *cc;
898
899   /**
900    * Higher level topology connection context.
901    */
902   struct ConnectTopologyContext *ct_ctx;
903
904   /**
905    * Whether this connection has been accounted for in the schedule_connect call.
906    */
907   int counted;
908 };
909
910 struct UnblacklistContext
911 {
912   /**
913    * The peergroup
914    */
915   struct GNUNET_TESTING_PeerGroup *pg;
916
917   /**
918    * uid of the first peer
919    */
920   uint32_t first_uid;
921 };
922
923 struct RandomContext
924 {
925   /**
926    * The peergroup
927    */
928   struct GNUNET_TESTING_PeerGroup *pg;
929
930   /**
931    * uid of the first peer
932    */
933   uint32_t first_uid;
934
935   /**
936    * Peer data for first peer.
937    */
938   struct PeerData *first;
939
940   /**
941    * Random percentage to use
942    */
943   double percentage;
944 };
945
946 struct MinimumContext
947 {
948   /**
949    * The peergroup
950    */
951   struct GNUNET_TESTING_PeerGroup *pg;
952
953   /**
954    * uid of the first peer
955    */
956   uint32_t first_uid;
957
958   /**
959    * Peer data for first peer.
960    */
961   struct PeerData *first;
962
963   /**
964    * Number of conns per peer
965    */
966   unsigned int num_to_add;
967
968   /**
969    * Permuted array of all possible connections.  Only add the Nth
970    * peer if it's in the Nth position.
971    */
972   unsigned int *pg_array;
973
974   /**
975    * What number is the current element we are iterating over?
976    */
977   unsigned int current;
978 };
979
980 struct DFSContext
981 {
982   /**
983    * The peergroup
984    */
985   struct GNUNET_TESTING_PeerGroup *pg;
986
987   /**
988    * uid of the first peer
989    */
990   uint32_t first_uid;
991
992   /**
993    * uid of the second peer
994    */
995   uint32_t second_uid;
996
997   /**
998    * Peer data for first peer.
999    */
1000   struct PeerData *first;
1001
1002   /**
1003    * Which peer has been chosen as the one to add?
1004    */
1005   unsigned int chosen;
1006
1007   /**
1008    * What number is the current element we are iterating over?
1009    */
1010   unsigned int current;
1011 };
1012
1013 /**
1014  * Simple struct to keep track of progress, and print a
1015  * nice little percentage meter for long running tasks.
1016  */
1017 struct ProgressMeter
1018 {
1019   unsigned int total;
1020
1021   unsigned int modnum;
1022
1023   unsigned int dotnum;
1024
1025   unsigned int completed;
1026
1027   int print;
1028
1029   char *startup_string;
1030 };
1031
1032 #if !OLD
1033 /**
1034  * Convert unique ID to hash code.
1035  *
1036  * @param uid unique ID to convert
1037  * @param hash set to uid (extended with zeros)
1038  */
1039 static void
1040 hash_from_uid (uint32_t uid, GNUNET_HashCode * hash)
1041 {
1042   memset (hash, 0, sizeof (GNUNET_HashCode));
1043   *((uint32_t *) hash) = uid;
1044 }
1045
1046 /**
1047  * Convert hash code to unique ID.
1048  *
1049  * @param uid unique ID to convert
1050  * @param hash set to uid (extended with zeros)
1051  */
1052 static void
1053 uid_from_hash (const GNUNET_HashCode * hash, uint32_t * uid)
1054 {
1055   memcpy (uid, hash, sizeof (uint32_t));
1056 }
1057 #endif
1058
1059 #if USE_SEND_HELLOS
1060 static struct GNUNET_CORE_MessageHandler no_handlers[] = {
1061   {NULL, 0, 0}
1062 };
1063 #endif
1064
1065 /**
1066  * Create a meter to keep track of the progress of some task.
1067  *
1068  * @param total the total number of items to complete
1069  * @param start_string a string to prefix the meter with (if printing)
1070  * @param print GNUNET_YES to print the meter, GNUNET_NO to count
1071  *              internally only
1072  *
1073  * @return the progress meter
1074  */
1075 static struct ProgressMeter *
1076 create_meter (unsigned int total, char *start_string, int print)
1077 {
1078   struct ProgressMeter *ret;
1079
1080   ret = GNUNET_malloc (sizeof (struct ProgressMeter));
1081   ret->print = print;
1082   ret->total = total;
1083   ret->modnum = total / 4;
1084   if (ret->modnum == 0)         /* Divide by zero check */
1085     ret->modnum = 1;
1086   ret->dotnum = (total / 50) + 1;
1087   if (start_string != NULL)
1088     ret->startup_string = GNUNET_strdup (start_string);
1089   else
1090     ret->startup_string = GNUNET_strdup ("");
1091
1092   return ret;
1093 }
1094
1095 /**
1096  * Update progress meter (increment by one).
1097  *
1098  * @param meter the meter to update and print info for
1099  *
1100  * @return GNUNET_YES if called the total requested,
1101  *         GNUNET_NO if more items expected
1102  */
1103 static int
1104 update_meter (struct ProgressMeter *meter)
1105 {
1106   if (meter->print == GNUNET_YES)
1107   {
1108     if (meter->completed % meter->modnum == 0)
1109     {
1110       if (meter->completed == 0)
1111       {
1112         FPRINTF (stdout, "%sProgress: [0%%", meter->startup_string);
1113       }
1114       else
1115         FPRINTF (stdout, "%d%%",
1116                  (int) (((float) meter->completed / meter->total) * 100));
1117     }
1118     else if (meter->completed % meter->dotnum == 0)
1119       FPRINTF (stdout, "%s",  ".");
1120
1121     if (meter->completed + 1 == meter->total)
1122       FPRINTF (stdout, "%d%%]\n", 100);
1123     fflush (stdout);
1124   }
1125   meter->completed++;
1126
1127   if (meter->completed == meter->total)
1128     return GNUNET_YES;
1129   if (meter->completed > meter->total)
1130     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Progress meter overflow!!\n");
1131   return GNUNET_NO;
1132 }
1133
1134 /**
1135  * Reset progress meter.
1136  *
1137  * @param meter the meter to reset
1138  *
1139  * @return GNUNET_YES if meter reset,
1140  *         GNUNET_SYSERR on error
1141  */
1142 static int
1143 reset_meter (struct ProgressMeter *meter)
1144 {
1145   if (meter == NULL)
1146     return GNUNET_SYSERR;
1147
1148   meter->completed = 0;
1149   return GNUNET_YES;
1150 }
1151
1152 /**
1153  * Release resources for meter
1154  *
1155  * @param meter the meter to free
1156  */
1157 static void
1158 free_meter (struct ProgressMeter *meter)
1159 {
1160   GNUNET_free_non_null (meter->startup_string);
1161   GNUNET_free (meter);
1162 }
1163
1164 /**
1165  * Get a topology from a string input.
1166  *
1167  * @param topology where to write the retrieved topology
1168  * @param topology_string The string to attempt to
1169  *        get a configuration value from
1170  * @return GNUNET_YES if topology string matched a
1171  *         known topology, GNUNET_NO if not
1172  */
1173 int
1174 GNUNET_TESTING_topology_get (enum GNUNET_TESTING_Topology *topology,
1175                              const char *topology_string)
1176 {
1177   /**
1178    * Strings representing topologies in enum
1179    */
1180   static const char *topology_strings[] = {
1181     /**
1182      * A clique (everyone connected to everyone else).
1183      */
1184     "CLIQUE",
1185
1186     /**
1187      * Small-world network (2d torus plus random links).
1188      */
1189     "SMALL_WORLD",
1190
1191     /**
1192      * Small-world network (ring plus random links).
1193      */
1194     "SMALL_WORLD_RING",
1195
1196     /**
1197      * Ring topology.
1198      */
1199     "RING",
1200
1201     /**
1202      * 2-d torus.
1203      */
1204     "2D_TORUS",
1205
1206     /**
1207      * Random graph.
1208      */
1209     "ERDOS_RENYI",
1210
1211     /**
1212      * Certain percentage of peers are unable to communicate directly
1213      * replicating NAT conditions
1214      */
1215     "INTERNAT",
1216
1217     /**
1218      * Scale free topology.
1219      */
1220     "SCALE_FREE",
1221
1222     /**
1223      * Straight line topology.
1224      */
1225     "LINE",
1226
1227     /**
1228      * All peers are disconnected.
1229      */
1230     "NONE",
1231
1232     /**
1233      * Read the topology from a file.
1234      */
1235     "FROM_FILE",
1236
1237     NULL
1238   };
1239
1240   int curr = 0;
1241
1242   if (topology_string == NULL)
1243     return GNUNET_NO;
1244   while (topology_strings[curr] != NULL)
1245   {
1246     if (strcasecmp (topology_strings[curr], topology_string) == 0)
1247     {
1248       *topology = curr;
1249       return GNUNET_YES;
1250     }
1251     curr++;
1252   }
1253   *topology = GNUNET_TESTING_TOPOLOGY_NONE;
1254   return GNUNET_NO;
1255 }
1256
1257 /**
1258  * Get connect topology option from string input.
1259  *
1260  * @param topology_option where to write the retrieved topology
1261  * @param topology_string The string to attempt to
1262  *        get a configuration value from
1263  * @return GNUNET_YES if string matched a known
1264  *         topology option, GNUNET_NO if not
1265  */
1266 int
1267 GNUNET_TESTING_topology_option_get (enum GNUNET_TESTING_TopologyOption
1268                                     *topology_option,
1269                                     const char *topology_string)
1270 {
1271   /**
1272    * Options for connecting a topology as strings.
1273    */
1274   static const char *topology_option_strings[] = {
1275     /**
1276      * Try to connect all peers specified in the topology.
1277      */
1278     "CONNECT_ALL",
1279
1280     /**
1281      * Choose a random subset of connections to create.
1282      */
1283     "CONNECT_RANDOM_SUBSET",
1284
1285     /**
1286      * Create at least X connections for each peer.
1287      */
1288     "CONNECT_MINIMUM",
1289
1290     /**
1291      * Using a depth first search, create one connection
1292      * per peer.  If any are missed (graph disconnected)
1293      * start over at those peers until all have at least one
1294      * connection.
1295      */
1296     "CONNECT_DFS",
1297
1298     /**
1299      * Find the N closest peers to each allowed peer in the
1300      * topology and make sure a connection to those peers
1301      * exists in the connect topology.
1302      */
1303     "CONNECT_CLOSEST",
1304
1305     /**
1306      * No options specified.
1307      */
1308     "CONNECT_NONE",
1309
1310     NULL
1311   };
1312   int curr = 0;
1313
1314   if (topology_string == NULL)
1315     return GNUNET_NO;
1316   while (NULL != topology_option_strings[curr])
1317   {
1318     if (strcasecmp (topology_option_strings[curr], topology_string) == 0)
1319     {
1320       *topology_option = curr;
1321       return GNUNET_YES;
1322     }
1323     curr++;
1324   }
1325   *topology_option = GNUNET_TESTING_TOPOLOGY_OPTION_NONE;
1326   return GNUNET_NO;
1327 }
1328
1329 /**
1330  * Function to iterate over options.  Copies
1331  * the options to the target configuration,
1332  * updating PORT values as needed.
1333  *
1334  * @param cls closure
1335  * @param section name of the section
1336  * @param option name of the option
1337  * @param value value of the option
1338  */
1339 static void
1340 update_config (void *cls, const char *section, const char *option,
1341                const char *value)
1342 {
1343   struct UpdateContext *ctx = cls;
1344   unsigned int ival;
1345   char cval[12];
1346   char uval[128];
1347   char *single_variable;
1348   char *per_host_variable;
1349   unsigned long long num_per_host;
1350
1351   GNUNET_asprintf (&single_variable, "single_%s_per_host", section);
1352   GNUNET_asprintf (&per_host_variable, "num_%s_per_host", section);
1353
1354   if ((0 == strcmp (option, "PORT")) && (1 == SSCANF (value, "%u", &ival)))
1355   {
1356     if ((ival != 0) &&
1357         (GNUNET_YES !=
1358          GNUNET_CONFIGURATION_get_value_yesno (ctx->orig, "testing",
1359                                                single_variable)))
1360     {
1361       GNUNET_snprintf (cval, sizeof (cval), "%u", ctx->nport++);
1362       value = cval;
1363     }
1364     else if ((ival != 0) &&
1365              (GNUNET_YES ==
1366               GNUNET_CONFIGURATION_get_value_yesno (ctx->orig, "testing",
1367                                                     single_variable)) &&
1368              GNUNET_CONFIGURATION_get_value_number (ctx->orig, "testing",
1369                                                     per_host_variable,
1370                                                     &num_per_host))
1371     {
1372       GNUNET_snprintf (cval, sizeof (cval), "%u",
1373                        ival + ctx->fdnum % num_per_host);
1374       value = cval;
1375     }
1376
1377     /* FIXME: REMOVE FOREVER HACK HACK HACK */
1378     if (0 == strcasecmp (section, "transport-tcp"))
1379       GNUNET_CONFIGURATION_set_value_string (ctx->ret, section,
1380                                              "ADVERTISED_PORT", value);
1381   }
1382
1383   if (0 == strcmp (option, "UNIXPATH"))
1384   {
1385     if (GNUNET_YES !=
1386         GNUNET_CONFIGURATION_get_value_yesno (ctx->orig, "testing",
1387                                               single_variable))
1388     {
1389       GNUNET_snprintf (uval, sizeof (uval), "/tmp/test-service-%s-%u", section,
1390                        ctx->upnum++);
1391       value = uval;
1392     }
1393     else if ((GNUNET_YES ==
1394               GNUNET_CONFIGURATION_get_value_number (ctx->orig, "testing",
1395                                                      per_host_variable,
1396                                                      &num_per_host)) &&
1397              (num_per_host > 0))
1398
1399     {
1400       GNUNET_snprintf (uval, sizeof (uval), "/tmp/test-service-%s-%u", section,
1401                        ctx->fdnum % num_per_host);
1402       value = uval;
1403     }
1404   }
1405
1406   if ((0 == strcmp (option, "HOSTNAME")) && (ctx->hostname != NULL))
1407   {
1408     value = ctx->hostname;
1409   }
1410   GNUNET_free (single_variable);
1411   GNUNET_free (per_host_variable);
1412   GNUNET_CONFIGURATION_set_value_string (ctx->ret, section, option, value);
1413 }
1414
1415 /**
1416  * Create a new configuration using the given configuration
1417  * as a template; however, each PORT in the existing cfg
1418  * must be renumbered by incrementing "*port".  If we run
1419  * out of "*port" numbers, return NULL.
1420  *
1421  * @param cfg template configuration
1422  * @param off the current peer offset
1423  * @param port port numbers to use, update to reflect
1424  *             port numbers that were used
1425  * @param upnum number to make unix domain socket names unique
1426  * @param hostname hostname of the controlling host, to allow control connections from
1427  * @param fdnum number used to offset the unix domain socket for grouped processes
1428  *              (such as statistics or peerinfo, which can be shared among others)
1429  *
1430  * @return new configuration, NULL on error
1431  */
1432 struct GNUNET_CONFIGURATION_Handle *
1433 GNUNET_TESTING_create_cfg (const struct GNUNET_CONFIGURATION_Handle *cfg, uint32_t off,
1434              uint16_t * port, uint32_t * upnum, const char *hostname,
1435              uint32_t * fdnum)
1436 {
1437   struct UpdateContext uc;
1438   uint16_t orig;
1439   char *control_host;
1440   char *allowed_hosts;
1441   unsigned long long skew_variance;
1442   unsigned long long skew_offset;
1443   long long actual_offset;
1444
1445   orig = *port;
1446   uc.nport = *port;
1447   uc.upnum = *upnum;
1448   uc.fdnum = *fdnum;
1449   uc.ret = GNUNET_CONFIGURATION_create ();
1450   uc.hostname = hostname;
1451   uc.orig = cfg;
1452
1453   GNUNET_CONFIGURATION_iterate (cfg, &update_config, &uc);
1454   if (uc.nport >= HIGH_PORT)
1455   {
1456     *port = orig;
1457     GNUNET_CONFIGURATION_destroy (uc.ret);
1458     return NULL;
1459   }
1460
1461   if ((GNUNET_OK ==
1462        GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "skew_variance",
1463                                               &skew_variance)) &&
1464       (skew_variance > 0))
1465   {
1466     skew_offset =
1467         GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
1468                                   skew_variance + 1);
1469     actual_offset =
1470         skew_offset - GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
1471                                                 skew_variance + 1);
1472     /* Min is -skew_variance, Max is skew_variance */
1473     skew_offset = skew_variance + actual_offset;        /* Normal distribution around 0 */
1474     GNUNET_CONFIGURATION_set_value_number (uc.ret, "testing", "skew_offset",
1475                                            skew_offset);
1476   }
1477
1478   if (GNUNET_CONFIGURATION_get_value_string
1479       (cfg, "testing", "control_host", &control_host) == GNUNET_OK)
1480   {
1481     if (hostname != NULL)
1482       GNUNET_asprintf (&allowed_hosts, "%s; 127.0.0.1; %s;", control_host,
1483                        hostname);
1484     else
1485       GNUNET_asprintf (&allowed_hosts, "%s; 127.0.0.1;", control_host);
1486
1487     GNUNET_CONFIGURATION_set_value_string (uc.ret, "core", "ACCEPT_FROM",
1488                                            allowed_hosts);
1489
1490     GNUNET_CONFIGURATION_set_value_string (uc.ret, "nse", "ACCEPT_FROM",
1491                                            allowed_hosts);
1492
1493     GNUNET_CONFIGURATION_set_value_string (uc.ret, "transport", "ACCEPT_FROM",
1494                                            allowed_hosts);
1495     GNUNET_CONFIGURATION_set_value_string (uc.ret, "dht", "ACCEPT_FROM",
1496                                            allowed_hosts);
1497     GNUNET_CONFIGURATION_set_value_string (uc.ret, "statistics", "ACCEPT_FROM",
1498                                            allowed_hosts);
1499
1500     GNUNET_CONFIGURATION_set_value_string (uc.ret, "core", "UNIXPATH", "");
1501     GNUNET_CONFIGURATION_set_value_string (uc.ret, "transport", "UNIXPATH", "");
1502     GNUNET_CONFIGURATION_set_value_string (uc.ret, "dht", "UNIXPATH", "");
1503     GNUNET_CONFIGURATION_set_value_string (uc.ret, "statistics", "UNIXPATH",
1504                                            "");
1505     GNUNET_CONFIGURATION_set_value_string (uc.ret, "nse", "UNIXPATH", "");
1506
1507     GNUNET_CONFIGURATION_set_value_string (uc.ret, "transport-tcp",
1508                                            "USE_LOCALADDR", "YES");
1509     GNUNET_CONFIGURATION_set_value_string (uc.ret, "transport-udp",
1510                                            "USE_LOCALADDR", "YES");
1511     GNUNET_free_non_null (control_host);
1512     GNUNET_free (allowed_hosts);
1513   }
1514
1515   /* arm needs to know to allow connections from the host on which it is running,
1516    * otherwise gnunet-arm is unable to connect to it in some instances */
1517   if (hostname != NULL)
1518   {
1519     GNUNET_asprintf (&allowed_hosts, "%s; 127.0.0.1;", hostname);
1520     GNUNET_CONFIGURATION_set_value_string (uc.ret, "nat", "BINDTO", hostname);
1521     GNUNET_CONFIGURATION_set_value_string (uc.ret, "nat", "INTERNAL_ADDRESS",
1522                                            hostname);
1523     GNUNET_CONFIGURATION_set_value_string (uc.ret, "nat", "EXTERNAL_ADDRESS",
1524                                            hostname);
1525     GNUNET_CONFIGURATION_set_value_string (uc.ret, "disablev6", "BINDTO",
1526                                            "YES");
1527     GNUNET_CONFIGURATION_set_value_string (uc.ret, "transport-tcp",
1528                                            "USE_LOCALADDR", "YES");
1529     GNUNET_CONFIGURATION_set_value_string (uc.ret, "transport-udp",
1530                                            "USE_LOCALADDR", "YES");
1531     GNUNET_CONFIGURATION_set_value_string (uc.ret, "arm", "ACCEPT_FROM",
1532                                            allowed_hosts);
1533     GNUNET_free (allowed_hosts);
1534   }
1535   else
1536   {
1537
1538     GNUNET_CONFIGURATION_set_value_string (uc.ret, "transport-tcp",
1539                                            "USE_LOCALADDR", "YES");
1540     GNUNET_CONFIGURATION_set_value_string (uc.ret, "transport-udp",
1541                                            "USE_LOCALADDR", "YES");
1542     GNUNET_CONFIGURATION_set_value_string (uc.ret, "nat", "BINDTO",
1543                                            "127.0.0.1");
1544     GNUNET_CONFIGURATION_set_value_string (uc.ret, "nat", "INTERNAL_ADDRESS",
1545                                            "127.0.0.1");
1546     GNUNET_CONFIGURATION_set_value_string (uc.ret, "nat", "EXTERNAL_ADDRESS",
1547                                            "127.0.0.1");
1548     GNUNET_CONFIGURATION_set_value_string (uc.ret, "nat", "disablev6",
1549                                            "YES");
1550   }
1551
1552   *port = (uint16_t) uc.nport;
1553   *upnum = uc.upnum;
1554   uc.fdnum++;
1555   *fdnum = uc.fdnum;
1556   return uc.ret;
1557 }
1558
1559 /*
1560  * Remove entries from the peer connection list
1561  *
1562  * @param pg the peer group we are working with
1563  * @param first index of the first peer
1564  * @param second index of the second peer
1565  * @param list the peer list to use
1566  * @param check UNUSED
1567  *
1568  * @return the number of connections added (can be 0, 1 or 2)
1569  *
1570  */
1571 static unsigned int
1572 remove_connections (struct GNUNET_TESTING_PeerGroup *pg, unsigned int first,
1573                     unsigned int second, enum PeerLists list,
1574                     unsigned int check)
1575 {
1576   int removed;
1577
1578 #if OLD
1579   struct PeerConnection **first_list;
1580   struct PeerConnection **second_list;
1581   struct PeerConnection *first_iter;
1582   struct PeerConnection *second_iter;
1583   struct PeerConnection **first_tail;
1584   struct PeerConnection **second_tail;
1585
1586 #else
1587   GNUNET_HashCode hash_first;
1588   GNUNET_HashCode hash_second;
1589
1590   hash_from_uid (first, &hash_first);
1591   hash_from_uid (second, &hash_second);
1592 #endif
1593
1594   removed = 0;
1595 #if OLD
1596   switch (list)
1597   {
1598   case ALLOWED:
1599     first_list = &pg->peers[first].allowed_peers_head;
1600     second_list = &pg->peers[second].allowed_peers_head;
1601     first_tail = &pg->peers[first].allowed_peers_tail;
1602     second_tail = &pg->peers[second].allowed_peers_tail;
1603     break;
1604   case CONNECT:
1605     first_list = &pg->peers[first].connect_peers_head;
1606     second_list = &pg->peers[second].connect_peers_head;
1607     first_tail = &pg->peers[first].connect_peers_tail;
1608     second_tail = &pg->peers[second].connect_peers_tail;
1609     break;
1610   case BLACKLIST:
1611     first_list = &pg->peers[first].blacklisted_peers_head;
1612     second_list = &pg->peers[second].blacklisted_peers_head;
1613     first_tail = &pg->peers[first].blacklisted_peers_tail;
1614     second_tail = &pg->peers[second].blacklisted_peers_tail;
1615     break;
1616   case WORKING_SET:
1617     first_list = &pg->peers[first].connect_peers_working_set_head;
1618     second_list = &pg->peers[second].connect_peers_working_set_head;
1619     first_tail = &pg->peers[first].connect_peers_working_set_tail;
1620     second_tail = &pg->peers[second].connect_peers_working_set_tail;
1621     break;
1622   default:
1623     GNUNET_break (0);
1624     return 0;
1625   }
1626
1627   first_iter = *first_list;
1628   while (first_iter != NULL)
1629   {
1630     if (first_iter->index == second)
1631     {
1632       GNUNET_CONTAINER_DLL_remove (*first_list, *first_tail, first_iter);
1633       GNUNET_free (first_iter);
1634       removed++;
1635       break;
1636     }
1637     first_iter = first_iter->next;
1638   }
1639
1640   second_iter = *second_list;
1641   while (second_iter != NULL)
1642   {
1643     if (second_iter->index == first)
1644     {
1645       GNUNET_CONTAINER_DLL_remove (*second_list, *second_tail, second_iter);
1646       GNUNET_free (second_iter);
1647       removed++;
1648       break;
1649     }
1650     second_iter = second_iter->next;
1651   }
1652 #else
1653   if (GNUNET_YES ==
1654       GNUNET_CONTAINER_multihashmap_contains (pg->
1655                                               peers[first].blacklisted_peers,
1656                                               &hash_second))
1657   {
1658     GNUNET_CONTAINER_multihashmap_remove_all (pg->
1659                                               peers[first].blacklisted_peers,
1660                                               &hash_second);
1661   }
1662
1663   if (GNUNET_YES ==
1664       GNUNET_CONTAINER_multihashmap_contains (pg->
1665                                               peers[second].blacklisted_peers,
1666                                               &hash_first))
1667   {
1668     GNUNET_CONTAINER_multihashmap_remove_all (pg->
1669                                               peers[second].blacklisted_peers,
1670                                               &hash_first);
1671   }
1672 #endif
1673
1674   return removed;
1675 }
1676
1677 /**
1678  * Add entries to the some list
1679  *
1680  * @param pg the peer group we are working with
1681  * @param first index of the first peer
1682  * @param second index of the second peer
1683  * @param list the list type that we should modify
1684  * @param check GNUNET_YES to check lists before adding
1685  *              GNUNET_NO to force add
1686  *
1687  * @return the number of connections added (can be 0, 1 or 2)
1688  *
1689  */
1690 static unsigned int
1691 add_connections (struct GNUNET_TESTING_PeerGroup *pg, unsigned int first,
1692                  unsigned int second, enum PeerLists list, unsigned int check)
1693 {
1694   int added;
1695   int add_first;
1696   int add_second;
1697
1698   struct PeerConnection **first_list;
1699   struct PeerConnection **second_list;
1700   struct PeerConnection *first_iter;
1701   struct PeerConnection *second_iter;
1702   struct PeerConnection *new_first;
1703   struct PeerConnection *new_second;
1704   struct PeerConnection **first_tail;
1705   struct PeerConnection **second_tail;
1706
1707   switch (list)
1708   {
1709   case ALLOWED:
1710     first_list = &pg->peers[first].allowed_peers_head;
1711     second_list = &pg->peers[second].allowed_peers_head;
1712     first_tail = &pg->peers[first].allowed_peers_tail;
1713     second_tail = &pg->peers[second].allowed_peers_tail;
1714     break;
1715   case CONNECT:
1716     first_list = &pg->peers[first].connect_peers_head;
1717     second_list = &pg->peers[second].connect_peers_head;
1718     first_tail = &pg->peers[first].connect_peers_tail;
1719     second_tail = &pg->peers[second].connect_peers_tail;
1720     break;
1721   case BLACKLIST:
1722     first_list = &pg->peers[first].blacklisted_peers_head;
1723     second_list = &pg->peers[second].blacklisted_peers_head;
1724     first_tail = &pg->peers[first].blacklisted_peers_tail;
1725     second_tail = &pg->peers[second].blacklisted_peers_tail;
1726     break;
1727   case WORKING_SET:
1728     first_list = &pg->peers[first].connect_peers_working_set_head;
1729     second_list = &pg->peers[second].connect_peers_working_set_head;
1730     first_tail = &pg->peers[first].connect_peers_working_set_tail;
1731     second_tail = &pg->peers[second].connect_peers_working_set_tail;
1732     break;
1733   default:
1734     GNUNET_break (0);
1735     return 0;
1736   }
1737
1738   add_first = GNUNET_YES;
1739   add_second = GNUNET_YES;
1740
1741   if (check == GNUNET_YES)
1742   {
1743     first_iter = *first_list;
1744     while (first_iter != NULL)
1745     {
1746       if (first_iter->index == second)
1747       {
1748         add_first = GNUNET_NO;
1749         break;
1750       }
1751       first_iter = first_iter->next;
1752     }
1753
1754     second_iter = *second_list;
1755     while (second_iter != NULL)
1756     {
1757       if (second_iter->index == first)
1758       {
1759         add_second = GNUNET_NO;
1760         break;
1761       }
1762       second_iter = second_iter->next;
1763     }
1764   }
1765
1766   added = 0;
1767   if (add_first)
1768   {
1769     new_first = GNUNET_malloc (sizeof (struct PeerConnection));
1770     new_first->index = second;
1771     GNUNET_CONTAINER_DLL_insert (*first_list, *first_tail, new_first);
1772     pg->peers[first].num_connections++;
1773     added++;
1774   }
1775
1776   if (add_second)
1777   {
1778     new_second = GNUNET_malloc (sizeof (struct PeerConnection));
1779     new_second->index = first;
1780     GNUNET_CONTAINER_DLL_insert (*second_list, *second_tail, new_second);
1781     pg->peers[second].num_connections++;
1782     added++;
1783   }
1784
1785   return added;
1786 }
1787
1788 /**
1789  * Scale free network construction as described in:
1790  *
1791  * "Emergence of Scaling in Random Networks." Science 286, 509-512, 1999.
1792  *
1793  * Start with a network of "one" peer, then progressively add
1794  * peers up to the total number.  At each step, iterate over
1795  * all possible peers and connect new peer based on number of
1796  * existing connections of the target peer.
1797  *
1798  * @param pg the peer group we are dealing with
1799  * @param proc the connection processor to use
1800  * @param list the peer list to use
1801  *
1802  * @return the number of connections created
1803  */
1804 static unsigned int
1805 create_scale_free (struct GNUNET_TESTING_PeerGroup *pg,
1806                    GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
1807 {
1808
1809   unsigned int total_connections;
1810   unsigned int outer_count;
1811   unsigned int i;
1812   unsigned int previous_total_connections;
1813   double random;
1814   double probability;
1815
1816   GNUNET_assert (pg->total > 1);
1817
1818   /* Add a connection between the first two nodes */
1819   total_connections = proc (pg, 0, 1, list, GNUNET_YES);
1820
1821   for (outer_count = 1; outer_count < pg->total; outer_count++)
1822   {
1823     previous_total_connections = total_connections;
1824     for (i = 0; i < outer_count; i++)
1825     {
1826       probability =
1827           pg->peers[i].num_connections / (double) previous_total_connections;
1828       random =
1829           ((double)
1830            GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
1831                                      UINT64_MAX)) / ((double) UINT64_MAX);
1832       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1833                   "Considering connecting peer %d to peer %d\n", outer_count,
1834                   i);
1835       if (random < probability)
1836       {
1837         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting peer %d to peer %d\n",
1838                     outer_count, i);
1839         total_connections += proc (pg, outer_count, i, list, GNUNET_YES);
1840       }
1841     }
1842   }
1843
1844   return total_connections;
1845 }
1846
1847 /**
1848  * Create a topology given a peer group (set of running peers)
1849  * and a connection processor.  Creates a small world topology
1850  * according to the rewired ring construction.  The basic
1851  * behavior is that a ring topology is created, but with some
1852  * probability instead of connecting a peer to the next
1853  * neighbor in the ring a connection will be created to a peer
1854  * selected uniformly at random.   We use the TESTING
1855  * PERCENTAGE option to specify what number of
1856  * connections each peer should have.  Default is 2,
1857  * which makes the ring, any given number is multiplied by
1858  * the log of the network size; i.e. a PERCENTAGE of 2 makes
1859  * each peer have on average 2logn connections.  The additional
1860  * connections are made at increasing distance around the ring
1861  * from the original peer, or to random peers based on the re-
1862  * wiring probability. The TESTING
1863  * PROBABILITY option is used as the probability that a given
1864  * connection is rewired.
1865  *
1866  * @param pg the peergroup to create the topology on
1867  * @param proc the connection processor to call to actually set
1868  *        up connections between two peers
1869  * @param list the peer list to use
1870  *
1871  * @return the number of connections that were set up
1872  *
1873  */
1874 static unsigned int
1875 create_small_world_ring (struct GNUNET_TESTING_PeerGroup *pg,
1876                          GNUNET_TESTING_ConnectionProcessor proc,
1877                          enum PeerLists list)
1878 {
1879   unsigned int i, j;
1880   int nodeToConnect;
1881   unsigned int natLog;
1882   unsigned int randomPeer;
1883   double random, logNModifier, probability;
1884   unsigned int smallWorldConnections;
1885   int connsPerPeer;
1886   char *p_string;
1887   int max;
1888   int min;
1889   unsigned int useAnd;
1890   int connect_attempts;
1891
1892   logNModifier = 0.5;           /* FIXME: default value? */
1893   if (GNUNET_OK ==
1894       GNUNET_CONFIGURATION_get_value_string (pg->cfg, "TESTING", "PERCENTAGE",
1895                                              &p_string))
1896   {
1897     if (SSCANF (p_string, "%lf", &logNModifier) != 1)
1898       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1899                   _
1900                   ("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1901                   p_string, "LOGNMODIFIER", "TESTING");
1902     GNUNET_free (p_string);
1903   }
1904   probability = 0.5;            /* FIXME: default percentage? */
1905   if (GNUNET_OK ==
1906       GNUNET_CONFIGURATION_get_value_string (pg->cfg, "TESTING", "PROBABILITY",
1907                                              &p_string))
1908   {
1909     if (SSCANF (p_string, "%lf", &probability) != 1)
1910       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1911                   _
1912                   ("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1913                   p_string, "PERCENTAGE", "TESTING");
1914     GNUNET_free (p_string);
1915   }
1916   natLog = log (pg->total);
1917   connsPerPeer = ceil (natLog * logNModifier);
1918
1919   if (connsPerPeer % 2 == 1)
1920     connsPerPeer += 1;
1921
1922   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Target is %d connections per peer.",
1923               connsPerPeer);
1924
1925   smallWorldConnections = 0;
1926   connect_attempts = 0;
1927   for (i = 0; i < pg->total; i++)
1928   {
1929     useAnd = 0;
1930     max = i + connsPerPeer / 2;
1931     min = i - connsPerPeer / 2;
1932
1933     if (max > pg->total - 1)
1934     {
1935       max = max - pg->total;
1936       useAnd = 1;
1937     }
1938
1939     if (min < 0)
1940     {
1941       min = pg->total - 1 + min;
1942       useAnd = 1;
1943     }
1944
1945     for (j = 0; j < connsPerPeer / 2; j++)
1946     {
1947       random =
1948           ((double)
1949            GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
1950                                      UINT64_MAX) / ((double) UINT64_MAX));
1951       if (random < probability)
1952       {
1953         /* Connect to uniformly selected random peer */
1954         randomPeer =
1955             GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, pg->total);
1956         while ((((randomPeer < max) && (randomPeer > min)) && (useAnd == 0)) ||
1957                (((randomPeer > min) || (randomPeer < max)) && (useAnd == 1)))
1958         {
1959           randomPeer =
1960               GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, pg->total);
1961         }
1962         smallWorldConnections += proc (pg, i, randomPeer, list, GNUNET_YES);
1963       }
1964       else
1965       {
1966         nodeToConnect = i + j + 1;
1967         if (nodeToConnect > pg->total - 1)
1968         {
1969           nodeToConnect = nodeToConnect - pg->total;
1970         }
1971         connect_attempts += proc (pg, i, nodeToConnect, list, GNUNET_YES);
1972       }
1973     }
1974
1975   }
1976
1977   connect_attempts += smallWorldConnections;
1978
1979   return connect_attempts;
1980 }
1981
1982 /**
1983  * Create a topology given a peer group (set of running peers)
1984  * and a connection processor.
1985  *
1986  * @param pg the peergroup to create the topology on
1987  * @param proc the connection processor to call to actually set
1988  *        up connections between two peers
1989  * @param list the peer list to use
1990  *
1991  * @return the number of connections that were set up
1992  *
1993  */
1994 static unsigned int
1995 create_nated_internet (struct GNUNET_TESTING_PeerGroup *pg,
1996                        GNUNET_TESTING_ConnectionProcessor proc,
1997                        enum PeerLists list)
1998 {
1999   unsigned int outer_count, inner_count;
2000   unsigned int cutoff;
2001   int connect_attempts;
2002   double nat_percentage;
2003   char *p_string;
2004
2005   nat_percentage = 0.6;         /* FIXME: default percentage? */
2006   if (GNUNET_OK ==
2007       GNUNET_CONFIGURATION_get_value_string (pg->cfg, "TESTING", "PERCENTAGE",
2008                                              &p_string))
2009   {
2010     if (SSCANF (p_string, "%lf", &nat_percentage) != 1)
2011       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2012                   _
2013                   ("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
2014                   p_string, "PERCENTAGE", "TESTING");
2015     GNUNET_free (p_string);
2016   }
2017
2018   cutoff = (unsigned int) (nat_percentage * pg->total);
2019   connect_attempts = 0;
2020   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
2021   {
2022     for (inner_count = outer_count + 1; inner_count < pg->total; inner_count++)
2023     {
2024       if ((outer_count > cutoff) || (inner_count > cutoff))
2025       {
2026         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting peer %d to peer %d\n",
2027                     outer_count, inner_count);
2028         connect_attempts +=
2029             proc (pg, outer_count, inner_count, list, GNUNET_YES);
2030       }
2031     }
2032   }
2033   return connect_attempts;
2034 }
2035
2036 #if TOPOLOGY_HACK
2037 /**
2038  * Create a topology given a peer group (set of running peers)
2039  * and a connection processor.
2040  *
2041  * @param pg the peergroup to create the topology on
2042  * @param proc the connection processor to call to actually set
2043  *        up connections between two peers
2044  * @param list the peer list to use
2045  *
2046  * @return the number of connections that were set up
2047  *
2048  */
2049 static unsigned int
2050 create_nated_internet_copy (struct GNUNET_TESTING_PeerGroup *pg,
2051                             GNUNET_TESTING_ConnectionProcessor proc,
2052                             enum PeerLists list)
2053 {
2054   unsigned int outer_count, inner_count;
2055   unsigned int cutoff;
2056   int connect_attempts;
2057   double nat_percentage;
2058   char *p_string;
2059   unsigned int count;
2060   struct ProgressMeter *conn_meter;
2061
2062   nat_percentage = 0.6;         /* FIXME: default percentage? */
2063   if (GNUNET_OK ==
2064       GNUNET_CONFIGURATION_get_value_string (pg->cfg, "TESTING", "PERCENTAGE",
2065                                              &p_string))
2066   {
2067     if (SSCANF (p_string, "%lf", &nat_percentage) != 1)
2068       GNUNET_log (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
2075   cutoff = (unsigned int) (nat_percentage * pg->total);
2076   count = 0;
2077   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
2078   {
2079     for (inner_count = outer_count + 1; inner_count < pg->total; inner_count++)
2080     {
2081       if ((outer_count > cutoff) || (inner_count > cutoff))
2082       {
2083         count++;
2084       }
2085     }
2086   }
2087   conn_meter = create_meter (count, "NAT COPY", GNUNET_YES);
2088   connect_attempts = 0;
2089   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
2090   {
2091     for (inner_count = outer_count + 1; inner_count < pg->total; inner_count++)
2092     {
2093       if ((outer_count > cutoff) || (inner_count > cutoff))
2094       {
2095         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting peer %d to peer %d\n",
2096                     outer_count, inner_count);
2097         connect_attempts +=
2098             proc (pg, outer_count, inner_count, list, GNUNET_YES);
2099         add_connections (pg, outer_count, inner_count, ALLOWED, GNUNET_NO);
2100         update_meter (conn_meter);
2101       }
2102     }
2103   }
2104   free_meter (conn_meter);
2105
2106   return connect_attempts;
2107 }
2108 #endif
2109
2110 /**
2111  * Create a topology given a peer group (set of running peers)
2112  * and a connection processor.
2113  *
2114  * @param pg the peergroup to create the topology on
2115  * @param proc the connection processor to call to actually set
2116  *        up connections between two peers
2117  * @param list the peer list to use
2118  *
2119  * @return the number of connections that were set up
2120  *
2121  */
2122 static unsigned int
2123 create_small_world (struct GNUNET_TESTING_PeerGroup *pg,
2124                     GNUNET_TESTING_ConnectionProcessor proc,
2125                     enum PeerLists list)
2126 {
2127   unsigned int i, j, k;
2128   unsigned int square;
2129   unsigned int rows;
2130   unsigned int cols;
2131   unsigned int toggle = 1;
2132   unsigned int nodeToConnect;
2133   unsigned int natLog;
2134   unsigned int node1Row;
2135   unsigned int node1Col;
2136   unsigned int node2Row;
2137   unsigned int node2Col;
2138   unsigned int distance;
2139   double probability, random, percentage;
2140   unsigned int smallWorldConnections;
2141   unsigned int small_world_it;
2142   char *p_string;
2143   int connect_attempts;
2144
2145   square = floor (sqrt (pg->total));
2146   rows = square;
2147   cols = square;
2148
2149   percentage = 0.5;             /* FIXME: default percentage? */
2150   if (GNUNET_OK ==
2151       GNUNET_CONFIGURATION_get_value_string (pg->cfg, "TESTING", "PERCENTAGE",
2152                                              &p_string))
2153   {
2154     if (SSCANF (p_string, "%lf", &percentage) != 1)
2155       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2156                   _
2157                   ("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
2158                   p_string, "PERCENTAGE", "TESTING");
2159     GNUNET_free (p_string);
2160   }
2161   if (percentage < 0.0)
2162   {
2163     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2164                 _
2165                 ("Invalid value `%s' for option `%s' in section `%s': got %f, needed value greater than 0\n"),
2166                 "PERCENTAGE", "TESTING", percentage);
2167     percentage = 0.5;
2168   }
2169   probability = 0.5;            /* FIXME: default percentage? */
2170   if (GNUNET_OK ==
2171       GNUNET_CONFIGURATION_get_value_string (pg->cfg, "TESTING", "PROBABILITY",
2172                                              &p_string))
2173   {
2174     if (SSCANF (p_string, "%lf", &probability) != 1)
2175       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2176                   _
2177                   ("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
2178                   p_string, "PROBABILITY", "TESTING");
2179     GNUNET_free (p_string);
2180   }
2181   if (square * square != pg->total)
2182   {
2183     while (rows * cols < pg->total)
2184     {
2185       if (toggle % 2 == 0)
2186         rows++;
2187       else
2188         cols++;
2189
2190       toggle++;
2191     }
2192   }
2193   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194               "Connecting nodes in 2d torus topology: %u rows %u columns\n",
2195               rows, cols);
2196   connect_attempts = 0;
2197   /* Rows and columns are all sorted out, now iterate over all nodes and connect each
2198    * to the node to its right and above.  Once this is over, we'll have our torus!
2199    * Special case for the last node (if the rows and columns are not equal), connect
2200    * to the first in the row to maintain topology.
2201    */
2202   for (i = 0; i < pg->total; i++)
2203   {
2204     /* First connect to the node to the right */
2205     if (((i + 1) % cols != 0) && (i + 1 != pg->total))
2206       nodeToConnect = i + 1;
2207     else if (i + 1 == pg->total)
2208       nodeToConnect = rows * cols - cols;
2209     else
2210       nodeToConnect = i - cols + 1;
2211
2212     connect_attempts += proc (pg, i, nodeToConnect, list, GNUNET_YES);
2213
2214     if (i < cols)
2215     {
2216       nodeToConnect = (rows * cols) - cols + i;
2217       if (nodeToConnect >= pg->total)
2218         nodeToConnect -= cols;
2219     }
2220     else
2221       nodeToConnect = i - cols;
2222
2223     if (nodeToConnect < pg->total)
2224       connect_attempts += proc (pg, i, nodeToConnect, list, GNUNET_YES);
2225   }
2226   natLog = log (pg->total);
2227   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2228               "natural log of %d is %d, will run %d iterations\n", pg->total,
2229               natLog, (int) (natLog * percentage));
2230   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2231               "Total connections added thus far: %u!\n", connect_attempts);
2232   smallWorldConnections = 0;
2233   small_world_it = (unsigned int) (natLog * percentage);
2234   if (small_world_it < 1)
2235     small_world_it = 1;
2236   GNUNET_assert (small_world_it > 0 && small_world_it < (unsigned int) -1);
2237   for (i = 0; i < small_world_it; i++)
2238   {
2239     for (j = 0; j < pg->total; j++)
2240     {
2241       /* Determine the row and column of node at position j on the 2d torus */
2242       node1Row = j / cols;
2243       node1Col = j - (node1Row * cols);
2244       for (k = 0; k < pg->total; k++)
2245       {
2246         /* Determine the row and column of node at position k on the 2d torus */
2247         node2Row = k / cols;
2248         node2Col = k - (node2Row * cols);
2249         /* Simple Cartesian distance */
2250         distance = abs (node1Row - node2Row) + abs (node1Col - node2Col);
2251         if (distance > 1)
2252         {
2253           /* Calculate probability as 1 over the square of the distance */
2254           probability = 1.0 / (distance * distance);
2255           /* Choose a random value between 0 and 1 */
2256           random =
2257               ((double)
2258                GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
2259                                          UINT64_MAX)) / ((double) UINT64_MAX);
2260           /* If random < probability, then connect the two nodes */
2261           if (random < probability)
2262             smallWorldConnections += proc (pg, j, k, list, GNUNET_YES);
2263
2264         }
2265       }
2266     }
2267   }
2268   connect_attempts += smallWorldConnections;
2269   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2270               "Total connections added for small world: %d!\n",
2271               smallWorldConnections);
2272   return connect_attempts;
2273 }
2274
2275 /**
2276  * Create a topology given a peer group (set of running peers)
2277  * and a connection processor.
2278  *
2279  * @param pg the peergroup to create the topology on
2280  * @param proc the connection processor to call to actually set
2281  *        up connections between two peers
2282  * @param list the peer list to use
2283  *
2284  * @return the number of connections that were set up
2285  *
2286  */
2287 static unsigned int
2288 create_erdos_renyi (struct GNUNET_TESTING_PeerGroup *pg,
2289                     GNUNET_TESTING_ConnectionProcessor proc,
2290                     enum PeerLists list)
2291 {
2292   double temp_rand;
2293   unsigned int outer_count;
2294   unsigned int inner_count;
2295   int connect_attempts;
2296   double probability;
2297   char *p_string;
2298
2299   probability = 0.5;            /* FIXME: default percentage? */
2300   if (GNUNET_OK ==
2301       GNUNET_CONFIGURATION_get_value_string (pg->cfg, "TESTING", "PROBABILITY",
2302                                              &p_string))
2303   {
2304     if (SSCANF (p_string, "%lf", &probability) != 1)
2305       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2306                   _
2307                   ("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
2308                   p_string, "PROBABILITY", "TESTING");
2309     GNUNET_free (p_string);
2310   }
2311   connect_attempts = 0;
2312   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
2313   {
2314     for (inner_count = outer_count + 1; inner_count < pg->total; inner_count++)
2315     {
2316       temp_rand =
2317           ((double)
2318            GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
2319                                      UINT64_MAX)) / ((double) UINT64_MAX);
2320       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "rand is %f probability is %f\n",
2321                   temp_rand, probability);
2322       if (temp_rand < probability)
2323       {
2324         connect_attempts +=
2325             proc (pg, outer_count, inner_count, list, GNUNET_YES);
2326       }
2327     }
2328   }
2329
2330   return connect_attempts;
2331 }
2332
2333 /**
2334  * Create a topology given a peer group (set of running peers)
2335  * and a connection processor.  This particular function creates
2336  * the connections for a 2d-torus, plus additional "closest"
2337  * connections per peer.
2338  *
2339  * @param pg the peergroup to create the topology on
2340  * @param proc the connection processor to call to actually set
2341  *        up connections between two peers
2342  * @param list the peer list to use
2343  *
2344  * @return the number of connections that were set up
2345  *
2346  */
2347 static unsigned int
2348 create_2d_torus (struct GNUNET_TESTING_PeerGroup *pg,
2349                  GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
2350 {
2351   unsigned int i;
2352   unsigned int square;
2353   unsigned int rows;
2354   unsigned int cols;
2355   unsigned int toggle = 1;
2356   unsigned int nodeToConnect;
2357   int connect_attempts;
2358
2359   connect_attempts = 0;
2360
2361   square = floor (sqrt (pg->total));
2362   rows = square;
2363   cols = square;
2364
2365   if (square * square != pg->total)
2366   {
2367     while (rows * cols < pg->total)
2368     {
2369       if (toggle % 2 == 0)
2370         rows++;
2371       else
2372         cols++;
2373
2374       toggle++;
2375     }
2376   }
2377   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2378               "Connecting nodes in 2d torus topology: %u rows %u columns\n",
2379               rows, cols);
2380   /* Rows and columns are all sorted out, now iterate over all nodes and connect each
2381    * to the node to its right and above.  Once this is over, we'll have our torus!
2382    * Special case for the last node (if the rows and columns are not equal), connect
2383    * to the first in the row to maintain topology.
2384    */
2385   for (i = 0; i < pg->total; i++)
2386   {
2387     /* First connect to the node to the right */
2388     if (((i + 1) % cols != 0) && (i + 1 != pg->total))
2389       nodeToConnect = i + 1;
2390     else if (i + 1 == pg->total)
2391       nodeToConnect = rows * cols - cols;
2392     else
2393       nodeToConnect = i - cols + 1;
2394     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting peer %d to peer %d\n", i,
2395                 nodeToConnect);
2396     connect_attempts += proc (pg, i, nodeToConnect, list, GNUNET_YES);
2397
2398     /* Second connect to the node immediately above */
2399     if (i < cols)
2400     {
2401       nodeToConnect = (rows * cols) - cols + i;
2402       if (nodeToConnect >= pg->total)
2403         nodeToConnect -= cols;
2404     }
2405     else
2406       nodeToConnect = i - cols;
2407
2408     if (nodeToConnect < pg->total)
2409     {
2410       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting peer %d to peer %d\n", i,
2411                   nodeToConnect);
2412       connect_attempts += proc (pg, i, nodeToConnect, list, GNUNET_YES);
2413     }
2414
2415   }
2416
2417   return connect_attempts;
2418 }
2419
2420 /**
2421  * Create a topology given a peer group (set of running peers)
2422  * and a connection processor.
2423  *
2424  * @param pg the peergroup to create the topology on
2425  * @param proc the connection processor to call to actually set
2426  *        up connections between two peers
2427  * @param list the peer list to use
2428  * @param check does the connection processor need to check before
2429  *              performing an action on the list?
2430  *
2431  * @return the number of connections that were set up
2432  *
2433  */
2434 static unsigned int
2435 create_clique (struct GNUNET_TESTING_PeerGroup *pg,
2436                GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list,
2437                unsigned int check)
2438 {
2439   unsigned int outer_count;
2440   unsigned int inner_count;
2441   int connect_attempts;
2442   struct ProgressMeter *conn_meter;
2443
2444   connect_attempts = 0;
2445
2446   conn_meter =
2447       create_meter ((((pg->total * pg->total) + pg->total) / 2) - pg->total,
2448                     "Create Clique ", GNUNET_NO);
2449   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
2450   {
2451     for (inner_count = outer_count + 1; inner_count < pg->total; inner_count++)
2452     {
2453       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting peer %d to peer %d\n",
2454                   outer_count, inner_count);
2455       connect_attempts += proc (pg, outer_count, inner_count, list, check);
2456       update_meter (conn_meter);
2457     }
2458   }
2459   reset_meter (conn_meter);
2460   free_meter (conn_meter);
2461   return connect_attempts;
2462 }
2463
2464 #if !OLD
2465 /**
2466  * Iterator over hash map entries.
2467  *
2468  * @param cls closure the peer group
2469  * @param key the key stored in the hashmap is the
2470  *            index of the peer to connect to
2471  * @param value value in the hash map, handle to the peer daemon
2472  * @return GNUNET_YES if we should continue to
2473  *         iterate,
2474  *         GNUNET_NO if not.
2475  */
2476 static int
2477 unblacklist_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2478 {
2479   struct UnblacklistContext *un_ctx = cls;
2480   uint32_t second_pos;
2481
2482   uid_from_hash (key, &second_pos);
2483
2484   unblacklist_connections (un_ctx->pg, un_ctx->first_uid, second_pos);
2485
2486   return GNUNET_YES;
2487 }
2488 #endif
2489
2490 #if !OLD
2491 /**
2492  * Create a blacklist topology based on the allowed topology
2493  * which disallows any connections not in the allowed topology
2494  * at the transport level.
2495  *
2496  * @param pg the peergroup to create the topology on
2497  * @param proc the connection processor to call to allow
2498  *        up connections between two peers
2499  *
2500  * @return the number of connections that were set up
2501  *
2502  */
2503 static unsigned int
2504 copy_allowed (struct GNUNET_TESTING_PeerGroup *pg,
2505               GNUNET_TESTING_ConnectionProcessor proc)
2506 {
2507   unsigned int count;
2508   unsigned int total;
2509   struct PeerConnection *iter;
2510
2511 #if !OLD
2512   struct UnblacklistContext un_ctx;
2513
2514   un_ctx.pg = pg;
2515 #endif
2516   total = 0;
2517   for (count = 0; count < pg->total - 1; count++)
2518   {
2519 #if OLD
2520     iter = pg->peers[count].allowed_peers_head;
2521     while (iter != NULL)
2522     {
2523       remove_connections (pg, count, iter->index, BLACKLIST, GNUNET_YES);
2524       //unblacklist_connections(pg, count, iter->index);
2525       iter = iter->next;
2526     }
2527 #else
2528     un_ctx.first_uid = count;
2529     total +=
2530         GNUNET_CONTAINER_multihashmap_iterate (pg->peers[count].allowed_peers,
2531                                                &unblacklist_iterator, &un_ctx);
2532 #endif
2533   }
2534   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Unblacklisted %u peers\n", total);
2535   return total;
2536 }
2537 #endif
2538
2539 /**
2540  * Create a topology given a peer group (set of running peers)
2541  * and a connection processor.
2542  *
2543  * @param pg the peergroup to create the topology on
2544  * @param proc the connection processor to call to actually set
2545  *        up connections between two peers
2546  * @param list which list should be modified
2547  *
2548  * @return the number of connections that were set up
2549  *
2550  */
2551 static unsigned int
2552 create_line (struct GNUNET_TESTING_PeerGroup *pg,
2553              GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
2554 {
2555   unsigned int count;
2556   unsigned int connect_attempts;
2557
2558   connect_attempts = 0;
2559   /* Connect each peer to the next highest numbered peer */
2560   for (count = 0; count < pg->total - 1; count++)
2561   {
2562     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting peer %d to peer %d\n",
2563                 count, count + 1);
2564     connect_attempts += proc (pg, count, count + 1, list, GNUNET_YES);
2565   }
2566
2567   return connect_attempts;
2568 }
2569
2570 /**
2571  * Create a topology given a peer group (set of running peers)
2572  * and a connection processor.
2573  *
2574  * @param pg the peergroup to create the topology on
2575  * @param filename the file to read topology information from
2576  * @param proc the connection processor to call to actually set
2577  *        up connections between two peers
2578  * @param list the peer list to use
2579  *
2580  * @return the number of connections that were set up
2581  *
2582  */
2583 static unsigned int
2584 create_from_file (struct GNUNET_TESTING_PeerGroup *pg, char *filename,
2585                   GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
2586 {
2587   int connect_attempts;
2588   unsigned int first_peer_index;
2589   unsigned int second_peer_index;
2590   struct stat frstat;
2591   int count;
2592   char *data;
2593   const char *buf;
2594   unsigned int total_peers;
2595   enum States curr_state;
2596
2597   connect_attempts = 0;
2598   if (GNUNET_OK != GNUNET_DISK_file_test (filename))
2599     GNUNET_DISK_fn_write (filename, NULL, 0, GNUNET_DISK_PERM_USER_READ);
2600
2601   if ((0 != STAT (filename, &frstat)) || (frstat.st_size == 0))
2602   {
2603     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2604                 "Could not open file `%s' specified for topology!", filename);
2605     return connect_attempts;
2606   }
2607
2608   data = GNUNET_malloc_large (frstat.st_size);
2609   GNUNET_assert (data != NULL);
2610   if (frstat.st_size != GNUNET_DISK_fn_read (filename, data, frstat.st_size))
2611   {
2612     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2613                 "Could not read file %s specified for host list, ending test!",
2614                 filename);
2615     GNUNET_free (data);
2616     return connect_attempts;
2617   }
2618
2619   buf = data;
2620   count = 0;
2621   first_peer_index = 0;
2622   /* First line should contain a single integer, specifying the number of peers */
2623   /* Each subsequent line should contain this format PEER_INDEX:OTHER_PEER_INDEX[,...] */
2624   curr_state = NUM_PEERS;
2625   while (count < frstat.st_size - 1)
2626   {
2627     if ((buf[count] == '\n') || (buf[count] == ' '))
2628     {
2629       count++;
2630       continue;
2631     }
2632
2633     switch (curr_state)
2634     {
2635     case NUM_PEERS:
2636       errno = 0;
2637       total_peers = strtoul (&buf[count], NULL, 10);
2638       if (errno != 0)
2639       {
2640         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2641                     "Failed to read number of peers from topology file!\n");
2642         GNUNET_free (data);
2643         return connect_attempts;
2644       }
2645       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found %u total peers in topology\n",
2646                   total_peers);
2647       GNUNET_assert (total_peers == pg->total);
2648       curr_state = PEER_INDEX;
2649       while ((buf[count] != '\n') && (count < frstat.st_size - 1))
2650         count++;
2651       count++;
2652       break;
2653     case PEER_INDEX:
2654       errno = 0;
2655       first_peer_index = strtoul (&buf[count], NULL, 10);
2656       if (errno != 0)
2657       {
2658         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2659                     "Failed to read peer index from topology file!\n");
2660         GNUNET_free (data);
2661         return connect_attempts;
2662       }
2663       while ((buf[count] != ':') && (count < frstat.st_size - 1))
2664         count++;
2665       count++;
2666       curr_state = OTHER_PEER_INDEX;
2667       break;
2668     case COLON:
2669       if (1 == sscanf (&buf[count], ":"))
2670         curr_state = OTHER_PEER_INDEX;
2671       count++;
2672       break;
2673     case OTHER_PEER_INDEX:
2674       errno = 0;
2675       second_peer_index = strtoul (&buf[count], NULL, 10);
2676       if (errno != 0)
2677       {
2678         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2679                     "Failed to peer index from topology file!\n");
2680         GNUNET_free (data);
2681         return connect_attempts;
2682       }
2683       /* Assume file is written with first peer 1, but array index is 0 */
2684       connect_attempts +=
2685           proc (pg, first_peer_index - 1, second_peer_index - 1, list,
2686                 GNUNET_YES);
2687       while ((buf[count] != '\n') && (buf[count] != ',') &&
2688              (count < frstat.st_size - 1))
2689         count++;
2690       if (buf[count] == '\n')
2691       {
2692         curr_state = PEER_INDEX;
2693       }
2694       else if (buf[count] != ',')
2695       {
2696         curr_state = OTHER_PEER_INDEX;
2697       }
2698       count++;
2699       break;
2700     default:
2701       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2702                   "Found bad data in topology file while in state %d!\n",
2703                   curr_state);
2704       GNUNET_break (0);
2705       GNUNET_free (data);
2706       return connect_attempts;
2707     }
2708   }
2709   GNUNET_free (data);
2710   return connect_attempts;
2711 }
2712
2713 /**
2714  * Create a topology given a peer group (set of running peers)
2715  * and a connection processor.
2716  *
2717  * @param pg the peergroup to create the topology on
2718  * @param proc the connection processor to call to actually set
2719  *        up connections between two peers
2720  * @param list the peer list to use
2721  *
2722  * @return the number of connections that were set up
2723  *
2724  */
2725 static unsigned int
2726 create_ring (struct GNUNET_TESTING_PeerGroup *pg,
2727              GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
2728 {
2729   unsigned int count;
2730   int connect_attempts;
2731
2732   connect_attempts = 0;
2733
2734   /* Connect each peer to the next highest numbered peer */
2735   for (count = 0; count < pg->total - 1; count++)
2736   {
2737     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting peer %d to peer %d\n",
2738                 count, count + 1);
2739     connect_attempts += proc (pg, count, count + 1, list, GNUNET_YES);
2740   }
2741
2742   /* Connect the last peer to the first peer */
2743   connect_attempts += proc (pg, pg->total - 1, 0, list, GNUNET_YES);
2744
2745   return connect_attempts;
2746 }
2747
2748 #if !OLD
2749 /**
2750  * Iterator for writing friends of a peer to a file.
2751  *
2752  * @param cls closure, an open writable file handle
2753  * @param key the key the daemon was stored under
2754  * @param value the GNUNET_TESTING_Daemon that needs to be written.
2755  *
2756  * @return GNUNET_YES to continue iteration
2757  *
2758  * TODO: Could replace friend_file_iterator and blacklist_file_iterator
2759  *       with a single file_iterator that takes a closure which contains
2760  *       the prefix to write before the peer.  Then this could be used
2761  *       for blacklisting multiple transports and writing the friend
2762  *       file.  I'm sure *someone* will complain loudly about other
2763  *       things that negate these functions even existing so no point in
2764  *       "fixing" now.
2765  */
2766 static int
2767 friend_file_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2768 {
2769   FILE *temp_friend_handle = cls;
2770   struct GNUNET_TESTING_Daemon *peer = value;
2771   struct GNUNET_PeerIdentity *temppeer;
2772   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2773
2774   temppeer = &peer->id;
2775   GNUNET_CRYPTO_hash_to_enc (&temppeer->hashPubKey, &peer_enc);
2776   FPRINTF (temp_friend_handle, "%s\n", (char *) &peer_enc);
2777
2778   return GNUNET_YES;
2779 }
2780
2781 struct BlacklistContext
2782 {
2783   /*
2784    * The (open) file handle to write to
2785    */
2786   FILE *temp_file_handle;
2787
2788   /*
2789    * The transport that this peer will be blacklisted on.
2790    */
2791   char *transport;
2792 };
2793
2794 /**
2795  * Iterator for writing blacklist data to appropriate files.
2796  *
2797  * @param cls closure, an open writable file handle
2798  * @param key the key the daemon was stored under
2799  * @param value the GNUNET_TESTING_Daemon that needs to be written.
2800  *
2801  * @return GNUNET_YES to continue iteration
2802  */
2803 static int
2804 blacklist_file_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2805 {
2806   struct BlacklistContext *blacklist_ctx = cls;
2807   struct GNUNET_TESTING_Daemon *peer = value;
2808   struct GNUNET_PeerIdentity *temppeer;
2809   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2810
2811   temppeer = &peer->id;
2812   GNUNET_CRYPTO_hash_to_enc (&temppeer->hashPubKey, &peer_enc);
2813   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Writing entry %s:%s to file\n",
2814               blacklist_ctx->transport, (char *) &peer_enc);
2815   FPRINTF (blacklist_ctx->temp_file_handle, "%s:%s\n", blacklist_ctx->transport,
2816            (char *) &peer_enc);
2817
2818   return GNUNET_YES;
2819 }
2820 #endif
2821
2822 /*
2823  * Create the friend files based on the PeerConnection's
2824  * of each peer in the peer group, and copy the files
2825  * to the appropriate place
2826  *
2827  * @param pg the peer group we are dealing with
2828  */
2829 static int
2830 create_and_copy_friend_files (struct GNUNET_TESTING_PeerGroup *pg)
2831 {
2832   FILE *temp_friend_handle;
2833   unsigned int pg_iter;
2834   char *temp_service_path;
2835   struct GNUNET_OS_Process **procarr;
2836   char *arg;
2837   char *mytemp;
2838
2839 #if NOT_STUPID
2840   enum GNUNET_OS_ProcessStatusType type;
2841   unsigned long return_code;
2842   int count;
2843   int max_wait = 10;
2844 #endif
2845   int ret;
2846
2847   ret = GNUNET_OK;
2848 #if OLD
2849   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2850   struct PeerConnection *conn_iter;
2851 #endif
2852   procarr = GNUNET_malloc (sizeof (struct GNUNET_OS_Process *) * pg->total);
2853   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2854   {
2855     mytemp = GNUNET_DISK_mktemp ("friends");
2856     GNUNET_assert (mytemp != NULL);
2857     temp_friend_handle = FOPEN (mytemp, "wt");
2858     GNUNET_assert (temp_friend_handle != NULL);
2859 #if OLD
2860     conn_iter = pg->peers[pg_iter].allowed_peers_head;
2861     while (conn_iter != NULL)
2862     {
2863       GNUNET_CRYPTO_hash_to_enc (&pg->peers[conn_iter->index].daemon->
2864                                  id.hashPubKey, &peer_enc);
2865       FPRINTF (temp_friend_handle, "%s\n", (char *) &peer_enc);
2866       conn_iter = conn_iter->next;
2867     }
2868 #else
2869     GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].allowed_peers,
2870                                            &friend_file_iterator,
2871                                            temp_friend_handle);
2872 #endif
2873     FCLOSE (temp_friend_handle);
2874
2875     if (GNUNET_OK !=
2876         GNUNET_CONFIGURATION_get_value_string (pg->peers[pg_iter].daemon->cfg,
2877                                                "PATHS", "SERVICEHOME",
2878                                                &temp_service_path))
2879     {
2880       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2881                   _
2882                   ("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
2883                   "SERVICEHOME", "PATHS");
2884       if (UNLINK (mytemp) != 0)
2885         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", mytemp);
2886       GNUNET_free (mytemp);
2887       break;
2888     }
2889
2890     if (pg->peers[pg_iter].daemon->hostname == NULL)    /* Local, just copy the file */
2891     {
2892       GNUNET_asprintf (&arg, "%s/friends", temp_service_path);
2893       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2894                   "Copying file with RENAME(%s,%s)\n", mytemp, arg);
2895       RENAME (mytemp, arg);
2896       procarr[pg_iter] = NULL;
2897       GNUNET_free (arg);
2898     }
2899     else                        /* Remote, scp the file to the correct place */
2900     {
2901       if (NULL != pg->peers[pg_iter].daemon->username)
2902         GNUNET_asprintf (&arg, "%s@%s:%s/friends",
2903                          pg->peers[pg_iter].daemon->username,
2904                          pg->peers[pg_iter].daemon->hostname,
2905                          temp_service_path);
2906       else
2907         GNUNET_asprintf (&arg, "%s:%s/friends",
2908                          pg->peers[pg_iter].daemon->hostname,
2909                          temp_service_path);
2910       procarr[pg_iter] =
2911         GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "scp", "scp", mytemp, arg, NULL);
2912       GNUNET_assert (procarr[pg_iter] != NULL);
2913       ret = GNUNET_OS_process_wait (procarr[pg_iter]);  /* FIXME: schedule this, throttle! */
2914       GNUNET_OS_process_destroy (procarr[pg_iter]);
2915       if (ret != GNUNET_OK)
2916       {
2917         /* FIXME: free contents of 'procarr' array */
2918         GNUNET_free (procarr);
2919         GNUNET_free (temp_service_path);
2920         GNUNET_free (mytemp);
2921         GNUNET_free (arg);
2922         return ret;
2923       }
2924       procarr[pg_iter] = NULL;
2925       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2926                   "Copying file with command scp %s %s\n", mytemp, arg);
2927       GNUNET_free (arg);
2928     }
2929     GNUNET_free (temp_service_path);
2930     GNUNET_free (mytemp);
2931   }
2932
2933 #if NOT_STUPID
2934   count = 0;
2935   ret = GNUNET_SYSERR;
2936   while ((count < max_wait) && (ret != GNUNET_OK))
2937   {
2938     ret = GNUNET_OK;
2939     for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2940     {
2941       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Checking copy status of file %d\n",
2942                   pg_iter);
2943       if (procarr[pg_iter] != NULL)     /* Check for already completed! */
2944       {
2945         if (GNUNET_OS_process_status (procarr[pg_iter], &type, &return_code) !=
2946             GNUNET_OK)
2947         {
2948           ret = GNUNET_SYSERR;
2949         }
2950         else if ((type != GNUNET_OS_PROCESS_EXITED) || (return_code != 0))
2951         {
2952           ret = GNUNET_SYSERR;
2953         }
2954         else
2955         {
2956           GNUNET_OS_process_destroy (procarr[pg_iter]);
2957           procarr[pg_iter] = NULL;
2958           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "File %d copied\n", pg_iter);
2959         }
2960       }
2961     }
2962     count++;
2963     if (ret == GNUNET_SYSERR)
2964     {
2965       /* FIXME: why sleep here? -CG */
2966       sleep (1);
2967     }
2968   }
2969
2970   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2971               "Finished copying all friend files!\n");
2972 #endif
2973   GNUNET_free (procarr);
2974   return ret;
2975 }
2976
2977 /*
2978  * Create the blacklist files based on the PeerConnection's
2979  * of each peer in the peer group, and copy the files
2980  * to the appropriate place.
2981  *
2982  * @param pg the peer group we are dealing with
2983  * @param transports space delimited list of transports to blacklist
2984  */
2985 static int
2986 create_and_copy_blacklist_files (struct GNUNET_TESTING_PeerGroup *pg,
2987                                  const char *transports)
2988 {
2989   FILE *temp_file_handle;
2990   unsigned int pg_iter;
2991   char *temp_service_path;
2992   struct GNUNET_OS_Process **procarr;
2993   char *arg;
2994   char *mytemp;
2995   enum GNUNET_OS_ProcessStatusType type;
2996   unsigned long return_code;
2997   int count;
2998   int ret;
2999   int max_wait = 10;
3000   int transport_len;
3001   unsigned int i;
3002   char *pos;
3003   char *temp_transports;
3004
3005 #if OLD
3006   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
3007   struct PeerConnection *conn_iter;
3008 #else
3009   static struct BlacklistContext blacklist_ctx;
3010 #endif
3011
3012   procarr = GNUNET_malloc (sizeof (struct GNUNET_OS_Process *) * pg->total);
3013   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3014   {
3015     mytemp = GNUNET_DISK_mktemp ("blacklist");
3016     GNUNET_assert (mytemp != NULL);
3017     temp_file_handle = FOPEN (mytemp, "wt");
3018     GNUNET_assert (temp_file_handle != NULL);
3019     temp_transports = GNUNET_strdup (transports);
3020 #if !OLD
3021     blacklist_ctx.temp_file_handle = temp_file_handle;
3022 #endif
3023     transport_len = strlen (temp_transports) + 1;
3024     pos = NULL;
3025
3026     for (i = 0; i < transport_len; i++)
3027     {
3028       if ((temp_transports[i] == ' ') && (pos == NULL))
3029         continue;               /* At start of string (whitespace) */
3030       else if ((temp_transports[i] == ' ') || (temp_transports[i] == '\0'))     /* At end of string */
3031       {
3032         temp_transports[i] = '\0';
3033 #if OLD
3034         conn_iter = pg->peers[pg_iter].blacklisted_peers_head;
3035         while (conn_iter != NULL)
3036         {
3037           GNUNET_CRYPTO_hash_to_enc (&pg->peers[conn_iter->index].daemon->
3038                                      id.hashPubKey, &peer_enc);
3039           FPRINTF (temp_file_handle, "%s:%s\n", pos, (char *) &peer_enc);
3040           conn_iter = conn_iter->next;
3041         }
3042 #else
3043         blacklist_ctx.transport = pos;
3044         (void) GNUNET_CONTAINER_multihashmap_iterate (pg->
3045                                                       peers
3046                                                       [pg_iter].blacklisted_peers,
3047                                                       &blacklist_file_iterator,
3048                                                       &blacklist_ctx);
3049 #endif
3050         pos = NULL;
3051       }                         /* At beginning of actual string */
3052       else if (pos == NULL)
3053       {
3054         pos = &temp_transports[i];
3055       }
3056     }
3057
3058     GNUNET_free (temp_transports);
3059     FCLOSE (temp_file_handle);
3060
3061     if (GNUNET_OK !=
3062         GNUNET_CONFIGURATION_get_value_string (pg->peers[pg_iter].daemon->cfg,
3063                                                "PATHS", "SERVICEHOME",
3064                                                &temp_service_path))
3065     {
3066       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3067                   _
3068                   ("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
3069                   "SERVICEHOME", "PATHS");
3070       if (UNLINK (mytemp) != 0)
3071         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", mytemp);
3072       GNUNET_free (mytemp);
3073       break;
3074     }
3075
3076     if (pg->peers[pg_iter].daemon->hostname == NULL)    /* Local, just copy the file */
3077     {
3078       GNUNET_asprintf (&arg, "%s/blacklist", temp_service_path);
3079       RENAME (mytemp, arg);
3080       procarr[pg_iter] = NULL;
3081       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3082                   "Copying file with RENAME (%s,%s)\n", mytemp, arg);
3083       GNUNET_free (arg);
3084     }
3085     else                        /* Remote, scp the file to the correct place */
3086     {
3087       if (NULL != pg->peers[pg_iter].daemon->username)
3088         GNUNET_asprintf (&arg, "%s@%s:%s/blacklist",
3089                          pg->peers[pg_iter].daemon->username,
3090                          pg->peers[pg_iter].daemon->hostname,
3091                          temp_service_path);
3092       else
3093         GNUNET_asprintf (&arg, "%s:%s/blacklist",
3094                          pg->peers[pg_iter].daemon->hostname,
3095                          temp_service_path);
3096       procarr[pg_iter] =
3097         GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "scp", "scp", mytemp, arg, NULL);
3098       GNUNET_assert (procarr[pg_iter] != NULL);
3099       GNUNET_OS_process_wait (procarr[pg_iter]);        /* FIXME: add scheduled blacklist file copy that parallelizes file copying! */
3100
3101       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3102                   "Copying file with command scp %s %s\n", mytemp, arg);
3103       GNUNET_free (arg);
3104     }
3105     GNUNET_free (temp_service_path);
3106     GNUNET_free (mytemp);
3107   }
3108
3109   count = 0;
3110   ret = GNUNET_SYSERR;
3111   while ((count < max_wait) && (ret != GNUNET_OK))
3112   {
3113     ret = GNUNET_OK;
3114     for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3115     {
3116       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3117                   "Checking copy status of file %d\n", pg_iter);
3118       if (procarr[pg_iter] != NULL)     /* Check for already completed! */
3119       {
3120         if (GNUNET_OS_process_status (procarr[pg_iter], &type, &return_code) !=
3121             GNUNET_OK)
3122         {
3123           ret = GNUNET_SYSERR;
3124         }
3125         else if ((type != GNUNET_OS_PROCESS_EXITED) || (return_code != 0))
3126         {
3127           ret = GNUNET_SYSERR;
3128         }
3129         else
3130         {
3131           GNUNET_OS_process_destroy (procarr[pg_iter]);
3132           procarr[pg_iter] = NULL;
3133           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "File %d copied\n", pg_iter);
3134         }
3135       }
3136     }
3137     count++;
3138     if (ret == GNUNET_SYSERR)
3139     {
3140       /* FIXME: why sleep here? -CG */
3141       sleep (1);
3142     }
3143   }
3144
3145   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3146               "Finished copying all blacklist files!\n");
3147   GNUNET_free (procarr);
3148   return ret;
3149 }
3150
3151 /* Forward Declaration */
3152 static void
3153 schedule_connect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
3154
3155 /**
3156  * Choose a random peer's next connection to create, and
3157  * call schedule_connect to set up the connect task.
3158  *
3159  * @param pg the peer group to connect
3160  */
3161 static void
3162 preschedule_connect (struct GNUNET_TESTING_PeerGroup *pg)
3163 {
3164   struct ConnectTopologyContext *ct_ctx = &pg->ct_ctx;
3165   struct PeerConnection *connection_iter;
3166   struct ConnectContext *connect_context;
3167   uint32_t random_peer;
3168
3169   if (ct_ctx->remaining_connections == 0)
3170     return;
3171   random_peer =
3172       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, pg->total);
3173   while (pg->peers[random_peer].connect_peers_head == NULL)
3174     random_peer =
3175         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, pg->total);
3176
3177   connection_iter = pg->peers[random_peer].connect_peers_head;
3178   connect_context = GNUNET_malloc (sizeof (struct ConnectContext));
3179   connect_context->first_index = random_peer;
3180   connect_context->second_index = connection_iter->index;
3181   connect_context->ct_ctx = ct_ctx;
3182   connect_context->task =
3183       GNUNET_SCHEDULER_add_now (&schedule_connect, connect_context);
3184   GNUNET_CONTAINER_DLL_insert (pg->cc_head, pg->cc_tail, connect_context);
3185   GNUNET_CONTAINER_DLL_remove (pg->peers[random_peer].connect_peers_head,
3186                                pg->peers[random_peer].connect_peers_tail,
3187                                connection_iter);
3188   GNUNET_free (connection_iter);
3189   ct_ctx->remaining_connections--;
3190 }
3191
3192 #if USE_SEND_HELLOS
3193 /* Forward declaration */
3194 static void
3195 schedule_send_hellos (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
3196
3197 /**
3198  * Close connections and free the hello context.
3199  *
3200  * @param cls the 'struct SendHelloContext *'
3201  * @param tc scheduler context
3202  */
3203 static void
3204 free_hello_context (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3205 {
3206   struct SendHelloContext *send_hello_context = cls;
3207
3208   if (send_hello_context->peer->daemon->server != NULL)
3209   {
3210     GNUNET_CORE_disconnect (send_hello_context->peer->daemon->server);
3211     send_hello_context->peer->daemon->server = NULL;
3212   }
3213   if (send_hello_context->peer->daemon->th != NULL)
3214   {
3215     GNUNET_TRANSPORT_disconnect (send_hello_context->peer->daemon->th);
3216     send_hello_context->peer->daemon->th = NULL;
3217   }
3218   if (send_hello_context->core_connect_task != GNUNET_SCHEDULER_NO_TASK)
3219   {
3220     GNUNET_SCHEDULER_cancel (send_hello_context->core_connect_task);
3221     send_hello_context->core_connect_task = GNUNET_SCHEDULER_NO_TASK;
3222   }
3223   send_hello_context->pg->outstanding_connects--;
3224   GNUNET_free (send_hello_context);
3225 }
3226
3227 /**
3228  * For peers that haven't yet connected, notify
3229  * the caller that they have failed (timeout).
3230  *
3231  * @param cls the 'struct SendHelloContext *'
3232  * @param tc scheduler context
3233  */
3234 static void
3235 notify_remaining_connections_failed (void *cls,
3236                                      const struct GNUNET_SCHEDULER_TaskContext
3237                                      *tc)
3238 {
3239   struct SendHelloContext *send_hello_context = cls;
3240   struct GNUNET_TESTING_PeerGroup *pg = send_hello_context->pg;
3241   struct PeerConnection *connection;
3242
3243   GNUNET_CORE_disconnect (send_hello_context->peer->daemon->server);
3244   send_hello_context->peer->daemon->server = NULL;
3245
3246   connection = send_hello_context->peer->connect_peers_head;
3247
3248   while (connection != NULL)
3249   {
3250     if (pg->notify_connection != NULL)
3251     {
3252       pg->notify_connection (pg->notify_connection_cls, &send_hello_context->peer->daemon->id, &pg->peers[connection->index].daemon->id, 0,     /* FIXME */
3253                              send_hello_context->peer->daemon->cfg,
3254                              pg->peers[connection->index].daemon->cfg,
3255                              send_hello_context->peer->daemon,
3256                              pg->peers[connection->index].daemon,
3257                              "Peers failed to connect (timeout)");
3258     }
3259     GNUNET_CONTAINER_DLL_remove (send_hello_context->peer->connect_peers_head,
3260                                  send_hello_context->peer->connect_peers_tail,
3261                                  connection);
3262     GNUNET_free (connection);
3263     connection = connection->next;
3264   }
3265   GNUNET_SCHEDULER_add_now (&free_hello_context, send_hello_context);
3266 #if BAD
3267   other_peer = &pg->peers[connection->index];
3268 #endif
3269 }
3270
3271 /**
3272  * For peers that haven't yet connected, send
3273  * CORE connect requests.
3274  *
3275  * @param cls the 'struct SendHelloContext *'
3276  * @param tc scheduler context
3277  */
3278 static void
3279 send_core_connect_requests (void *cls,
3280                             const struct GNUNET_SCHEDULER_TaskContext *tc)
3281 {
3282   struct SendHelloContext *send_hello_context = cls;
3283   struct PeerConnection *conn;
3284
3285   GNUNET_assert (send_hello_context->peer->daemon->server != NULL);
3286
3287   send_hello_context->core_connect_task = GNUNET_SCHEDULER_NO_TASK;
3288
3289   send_hello_context->connect_attempts++;
3290   if (send_hello_context->connect_attempts <
3291       send_hello_context->pg->ct_ctx.connect_attempts)
3292   {
3293     conn = send_hello_context->peer->connect_peers_head;
3294     while (conn != NULL)
3295     {
3296       GNUNET_TRANSPORT_try_connect (send_hello_context->peer->daemon->th,
3297                                     &send_hello_context->pg->peers[conn->
3298                                                                    index].daemon->
3299                                     id);
3300       conn = conn->next;
3301     }
3302     send_hello_context->core_connect_task =
3303         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
3304                                       (send_hello_context->pg->
3305                                        ct_ctx.connect_timeout,
3306                                        send_hello_context->pg->
3307                                        ct_ctx.connect_attempts),
3308                                       &send_core_connect_requests,
3309                                       send_hello_context);
3310   }
3311   else
3312   {
3313     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3314                 "Timeout before all connections created, marking rest as failed!\n");
3315     GNUNET_SCHEDULER_add_now (&notify_remaining_connections_failed,
3316                               send_hello_context);
3317   }
3318
3319 }
3320
3321 /**
3322  * Success, connection is up.  Signal client our success.
3323  *
3324  * @param cls our "struct SendHelloContext"
3325  * @param peer identity of the peer that has connected
3326  * @param atsi performance information
3327  *
3328  * FIXME: remove peers from BOTH lists, call notify twice, should
3329  * double the speed of connections as long as the list iteration
3330  * doesn't take too long!
3331  */
3332 static void
3333 core_connect_notify (void *cls, const struct GNUNET_PeerIdentity *peer,
3334                      const struct GNUNET_ATS_Information *atsi)
3335 {
3336   struct SendHelloContext *send_hello_context = cls;
3337   struct PeerConnection *connection;
3338   struct GNUNET_TESTING_PeerGroup *pg = send_hello_context->pg;
3339
3340 #if BAD
3341   struct PeerData *other_peer;
3342 #endif
3343   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected peer %s to peer %s\n",
3344               ctx->d1->shortname, GNUNET_i2s (peer));
3345   if (0 ==
3346       memcmp (&send_hello_context->peer->daemon->id, peer,
3347               sizeof (struct GNUNET_PeerIdentity)))
3348     return;
3349
3350   connection = send_hello_context->peer->connect_peers_head;
3351 #if BAD
3352   other_peer = NULL;
3353 #endif
3354
3355   while ((connection != NULL) &&
3356          (0 !=
3357           memcmp (&pg->peers[connection->index].daemon->id, peer,
3358                   sizeof (struct GNUNET_PeerIdentity))))
3359   {
3360     connection = connection->next;
3361   }
3362
3363   if (connection == NULL)
3364   {
3365     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3366                 "Connected peer %s to %s, not in list (no problem(?))\n",
3367                 GNUNET_i2s (peer), send_hello_context->peer->daemon->shortname);
3368   }
3369   else
3370   {
3371 #if BAD
3372     other_peer = &pg->peers[connection->index];
3373 #endif
3374     if (pg->notify_connection != NULL)
3375     {
3376       pg->notify_connection (pg->notify_connection_cls, &send_hello_context->peer->daemon->id, peer, 0, /* FIXME */
3377                              send_hello_context->peer->daemon->cfg,
3378                              pg->peers[connection->index].daemon->cfg,
3379                              send_hello_context->peer->daemon,
3380                              pg->peers[connection->index].daemon, NULL);
3381     }
3382     GNUNET_CONTAINER_DLL_remove (send_hello_context->peer->connect_peers_head,
3383                                  send_hello_context->peer->connect_peers_tail,
3384                                  connection);
3385     GNUNET_free (connection);
3386   }
3387
3388 #if BAD
3389   /* Notify of reverse connection and remove from other peers list of outstanding */
3390   if (other_peer != NULL)
3391   {
3392     connection = other_peer->connect_peers_head;
3393     while ((connection != NULL) &&
3394            (0 !=
3395             memcmp (&send_hello_context->peer->daemon->id,
3396                     &pg->peers[connection->index].daemon->id,
3397                     sizeof (struct GNUNET_PeerIdentity))))
3398     {
3399       connection = connection->next;
3400     }
3401     if (connection != NULL)
3402     {
3403       if (pg->notify_connection != NULL)
3404       {
3405         pg->notify_connection (pg->notify_connection_cls, peer, &send_hello_context->peer->daemon->id, 0,       /* FIXME */
3406                                pg->peers[connection->index].daemon->cfg,
3407                                send_hello_context->peer->daemon->cfg,
3408                                pg->peers[connection->index].daemon,
3409                                send_hello_context->peer->daemon, NULL);
3410       }
3411
3412       GNUNET_CONTAINER_DLL_remove (other_peer->connect_peers_head,
3413                                    other_peer->connect_peers_tail, connection);
3414       GNUNET_free (connection);
3415     }
3416   }
3417 #endif
3418
3419   if (send_hello_context->peer->connect_peers_head == NULL)
3420   {
3421     GNUNET_SCHEDULER_add_now (&free_hello_context, send_hello_context);
3422   }
3423 }
3424
3425 /**
3426  * Notify of a successful connection to the core service.
3427  *
3428  * @param cls a struct SendHelloContext *
3429  * @param server handle to the core service
3430  * @param my_identity the peer identity of this peer
3431  */
3432 void
3433 core_init (void *cls, struct GNUNET_CORE_Handle *server,
3434            struct GNUNET_PeerIdentity *my_identity)
3435 {
3436   struct SendHelloContext *send_hello_context = cls;
3437
3438   send_hello_context->core_ready = GNUNET_YES;
3439 }
3440
3441 /**
3442  * Function called once a hello has been sent
3443  * to the transport, move on to the next one
3444  * or go away forever.
3445  *
3446  * @param cls the 'struct SendHelloContext *'
3447  * @param tc scheduler context
3448  */
3449 static void
3450 hello_sent_callback (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3451 {
3452   struct SendHelloContext *send_hello_context = cls;
3453
3454   //unsigned int pg_iter;
3455   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3456   {
3457     GNUNET_free (send_hello_context);
3458     return;
3459   }
3460
3461   send_hello_context->pg->remaining_hellos--;
3462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent HELLO, have %d remaining!\n",
3463               send_hello_context->pg->remaining_hellos);
3464   if (send_hello_context->peer_pos == NULL)     /* All HELLOs (for this peer!) have been transmitted! */
3465   {
3466     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3467                 "All hellos for this peer sent, disconnecting transport!\n");
3468     GNUNET_assert (send_hello_context->peer->daemon->th != NULL);
3469     GNUNET_TRANSPORT_disconnect (send_hello_context->peer->daemon->th);
3470     send_hello_context->peer->daemon->th = NULL;
3471     GNUNET_assert (send_hello_context->peer->daemon->server == NULL);
3472     send_hello_context->peer->daemon->server =
3473         GNUNET_CORE_connect (send_hello_context->peer->cfg, 1,
3474                              send_hello_context, &core_init,
3475                              &core_connect_notify, NULL, NULL, NULL, GNUNET_NO,
3476                              NULL, GNUNET_NO, no_handlers);
3477
3478     send_hello_context->core_connect_task =
3479         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
3480                                       (send_hello_context->pg->
3481                                        ct_ctx.connect_timeout,
3482                                        send_hello_context->pg->
3483                                        ct_ctx.connect_attempts),
3484                                       &send_core_connect_requests,
3485                                       send_hello_context);
3486   }
3487   else
3488     GNUNET_SCHEDULER_add_now (&schedule_send_hellos, send_hello_context);
3489 }
3490
3491 /**
3492  * Connect to a peer, give it all the HELLO's of those peers
3493  * we will later ask it to connect to.
3494  *
3495  * @param ct_ctx the overall connection context
3496  */
3497 static void
3498 schedule_send_hellos (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3499 {
3500   struct SendHelloContext *send_hello_context = cls;
3501   struct GNUNET_TESTING_PeerGroup *pg = send_hello_context->pg;
3502
3503   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3504   {
3505     GNUNET_free (send_hello_context);
3506     return;
3507   }
3508
3509   GNUNET_assert (send_hello_context->peer_pos != NULL); /* All of the HELLO sends to be scheduled have been scheduled! */
3510
3511   if (((send_hello_context->peer->daemon->th == NULL) &&
3512        (pg->outstanding_connects > pg->max_outstanding_connections)) ||
3513       (pg->stop_connects == GNUNET_YES))
3514   {
3515     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3516                 "Delaying connect, we have too many outstanding connections!\n");
3517     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3518                                   (GNUNET_TIME_UNIT_MILLISECONDS, 100),
3519                                   &schedule_send_hellos, send_hello_context);
3520   }
3521   else
3522   {
3523     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3524                 "Creating connection, outstanding_connections is %d\n",
3525                 outstanding_connects);
3526     if (send_hello_context->peer->daemon->th == NULL)
3527     {
3528       pg->outstanding_connects++;       /* Actual TRANSPORT, CORE connections! */
3529       send_hello_context->peer->daemon->th =
3530           GNUNET_TRANSPORT_connect (send_hello_context->peer->cfg, NULL,
3531                                     send_hello_context, NULL, NULL, NULL);
3532     }
3533     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3534                 "Offering HELLO of peer %s to peer %s\n",
3535                 send_hello_context->peer->daemon->shortname,
3536                 pg->peers[send_hello_context->peer_pos->index].
3537                 daemon->shortname);
3538     GNUNET_TRANSPORT_offer_hello (send_hello_context->peer->daemon->th,
3539                                   (const struct GNUNET_MessageHeader *)
3540                                   pg->peers[send_hello_context->peer_pos->
3541                                             index].daemon->hello,
3542                                   &hello_sent_callback, send_hello_context);
3543     send_hello_context->peer_pos = send_hello_context->peer_pos->next;
3544     GNUNET_assert (send_hello_context->peer->daemon->th != NULL);
3545   }
3546 }
3547 #endif
3548
3549 /**
3550  * Internal notification of a connection, kept so that we can ensure some connections
3551  * happen instead of flooding all testing daemons with requests to connect.
3552  */
3553 static void
3554 internal_connect_notify (void *cls, const struct GNUNET_PeerIdentity *first,
3555                          const struct GNUNET_PeerIdentity *second,
3556                          uint32_t distance,
3557                          const struct GNUNET_CONFIGURATION_Handle *first_cfg,
3558                          const struct GNUNET_CONFIGURATION_Handle *second_cfg,
3559                          struct GNUNET_TESTING_Daemon *first_daemon,
3560                          struct GNUNET_TESTING_Daemon *second_daemon,
3561                          const char *emsg)
3562 {
3563   struct ConnectContext *connect_ctx = cls;
3564   struct ConnectTopologyContext *ct_ctx = connect_ctx->ct_ctx;
3565   struct GNUNET_TESTING_PeerGroup *pg = ct_ctx->pg;
3566   struct PeerConnection *connection;
3567
3568   GNUNET_assert (NULL != connect_ctx->cc);
3569   connect_ctx->cc = NULL;
3570   GNUNET_assert (0 < pg->outstanding_connects);
3571   pg->outstanding_connects--;
3572   GNUNET_CONTAINER_DLL_remove (pg->cc_head, pg->cc_tail, connect_ctx);
3573   /*
3574    * Check whether the inverse connection has been scheduled yet,
3575    * if not, we can remove it from the other peers list and avoid
3576    * even trying to connect them again!
3577    */
3578   connection = pg->peers[connect_ctx->second_index].connect_peers_head;
3579 #if BAD
3580   other_peer = NULL;
3581 #endif
3582
3583   while ((connection != NULL) &&
3584          (0 !=
3585           memcmp (first, &pg->peers[connection->index].daemon->id,
3586                   sizeof (struct GNUNET_PeerIdentity))))
3587     connection = connection->next;
3588
3589   if (connection != NULL)       /* Can safely remove! */
3590   {
3591     GNUNET_assert (0 < ct_ctx->remaining_connections);
3592     ct_ctx->remaining_connections--;
3593     if (pg->notify_connection != NULL)  /* Notify of reverse connection */
3594       pg->notify_connection (pg->notify_connection_cls, second, first, distance,
3595                              second_cfg, first_cfg, second_daemon, first_daemon,
3596                              emsg);
3597
3598     GNUNET_CONTAINER_DLL_remove (pg->
3599                                  peers[connect_ctx->
3600                                        second_index].connect_peers_head,
3601                                  pg->peers[connect_ctx->
3602                                            second_index].connect_peers_tail,
3603                                  connection);
3604     GNUNET_free (connection);
3605   }
3606
3607   if (ct_ctx->remaining_connections == 0)
3608   {
3609     if (ct_ctx->notify_connections_done != NULL)
3610     {
3611       ct_ctx->notify_connections_done (ct_ctx->notify_cls, NULL);
3612       ct_ctx->notify_connections_done = NULL;
3613     }
3614   }
3615   else
3616     preschedule_connect (pg);
3617
3618   if (pg->notify_connection != NULL)
3619     pg->notify_connection (pg->notify_connection_cls, first, second, distance,
3620                            first_cfg, second_cfg, first_daemon, second_daemon,
3621                            emsg);
3622   GNUNET_free (connect_ctx);
3623 }
3624
3625 /**
3626  * Either delay a connection (because there are too many outstanding)
3627  * or schedule it for right now.
3628  *
3629  * @param cls a connection context
3630  * @param tc the task runtime context
3631  */
3632 static void
3633 schedule_connect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3634 {
3635   struct ConnectContext *connect_context = cls;
3636   struct GNUNET_TESTING_PeerGroup *pg = connect_context->ct_ctx->pg;
3637
3638   connect_context->task = GNUNET_SCHEDULER_NO_TASK;
3639   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3640     return;
3641
3642   if ((pg->outstanding_connects > pg->max_outstanding_connections) ||
3643       (pg->stop_connects == GNUNET_YES))
3644   {
3645     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3646                 "Delaying connect, we have too many outstanding connections!\n");
3647     connect_context->task =
3648         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3649                                       (GNUNET_TIME_UNIT_MILLISECONDS, 100),
3650                                       &schedule_connect, connect_context);
3651     return;
3652   }
3653   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3654               "Creating connection, outstanding_connections is %d (max %d)\n",
3655               pg->outstanding_connects, pg->max_outstanding_connections);
3656   pg->outstanding_connects++;
3657   pg->total_connects_scheduled++;
3658   GNUNET_assert (NULL == connect_context->cc);
3659   connect_context->cc =
3660       GNUNET_TESTING_daemons_connect (pg->
3661                                       peers[connect_context->
3662                                             first_index].daemon,
3663                                       pg->peers[connect_context->
3664                                                 second_index].daemon,
3665                                       connect_context->ct_ctx->connect_timeout,
3666                                       connect_context->ct_ctx->connect_attempts,
3667 #if USE_SEND_HELLOS
3668                                       GNUNET_NO,
3669 #else
3670                                       GNUNET_YES,
3671 #endif
3672                                       &internal_connect_notify,
3673                                       connect_context);
3674
3675 }
3676
3677 #if !OLD
3678 /**
3679  * Iterator for actually scheduling connections to be created
3680  * between two peers.
3681  *
3682  * @param cls closure, a GNUNET_TESTING_Daemon
3683  * @param key the key the second Daemon was stored under
3684  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
3685  *
3686  * @return GNUNET_YES to continue iteration
3687  */
3688 static int
3689 connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
3690 {
3691   struct ConnectTopologyContext *ct_ctx = cls;
3692   struct PeerData *first = ct_ctx->first;
3693   struct GNUNET_TESTING_Daemon *second = value;
3694   struct ConnectContext *connect_context;
3695
3696   connect_context = GNUNET_malloc (sizeof (struct ConnectContext));
3697   connect_context->first = first->daemon;
3698   connect_context->second = second;
3699   connect_context->ct_ctx = ct_ctx;
3700   connect_context->task =
3701       GNUNET_SCHEDULER_add_now (&schedule_connect, connect_context);
3702   GNUNET_CONTAINER_DLL_insert (ct_ctx->pg->cc_head, ct_ctx->pg->cc_tail,
3703                                connect_context);
3704   return GNUNET_YES;
3705 }
3706 #endif
3707
3708 #if !OLD
3709 /**
3710  * Iterator for copying all entries in the allowed hashmap to the
3711  * connect hashmap.
3712  *
3713  * @param cls closure, a GNUNET_TESTING_Daemon
3714  * @param key the key the second Daemon was stored under
3715  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
3716  *
3717  * @return GNUNET_YES to continue iteration
3718  */
3719 static int
3720 copy_topology_iterator (void *cls, const GNUNET_HashCode * key, void *value)
3721 {
3722   struct PeerData *first = cls;
3723
3724   GNUNET_assert (GNUNET_OK ==
3725                  GNUNET_CONTAINER_multihashmap_put (first->connect_peers, key,
3726                                                     value,
3727                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3728
3729   return GNUNET_YES;
3730 }
3731 #endif
3732
3733 /**
3734  * Make the peers to connect the same as those that are allowed to be
3735  * connected.
3736  *
3737  * @param pg the peer group
3738  */
3739 static int
3740 copy_allowed_topology (struct GNUNET_TESTING_PeerGroup *pg)
3741 {
3742   unsigned int pg_iter;
3743   int ret;
3744   int total;
3745
3746 #if OLD
3747   struct PeerConnection *iter;
3748 #endif
3749   total = 0;
3750   ret = 0;
3751   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3752   {
3753 #if OLD
3754     iter = pg->peers[pg_iter].allowed_peers_head;
3755     while (iter != NULL)
3756     {
3757       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3758                   "Creating connection between %d and %d\n", pg_iter,
3759                   iter->index);
3760       total += add_connections (pg, pg_iter, iter->index, CONNECT, GNUNET_YES);
3761       //total += add_actual_connections(pg, pg_iter, iter->index);
3762       iter = iter->next;
3763     }
3764 #else
3765     ret =
3766         GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].allowed_peers,
3767                                                &copy_topology_iterator,
3768                                                &pg->peers[pg_iter]);
3769 #endif
3770     if (GNUNET_SYSERR == ret)
3771       return GNUNET_SYSERR;
3772
3773     total = total + ret;
3774   }
3775
3776   return total;
3777 }
3778
3779 /**
3780  * Connect the topology as specified by the PeerConnection's
3781  * of each peer in the peer group
3782  *
3783  * @param pg the peer group we are dealing with
3784  * @param connect_timeout how long try connecting two peers
3785  * @param connect_attempts how many times (max) to attempt
3786  * @param notify_callback callback to notify when finished
3787  * @param notify_cls closure for notify callback
3788  *
3789  * @return the number of connections that will be attempted
3790  */
3791 static int
3792 connect_topology (struct GNUNET_TESTING_PeerGroup *pg,
3793                   struct GNUNET_TIME_Relative connect_timeout,
3794                   unsigned int connect_attempts,
3795                   GNUNET_TESTING_NotifyCompletion notify_callback,
3796                   void *notify_cls)
3797 {
3798   unsigned int pg_iter;
3799   unsigned int total;
3800
3801 #if OLD
3802   struct PeerConnection *connection_iter;
3803 #endif
3804 #if USE_SEND_HELLOS
3805   struct SendHelloContext *send_hello_context;
3806 #endif
3807
3808   total = 0;
3809   pg->ct_ctx.notify_connections_done = notify_callback;
3810   pg->ct_ctx.notify_cls = notify_cls;
3811   pg->ct_ctx.pg = pg;
3812
3813   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3814   {
3815 #if OLD
3816     connection_iter = pg->peers[pg_iter].connect_peers_head;
3817     while (connection_iter != NULL)
3818     {
3819       connection_iter = connection_iter->next;
3820       total++;
3821     }
3822 #else
3823     total +=
3824         GNUNET_CONTAINER_multihashmap_size (pg->peers[pg_iter].connect_peers);
3825 #endif
3826   }
3827
3828   if (total == 0)
3829     return total;
3830
3831   pg->ct_ctx.connect_timeout = connect_timeout;
3832   pg->ct_ctx.connect_attempts = connect_attempts;
3833   pg->ct_ctx.remaining_connections = total;
3834
3835 #if USE_SEND_HELLOS
3836   /* First give all peers the HELLO's of other peers (connect to first peer's transport service, give HELLO's of other peers, continue...) */
3837   pg->remaining_hellos = total;
3838   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3839   {
3840     send_hello_context = GNUNET_malloc (sizeof (struct SendHelloContext));
3841     send_hello_context->peer = &pg->peers[pg_iter];
3842     send_hello_context->peer_pos = pg->peers[pg_iter].connect_peers_head;
3843     send_hello_context->pg = pg;
3844     GNUNET_SCHEDULER_add_now (&schedule_send_hellos, send_hello_context);
3845   }
3846 #else
3847   for (pg_iter = 0; pg_iter < pg->max_outstanding_connections; pg_iter++)
3848   {
3849     preschedule_connect (pg);
3850   }
3851 #endif
3852   return total;
3853
3854 }
3855
3856 /**
3857  * Takes a peer group and creates a topology based on the
3858  * one specified.  Creates a topology means generates friend
3859  * files for the peers so they can only connect to those allowed
3860  * by the topology.  This will only have an effect once peers
3861  * are started if the FRIENDS_ONLY option is set in the base
3862  * config.  Also takes an optional restrict topology which
3863  * disallows connections based on particular transports
3864  * UNLESS they are specified in the restricted topology.
3865  *
3866  * @param pg the peer group struct representing the running peers
3867  * @param topology which topology to connect the peers in
3868  * @param restrict_topology disallow restrict_transports transport
3869  *                          connections to peers NOT in this topology
3870  *                          use GNUNET_TESTING_TOPOLOGY_NONE for no restrictions
3871  * @param restrict_transports space delimited list of transports to blacklist
3872  *                            to create restricted topology
3873  *
3874  * @return the maximum number of connections were all allowed peers
3875  *         connected to each other
3876  */
3877 unsigned int
3878 GNUNET_TESTING_create_topology (struct GNUNET_TESTING_PeerGroup *pg,
3879                                 enum GNUNET_TESTING_Topology topology,
3880                                 enum GNUNET_TESTING_Topology restrict_topology,
3881                                 const char *restrict_transports)
3882 {
3883   int ret;
3884
3885   unsigned int num_connections;
3886   int unblacklisted_connections;
3887   char *filename;
3888   struct PeerConnection *conn_iter;
3889   struct PeerConnection *temp_conn;
3890   unsigned int off;
3891
3892 #if !OLD
3893   unsigned int i;
3894
3895   for (i = 0; i < pg->total; i++)
3896   {
3897     pg->peers[i].allowed_peers = GNUNET_CONTAINER_multihashmap_create (100);
3898     pg->peers[i].connect_peers = GNUNET_CONTAINER_multihashmap_create (100);
3899     pg->peers[i].blacklisted_peers = GNUNET_CONTAINER_multihashmap_create (100);
3900     pg->peers[i].pg = pg;
3901   }
3902 #endif
3903
3904   switch (topology)
3905   {
3906   case GNUNET_TESTING_TOPOLOGY_CLIQUE:
3907     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating clique topology\n");
3908     num_connections = create_clique (pg, &add_connections, ALLOWED, GNUNET_NO);
3909     break;
3910   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
3911     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3912                 "Creating small world (ring) topology\n");
3913     num_connections = create_small_world_ring (pg, &add_connections, ALLOWED);
3914     break;
3915   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
3916     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3917                 "Creating small world (2d-torus) topology\n");
3918     num_connections = create_small_world (pg, &add_connections, ALLOWED);
3919     break;
3920   case GNUNET_TESTING_TOPOLOGY_RING:
3921     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating ring topology\n");
3922     num_connections = create_ring (pg, &add_connections, ALLOWED);
3923     break;
3924   case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
3925     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating 2d torus topology\n");
3926     num_connections = create_2d_torus (pg, &add_connections, ALLOWED);
3927     break;
3928   case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
3929     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating Erdos-Renyi topology\n");
3930     num_connections = create_erdos_renyi (pg, &add_connections, ALLOWED);
3931     break;
3932   case GNUNET_TESTING_TOPOLOGY_INTERNAT:
3933     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating InterNAT topology\n");
3934     num_connections = create_nated_internet (pg, &add_connections, ALLOWED);
3935     break;
3936   case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
3937     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating Scale Free topology\n");
3938     num_connections = create_scale_free (pg, &add_connections, ALLOWED);
3939     break;
3940   case GNUNET_TESTING_TOPOLOGY_LINE:
3941     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3942                 "Creating straight line topology\n");
3943     num_connections = create_line (pg, &add_connections, ALLOWED);
3944     break;
3945   case GNUNET_TESTING_TOPOLOGY_FROM_FILE:
3946     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating topology from file!\n");
3947     if (GNUNET_OK ==
3948         GNUNET_CONFIGURATION_get_value_string (pg->cfg, "testing",
3949                                                "topology_file", &filename))
3950       num_connections =
3951           create_from_file (pg, filename, &add_connections, ALLOWED);
3952     else
3953     {
3954       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3955                   "Missing configuration option TESTING:TOPOLOGY_FILE for creating topology from file!\n");
3956       num_connections = 0;
3957     }
3958     break;
3959   case GNUNET_TESTING_TOPOLOGY_NONE:
3960     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3961                 _
3962                 ("Creating no allowed topology (all peers can connect at core level)\n"));
3963     num_connections = pg->total * pg->total;    /* Clique is allowed! */
3964     break;
3965   default:
3966     num_connections = 0;
3967     break;
3968   }
3969
3970   if (GNUNET_YES ==
3971       GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "TESTING", "F2F"))
3972   {
3973     ret = create_and_copy_friend_files (pg);
3974     if (ret != GNUNET_OK)
3975     {
3976       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3977                   "Failed during friend file copying!\n");
3978       return GNUNET_SYSERR;
3979     }
3980     else
3981     {
3982       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3983                   "Friend files created/copied successfully!\n");
3984     }
3985   }
3986
3987   /* Use the create clique method to initially set all connections as blacklisted. */
3988   if ((restrict_topology != GNUNET_TESTING_TOPOLOGY_NONE) &&
3989       (restrict_topology != GNUNET_TESTING_TOPOLOGY_FROM_FILE))
3990     create_clique (pg, &add_connections, BLACKLIST, GNUNET_NO);
3991   else
3992     return num_connections;
3993
3994   unblacklisted_connections = 0;
3995   /* Un-blacklist connections as per the topology specified */
3996   switch (restrict_topology)
3997   {
3998   case GNUNET_TESTING_TOPOLOGY_CLIQUE:
3999     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4000                 "Blacklisting all but clique topology\n");
4001     unblacklisted_connections =
4002         create_clique (pg, &remove_connections, BLACKLIST, GNUNET_NO);
4003     break;
4004   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
4005     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4006                 "Blacklisting all but small world (ring) topology\n");
4007     unblacklisted_connections =
4008         create_small_world_ring (pg, &remove_connections, BLACKLIST);
4009     break;
4010   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
4011     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4012                 "Blacklisting all but small world (2d-torus) topology\n");
4013     unblacklisted_connections =
4014         create_small_world (pg, &remove_connections, BLACKLIST);
4015     break;
4016   case GNUNET_TESTING_TOPOLOGY_RING:
4017     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4018                 "Blacklisting all but ring topology\n");
4019     unblacklisted_connections =
4020         create_ring (pg, &remove_connections, BLACKLIST);
4021     break;
4022   case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
4023     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4024                 "Blacklisting all but 2d torus topology\n");
4025     unblacklisted_connections =
4026         create_2d_torus (pg, &remove_connections, BLACKLIST);
4027     break;
4028   case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
4029     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4030                 "Blacklisting all but Erdos-Renyi topology\n");
4031     unblacklisted_connections =
4032         create_erdos_renyi (pg, &remove_connections, BLACKLIST);
4033     break;
4034   case GNUNET_TESTING_TOPOLOGY_INTERNAT:
4035     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4036                 "Blacklisting all but InterNAT topology\n");
4037
4038 #if TOPOLOGY_HACK
4039     for (off = 0; off < pg->total; off++)
4040     {
4041       conn_iter = pg->peers[off].allowed_peers_head;
4042       while (conn_iter != NULL)
4043       {
4044         temp_conn = conn_iter->next;
4045         GNUNET_free (conn_iter);
4046         conn_iter = temp_conn;
4047       }
4048       pg->peers[off].allowed_peers_head = NULL;
4049       pg->peers[off].allowed_peers_tail = NULL;
4050
4051       conn_iter = pg->peers[off].connect_peers_head;
4052       while (conn_iter != NULL)
4053       {
4054         temp_conn = conn_iter->next;
4055         GNUNET_free (conn_iter);
4056         conn_iter = temp_conn;
4057       }
4058       pg->peers[off].connect_peers_head = NULL;
4059       pg->peers[off].connect_peers_tail = NULL;
4060     }
4061     unblacklisted_connections =
4062         create_nated_internet_copy (pg, &remove_connections, BLACKLIST);
4063 #else
4064     unblacklisted_connections =
4065         create_nated_internet (pg, &remove_connections, BLACKLIST);
4066 #endif
4067
4068     break;
4069   case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
4070     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4071                 "Blacklisting all but Scale Free topology\n");
4072     unblacklisted_connections =
4073         create_scale_free (pg, &remove_connections, BLACKLIST);
4074     break;
4075   case GNUNET_TESTING_TOPOLOGY_LINE:
4076     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4077                 "Blacklisting all but straight line topology\n");
4078     unblacklisted_connections =
4079         create_line (pg, &remove_connections, BLACKLIST);
4080   default:
4081     break;
4082   }
4083
4084   if ((unblacklisted_connections > 0) && (restrict_transports != NULL))
4085   {
4086     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating blacklist with `%s'\n",
4087                 restrict_transports);
4088     ret = create_and_copy_blacklist_files (pg, restrict_transports);
4089     if (ret != GNUNET_OK)
4090     {
4091       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4092                   "Failed during blacklist file copying!\n");
4093       return 0;
4094     }
4095     else
4096     {
4097       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4098                   "Blacklist files created/copied successfully!\n");
4099     }
4100   }
4101   return num_connections;
4102 }
4103
4104 #if !OLD
4105 /**
4106  * Iterator for choosing random peers to connect.
4107  *
4108  * @param cls closure, a RandomContext
4109  * @param key the key the second Daemon was stored under
4110  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
4111  *
4112  * @return GNUNET_YES to continue iteration
4113  */
4114 static int
4115 random_connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
4116 {
4117   struct RandomContext *random_ctx = cls;
4118   double random_number;
4119   uint32_t second_pos;
4120   GNUNET_HashCode first_hash;
4121
4122   random_number =
4123       ((double)
4124        GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
4125                                  UINT64_MAX)) / ((double) UINT64_MAX);
4126   if (random_number < random_ctx->percentage)
4127   {
4128     GNUNET_assert (GNUNET_OK ==
4129                    GNUNET_CONTAINER_multihashmap_put (random_ctx->
4130                                                       first->connect_peers_working_set,
4131                                                       key, value,
4132                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4133   }
4134
4135   /* Now we have considered this particular connection, remove it from the second peer so it's not double counted */
4136   uid_from_hash (key, &second_pos);
4137   hash_from_uid (random_ctx->first_uid, &first_hash);
4138   GNUNET_assert (random_ctx->pg->total > second_pos);
4139   GNUNET_assert (GNUNET_YES ==
4140                  GNUNET_CONTAINER_multihashmap_remove (random_ctx->
4141                                                        pg->peers
4142                                                        [second_pos].connect_peers,
4143                                                        &first_hash,
4144                                                        random_ctx->
4145                                                        first->daemon));
4146
4147   return GNUNET_YES;
4148 }
4149
4150 /**
4151  * Iterator for adding at least X peers to a peers connection set.
4152  *
4153  * @param cls closure, MinimumContext
4154  * @param key the key the second Daemon was stored under
4155  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
4156  *
4157  * @return GNUNET_YES to continue iteration
4158  */
4159 static int
4160 minimum_connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
4161 {
4162   struct MinimumContext *min_ctx = cls;
4163   uint32_t second_pos;
4164   GNUNET_HashCode first_hash;
4165   unsigned int i;
4166
4167   if (GNUNET_CONTAINER_multihashmap_size
4168       (min_ctx->first->connect_peers_working_set) < min_ctx->num_to_add)
4169   {
4170     for (i = 0; i < min_ctx->num_to_add; i++)
4171     {
4172       if (min_ctx->pg_array[i] == min_ctx->current)
4173       {
4174         GNUNET_assert (GNUNET_OK ==
4175                        GNUNET_CONTAINER_multihashmap_put (min_ctx->
4176                                                           first->connect_peers_working_set,
4177                                                           key, value,
4178                                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4179         uid_from_hash (key, &second_pos);
4180         hash_from_uid (min_ctx->first_uid, &first_hash);
4181         GNUNET_assert (min_ctx->pg->total > second_pos);
4182         GNUNET_assert (GNUNET_OK ==
4183                        GNUNET_CONTAINER_multihashmap_put (min_ctx->
4184                                                           pg->peers
4185                                                           [second_pos].connect_peers_working_set,
4186                                                           &first_hash,
4187                                                           min_ctx->first->
4188                                                           daemon,
4189                                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4190         /* Now we have added this particular connection, remove it from the second peer's map so it's not double counted */
4191         GNUNET_assert (GNUNET_YES ==
4192                        GNUNET_CONTAINER_multihashmap_remove (min_ctx->
4193                                                              pg->peers
4194                                                              [second_pos].connect_peers,
4195                                                              &first_hash,
4196                                                              min_ctx->
4197                                                              first->daemon));
4198       }
4199     }
4200     min_ctx->current++;
4201     return GNUNET_YES;
4202   }
4203   else
4204     return GNUNET_NO;           /* We can stop iterating, we have enough peers! */
4205
4206 }
4207
4208 /**
4209  * Iterator for adding peers to a connection set based on a depth first search.
4210  *
4211  * @param cls closure, MinimumContext
4212  * @param key the key the second daemon was stored under
4213  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
4214  *
4215  * @return GNUNET_YES to continue iteration
4216  */
4217 static int
4218 dfs_connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
4219 {
4220   struct DFSContext *dfs_ctx = cls;
4221   GNUNET_HashCode first_hash;
4222
4223   if (dfs_ctx->current == dfs_ctx->chosen)
4224   {
4225     GNUNET_assert (GNUNET_OK ==
4226                    GNUNET_CONTAINER_multihashmap_put (dfs_ctx->
4227                                                       first->connect_peers_working_set,
4228                                                       key, value,
4229                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4230     uid_from_hash (key, &dfs_ctx->second_uid);
4231     hash_from_uid (dfs_ctx->first_uid, &first_hash);
4232     GNUNET_assert (GNUNET_OK ==
4233                    GNUNET_CONTAINER_multihashmap_put (dfs_ctx->
4234                                                       pg->peers[dfs_ctx->
4235                                                                 second_uid].connect_peers_working_set,
4236                                                       &first_hash,
4237                                                       dfs_ctx->first->daemon,
4238                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4239     GNUNET_assert (GNUNET_YES ==
4240                    GNUNET_CONTAINER_multihashmap_remove (dfs_ctx->
4241                                                          pg->peers
4242                                                          [dfs_ctx->second_uid].connect_peers,
4243                                                          &first_hash,
4244                                                          dfs_ctx->
4245                                                          first->daemon));
4246     /* Can't remove second from first yet because we are currently iterating, hence the return value in the DFSContext! */
4247     return GNUNET_NO;           /* We have found our peer, don't iterate more */
4248   }
4249
4250   dfs_ctx->current++;
4251   return GNUNET_YES;
4252 }
4253 #endif
4254
4255 /**
4256  * From the set of connections possible, choose percentage percent of connections
4257  * to actually connect.
4258  *
4259  * @param pg the peergroup we are dealing with
4260  * @param percentage what percent of total connections to make
4261  */
4262 void
4263 choose_random_connections (struct GNUNET_TESTING_PeerGroup *pg,
4264                            double percentage)
4265 {
4266   uint32_t pg_iter;
4267
4268 #if OLD
4269   struct PeerConnection *conn_iter;
4270   double random_number;
4271 #else
4272   struct RandomContext random_ctx;
4273 #endif
4274
4275   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4276   {
4277 #if OLD
4278     conn_iter = pg->peers[pg_iter].connect_peers_head;
4279     while (conn_iter != NULL)
4280     {
4281       random_number =
4282           ((double)
4283            GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
4284                                      UINT64_MAX)) / ((double) UINT64_MAX);
4285       if (random_number < percentage)
4286       {
4287         add_connections (pg, pg_iter, conn_iter->index, WORKING_SET,
4288                          GNUNET_YES);
4289       }
4290       conn_iter = conn_iter->next;
4291     }
4292 #else
4293     random_ctx.first_uid = pg_iter;
4294     random_ctx.first = &pg->peers[pg_iter];
4295     random_ctx.percentage = percentage;
4296     random_ctx.pg = pg;
4297     pg->peers[pg_iter].connect_peers_working_set =
4298         GNUNET_CONTAINER_multihashmap_create (pg->total);
4299     GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].connect_peers,
4300                                            &random_connect_iterator,
4301                                            &random_ctx);
4302     /* Now remove the old connections */
4303     GNUNET_CONTAINER_multihashmap_destroy (pg->peers[pg_iter].connect_peers);
4304     /* And replace with the random set */
4305     pg->peers[pg_iter].connect_peers =
4306         pg->peers[pg_iter].connect_peers_working_set;
4307 #endif
4308   }
4309
4310   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4311   {
4312     conn_iter = pg->peers[pg_iter].connect_peers_head;
4313     while (pg->peers[pg_iter].connect_peers_head != NULL)
4314       remove_connections (pg, pg_iter,
4315                           pg->peers[pg_iter].connect_peers_head->index, CONNECT,
4316                           GNUNET_YES);
4317
4318     pg->peers[pg_iter].connect_peers_head =
4319         pg->peers[pg_iter].connect_peers_working_set_head;
4320     pg->peers[pg_iter].connect_peers_tail =
4321         pg->peers[pg_iter].connect_peers_working_set_tail;
4322     pg->peers[pg_iter].connect_peers_working_set_head = NULL;
4323     pg->peers[pg_iter].connect_peers_working_set_tail = NULL;
4324   }
4325 }
4326
4327 /**
4328  * Count the number of connections in a linked list of connections.
4329  *
4330  * @param conn_list the connection list to get the count of
4331  *
4332  * @return the number of elements in the list
4333  */
4334 static unsigned int
4335 count_connections (struct PeerConnection *conn_list)
4336 {
4337   struct PeerConnection *iter;
4338   unsigned int count;
4339
4340   count = 0;
4341   iter = conn_list;
4342   while (iter != NULL)
4343   {
4344     iter = iter->next;
4345     count++;
4346   }
4347   return count;
4348 }
4349
4350 static unsigned int
4351 count_workingset_connections (struct GNUNET_TESTING_PeerGroup *pg)
4352 {
4353   unsigned int count;
4354   unsigned int pg_iter;
4355
4356 #if OLD
4357   struct PeerConnection *conn_iter;
4358 #endif
4359   count = 0;
4360
4361   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4362   {
4363 #if OLD
4364     conn_iter = pg->peers[pg_iter].connect_peers_working_set_head;
4365     while (conn_iter != NULL)
4366     {
4367       count++;
4368       conn_iter = conn_iter->next;
4369     }
4370 #else
4371     count +=
4372         GNUNET_CONTAINER_multihashmap_size (pg->
4373                                             peers
4374                                             [pg_iter].connect_peers_working_set);
4375 #endif
4376   }
4377
4378   return count;
4379 }
4380
4381 static unsigned int
4382 count_allowed_connections (struct GNUNET_TESTING_PeerGroup *pg)
4383 {
4384   unsigned int count;
4385   unsigned int pg_iter;
4386
4387 #if OLD
4388   struct PeerConnection *conn_iter;
4389 #endif
4390
4391   count = 0;
4392   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4393   {
4394 #if OLD
4395     conn_iter = pg->peers[pg_iter].allowed_peers_head;
4396     while (conn_iter != NULL)
4397     {
4398       count++;
4399       conn_iter = conn_iter->next;
4400     }
4401 #else
4402     count +=
4403         GNUNET_CONTAINER_multihashmap_size (pg->peers[pg_iter].allowed_peers);
4404 #endif
4405   }
4406
4407   return count;
4408 }
4409
4410 /**
4411  * From the set of connections possible, choose at least num connections per
4412  * peer.
4413  *
4414  * @param pg the peergroup we are dealing with
4415  * @param num how many connections at least should each peer have (if possible)?
4416  */
4417 static void
4418 choose_minimum (struct GNUNET_TESTING_PeerGroup *pg, unsigned int num)
4419 {
4420 #if !OLD
4421   struct MinimumContext minimum_ctx;
4422 #else
4423   struct PeerConnection *conn_iter;
4424   unsigned int temp_list_size;
4425   unsigned int i;
4426   unsigned int count;
4427   uint32_t random;              /* Random list entry to connect peer to */
4428 #endif
4429   uint32_t pg_iter;
4430
4431 #if OLD
4432   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4433   {
4434     temp_list_size = count_connections (pg->peers[pg_iter].connect_peers_head);
4435     if (temp_list_size == 0)
4436     {
4437       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Peer %d has 0 connections!?!?\n",
4438                   pg_iter);
4439       break;
4440     }
4441     for (i = 0; i < num; i++)
4442     {
4443       random =
4444           GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, temp_list_size);
4445       conn_iter = pg->peers[pg_iter].connect_peers_head;
4446       for (count = 0; count < random; count++)
4447         conn_iter = conn_iter->next;
4448       /* We now have a random connection, connect it! */
4449       GNUNET_assert (conn_iter != NULL);
4450       add_connections (pg, pg_iter, conn_iter->index, WORKING_SET, GNUNET_YES);
4451     }
4452   }
4453 #else
4454   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4455   {
4456     pg->peers[pg_iter].connect_peers_working_set =
4457         GNUNET_CONTAINER_multihashmap_create (num);
4458   }
4459
4460   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4461   {
4462     minimum_ctx.first_uid = pg_iter;
4463     minimum_ctx.pg_array =
4464         GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
4465                                       GNUNET_CONTAINER_multihashmap_size
4466                                       (pg->peers[pg_iter].connect_peers));
4467     minimum_ctx.first = &pg->peers[pg_iter];
4468     minimum_ctx.pg = pg;
4469     minimum_ctx.num_to_add = num;
4470     minimum_ctx.current = 0;
4471     GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].connect_peers,
4472                                            &minimum_connect_iterator,
4473                                            &minimum_ctx);
4474   }
4475
4476   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4477   {
4478     /* Remove the "old" connections */
4479     GNUNET_CONTAINER_multihashmap_destroy (pg->peers[pg_iter].connect_peers);
4480     /* And replace with the working set */
4481     pg->peers[pg_iter].connect_peers =
4482         pg->peers[pg_iter].connect_peers_working_set;
4483   }
4484 #endif
4485   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4486   {
4487     while (pg->peers[pg_iter].connect_peers_head != NULL)
4488     {
4489       conn_iter = pg->peers[pg_iter].connect_peers_head;
4490       GNUNET_CONTAINER_DLL_remove (pg->peers[pg_iter].connect_peers_head,
4491                                    pg->peers[pg_iter].connect_peers_tail,
4492                                    conn_iter);
4493       GNUNET_free (conn_iter);
4494       /*remove_connections(pg, pg_iter, pg->peers[pg_iter].connect_peers_head->index, CONNECT, GNUNET_YES); */
4495     }
4496
4497     pg->peers[pg_iter].connect_peers_head =
4498         pg->peers[pg_iter].connect_peers_working_set_head;
4499     pg->peers[pg_iter].connect_peers_tail =
4500         pg->peers[pg_iter].connect_peers_working_set_tail;
4501     pg->peers[pg_iter].connect_peers_working_set_head = NULL;
4502     pg->peers[pg_iter].connect_peers_working_set_tail = NULL;
4503   }
4504 }
4505
4506 #if !OLD
4507 struct FindClosestContext
4508 {
4509     /**
4510      * The currently known closest peer.
4511      */
4512   struct GNUNET_TESTING_Daemon *closest;
4513
4514     /**
4515      * The info for the peer we are adding connections for.
4516      */
4517   struct PeerData *curr_peer;
4518
4519     /**
4520      * The distance (bits) between the current
4521      * peer and the currently known closest.
4522      */
4523   unsigned int closest_dist;
4524
4525     /**
4526      * The offset of the closest known peer in
4527      * the peer group.
4528      */
4529   unsigned int closest_num;
4530 };
4531
4532 /**
4533  * Iterator over hash map entries of the allowed
4534  * peer connections.  Find the closest, not already
4535  * connected peer and return it.
4536  *
4537  * @param cls closure (struct FindClosestContext)
4538  * @param key current key code (hash of offset in pg)
4539  * @param value value in the hash map - a GNUNET_TESTING_Daemon
4540  * @return GNUNET_YES if we should continue to
4541  *         iterate,
4542  *         GNUNET_NO if not.
4543  */
4544 static int
4545 find_closest_peers (void *cls, const GNUNET_HashCode * key, void *value)
4546 {
4547   struct FindClosestContext *closest_ctx = cls;
4548   struct GNUNET_TESTING_Daemon *daemon = value;
4549
4550   if (((closest_ctx->closest == NULL) ||
4551        (GNUNET_CRYPTO_hash_matching_bits
4552         (&daemon->id.hashPubKey,
4553          &closest_ctx->curr_peer->daemon->id.hashPubKey) >
4554         closest_ctx->closest_dist)) &&
4555       (GNUNET_YES !=
4556        GNUNET_CONTAINER_multihashmap_contains (closest_ctx->
4557                                                curr_peer->connect_peers, key)))
4558   {
4559     closest_ctx->closest_dist =
4560         GNUNET_CRYPTO_hash_matching_bits (&daemon->id.hashPubKey,
4561                                           &closest_ctx->curr_peer->daemon->
4562                                           id.hashPubKey);
4563     closest_ctx->closest = daemon;
4564     uid_from_hash (key, &closest_ctx->closest_num);
4565   }
4566   return GNUNET_YES;
4567 }
4568
4569 /**
4570  * From the set of connections possible, choose at num connections per
4571  * peer based on depth which are closest out of those allowed.  Guaranteed
4572  * to add num peers to connect to, provided there are that many peers
4573  * in the underlay topology to connect to.
4574  *
4575  * @param pg the peergroup we are dealing with
4576  * @param num how many connections at least should each peer have (if possible)?
4577  * @param proc processor to actually add the connections
4578  * @param list the peer list to use
4579  */
4580 void
4581 add_closest (struct GNUNET_TESTING_PeerGroup *pg, unsigned int num,
4582              GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
4583 {
4584 #if OLD
4585
4586 #else
4587   struct FindClosestContext closest_ctx;
4588 #endif
4589   uint32_t pg_iter;
4590   uint32_t i;
4591
4592   for (i = 0; i < num; i++)     /* Each time find a closest peer (from those available) */
4593   {
4594     for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4595     {
4596       closest_ctx.curr_peer = &pg->peers[pg_iter];
4597       closest_ctx.closest = NULL;
4598       closest_ctx.closest_dist = 0;
4599       closest_ctx.closest_num = 0;
4600       GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].allowed_peers,
4601                                              &find_closest_peers, &closest_ctx);
4602       if (closest_ctx.closest != NULL)
4603       {
4604         GNUNET_assert (closest_ctx.closest_num < pg->total);
4605         proc (pg, pg_iter, closest_ctx.closest_num, list);
4606       }
4607     }
4608   }
4609 }
4610 #endif
4611
4612 /**
4613  * From the set of connections possible, choose at least num connections per
4614  * peer based on depth first traversal of peer connections.  If DFS leaves
4615  * peers unconnected, ensure those peers get connections.
4616  *
4617  * @param pg the peergroup we are dealing with
4618  * @param num how many connections at least should each peer have (if possible)?
4619  */
4620 void
4621 perform_dfs (struct GNUNET_TESTING_PeerGroup *pg, unsigned int num)
4622 {
4623   uint32_t pg_iter;
4624   uint32_t dfs_count;
4625   uint32_t starting_peer;
4626   uint32_t least_connections;
4627   uint32_t random_connection;
4628
4629 #if OLD
4630   unsigned int temp_count;
4631   struct PeerConnection *peer_iter;
4632 #else
4633   struct DFSContext dfs_ctx;
4634   GNUNET_HashCode second_hash;
4635 #endif
4636
4637 #if OLD
4638   starting_peer = 0;
4639   dfs_count = 0;
4640   while ((count_workingset_connections (pg) < num * pg->total) &&
4641          (count_allowed_connections (pg) > 0))
4642   {
4643     if (dfs_count % pg->total == 0)     /* Restart the DFS at some weakly connected peer */
4644     {
4645       least_connections = -1;   /* Set to very high number */
4646       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4647       {
4648         temp_count =
4649             count_connections (pg->
4650                                peers[pg_iter].connect_peers_working_set_head);
4651         if (temp_count < least_connections)
4652         {
4653           starting_peer = pg_iter;
4654           least_connections = temp_count;
4655         }
4656       }
4657     }
4658
4659     temp_count =
4660         count_connections (pg->peers[starting_peer].connect_peers_head);
4661     if (temp_count == 0)
4662       continue;                 /* FIXME: infinite loop? */
4663
4664     random_connection =
4665         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, temp_count);
4666     temp_count = 0;
4667     peer_iter = pg->peers[starting_peer].connect_peers_head;
4668     while (temp_count < random_connection)
4669     {
4670       peer_iter = peer_iter->next;
4671       temp_count++;
4672     }
4673     GNUNET_assert (peer_iter != NULL);
4674     add_connections (pg, starting_peer, peer_iter->index, WORKING_SET,
4675                      GNUNET_NO);
4676     remove_connections (pg, starting_peer, peer_iter->index, CONNECT,
4677                         GNUNET_YES);
4678     starting_peer = peer_iter->index;
4679     dfs_count++;
4680   }
4681
4682 #else
4683   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4684   {
4685     pg->peers[pg_iter].connect_peers_working_set =
4686         GNUNET_CONTAINER_multihashmap_create (num);
4687   }
4688
4689   starting_peer = 0;
4690   dfs_count = 0;
4691   while ((count_workingset_connections (pg) < num * pg->total) &&
4692          (count_allowed_connections (pg) > 0))
4693   {
4694     if (dfs_count % pg->total == 0)     /* Restart the DFS at some weakly connected peer */
4695     {
4696       least_connections = -1;   /* Set to very high number */
4697       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4698       {
4699         if (GNUNET_CONTAINER_multihashmap_size
4700             (pg->peers[pg_iter].connect_peers_working_set) < least_connections)
4701         {
4702           starting_peer = pg_iter;
4703           least_connections =
4704               GNUNET_CONTAINER_multihashmap_size (pg->
4705                                                   peers
4706                                                   [pg_iter].connect_peers_working_set);
4707         }
4708       }
4709     }
4710
4711     if (GNUNET_CONTAINER_multihashmap_size (pg->peers[starting_peer].connect_peers) == 0)       /* Ensure there is at least one peer left to connect! */
4712     {
4713       dfs_count = 0;
4714       continue;
4715     }
4716
4717     /* Choose a random peer from the chosen peers set of connections to add */
4718     dfs_ctx.chosen =
4719         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4720                                   GNUNET_CONTAINER_multihashmap_size (pg->peers
4721                                                                       [starting_peer].connect_peers));
4722     dfs_ctx.first_uid = starting_peer;
4723     dfs_ctx.first = &pg->peers[starting_peer];
4724     dfs_ctx.pg = pg;
4725     dfs_ctx.current = 0;
4726
4727     GNUNET_CONTAINER_multihashmap_iterate (pg->
4728                                            peers[starting_peer].connect_peers,
4729                                            &dfs_connect_iterator, &dfs_ctx);
4730     /* Remove the second from the first, since we will be continuing the search and may encounter the first peer again! */
4731     hash_from_uid (dfs_ctx.second_uid, &second_hash);
4732     GNUNET_assert (GNUNET_YES ==
4733                    GNUNET_CONTAINER_multihashmap_remove (pg->peers
4734                                                          [starting_peer].connect_peers,
4735                                                          &second_hash,
4736                                                          pg->
4737                                                          peers
4738                                                          [dfs_ctx.second_uid].daemon));
4739     starting_peer = dfs_ctx.second_uid;
4740   }
4741
4742   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4743   {
4744     /* Remove the "old" connections */
4745     GNUNET_CONTAINER_multihashmap_destroy (pg->peers[pg_iter].connect_peers);
4746     /* And replace with the working set */
4747     pg->peers[pg_iter].connect_peers =
4748         pg->peers[pg_iter].connect_peers_working_set;
4749   }
4750 #endif
4751 }
4752
4753 /**
4754  * Internal callback for topology information for a particular peer.
4755  */
4756 static void
4757 internal_topology_callback (void *cls, const struct GNUNET_PeerIdentity *peer,
4758                             const struct GNUNET_ATS_Information *atsi,
4759                             unsigned int atsi_count)
4760 {
4761   struct CoreContext *core_ctx = cls;
4762   struct TopologyIterateContext *iter_ctx = core_ctx->iter_context;
4763
4764   if (peer == NULL)             /* Either finished, or something went wrong */
4765   {
4766     iter_ctx->completed++;
4767     iter_ctx->connected--;
4768     /* One core context allocated per iteration, must free! */
4769     GNUNET_free (core_ctx);
4770   }
4771   else
4772   {
4773     iter_ctx->topology_cb (iter_ctx->cls, &core_ctx->daemon->id, peer, NULL);
4774   }
4775
4776   if (iter_ctx->completed == iter_ctx->total)
4777   {
4778     iter_ctx->topology_cb (iter_ctx->cls, NULL, NULL, NULL);
4779     /* Once all are done, free the iteration context */
4780     GNUNET_free (iter_ctx);
4781   }
4782 }
4783
4784 /**
4785  * Check running topology iteration tasks, if below max start a new one, otherwise
4786  * schedule for some time in the future.
4787  */
4788 static void
4789 schedule_get_topology (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4790 {
4791   struct CoreContext *core_context = cls;
4792   struct TopologyIterateContext *topology_context =
4793       (struct TopologyIterateContext *) core_context->iter_context;
4794   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4795     return;
4796
4797   if (topology_context->connected >
4798       topology_context->pg->max_outstanding_connections)
4799   {
4800     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4801                 "Delaying connect, we have too many outstanding connections!\n");
4802     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4803                                   (GNUNET_TIME_UNIT_MILLISECONDS, 100),
4804                                   &schedule_get_topology, core_context);
4805   }
4806   else
4807   {
4808     topology_context->connected++;
4809
4810     if (GNUNET_OK !=
4811         GNUNET_CORE_iterate_peers (core_context->daemon->cfg,
4812                                    &internal_topology_callback, core_context))
4813     {
4814       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Topology iteration failed.\n");
4815       internal_topology_callback (core_context, NULL, NULL, 0);
4816     }
4817   }
4818 }
4819
4820 /**
4821  * Iterate over all (running) peers in the peer group, retrieve
4822  * all connections that each currently has.
4823  */
4824 void
4825 GNUNET_TESTING_get_topology (struct GNUNET_TESTING_PeerGroup *pg,
4826                              GNUNET_TESTING_NotifyTopology cb, void *cls)
4827 {
4828   struct TopologyIterateContext *topology_context;
4829   struct CoreContext *core_ctx;
4830   unsigned int i;
4831   unsigned int total_count;
4832
4833   /* Allocate a single topology iteration context */
4834   topology_context = GNUNET_malloc (sizeof (struct TopologyIterateContext));
4835   topology_context->topology_cb = cb;
4836   topology_context->cls = cls;
4837   topology_context->pg = pg;
4838   total_count = 0;
4839   for (i = 0; i < pg->total; i++)
4840   {
4841     if (pg->peers[i].daemon->running == GNUNET_YES)
4842     {
4843       /* Allocate one core context per core we need to connect to */
4844       core_ctx = GNUNET_malloc (sizeof (struct CoreContext));
4845       core_ctx->daemon = pg->peers[i].daemon;
4846       /* Set back pointer to topology iteration context */
4847       core_ctx->iter_context = topology_context;
4848       GNUNET_SCHEDULER_add_now (&schedule_get_topology, core_ctx);
4849       total_count++;
4850     }
4851   }
4852   if (total_count == 0)
4853   {
4854     cb (cls, NULL, NULL, "Cannot iterate over topology, no running peers!");
4855     GNUNET_free (topology_context);
4856   }
4857   else
4858     topology_context->total = total_count;
4859   return;
4860 }
4861
4862 /**
4863  * Callback function to process statistic values.
4864  * This handler is here only really to insert a peer
4865  * identity (or daemon) so the statistics can be uniquely
4866  * tied to a single running peer.
4867  *
4868  * @param cls closure
4869  * @param subsystem name of subsystem that created the statistic
4870  * @param name the name of the datum
4871  * @param value the current value
4872  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
4873  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
4874  */
4875 static int
4876 internal_stats_callback (void *cls, const char *subsystem, const char *name,
4877                          uint64_t value, int is_persistent)
4878 {
4879   struct StatsCoreContext *core_context = cls;
4880   struct StatsIterateContext *stats_context =
4881       (struct StatsIterateContext *) core_context->iter_context;
4882
4883   return stats_context->proc (stats_context->cls, &core_context->daemon->id,
4884                               subsystem, name, value, is_persistent);
4885 }
4886
4887
4888 /**
4889  * We don't need the statistics handle anymore, destroy it.
4890  * 
4891  * @param cls Closure (the statistics handle to destroy)
4892  * @param tc Task Context
4893  */
4894 static void
4895 internal_destroy_statistics (void *cls,
4896                              const struct GNUNET_SCHEDULER_TaskContext *tc)
4897 {
4898   struct GNUNET_STATISTICS_Handle *h = cls;
4899
4900   GNUNET_STATISTICS_destroy (h, GNUNET_NO);
4901 }
4902
4903
4904 /**
4905  * Internal continuation call for statistics iteration.
4906  *
4907  * @param cls closure, the CoreContext for this iteration
4908  * @param success whether or not the statistics iterations
4909  *        was canceled or not (we don't care)
4910  */
4911 static void
4912 internal_stats_cont (void *cls, int success)
4913 {
4914   struct StatsCoreContext *core_context = cls;
4915   struct StatsIterateContext *stats_context =
4916       (struct StatsIterateContext *) core_context->iter_context;
4917
4918   stats_context->connected--;
4919   stats_context->completed++;
4920
4921   if (stats_context->completed == stats_context->total)
4922   {
4923     stats_context->cont (stats_context->cls, GNUNET_YES);
4924     GNUNET_free (stats_context);
4925   }
4926
4927   if (core_context->stats_handle != NULL)
4928     /* Cannot destroy handle inside the continuation */
4929     GNUNET_SCHEDULER_add_now (&internal_destroy_statistics,
4930                               core_context->stats_handle);
4931
4932   GNUNET_free (core_context);
4933 }
4934
4935 /**
4936  * Check running topology iteration tasks, if below max start a new one, otherwise
4937  * schedule for some time in the future.
4938  */
4939 static void
4940 schedule_get_statistics (void *cls,
4941                          const struct GNUNET_SCHEDULER_TaskContext *tc)
4942 {
4943   struct StatsCoreContext *core_context = cls;
4944   struct StatsIterateContext *stats_context =
4945       (struct StatsIterateContext *) core_context->iter_context;
4946
4947   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4948     return;
4949
4950   if (stats_context->connected > stats_context->pg->max_outstanding_connections)
4951   {
4952     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4953                 "Delaying connect, we have too many outstanding connections!\n");
4954     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4955                                   (GNUNET_TIME_UNIT_MILLISECONDS, 100),
4956                                   &schedule_get_statistics, core_context);
4957   }
4958   else
4959   {
4960     stats_context->connected++;
4961     core_context->stats_handle =
4962         GNUNET_STATISTICS_create ("testing", core_context->daemon->cfg);
4963     if (core_context->stats_handle == NULL)
4964     {
4965       internal_stats_cont (core_context, GNUNET_NO);
4966       return;
4967     }
4968
4969     core_context->stats_get_handle =
4970         GNUNET_STATISTICS_get (core_context->stats_handle, NULL, NULL,
4971                                GNUNET_TIME_relative_get_forever (),
4972                                &internal_stats_cont, &internal_stats_callback,
4973                                core_context);
4974     if (core_context->stats_get_handle == NULL)
4975       internal_stats_cont (core_context, GNUNET_NO);
4976
4977   }
4978 }
4979
4980 struct DuplicateStats
4981 {
4982   /**
4983    * Next item in the list
4984    */
4985   struct DuplicateStats *next;
4986
4987   /**
4988    * Nasty string, concatenation of relevant information.
4989    */
4990   char *unique_string;
4991 };
4992
4993 /**
4994  * Check whether the combination of port/host/unix domain socket
4995  * already exists in the list of peers being checked for statistics.
4996  *
4997  * @param pg the peergroup in question
4998  * @param specific_peer the peer we're concerned with
4999  * @param stats_list the list to return to the caller
5000  *
5001  * @return GNUNET_YES if the statistics instance has been seen already,
5002  *         GNUNET_NO if not (and we may have added it to the list)
5003  */
5004 static int
5005 stats_check_existing (struct GNUNET_TESTING_PeerGroup *pg,
5006                       struct PeerData *specific_peer,
5007                       struct DuplicateStats **stats_list)
5008 {
5009   struct DuplicateStats *pos;
5010   char *unix_domain_socket;
5011   unsigned long long port;
5012   char *to_match;
5013
5014   if (GNUNET_YES !=
5015       GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "testing",
5016                                             "single_statistics_per_host"))
5017     return GNUNET_NO;           /* Each peer has its own statistics instance, do nothing! */
5018
5019   pos = *stats_list;
5020   if (GNUNET_OK !=
5021       GNUNET_CONFIGURATION_get_value_string (specific_peer->cfg, "statistics",
5022                                              "unixpath", &unix_domain_socket))
5023     return GNUNET_NO;
5024
5025   if (GNUNET_OK !=
5026       GNUNET_CONFIGURATION_get_value_number (specific_peer->cfg, "statistics",
5027                                              "port", &port))
5028   {
5029     GNUNET_free (unix_domain_socket);
5030     return GNUNET_NO;
5031   }
5032
5033   if (specific_peer->daemon->hostname != NULL)
5034     GNUNET_asprintf (&to_match, "%s%s%llu", specific_peer->daemon->hostname,
5035                      unix_domain_socket, port);
5036   else
5037     GNUNET_asprintf (&to_match, "%s%llu", unix_domain_socket, port);
5038
5039   while (pos != NULL)
5040   {
5041     if (0 == strcmp (to_match, pos->unique_string))
5042     {
5043       GNUNET_free (unix_domain_socket);
5044       GNUNET_free (to_match);
5045       return GNUNET_YES;
5046     }
5047     pos = pos->next;
5048   }
5049   pos = GNUNET_malloc (sizeof (struct DuplicateStats));
5050   pos->unique_string = to_match;
5051   pos->next = *stats_list;
5052   *stats_list = pos;
5053   GNUNET_free (unix_domain_socket);
5054   return GNUNET_NO;
5055 }
5056
5057 /**
5058  * Iterate over all (running) peers in the peer group, retrieve
5059  * all statistics from each.
5060  *
5061  * @param pg the peergroup to iterate statistics of
5062  * @param cont continuation to call once all stats have been retrieved
5063  * @param proc processing function for each statistic from each peer
5064  * @param cls closure to pass to proc
5065  *
5066  */
5067 void
5068 GNUNET_TESTING_get_statistics (struct GNUNET_TESTING_PeerGroup *pg,
5069                                GNUNET_STATISTICS_Callback cont,
5070                                GNUNET_TESTING_STATISTICS_Iterator proc,
5071                                void *cls)
5072 {
5073   struct StatsIterateContext *stats_context;
5074   struct StatsCoreContext *core_ctx;
5075   unsigned int i;
5076   unsigned int total_count;
5077   struct DuplicateStats *stats_list;
5078   struct DuplicateStats *pos;
5079
5080   stats_list = NULL;
5081
5082   /* Allocate a single stats iteration context */
5083   stats_context = GNUNET_malloc (sizeof (struct StatsIterateContext));
5084   stats_context->cont = cont;
5085   stats_context->proc = proc;
5086   stats_context->cls = cls;
5087   stats_context->pg = pg;
5088   total_count = 0;
5089
5090   for (i = 0; i < pg->total; i++)
5091   {
5092     if ((pg->peers[i].daemon->running == GNUNET_YES) &&
5093         (GNUNET_NO == stats_check_existing (pg, &pg->peers[i], &stats_list)))
5094     {
5095       /* Allocate one core context per core we need to connect to */
5096       core_ctx = GNUNET_malloc (sizeof (struct StatsCoreContext));
5097       core_ctx->daemon = pg->peers[i].daemon;
5098       /* Set back pointer to topology iteration context */
5099       core_ctx->iter_context = stats_context;
5100       GNUNET_SCHEDULER_add_now (&schedule_get_statistics, core_ctx);
5101       total_count++;
5102     }
5103   }
5104
5105   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5106               "Retrieving stats from %u total instances.\n", total_count);
5107   if (0 != total_count)
5108     stats_context->total = total_count;
5109   else
5110     GNUNET_free (stats_context);
5111   if (stats_list != NULL)
5112   {
5113     pos = stats_list;
5114     while (pos != NULL)
5115     {
5116       GNUNET_free (pos->unique_string);
5117       stats_list = pos->next;
5118       GNUNET_free (pos);
5119       pos = stats_list->next;
5120     }
5121   }
5122   return;
5123 }
5124
5125 /**
5126  * Stop the connection process temporarily.
5127  *
5128  * @param pg the peer group to stop connecting
5129  */
5130 void
5131 GNUNET_TESTING_stop_connections (struct GNUNET_TESTING_PeerGroup *pg)
5132 {
5133   pg->stop_connects = GNUNET_YES;
5134 }
5135
5136 /**
5137  * Resume the connection process temporarily.
5138  *
5139  * @param pg the peer group to resume connecting
5140  */
5141 void
5142 GNUNET_TESTING_resume_connections (struct GNUNET_TESTING_PeerGroup *pg)
5143 {
5144   pg->stop_connects = GNUNET_NO;
5145 }
5146
5147 /**
5148  * There are many ways to connect peers that are supported by this function.
5149  * To connect peers in the same topology that was created via the
5150  * GNUNET_TESTING_create_topology, the topology variable must be set to
5151  * GNUNET_TESTING_TOPOLOGY_NONE.  If the topology variable is specified,
5152  * a new instance of that topology will be generated and attempted to be
5153  * connected.  This could result in some connections being impossible,
5154  * because some topologies are non-deterministic.
5155  *
5156  * @param pg the peer group struct representing the running peers
5157  * @param topology which topology to connect the peers in
5158  * @param options options for connecting the topology
5159  * @param option_modifier modifier for options that take a parameter
5160  * @param connect_timeout how long to wait before giving up on connecting
5161  *                        two peers
5162  * @param connect_attempts how many times to attempt to connect two peers
5163  *                         over the connect_timeout duration
5164  * @param notify_callback notification to be called once all connections completed
5165  * @param notify_cls closure for notification callback
5166  *
5167  * @return the number of connections that will be attempted, GNUNET_SYSERR on error
5168  */
5169 int
5170 GNUNET_TESTING_connect_topology (struct GNUNET_TESTING_PeerGroup *pg,
5171                                  enum GNUNET_TESTING_Topology topology,
5172                                  enum GNUNET_TESTING_TopologyOption options,
5173                                  double option_modifier,
5174                                  struct GNUNET_TIME_Relative connect_timeout,
5175                                  unsigned int connect_attempts,
5176                                  GNUNET_TESTING_NotifyCompletion
5177                                  notify_callback, void *notify_cls)
5178 {
5179   switch (topology)
5180   {
5181   case GNUNET_TESTING_TOPOLOGY_CLIQUE:
5182     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5183                 "Creating clique CONNECT topology\n");
5184     create_clique (pg, &add_connections, CONNECT, GNUNET_NO);
5185     break;
5186   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
5187     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5188                 "Creating small world (ring) CONNECT topology\n");
5189     create_small_world_ring (pg, &add_connections, CONNECT);
5190     break;
5191   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
5192     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5193                 "Creating small world (2d-torus) CONNECT topology\n");
5194     create_small_world (pg, &add_connections, CONNECT);
5195     break;
5196   case GNUNET_TESTING_TOPOLOGY_RING:
5197     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating ring CONNECT topology\n");
5198     create_ring (pg, &add_connections, CONNECT);
5199     break;
5200   case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
5201     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5202                 "Creating 2d torus CONNECT topology\n");
5203     create_2d_torus (pg, &add_connections, CONNECT);
5204     break;
5205   case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
5206     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5207                 "Creating Erdos-Renyi CONNECT topology\n");
5208     create_erdos_renyi (pg, &add_connections, CONNECT);
5209     break;
5210   case GNUNET_TESTING_TOPOLOGY_INTERNAT:
5211     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5212                 "Creating InterNAT CONNECT topology\n");
5213     create_nated_internet (pg, &add_connections, CONNECT);
5214     break;
5215   case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
5216     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5217                 "Creating Scale Free CONNECT topology\n");
5218     create_scale_free (pg, &add_connections, CONNECT);
5219     break;
5220   case GNUNET_TESTING_TOPOLOGY_LINE:
5221     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5222                 "Creating straight line CONNECT topology\n");
5223     create_line (pg, &add_connections, CONNECT);
5224     break;
5225   case GNUNET_TESTING_TOPOLOGY_NONE:
5226     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating no CONNECT topology\n");
5227     copy_allowed_topology (pg);
5228     break;
5229   default:
5230     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5231                 _("Unknown topology specification, can't connect peers!\n"));
5232     return GNUNET_SYSERR;
5233   }
5234
5235   switch (options)
5236   {
5237   case GNUNET_TESTING_TOPOLOGY_OPTION_RANDOM:
5238     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5239                 "Connecting random subset (%'.2f percent) of possible peers\n",
5240                 100 * option_modifier);
5241     choose_random_connections (pg, option_modifier);
5242     break;
5243   case GNUNET_TESTING_TOPOLOGY_OPTION_MINIMUM:
5244     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5245                 "Connecting a minimum of %u peers each (if possible)\n",
5246                 (unsigned int) option_modifier);
5247     choose_minimum (pg, (unsigned int) option_modifier);
5248     break;
5249   case GNUNET_TESTING_TOPOLOGY_OPTION_DFS:
5250     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5251                 "Using DFS to connect a minimum of %u peers each (if possible)\n",
5252                 (unsigned int) option_modifier);
5253 #if FIXME
5254     perform_dfs (pg, (int) option_modifier);
5255 #endif
5256     break;
5257   case GNUNET_TESTING_TOPOLOGY_OPTION_ADD_CLOSEST:
5258     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5259                 "Finding additional %u closest peers each (if possible)\n",
5260                 (unsigned int) option_modifier);
5261 #if FIXME
5262     add_closest (pg, (unsigned int) option_modifier, &add_connections, CONNECT);
5263 #endif
5264     break;
5265   case GNUNET_TESTING_TOPOLOGY_OPTION_NONE:
5266     break;
5267   case GNUNET_TESTING_TOPOLOGY_OPTION_ALL:
5268     break;
5269   default:
5270     break;
5271   }
5272
5273   return connect_topology (pg, connect_timeout, connect_attempts,
5274                            notify_callback, notify_cls);
5275 }
5276
5277 /**
5278  * Lookup and return the number of SSH connections to a host.
5279  *
5280  * @param hostname the hostname to lookup in the list
5281  * @param pg the peergroup that the host belongs to
5282  *
5283  * @return the number of current ssh connections to the host
5284  */
5285 static unsigned int
5286 count_outstanding_at_host (const char *hostname,
5287                            struct GNUNET_TESTING_PeerGroup *pg)
5288 {
5289   struct OutstandingSSH *pos;
5290
5291   pos = pg->ssh_head;
5292   while ((pos != NULL) && (strcmp (pos->hostname, hostname) != 0))
5293     pos = pos->next;
5294   GNUNET_assert (pos != NULL);
5295   return pos->outstanding;
5296 }
5297
5298 /**
5299  * Increment the number of SSH connections to a host by one.
5300  *
5301  * @param hostname the hostname to lookup in the list
5302  * @param pg the peergroup that the host belongs to
5303  *
5304  */
5305 static void
5306 increment_outstanding_at_host (const char *hostname,
5307                                struct GNUNET_TESTING_PeerGroup *pg)
5308 {
5309   struct OutstandingSSH *pos;
5310
5311   pos = pg->ssh_head;
5312   while ((NULL != pos) && (strcmp (pos->hostname, hostname) != 0))
5313     pos = pos->next;
5314   GNUNET_assert (NULL != pos);
5315   pos->outstanding++;
5316 }
5317
5318 /**
5319  * Decrement the number of SSH connections to a host by one.
5320  *
5321  * @param hostname the hostname to lookup in the list
5322  * @param pg the peergroup that the host belongs to
5323  *
5324  */
5325 static void
5326 decrement_outstanding_at_host (const char *hostname,
5327                                struct GNUNET_TESTING_PeerGroup *pg)
5328 {
5329   struct OutstandingSSH *pos;
5330
5331   pos = pg->ssh_head;
5332   while ((pos != NULL) && (strcmp (pos->hostname, hostname) != 0))
5333     pos = pos->next;
5334   GNUNET_assert (pos != NULL);
5335   pos->outstanding--;
5336 }
5337
5338 /**
5339  * Callback that is called whenever a hostkey is generated
5340  * for a peer.  Call the real callback and decrement the
5341  * starting counter for the peergroup.
5342  *
5343  * @param cls closure
5344  * @param id identifier for the daemon, NULL on error
5345  * @param d handle for the daemon
5346  * @param emsg error message (NULL on success)
5347  */
5348 static void
5349 internal_hostkey_callback (void *cls, const struct GNUNET_PeerIdentity *id,
5350                            struct GNUNET_TESTING_Daemon *d, const char *emsg)
5351 {
5352   struct InternalStartContext *internal_context = cls;
5353
5354   internal_context->peer->pg->starting--;
5355   internal_context->peer->pg->started++;
5356   if (internal_context->hostname != NULL)
5357     decrement_outstanding_at_host (internal_context->hostname,
5358                                    internal_context->peer->pg);
5359   if (internal_context->hostkey_callback != NULL)
5360     internal_context->hostkey_callback (internal_context->hostkey_cls, id, d,
5361                                         emsg);
5362   else if (internal_context->peer->pg->started ==
5363            internal_context->peer->pg->total)
5364   {
5365     internal_context->peer->pg->started = 0;    /* Internal startup may use this counter! */
5366     GNUNET_TESTING_daemons_continue_startup (internal_context->peer->pg);
5367   }
5368 }
5369
5370 /**
5371  * Callback that is called whenever a peer has finished starting.
5372  * Call the real callback and decrement the starting counter
5373  * for the peergroup.
5374  *
5375  * @param cls closure
5376  * @param id identifier for the daemon, NULL on error
5377  * @param cfg config
5378  * @param d handle for the daemon
5379  * @param emsg error message (NULL on success)
5380  */
5381 static void
5382 internal_startup_callback (void *cls, const struct GNUNET_PeerIdentity *id,
5383                            const struct GNUNET_CONFIGURATION_Handle *cfg,
5384                            struct GNUNET_TESTING_Daemon *d, const char *emsg)
5385 {
5386   struct InternalStartContext *internal_context = cls;
5387
5388   internal_context->peer->pg->starting--;
5389   if (internal_context->hostname != NULL)
5390     decrement_outstanding_at_host (internal_context->hostname,
5391                                    internal_context->peer->pg);
5392   if (internal_context->start_cb != NULL)
5393     internal_context->start_cb (internal_context->start_cb_cls, id, cfg, d,
5394                                 emsg);
5395 }
5396
5397
5398 /**
5399  * Calls GNUNET_TESTING_daemon_continue_startup to set the daemon's state
5400  * from HOSTKEY_CREATED to TOPOLOGY_SETUP. Makes sure not to saturate a host
5401  * with requests delaying them when needed.
5402  *
5403  * @param cls closure: internal context of the daemon.
5404  * @param tc TaskContext
5405  */
5406 static void
5407 internal_continue_startup (void *cls,
5408                            const struct GNUNET_SCHEDULER_TaskContext *tc)
5409 {
5410   struct InternalStartContext *internal_context = cls;
5411
5412   internal_context->peer->startup_task = GNUNET_SCHEDULER_NO_TASK;
5413
5414   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
5415   {
5416     return;
5417   }
5418
5419   if ((internal_context->peer->pg->starting <
5420        internal_context->peer->pg->max_concurrent_ssh) ||
5421       ((internal_context->hostname != NULL) &&
5422        (count_outstanding_at_host
5423         (internal_context->hostname,
5424          internal_context->peer->pg) <
5425         internal_context->peer->pg->max_concurrent_ssh)))
5426   {
5427     if (internal_context->hostname != NULL)
5428       increment_outstanding_at_host (internal_context->hostname,
5429                                      internal_context->peer->pg);
5430     internal_context->peer->pg->starting++;
5431     GNUNET_TESTING_daemon_continue_startup (internal_context->peer->daemon);
5432   }
5433   else
5434   {
5435     internal_context->peer->startup_task =
5436         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
5437                                       (GNUNET_TIME_UNIT_MILLISECONDS, 100),
5438                                       &internal_continue_startup,
5439                                       internal_context);
5440   }
5441 }
5442
5443 /**
5444  * Callback for informing us about a successful
5445  * or unsuccessful churn start call.
5446  *
5447  * @param cls a ChurnContext
5448  * @param id the peer identity of the started peer
5449  * @param cfg the handle to the configuration of the peer
5450  * @param d handle to the daemon for the peer
5451  * @param emsg NULL on success, non-NULL on failure
5452  *
5453  */
5454 void
5455 churn_start_callback (void *cls, const struct GNUNET_PeerIdentity *id,
5456                       const struct GNUNET_CONFIGURATION_Handle *cfg,
5457                       struct GNUNET_TESTING_Daemon *d, const char *emsg)
5458 {
5459   struct ChurnRestartContext *startup_ctx = cls;
5460   struct ChurnContext *churn_ctx = startup_ctx->churn_ctx;
5461
5462   unsigned int total_left;
5463   char *error_message;
5464
5465   error_message = NULL;
5466   if (emsg != NULL)
5467   {
5468     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5469                 "Churn stop callback failed with error `%s'\n", emsg);
5470     churn_ctx->num_failed_start++;
5471   }
5472   else
5473   {
5474     churn_ctx->num_to_start--;
5475   }
5476
5477   total_left =
5478       (churn_ctx->num_to_stop - churn_ctx->num_failed_stop) +
5479       (churn_ctx->num_to_start - churn_ctx->num_failed_start);
5480
5481   if (total_left == 0)
5482   {
5483     if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
5484       GNUNET_asprintf (&error_message,
5485                        "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!",
5486                        churn_ctx->num_failed_start, churn_ctx->num_failed_stop);
5487     churn_ctx->cb (churn_ctx->cb_cls, error_message);
5488     GNUNET_free_non_null (error_message);
5489     GNUNET_free (churn_ctx);
5490     GNUNET_free (startup_ctx);
5491   }
5492 }
5493
5494 static void
5495 schedule_churn_restart (void *cls,
5496                         const struct GNUNET_SCHEDULER_TaskContext *tc)
5497 {
5498   struct PeerRestartContext *peer_restart_ctx = cls;
5499   struct ChurnRestartContext *startup_ctx = peer_restart_ctx->churn_restart_ctx;
5500
5501   if (startup_ctx->outstanding > startup_ctx->pg->max_concurrent_ssh)
5502     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
5503                                   (GNUNET_TIME_UNIT_MILLISECONDS, 100),
5504                                   &schedule_churn_restart, peer_restart_ctx);
5505   else
5506   {
5507     if (startup_ctx->churn_ctx->service != NULL)
5508       GNUNET_TESTING_daemon_start_stopped_service (peer_restart_ctx->daemon,
5509                                                    startup_ctx->
5510                                                    churn_ctx->service,
5511                                                    startup_ctx->timeout,
5512                                                    &churn_start_callback,
5513                                                    startup_ctx);
5514     else
5515       GNUNET_TESTING_daemon_start_stopped (peer_restart_ctx->daemon,
5516                                            startup_ctx->timeout,
5517                                            &churn_start_callback, startup_ctx);
5518     GNUNET_free (peer_restart_ctx);
5519   }
5520 }
5521
5522 /**
5523  * Callback for informing us about a successful
5524  * or unsuccessful churn start call.
5525  *
5526  * @param cls a struct ServiceStartContext *startup_ctx
5527  * @param id the peer identity of the started peer
5528  * @param cfg the handle to the configuration of the peer
5529  * @param d handle to the daemon for the peer
5530  * @param emsg NULL on success, non-NULL on failure
5531  *
5532  */
5533 void
5534 service_start_callback (void *cls, const struct GNUNET_PeerIdentity *id,
5535                         const struct GNUNET_CONFIGURATION_Handle *cfg,
5536                         struct GNUNET_TESTING_Daemon *d, const char *emsg)
5537 {
5538   struct ServiceStartContext *startup_ctx = (struct ServiceStartContext *) cls;
5539
5540   if (emsg != NULL)
5541   {
5542     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5543                 "Service start failed with error `%s'\n", emsg);
5544   }
5545
5546   startup_ctx->outstanding--;
5547   startup_ctx->remaining--;
5548
5549   if (startup_ctx->remaining == 0)
5550   {
5551     startup_ctx->cb (startup_ctx->cb_cls, NULL);
5552     GNUNET_free (startup_ctx->service);
5553     GNUNET_free (startup_ctx);
5554   }
5555 }
5556
5557 static void
5558 schedule_service_start (void *cls,
5559                         const struct GNUNET_SCHEDULER_TaskContext *tc)
5560 {
5561   struct PeerServiceStartContext *peer_ctx = cls;
5562   struct ServiceStartContext *startup_ctx = peer_ctx->start_ctx;
5563
5564   if (startup_ctx->outstanding > startup_ctx->pg->max_concurrent_ssh)
5565     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
5566                                   (GNUNET_TIME_UNIT_MILLISECONDS, 100),
5567                                   &schedule_service_start, peer_ctx);
5568   else
5569   {
5570
5571     GNUNET_TESTING_daemon_start_service (peer_ctx->daemon, startup_ctx->service,
5572                                          startup_ctx->timeout,
5573                                          &service_start_callback, startup_ctx);
5574     GNUNET_free (peer_ctx);
5575   }
5576 }
5577
5578
5579 static void
5580 internal_start (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5581 {
5582   struct InternalStartContext *internal_context = cls;
5583
5584   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
5585   {
5586     return;
5587   }
5588
5589   if ((internal_context->peer->pg->starting <
5590        internal_context->peer->pg->max_concurrent_ssh) ||
5591       ((internal_context->hostname != NULL) &&
5592        (count_outstanding_at_host
5593         (internal_context->hostname,
5594          internal_context->peer->pg) <
5595         internal_context->peer->pg->max_concurrent_ssh)))
5596   {
5597     if (internal_context->hostname != NULL)
5598       increment_outstanding_at_host (internal_context->hostname,
5599                                      internal_context->peer->pg);
5600     internal_context->peer->pg->starting++;
5601     internal_context->peer->daemon =
5602         GNUNET_TESTING_daemon_start (internal_context->peer->cfg,
5603                                      internal_context->timeout, GNUNET_NO,
5604                                      internal_context->hostname,
5605                                      internal_context->username,
5606                                      internal_context->sshport,
5607                                      internal_context->hostkey,
5608                                      &internal_hostkey_callback,
5609                                      internal_context,
5610                                      &internal_startup_callback,
5611                                      internal_context);
5612   }
5613   else
5614   {
5615     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
5616                                   (GNUNET_TIME_UNIT_MILLISECONDS, 100),
5617                                   &internal_start, internal_context);
5618   }
5619 }
5620
5621 #if USE_START_HELPER
5622
5623 struct PeerStartHelperContext
5624 {
5625   struct GNUNET_TESTING_PeerGroup *pg;
5626
5627   struct HostData *host;
5628
5629   struct GNUNET_OS_Process *proc;
5630 };
5631
5632 static void
5633 check_peers_started (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5634 {
5635   struct PeerStartHelperContext *helper = cls;
5636   enum GNUNET_OS_ProcessStatusType type;
5637   unsigned long code;
5638   unsigned int i;
5639   GNUNET_TESTING_NotifyDaemonRunning cb;
5640
5641   if (GNUNET_NO == GNUNET_OS_process_status (helper->proc, &type, &code))       /* Still running, wait some more! */
5642   {
5643     GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT,
5644                                   &check_peers_started, helper);
5645     return;
5646   }
5647
5648   helper->pg->starting--;
5649   if (helper->pg->starting == 0)        /* All peers have finished starting! */
5650   {
5651     /* Call the peer started callback for each peer, set proper FSM state (?) */
5652     for (i = 0; i < helper->pg->total; i++)
5653     {
5654       cb = helper->pg->peers[i].daemon->cb;
5655       helper->pg->peers[i].daemon->cb = NULL;
5656       helper->pg->peers[i].daemon->running = GNUNET_YES;
5657       helper->pg->peers[i].daemon->phase = SP_START_DONE;
5658       if (NULL != cb)
5659       {
5660         if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
5661           cb (helper->pg->peers[i].daemon->cb_cls,
5662               &helper->pg->peers[i].daemon->id,
5663               helper->pg->peers[i].daemon->cfg, helper->pg->peers[i].daemon,
5664               "Failed to execute peerStartHelper.pl, or return code bad!");
5665         else
5666           cb (helper->pg->peers[i].daemon->cb_cls,
5667               &helper->pg->peers[i].daemon->id,
5668               helper->pg->peers[i].daemon->cfg, helper->pg->peers[i].daemon,
5669               NULL);
5670
5671       }
5672
5673     }
5674   }
5675   GNUNET_OS_process_destroy (helper->proc);
5676 }
5677
5678 static void
5679 start_peer_helper (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5680 {
5681   struct PeerStartHelperContext *helper = cls;
5682   char *baseservicehome;
5683   char *tempdir;
5684   char *arg;
5685
5686   /* ssh user@host peerStartHelper /path/to/basedirectory */
5687   GNUNET_assert (GNUNET_OK ==
5688                  GNUNET_CONFIGURATION_get_value_string (helper->pg->cfg,
5689                                                         "PATHS", "SERVICEHOME",
5690                                                         &baseservicehome));
5691   GNUNET_asprintf (&tempdir, "%s/%s/", baseservicehome, helper->host->hostname);
5692   if (NULL != helper->host->username)
5693     GNUNET_asprintf (&arg, "%s@%s", helper->host->username,
5694                      helper->host->hostname);
5695   else
5696     GNUNET_asprintf (&arg, "%s", helper->host->hostname);
5697
5698   /* FIXME: Doesn't support ssh_port option! */
5699   helper->proc =
5700     GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "ssh", "ssh", arg,
5701                                "peerStartHelper.pl", tempdir, NULL);
5702   GNUNET_assert (helper->proc != NULL);
5703   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting peers with cmd ssh %s %s %s\n",
5704               arg, "peerStartHelper.pl", tempdir);
5705   GNUNET_SCHEDULER_add_now (&check_peers_started, helper);
5706   GNUNET_free (tempdir);
5707   GNUNET_free (baseservicehome);
5708   GNUNET_free (arg);
5709 }
5710 #endif
5711
5712 /**
5713  * Function which continues a peer group starting up
5714  * after successfully generating hostkeys for each peer.
5715  *
5716  * @param pg the peer group to continue starting
5717  *
5718  */
5719 void
5720 GNUNET_TESTING_daemons_continue_startup (struct GNUNET_TESTING_PeerGroup *pg)
5721 {
5722   unsigned int i;
5723
5724 #if USE_START_HELPER
5725   if ((pg->num_hosts > 0) && (pg->hostkey_data != NULL))
5726   {
5727     struct PeerStartHelperContext *helper;
5728
5729     pg->starting = pg->num_hosts;
5730     for (i = 0; i < pg->num_hosts; i++)
5731     {
5732       helper = GNUNET_malloc (sizeof (struct PeerStartHelperContext));
5733       helper->pg = pg;
5734       helper->host = &pg->hosts[i];
5735       GNUNET_SCHEDULER_add_now (&start_peer_helper, helper);
5736     }
5737   }
5738   else
5739   {
5740     pg->starting = 0;
5741     for (i = 0; i < pg->total; i++)
5742     {
5743       pg->peers[i].startup_task =
5744           GNUNET_SCHEDULER_add_now (&internal_continue_startup,
5745                                     &pg->peers[i].internal_context);
5746     }
5747   }
5748 #else
5749   pg->starting = 0;
5750   for (i = 0; i < pg->total; i++)
5751   {
5752     pg->peers[i].startup_task =
5753         GNUNET_SCHEDULER_add_now (&internal_continue_startup,
5754                                   &pg->peers[i].internal_context);
5755   }
5756 #endif
5757 }
5758
5759 #if USE_START_HELPER
5760 static void
5761 call_hostkey_callbacks (void *cls,
5762                         const struct GNUNET_SCHEDULER_TaskContext *tc)
5763 {
5764   struct GNUNET_TESTING_PeerGroup *pg = cls;
5765   unsigned int i;
5766
5767   for (i = 0; i < pg->total; i++)
5768   {
5769     if (pg->peers[i].internal_context.hostkey_callback != NULL)
5770       pg->peers[i].internal_context.hostkey_callback (pg->peers[i].
5771                                                       internal_context.hostkey_cls,
5772                                                       &pg->peers[i].daemon->id,
5773                                                       pg->peers[i].daemon,
5774                                                       NULL);
5775   }
5776
5777   if (pg->peers[0].internal_context.hostkey_callback == NULL)
5778     GNUNET_TESTING_daemons_continue_startup (pg);
5779 }
5780 #endif
5781
5782 /**
5783  * Start count gnunet instances with the same set of transports and
5784  * applications.  The port numbers (any option called "PORT") will be
5785  * adjusted to ensure that no two peers running on the same system
5786  * have the same port(s) in their respective configurations.
5787  *
5788  * @param cfg configuration template to use
5789  * @param total number of daemons to start
5790  * @param max_concurrent_connections for testing, how many peers can
5791  *                                   we connect to simultaneously
5792  * @param max_concurrent_ssh when starting with ssh, how many ssh
5793  *        connections will we allow at once (based on remote hosts allowed!)
5794  * @param timeout total time allowed for peers to start
5795  * @param hostkey_callback function to call on each peers hostkey generation
5796  *        if NULL, peers will be started by this call, if non-null,
5797  *        GNUNET_TESTING_daemons_continue_startup must be called after
5798  *        successful hostkey generation
5799  * @param hostkey_cls closure for hostkey callback
5800  * @param cb function to call on each daemon that was started
5801  * @param cb_cls closure for cb
5802  * @param connect_callback function to call each time two hosts are connected
5803  * @param connect_callback_cls closure for connect_callback
5804  * @param hostnames linked list of host structs to use to start peers on
5805  *                  (NULL to run on localhost only)
5806  *
5807  * @return NULL on error, otherwise handle to control peer group
5808  */
5809 struct GNUNET_TESTING_PeerGroup *
5810 GNUNET_TESTING_daemons_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
5811                               unsigned int total,
5812                               unsigned int max_concurrent_connections,
5813                               unsigned int max_concurrent_ssh,
5814                               struct GNUNET_TIME_Relative timeout,
5815                               GNUNET_TESTING_NotifyHostkeyCreated
5816                               hostkey_callback, void *hostkey_cls,
5817                               GNUNET_TESTING_NotifyDaemonRunning cb,
5818                               void *cb_cls,
5819                               GNUNET_TESTING_NotifyConnection connect_callback,
5820                               void *connect_callback_cls,
5821                               const struct GNUNET_TESTING_Host *hostnames)
5822 {
5823   struct GNUNET_TESTING_PeerGroup *pg;
5824   const struct GNUNET_TESTING_Host *hostpos;
5825   const char *hostname;
5826   const char *username;
5827   char *baseservicehome;
5828   char *newservicehome;
5829   char *tmpdir;
5830   char *hostkeys_file;
5831   char *arg;
5832   char *ssh_port_str;
5833   struct GNUNET_DISK_FileHandle *fd;
5834   struct GNUNET_CONFIGURATION_Handle *pcfg;
5835   unsigned int off;
5836   struct OutstandingSSH *ssh_entry;
5837   unsigned int hostcnt;
5838   unsigned int i;
5839   uint16_t minport;
5840   uint16_t sshport;
5841   uint32_t upnum;
5842   uint32_t fdnum;
5843   uint64_t fs;
5844   uint64_t total_hostkeys;
5845   struct GNUNET_OS_Process *proc;
5846
5847   username = NULL;
5848   if (0 == total)
5849   {
5850     GNUNET_break (0);
5851     return NULL;
5852   }
5853
5854   upnum = 0;
5855   fdnum = 0;
5856   pg = GNUNET_malloc (sizeof (struct GNUNET_TESTING_PeerGroup));
5857   pg->cfg = cfg;
5858   pg->notify_connection = connect_callback;
5859   pg->notify_connection_cls = connect_callback_cls;
5860   pg->total = total;
5861   pg->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
5862   pg->peers = GNUNET_malloc (total * sizeof (struct PeerData));
5863   pg->max_outstanding_connections = max_concurrent_connections;
5864   pg->max_concurrent_ssh = max_concurrent_ssh;
5865   if (NULL != hostnames)
5866   {
5867     off = 0;
5868     hostpos = hostnames;
5869     while (hostpos != NULL)
5870     {
5871       hostpos = hostpos->next;
5872       off++;
5873     }
5874     pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
5875     off = 0;
5876
5877     hostpos = hostnames;
5878     while (hostpos != NULL)
5879     {
5880       pg->hosts[off].minport = LOW_PORT;
5881       pg->hosts[off].hostname = GNUNET_strdup (hostpos->hostname);
5882       if (hostpos->username != NULL)
5883         pg->hosts[off].username = GNUNET_strdup (hostpos->username);
5884       pg->hosts[off].sshport = hostpos->port;
5885       hostpos = hostpos->next;
5886       off++;
5887     }
5888
5889     if (off == 0)
5890     {
5891       pg->hosts = NULL;
5892     }
5893     hostcnt = off;
5894     minport = 0;
5895     pg->num_hosts = off;
5896   }
5897   else
5898   {
5899     hostcnt = 0;
5900     minport = LOW_PORT;
5901   }
5902
5903   /* Create the servicehome directory for each remote peer */
5904   GNUNET_assert (GNUNET_OK ==
5905                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
5906                                                         "SERVICEHOME",
5907                                                         &baseservicehome));
5908   for (i = 0; i < pg->num_hosts; i++)
5909   {
5910     ssh_entry = GNUNET_malloc (sizeof (struct OutstandingSSH));
5911     ssh_entry->hostname = pg->hosts[i].hostname;        /* Don't free! */
5912     GNUNET_CONTAINER_DLL_insert (pg->ssh_head, pg->ssh_tail, ssh_entry);
5913     GNUNET_asprintf (&tmpdir, "%s/%s", baseservicehome, pg->hosts[i].hostname);
5914     if (NULL != pg->hosts[i].username)
5915       GNUNET_asprintf (&arg, "%s@%s", pg->hosts[i].username,
5916                        pg->hosts[i].hostname);
5917     else
5918       GNUNET_asprintf (&arg, "%s", pg->hosts[i].hostname);
5919     if (pg->hosts[i].sshport != 0)
5920     {
5921       GNUNET_asprintf (&ssh_port_str, "%d", pg->hosts[i].sshport);
5922       proc =
5923         GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "ssh", "ssh", "-P", ssh_port_str,
5924                                    "-q",
5925                                    arg, "mkdir -p", tmpdir, NULL);
5926     }
5927     else
5928       proc =
5929         GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "ssh", "ssh", arg, "mkdir -p",
5930                                    tmpdir, NULL);
5931     GNUNET_assert (proc != NULL);
5932     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5933                 "Creating remote dir with command ssh %s %s %s\n", arg,
5934                 " mkdir -p ", tmpdir);
5935     GNUNET_free (tmpdir);
5936     GNUNET_free (arg);
5937     GNUNET_OS_process_wait (proc);
5938     GNUNET_OS_process_destroy (proc);
5939   }
5940   GNUNET_free (baseservicehome);
5941   baseservicehome = NULL;
5942
5943   if (GNUNET_YES ==
5944       GNUNET_CONFIGURATION_get_value_string (cfg, "TESTING", "HOSTKEYSFILE",
5945                                              &hostkeys_file))
5946   {
5947     if (GNUNET_YES != GNUNET_DISK_file_test (hostkeys_file))
5948       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5949                   _("Could not read hostkeys file!\n"));
5950     else
5951     {
5952       /* Check hostkey file size, read entire thing into memory */
5953       fd = GNUNET_DISK_file_open (hostkeys_file, GNUNET_DISK_OPEN_READ,
5954                                   GNUNET_DISK_PERM_NONE);
5955       if (NULL == fd)
5956       {
5957         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open",
5958                                   hostkeys_file);
5959         GNUNET_free (hostkeys_file);
5960         for (i = 0; i < pg->num_hosts; i++)
5961         {
5962           GNUNET_free (pg->hosts[i].hostname);
5963           GNUNET_free_non_null (pg->hosts[i].username);
5964         }
5965         GNUNET_free (pg->peers);
5966         GNUNET_free (pg->hosts);
5967         GNUNET_free (pg);
5968         return NULL;
5969       }
5970
5971       if (GNUNET_OK != GNUNET_DISK_file_size (hostkeys_file, &fs, GNUNET_YES, GNUNET_YES))
5972         fs = 0;
5973       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5974                   "Found file size %llu for hostkeys\n", fs);
5975       if (0 != (fs % HOSTKEYFILESIZE))
5976       {
5977         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5978                     "File size %llu seems incorrect for hostkeys...\n", fs);
5979       }
5980       else
5981       {
5982         total_hostkeys = fs / HOSTKEYFILESIZE;
5983         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5984                     "Will read %llu hostkeys from file\n", total_hostkeys);
5985         pg->hostkey_data = GNUNET_malloc_large (fs);
5986         GNUNET_assert (fs == GNUNET_DISK_file_read (fd, pg->hostkey_data, fs));
5987       }
5988       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
5989     }
5990     GNUNET_free (hostkeys_file);
5991   }
5992
5993   for (off = 0; off < total; off++)
5994   {
5995     if (hostcnt > 0)
5996     {
5997       hostname = pg->hosts[off % hostcnt].hostname;
5998       username = pg->hosts[off % hostcnt].username;
5999       sshport = pg->hosts[off % hostcnt].sshport;
6000       pcfg =
6001           GNUNET_TESTING_create_cfg (cfg, off, &pg->hosts[off % hostcnt].minport, &upnum,
6002                        hostname, &fdnum);
6003     }
6004     else
6005     {
6006       hostname = NULL;
6007       username = NULL;
6008       sshport = 0;
6009       pcfg = GNUNET_TESTING_create_cfg (cfg, off, &minport, &upnum, hostname, &fdnum);
6010     }
6011
6012     if (NULL == pcfg)
6013     {
6014       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6015                   _
6016                   ("Could not create configuration for peer number %u on `%s'!\n"),
6017                   off, hostname == NULL ? "localhost" : hostname);
6018       continue;
6019     }
6020
6021     if (GNUNET_YES ==
6022         GNUNET_CONFIGURATION_get_value_string (pcfg, "PATHS", "SERVICEHOME",
6023                                                &baseservicehome))
6024     {
6025       if (hostname != NULL)
6026         GNUNET_asprintf (&newservicehome, "%s/%s/%d/", baseservicehome,
6027                          hostname, off);
6028       else
6029         GNUNET_asprintf (&newservicehome, "%s/%d/", baseservicehome, off);
6030       GNUNET_free (baseservicehome);
6031       baseservicehome = NULL;
6032     }
6033     else
6034     {
6035       tmpdir = getenv ("TMPDIR");
6036       tmpdir = tmpdir ? tmpdir : "/tmp";
6037       if (hostname != NULL)
6038         GNUNET_asprintf (&newservicehome, "%s/%s/%s/%d/", tmpdir, hostname,
6039                          "gnunet-testing-test-test", off);
6040       else
6041         GNUNET_asprintf (&newservicehome, "%s/%s/%d/", tmpdir,
6042                          "gnunet-testing-test-test", off);
6043     }
6044     GNUNET_CONFIGURATION_set_value_string (pcfg, "PATHS", "SERVICEHOME",
6045                                            newservicehome);
6046     GNUNET_free (newservicehome);
6047     pg->peers[off].cfg = pcfg;
6048     pg->peers[off].pg = pg;
6049     pg->peers[off].internal_context.peer = &pg->peers[off];
6050     pg->peers[off].internal_context.timeout = timeout;
6051     pg->peers[off].internal_context.hostname = hostname;
6052     pg->peers[off].internal_context.username = username;
6053     pg->peers[off].internal_context.sshport = sshport;
6054     if (pg->hostkey_data != NULL)
6055       pg->peers[off].internal_context.hostkey =
6056           &pg->hostkey_data[off * HOSTKEYFILESIZE];
6057     pg->peers[off].internal_context.hostkey_callback = hostkey_callback;
6058     pg->peers[off].internal_context.hostkey_cls = hostkey_cls;
6059     pg->peers[off].internal_context.start_cb = cb;
6060     pg->peers[off].internal_context.start_cb_cls = cb_cls;
6061 #if !USE_START_HELPER
6062     GNUNET_SCHEDULER_add_now (&internal_start,
6063                               &pg->peers[off].internal_context);
6064 #else
6065     if ((pg->hostkey_data != NULL) && (hostcnt > 0))
6066     {
6067       pg->peers[off].daemon =
6068           GNUNET_TESTING_daemon_start (pcfg, timeout, GNUNET_YES, hostname,
6069                                        username, sshport,
6070                                        pg->peers[off].internal_context.hostkey,
6071                                        &internal_hostkey_callback,
6072                                        &pg->peers[off].internal_context,
6073                                        &internal_startup_callback,
6074                                        &pg->peers[off].internal_context);
6075           /**
6076            * At this point, given that we had a hostkeyfile,
6077            * we can call the hostkey callback!
6078            * But first, we should copy (rsync) all of the configs
6079            * and hostkeys to the remote peers.  Then let topology
6080            * creation happen, then call the peer start helper processes,
6081            * then set pg->whatever_phase for each peer and let them
6082            * enter the fsm to get the HELLO's for peers and start connecting.
6083            */
6084     }
6085     else
6086     {
6087       GNUNET_SCHEDULER_add_now (&internal_start,
6088                                 &pg->peers[off].internal_context);
6089     }
6090
6091 #endif
6092   }
6093
6094 #if USE_START_HELPER            /* Now the peergroup has been set up, hostkeys and configs written to files. */
6095   if ((pg->hostkey_data != NULL) && (hostcnt > 0))
6096   {
6097     for (off = 0; off < hostcnt; off++)
6098     {
6099
6100       if (hostcnt > 0)
6101       {
6102         hostname = pg->hosts[off % hostcnt].hostname;
6103         username = pg->hosts[off % hostcnt].username;
6104         sshport = pg->hosts[off % hostcnt].sshport;
6105       }
6106       else
6107       {
6108         hostname = NULL;
6109         username = NULL;
6110         sshport = 0;
6111       }
6112
6113       if (GNUNET_YES ==
6114           GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS", "SERVICEHOME",
6115                                                  &baseservicehome))
6116       {
6117         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "baseservice home is %s\n",
6118                     baseservicehome);
6119         if (hostname != NULL)
6120           GNUNET_asprintf (&newservicehome, "%s/%s/", baseservicehome,
6121                            hostname);
6122         else
6123           GNUNET_asprintf (&newservicehome, "%s/", baseservicehome);
6124         GNUNET_free (baseservicehome);
6125         baseservicehome = NULL;
6126       }
6127       else
6128       {
6129         tmpdir = getenv ("TMPDIR");
6130         tmpdir = tmpdir ? tmpdir : "/tmp";
6131         if (hostname != NULL)
6132           GNUNET_asprintf (&newservicehome, "%s/%s/%s/", tmpdir, hostname,
6133                            "gnunet-testing-test-test");
6134         else
6135           GNUNET_asprintf (&newservicehome, "%s/%s/", tmpdir,
6136                            "gnunet-testing-test-test", off);
6137       }
6138
6139       if (NULL != username)
6140         GNUNET_asprintf (&arg, "%s@%s:%s", username, pg->hosts[off].hostname,
6141                          newservicehome);
6142       else
6143         GNUNET_asprintf (&arg, "%s:%s", pg->hosts[off].hostname,
6144                          newservicehome);
6145
6146       /* FIXME: Doesn't support ssh_port option! */
6147       proc =
6148         GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "rsync", "rsync", "-r",
6149                                    newservicehome, arg, NULL);
6150       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6151                   "copying directory with command rsync -r %s %s\n",
6152                   newservicehome, arg);
6153       GNUNET_free (newservicehome);
6154       GNUNET_free (arg);
6155       if (NULL == proc)
6156       {
6157         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6158                     _
6159                     ("Could not start `%s' process to copy configuration directory.\n"),
6160                     "scp");
6161         GNUNET_assert (0);
6162       }
6163       GNUNET_OS_process_wait (proc);
6164       GNUNET_OS_process_destroy (proc);
6165     }
6166     /* Now all the configuration files and hostkeys are copied to the remote host.  Call the hostkey callback for each peer! */
6167     GNUNET_SCHEDULER_add_now (&call_hostkey_callbacks, pg);
6168   }
6169 #endif
6170   return pg;
6171 }
6172
6173 /*
6174  * Get a daemon by number, so callers don't have to do nasty
6175  * offsetting operation.
6176  */
6177 struct GNUNET_TESTING_Daemon *
6178 GNUNET_TESTING_daemon_get (struct GNUNET_TESTING_PeerGroup *pg,
6179                            unsigned int position)
6180 {
6181   if (position < pg->total)
6182     return pg->peers[position].daemon;
6183   return NULL;
6184 }
6185
6186 /*
6187  * Get a daemon by peer identity, so callers can
6188  * retrieve the daemon without knowing it's offset.
6189  *
6190  * @param pg the peer group to retrieve the daemon from
6191  * @param peer_id the peer identity of the daemon to retrieve
6192  *
6193  * @return the daemon on success, or NULL if no such peer identity is found
6194  */
6195 struct GNUNET_TESTING_Daemon *
6196 GNUNET_TESTING_daemon_get_by_id (struct GNUNET_TESTING_PeerGroup *pg,
6197                                  const struct GNUNET_PeerIdentity *peer_id)
6198 {
6199   unsigned int i;
6200
6201   for (i = 0; i < pg->total; i++)
6202   {
6203     if (0 ==
6204         memcmp (&pg->peers[i].daemon->id, peer_id,
6205                 sizeof (struct GNUNET_PeerIdentity)))
6206       return pg->peers[i].daemon;
6207   }
6208   return NULL;
6209 }
6210
6211 /**
6212  * Prototype of a function that will be called when a
6213  * particular operation was completed the testing library.
6214  *
6215  * @param cls closure (a struct RestartContext)
6216  * @param id id of the peer that was restarted
6217  * @param cfg handle to the configuration of the peer
6218  * @param d handle to the daemon that was restarted
6219  * @param emsg NULL on success
6220  */
6221 static void
6222 restart_callback (void *cls, const struct GNUNET_PeerIdentity *id,
6223                   const struct GNUNET_CONFIGURATION_Handle *cfg,
6224                   struct GNUNET_TESTING_Daemon *d, const char *emsg)
6225 {
6226   struct RestartContext *restart_context = cls;
6227
6228   if (emsg == NULL)
6229   {
6230     restart_context->peers_restarted++;
6231   }
6232   else
6233   {
6234     restart_context->peers_restart_failed++;
6235   }
6236
6237   if (restart_context->peers_restarted == restart_context->peer_group->total)
6238   {
6239     restart_context->callback (restart_context->callback_cls, NULL);
6240     GNUNET_free (restart_context);
6241   }
6242   else if (restart_context->peers_restart_failed +
6243            restart_context->peers_restarted ==
6244            restart_context->peer_group->total)
6245   {
6246     restart_context->callback (restart_context->callback_cls,
6247                                "Failed to restart peers!");
6248     GNUNET_free (restart_context);
6249   }
6250
6251 }
6252
6253 /**
6254  * Callback for informing us about a successful
6255  * or unsuccessful churn stop call.
6256  *
6257  * @param cls a ChurnContext
6258  * @param emsg NULL on success, non-NULL on failure
6259  *
6260  */
6261 static void
6262 churn_stop_callback (void *cls, const char *emsg)
6263 {
6264   struct ShutdownContext *shutdown_ctx = cls;
6265   struct ChurnContext *churn_ctx = shutdown_ctx->cb_cls;
6266   unsigned int total_left;
6267   char *error_message;
6268
6269   error_message = NULL;
6270   shutdown_ctx->outstanding--;
6271
6272   if (emsg != NULL)
6273   {
6274     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6275                 "Churn stop callback failed with error `%s'\n", emsg);
6276     churn_ctx->num_failed_stop++;
6277   }
6278   else
6279   {
6280     churn_ctx->num_to_stop--;
6281   }
6282
6283   total_left =
6284       (churn_ctx->num_to_stop - churn_ctx->num_failed_stop) +
6285       (churn_ctx->num_to_start - churn_ctx->num_failed_start);
6286
6287   if (total_left == 0)
6288   {
6289     if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
6290     {
6291       GNUNET_asprintf (&error_message,
6292                        "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!",
6293                        churn_ctx->num_failed_start, churn_ctx->num_failed_stop);
6294     }
6295     churn_ctx->cb (churn_ctx->cb_cls, error_message);
6296     GNUNET_free_non_null (error_message);
6297     GNUNET_free (churn_ctx);
6298     GNUNET_free (shutdown_ctx);
6299   }
6300 }
6301
6302 /**
6303  * Count the number of running peers.
6304  *
6305  * @param pg handle for the peer group
6306  *
6307  * @return the number of currently running peers in the peer group
6308  */
6309 unsigned int
6310 GNUNET_TESTING_daemons_running (struct GNUNET_TESTING_PeerGroup *pg)
6311 {
6312   unsigned int i;
6313   unsigned int running = 0;
6314
6315   for (i = 0; i < pg->total; i++)
6316   {
6317     if (pg->peers[i].daemon->running == GNUNET_YES)
6318     {
6319       GNUNET_assert (running != -1);
6320       running++;
6321     }
6322   }
6323   return running;
6324 }
6325
6326 /**
6327  * Task to rate limit the number of outstanding peer shutdown
6328  * requests.  This is necessary for making sure we don't do
6329  * too many ssh connections at once, but is generally nicer
6330  * to any system as well (graduated task starts, as opposed
6331  * to calling gnunet-arm N times all at once).
6332  */
6333 static void
6334 schedule_churn_shutdown_task (void *cls,
6335                               const struct GNUNET_SCHEDULER_TaskContext *tc)
6336 {
6337   struct PeerShutdownContext *peer_shutdown_ctx = cls;
6338   struct ShutdownContext *shutdown_ctx;
6339   struct ChurnContext *churn_ctx;
6340
6341   GNUNET_assert (peer_shutdown_ctx != NULL);
6342   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
6343   GNUNET_assert (shutdown_ctx != NULL);
6344   churn_ctx = (struct ChurnContext *) shutdown_ctx->cb_cls;
6345   if (shutdown_ctx->outstanding > churn_ctx->pg->max_concurrent_ssh)
6346     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
6347                                   (GNUNET_TIME_UNIT_MILLISECONDS, 100),
6348                                   &schedule_churn_shutdown_task,
6349                                   peer_shutdown_ctx);
6350   else
6351   {
6352     shutdown_ctx->outstanding++;
6353     if (churn_ctx->service != NULL)
6354       GNUNET_TESTING_daemon_stop_service (peer_shutdown_ctx->daemon,
6355                                           churn_ctx->service,
6356                                           shutdown_ctx->timeout,
6357                                           shutdown_ctx->cb, shutdown_ctx);
6358     else
6359       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon,
6360                                   shutdown_ctx->timeout, shutdown_ctx->cb,
6361                                   shutdown_ctx, GNUNET_NO, GNUNET_YES);
6362     GNUNET_free (peer_shutdown_ctx);
6363   }
6364 }
6365
6366
6367 /**
6368  * Simulate churn by stopping some peers (and possibly
6369  * re-starting others if churn is called multiple times).  This
6370  * function can only be used to create leave-join churn (peers "never"
6371  * leave for good).  First "voff" random peers that are currently
6372  * online will be taken offline; then "von" random peers that are then
6373  * offline will be put back online.  No notifications will be
6374  * generated for any of these operations except for the callback upon
6375  * completion.
6376  *
6377  * @param pg handle for the peer group
6378  * @param service the service to churn off/on, NULL to churn peer
6379  * @param voff number of peers that should go offline
6380  * @param von number of peers that should come back online;
6381  *            must be zero on first call (since "testbed_start"
6382  *            always starts all of the peers)
6383  * @param timeout how long to wait for operations to finish before
6384  *        giving up
6385  * @param cb function to call at the end
6386  * @param cb_cls closure for cb
6387  */
6388 void
6389 GNUNET_TESTING_daemons_churn (struct GNUNET_TESTING_PeerGroup *pg,
6390                               char *service, unsigned int voff,
6391                               unsigned int von,
6392                               struct GNUNET_TIME_Relative timeout,
6393                               GNUNET_TESTING_NotifyCompletion cb, void *cb_cls)
6394 {
6395   struct ChurnContext *churn_ctx;
6396   struct ShutdownContext *shutdown_ctx;
6397   struct PeerShutdownContext *peer_shutdown_ctx;
6398   struct PeerRestartContext *peer_restart_ctx;
6399   struct ChurnRestartContext *churn_startup_ctx;
6400
6401   unsigned int running;
6402   unsigned int stopped;
6403   unsigned int total_running;
6404   unsigned int total_stopped;
6405   unsigned int i;
6406   unsigned int *running_arr;
6407   unsigned int *stopped_arr;
6408   unsigned int *running_permute;
6409   unsigned int *stopped_permute;
6410   char *pos;
6411
6412   shutdown_ctx = NULL;
6413   peer_shutdown_ctx = NULL;
6414   peer_restart_ctx = NULL;
6415   churn_startup_ctx = NULL;
6416
6417   running = 0;
6418   stopped = 0;
6419
6420   if ((von == 0) && (voff == 0))        /* No peers at all? */
6421   {
6422     cb (cb_cls, NULL);
6423     return;
6424   }
6425
6426   for (i = 0; i < pg->total; i++)
6427   {
6428     if (service == NULL)
6429     {
6430       if (pg->peers[i].daemon->running == GNUNET_YES)
6431       {
6432         GNUNET_assert (running != -1);
6433         running++;
6434       }
6435       else
6436       {
6437         GNUNET_assert (stopped != -1);
6438         stopped++;
6439       }
6440     }
6441     else
6442     {
6443       /* FIXME: make churned services a list! */
6444       pos = pg->peers[i].daemon->churned_services;
6445       /* FIXME: while (pos != NULL) */
6446       if (pos != NULL)
6447       {
6448 #if FIXME
6449         if (0 == strcasecmp (pos, service))
6450         {
6451
6452           break;
6453         }
6454 #endif
6455         GNUNET_assert (stopped != -1);
6456         stopped++;
6457         /* FIXME: pos = pos->next; */
6458       }
6459       if (pos == NULL)
6460       {
6461         GNUNET_assert (running != -1);
6462         running++;
6463       }
6464     }
6465   }
6466
6467   if (voff > running)
6468   {
6469     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6470                 "Trying to stop more peers (%d) than are currently running (%d)!\n",
6471                 voff, running);
6472     cb (cb_cls, "Trying to stop more peers than are currently running!");
6473     return;
6474   }
6475
6476   if (von > stopped)
6477   {
6478     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6479                 "Trying to start more peers (%d) than are currently stopped (%d)!\n",
6480                 von, stopped);
6481     cb (cb_cls, "Trying to start more peers than are currently stopped!");
6482     return;
6483   }
6484
6485   churn_ctx = GNUNET_malloc (sizeof (struct ChurnContext));
6486
6487   if (service != NULL)
6488     churn_ctx->service = GNUNET_strdup (service);
6489   running_arr = NULL;
6490   if (running > 0)
6491     running_arr = GNUNET_malloc (running * sizeof (unsigned int));
6492
6493   stopped_arr = NULL;
6494   if (stopped > 0)
6495     stopped_arr = GNUNET_malloc (stopped * sizeof (unsigned int));
6496
6497   running_permute = NULL;
6498   stopped_permute = NULL;
6499
6500   if (running > 0)
6501     running_permute =
6502         GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, running);
6503   if (stopped > 0)
6504     stopped_permute =
6505         GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, stopped);
6506
6507   total_running = running;
6508   total_stopped = stopped;
6509   running = 0;
6510   stopped = 0;
6511
6512   churn_ctx->num_to_start = von;
6513   churn_ctx->num_to_stop = voff;
6514   churn_ctx->cb = cb;
6515   churn_ctx->cb_cls = cb_cls;
6516   churn_ctx->pg = pg;
6517
6518   for (i = 0; i < pg->total; i++)
6519   {
6520     if (service == NULL)
6521     {
6522       if (pg->peers[i].daemon->running == GNUNET_YES)
6523       {
6524         GNUNET_assert ((running_arr != NULL) && (total_running > running));
6525         running_arr[running] = i;
6526         running++;
6527       }
6528       else
6529       {
6530         GNUNET_assert ((stopped_arr != NULL) && (total_stopped > stopped));
6531         stopped_arr[stopped] = i;
6532         stopped++;
6533       }
6534     }
6535     else
6536     {
6537       /* FIXME: make churned services a list! */
6538       pos = pg->peers[i].daemon->churned_services;
6539       /* FIXME: while (pos != NULL) */
6540       if (pos != NULL)
6541       {
6542         GNUNET_assert ((stopped_arr != NULL) && (total_stopped > stopped));
6543         stopped_arr[stopped] = i;
6544         stopped++;
6545         /* FIXME: pos = pos->next; */
6546       }
6547       if (pos == NULL)
6548       {
6549         GNUNET_assert ((running_arr != NULL) && (total_running > running));
6550         running_arr[running] = i;
6551         running++;
6552       }
6553     }
6554   }
6555
6556   GNUNET_assert (running >= voff);
6557   if (voff > 0)
6558   {
6559     shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
6560     shutdown_ctx->cb = &churn_stop_callback;
6561     shutdown_ctx->cb_cls = churn_ctx;
6562     shutdown_ctx->total_peers = voff;
6563     shutdown_ctx->timeout = timeout;
6564   }
6565
6566   for (i = 0; i < voff; i++)
6567   {
6568     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Stopping peer %d!\n",
6569                 running_arr[running_permute[i]]);
6570     GNUNET_assert (running_arr != NULL);
6571     peer_shutdown_ctx = GNUNET_malloc (sizeof (struct PeerShutdownContext));
6572     peer_shutdown_ctx->daemon =
6573         pg->peers[running_arr[running_permute[i]]].daemon;
6574     peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
6575     GNUNET_SCHEDULER_add_now (&schedule_churn_shutdown_task, peer_shutdown_ctx);
6576   }
6577
6578   GNUNET_assert (stopped >= von);
6579   if (von > 0)
6580   {
6581     churn_startup_ctx = GNUNET_malloc (sizeof (struct ChurnRestartContext));
6582     churn_startup_ctx->churn_ctx = churn_ctx;
6583     churn_startup_ctx->timeout = timeout;
6584     churn_startup_ctx->pg = pg;
6585   }
6586   for (i = 0; i < von; i++)
6587   {
6588     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting up peer %d!\n",
6589                 stopped_arr[stopped_permute[i]]);
6590     GNUNET_assert (stopped_arr != NULL);
6591     peer_restart_ctx = GNUNET_malloc (sizeof (struct PeerRestartContext));
6592     peer_restart_ctx->churn_restart_ctx = churn_startup_ctx;
6593     peer_restart_ctx->daemon =
6594         pg->peers[stopped_arr[stopped_permute[i]]].daemon;
6595     GNUNET_SCHEDULER_add_now (&schedule_churn_restart, peer_restart_ctx);
6596   }
6597
6598   GNUNET_free_non_null (running_arr);
6599   GNUNET_free_non_null (stopped_arr);
6600   GNUNET_free_non_null (running_permute);
6601   GNUNET_free_non_null (stopped_permute);
6602 }
6603
6604 /*
6605  * Start a given service for each of the peers in the peer group.
6606  *
6607  * @param pg handle for the peer group
6608  * @param service the service to start
6609  * @param timeout how long to wait for operations to finish before
6610  *        giving up
6611  * @param cb function to call once finished
6612  * @param cb_cls closure for cb
6613  *
6614  */
6615 void
6616 GNUNET_TESTING_daemons_start_service (struct GNUNET_TESTING_PeerGroup *pg,
6617                                       char *service,
6618                                       struct GNUNET_TIME_Relative timeout,
6619                                       GNUNET_TESTING_NotifyCompletion cb,
6620                                       void *cb_cls)
6621 {
6622   struct ServiceStartContext *start_ctx;
6623   struct PeerServiceStartContext *peer_start_ctx;
6624   unsigned int i;
6625
6626   GNUNET_assert (service != NULL);
6627
6628   start_ctx = GNUNET_malloc (sizeof (struct ServiceStartContext));
6629   start_ctx->pg = pg;
6630   start_ctx->remaining = pg->total;
6631   start_ctx->cb = cb;
6632   start_ctx->cb_cls = cb_cls;
6633   start_ctx->service = GNUNET_strdup (service);
6634   start_ctx->timeout = timeout;
6635
6636   for (i = 0; i < pg->total; i++)
6637   {
6638     peer_start_ctx = GNUNET_malloc (sizeof (struct PeerServiceStartContext));
6639     peer_start_ctx->start_ctx = start_ctx;
6640     peer_start_ctx->daemon = pg->peers[i].daemon;
6641     GNUNET_SCHEDULER_add_now (&schedule_service_start, peer_start_ctx);
6642   }
6643 }
6644
6645 /**
6646  * Restart all peers in the given group.
6647  *
6648  * @param pg the handle to the peer group
6649  * @param callback function to call on completion (or failure)
6650  * @param callback_cls closure for the callback function
6651  */
6652 void
6653 GNUNET_TESTING_daemons_restart (struct GNUNET_TESTING_PeerGroup *pg,
6654                                 GNUNET_TESTING_NotifyCompletion callback,
6655                                 void *callback_cls)
6656 {
6657   struct RestartContext *restart_context;
6658   unsigned int off;
6659
6660   if (pg->total > 0)
6661   {
6662     restart_context = GNUNET_malloc (sizeof (struct RestartContext));
6663     restart_context->peer_group = pg;
6664     restart_context->peers_restarted = 0;
6665     restart_context->callback = callback;
6666     restart_context->callback_cls = callback_cls;
6667
6668     for (off = 0; off < pg->total; off++)
6669     {
6670       GNUNET_TESTING_daemon_restart (pg->peers[off].daemon, &restart_callback,
6671                                      restart_context);
6672     }
6673   }
6674 }
6675
6676
6677 /**
6678  * Start or stop an individual peer from the given group.
6679  *
6680  * @param pg handle to the peer group
6681  * @param offset which peer to start or stop
6682  * @param desired_status GNUNET_YES to have it running, GNUNET_NO to stop it
6683  * @param timeout how long to wait for shutdown
6684  * @param cb function to call at the end
6685  * @param cb_cls closure for cb
6686  */
6687 void
6688 GNUNET_TESTING_daemons_vary (struct GNUNET_TESTING_PeerGroup *pg,
6689                              unsigned int offset, int desired_status,
6690                              struct GNUNET_TIME_Relative timeout,
6691                              GNUNET_TESTING_NotifyCompletion cb, void *cb_cls)
6692 {
6693   struct ShutdownContext *shutdown_ctx;
6694   struct ChurnRestartContext *startup_ctx;
6695   struct ChurnContext *churn_ctx;
6696
6697   if (GNUNET_NO == desired_status)
6698   {
6699     if (NULL != pg->peers[offset].daemon)
6700     {
6701       shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
6702       churn_ctx = GNUNET_malloc (sizeof (struct ChurnContext));
6703       churn_ctx->num_to_start = 0;
6704       churn_ctx->num_to_stop = 1;
6705       churn_ctx->cb = cb;
6706       churn_ctx->cb_cls = cb_cls;
6707       shutdown_ctx->cb_cls = churn_ctx;
6708       GNUNET_TESTING_daemon_stop (pg->peers[offset].daemon, timeout,
6709                                   &churn_stop_callback, shutdown_ctx, GNUNET_NO,
6710                                   GNUNET_YES);
6711     }
6712   }
6713   else if (GNUNET_YES == desired_status)
6714   {
6715     if (NULL == pg->peers[offset].daemon)
6716     {
6717       startup_ctx = GNUNET_malloc (sizeof (struct ChurnRestartContext));
6718       churn_ctx = GNUNET_malloc (sizeof (struct ChurnContext));
6719       churn_ctx->num_to_start = 1;
6720       churn_ctx->num_to_stop = 0;
6721       churn_ctx->cb = cb;
6722       churn_ctx->cb_cls = cb_cls;
6723       startup_ctx->churn_ctx = churn_ctx;
6724       GNUNET_TESTING_daemon_start_stopped (pg->peers[offset].daemon, timeout,
6725                                            &churn_start_callback, startup_ctx);
6726     }
6727   }
6728   else
6729     GNUNET_break (0);
6730 }
6731
6732
6733 /**
6734  * Callback for shutting down peers in a peer group.
6735  *
6736  * @param cls closure (struct ShutdownContext)
6737  * @param emsg NULL on success
6738  */
6739 static void
6740 internal_shutdown_callback (void *cls, const char *emsg)
6741 {
6742   struct PeerShutdownContext *peer_shutdown_ctx = cls;
6743   struct ShutdownContext *shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
6744   unsigned int off;
6745   int i;
6746   struct OutstandingSSH *ssh_pos;
6747
6748   shutdown_ctx->outstanding--;
6749   if (peer_shutdown_ctx->daemon->hostname != NULL)
6750     decrement_outstanding_at_host (peer_shutdown_ctx->daemon->hostname,
6751                                    shutdown_ctx->pg);
6752
6753   if (emsg == NULL)
6754   {
6755     shutdown_ctx->peers_down++;
6756   }
6757   else
6758   {
6759     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "internal_shutdown_callback",
6760                      "Failed to stop a peer: %s\n", emsg);
6761     shutdown_ctx->peers_failed++;
6762   }
6763
6764   if ((shutdown_ctx->cb != NULL) &&
6765       (shutdown_ctx->peers_down + shutdown_ctx->peers_failed ==
6766        shutdown_ctx->total_peers))
6767   {
6768     if (shutdown_ctx->peers_failed > 0)
6769       shutdown_ctx->cb (shutdown_ctx->cb_cls,
6770                         "Not all peers successfully shut down!");
6771     else
6772       shutdown_ctx->cb (shutdown_ctx->cb_cls, NULL);
6773
6774     for (i = 0; i < shutdown_ctx->pg->total; i++)
6775     {
6776       if (shutdown_ctx->pg->peers[i].startup_task != GNUNET_SCHEDULER_NO_TASK)
6777         GNUNET_SCHEDULER_cancel (shutdown_ctx->pg->peers[i].startup_task);
6778     }
6779     GNUNET_free (shutdown_ctx->pg->peers);
6780     GNUNET_free_non_null (shutdown_ctx->pg->hostkey_data);
6781     for (off = 0; off < shutdown_ctx->pg->num_hosts; off++)
6782     {
6783       GNUNET_free (shutdown_ctx->pg->hosts[off].hostname);
6784       GNUNET_free_non_null (shutdown_ctx->pg->hosts[off].username);
6785     }
6786     GNUNET_free_non_null (shutdown_ctx->pg->hosts);
6787     while (NULL != (ssh_pos = shutdown_ctx->pg->ssh_head))
6788     {
6789       GNUNET_CONTAINER_DLL_remove (shutdown_ctx->pg->ssh_head,
6790                                    shutdown_ctx->pg->ssh_tail, ssh_pos);
6791       GNUNET_free (ssh_pos);
6792     }
6793     GNUNET_free (shutdown_ctx->pg);
6794     GNUNET_free (shutdown_ctx);
6795   }
6796   GNUNET_free (peer_shutdown_ctx);
6797 }
6798
6799
6800 /**
6801  * Task to rate limit the number of outstanding peer shutdown
6802  * requests.  This is necessary for making sure we don't do
6803  * too many ssh connections at once, but is generally nicer
6804  * to any system as well (graduated task starts, as opposed
6805  * to calling gnunet-arm N times all at once).
6806  */
6807 static void
6808 schedule_shutdown_task (void *cls,
6809                         const struct GNUNET_SCHEDULER_TaskContext *tc)
6810 {
6811   struct PeerShutdownContext *peer_shutdown_ctx = cls;
6812   struct ShutdownContext *shutdown_ctx;
6813   struct GNUNET_TESTING_Daemon *d;
6814
6815   GNUNET_assert (peer_shutdown_ctx != NULL);
6816   d = peer_shutdown_ctx->daemon;
6817   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
6818   GNUNET_assert (shutdown_ctx != NULL);
6819
6820   if ((shutdown_ctx->outstanding < shutdown_ctx->pg->max_concurrent_ssh) ||
6821       ((d->hostname != NULL) &&
6822        (count_outstanding_at_host
6823         (d->hostname,
6824          shutdown_ctx->pg) < shutdown_ctx->pg->max_concurrent_ssh)))
6825   {
6826     if (d->hostname != NULL)
6827       increment_outstanding_at_host (d->hostname,
6828                                      shutdown_ctx->pg);
6829     shutdown_ctx->outstanding++;
6830     GNUNET_TESTING_daemon_stop (d,
6831                                 shutdown_ctx->timeout,
6832                                 &internal_shutdown_callback, peer_shutdown_ctx,
6833                                 shutdown_ctx->delete_files, GNUNET_NO);
6834   }
6835   else
6836     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
6837                                   (GNUNET_TIME_UNIT_MILLISECONDS, 100),
6838                                   &schedule_shutdown_task, peer_shutdown_ctx);
6839
6840 }
6841
6842 /**
6843  * Read a testing hosts file based on a configuration.
6844  * Returns a DLL of hosts (caller must free!) on success
6845  * or NULL on failure.
6846  *
6847  * @param cfg a configuration with a testing section
6848  *
6849  * @return DLL of hosts on success, NULL on failure
6850  */
6851 struct GNUNET_TESTING_Host *
6852 GNUNET_TESTING_hosts_load (const struct GNUNET_CONFIGURATION_Handle *cfg)
6853 {
6854   struct GNUNET_TESTING_Host *hosts;
6855   struct GNUNET_TESTING_Host *temphost;
6856   char *data;
6857   char *buf;
6858   char *hostfile;
6859   struct stat frstat;
6860   int count;
6861   int ret;
6862
6863   /* Check for a hostfile containing user@host:port triples */
6864   if (GNUNET_OK !=
6865       GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "hostfile",
6866                                              &hostfile))
6867     return NULL;
6868
6869   hosts = NULL;
6870   temphost = NULL;
6871   data = NULL;
6872   if (hostfile != NULL)
6873   {
6874     if (GNUNET_OK != GNUNET_DISK_file_test (hostfile))
6875       GNUNET_DISK_fn_write (hostfile, NULL, 0,
6876                             GNUNET_DISK_PERM_USER_READ |
6877                             GNUNET_DISK_PERM_USER_WRITE);
6878     if ((0 != STAT (hostfile, &frstat)) || (frstat.st_size == 0))
6879     {
6880       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6881                   "Could not open file specified for host list, ending test!");
6882       GNUNET_free (hostfile);
6883       return NULL;
6884     }
6885
6886     data = GNUNET_malloc_large (frstat.st_size);
6887     GNUNET_assert (data != NULL);
6888     if (frstat.st_size != GNUNET_DISK_fn_read (hostfile, data, frstat.st_size))
6889     {
6890       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6891                   "Could not read file %s specified for host list, ending test!",
6892                   hostfile);
6893       GNUNET_free (hostfile);
6894       GNUNET_free (data);
6895       return NULL;
6896     }
6897
6898     GNUNET_free_non_null (hostfile);
6899
6900     buf = data;
6901     count = 0;
6902     while (count < frstat.st_size - 1)
6903     {
6904       count++;
6905       if (((data[count] == '\n')) && (buf != &data[count]))
6906       {
6907         data[count] = '\0';
6908         temphost = GNUNET_malloc (sizeof (struct GNUNET_TESTING_Host));
6909         ret =
6910             SSCANF (buf, "%a[a-zA-Z0-9_]@%a[a-zA-Z0-9.]:%hd",
6911                     &temphost->username, &temphost->hostname, &temphost->port);
6912         if (3 == ret)
6913         {
6914           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6915                       "Successfully read host %s, port %d and user %s from file\n",
6916                       temphost->hostname, temphost->port, temphost->username);
6917         }
6918         else
6919         {
6920           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6921                       "Error reading line `%s' in hostfile\n", buf);
6922           GNUNET_free (temphost);
6923           buf = &data[count + 1];
6924           continue;
6925         }
6926         temphost->next = hosts;
6927         hosts = temphost;
6928         buf = &data[count + 1];
6929       }
6930       else if ((data[count] == '\n') || (data[count] == '\0'))
6931         buf = &data[count + 1];
6932     }
6933   }
6934   GNUNET_free_non_null (data);
6935
6936   return hosts;
6937 }
6938
6939 /**
6940  * Shutdown all peers started in the given group.
6941  *
6942  * @param pg handle to the peer group
6943  * @param timeout how long to wait for shutdown
6944  * @param cb callback to notify upon success or failure
6945  * @param cb_cls closure for cb
6946  */
6947 void
6948 GNUNET_TESTING_daemons_stop (struct GNUNET_TESTING_PeerGroup *pg,
6949                              struct GNUNET_TIME_Relative timeout,
6950                              GNUNET_TESTING_NotifyCompletion cb, void *cb_cls)
6951 {
6952   unsigned int off;
6953   struct ShutdownContext *shutdown_ctx;
6954   struct PeerShutdownContext *peer_shutdown_ctx;
6955
6956 #if OLD
6957   struct PeerConnection *conn_iter;
6958   struct PeerConnection *temp_conn;
6959 #endif
6960   struct ConnectContext *cc;
6961
6962   GNUNET_assert (pg->total > 0);
6963   while (NULL != (cc = pg->cc_head))
6964   {
6965     GNUNET_CONTAINER_DLL_remove (pg->cc_head, pg->cc_tail, cc);
6966     if (GNUNET_SCHEDULER_NO_TASK != cc->task)
6967       GNUNET_SCHEDULER_cancel (cc->task);
6968     if (NULL != cc->cc)
6969       GNUNET_TESTING_daemons_connect_cancel (cc->cc);
6970     GNUNET_free (cc);
6971   }
6972
6973   shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
6974   shutdown_ctx->delete_files =
6975       GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "TESTING", "DELETE_FILES");
6976   shutdown_ctx->cb = cb;
6977   shutdown_ctx->cb_cls = cb_cls;
6978   shutdown_ctx->total_peers = pg->total;
6979   shutdown_ctx->timeout = timeout;
6980   shutdown_ctx->pg = pg;
6981
6982   for (off = 0; off < pg->total; off++)
6983   {
6984     GNUNET_assert (NULL != pg->peers[off].daemon);
6985     peer_shutdown_ctx = GNUNET_malloc (sizeof (struct PeerShutdownContext));
6986     peer_shutdown_ctx->daemon = pg->peers[off].daemon;
6987     peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
6988     GNUNET_SCHEDULER_add_now (&schedule_shutdown_task, peer_shutdown_ctx);
6989
6990     if (NULL != pg->peers[off].cfg)
6991     {
6992       GNUNET_CONFIGURATION_destroy (pg->peers[off].cfg);
6993       pg->peers[off].cfg = NULL;
6994     }
6995 #if OLD
6996 // FIXME Do DLL remove for all pg->peers[off].LIST
6997     conn_iter = pg->peers[off].allowed_peers_head;
6998     while (conn_iter != NULL)
6999     {
7000       temp_conn = conn_iter->next;
7001       GNUNET_free (conn_iter);
7002       conn_iter = temp_conn;
7003     }
7004     pg->peers[off].allowed_peers_head = NULL;
7005
7006     conn_iter = pg->peers[off].connect_peers_head;
7007     while (conn_iter != NULL)
7008     {
7009       temp_conn = conn_iter->next;
7010       GNUNET_free (conn_iter);
7011       conn_iter = temp_conn;
7012     }
7013     pg->peers[off].connect_peers_head = NULL;
7014
7015     conn_iter = pg->peers[off].blacklisted_peers_head;
7016     while (conn_iter != NULL)
7017     {
7018       temp_conn = conn_iter->next;
7019       GNUNET_free (conn_iter);
7020       conn_iter = temp_conn;
7021     }
7022     pg->peers[off].blacklisted_peers_head = NULL;
7023
7024     conn_iter = pg->peers[off].connect_peers_working_set_head;
7025     while (conn_iter != NULL)
7026     {
7027       temp_conn = conn_iter->next;
7028       GNUNET_free (conn_iter);
7029       conn_iter = temp_conn;
7030     }
7031     pg->peers[off].connect_peers_working_set_head = NULL;
7032 #else
7033     if (pg->peers[off].allowed_peers != NULL)
7034       GNUNET_CONTAINER_multihashmap_destroy (pg->peers[off].allowed_peers);
7035     if (pg->peers[off].connect_peers != NULL)
7036       GNUNET_CONTAINER_multihashmap_destroy (pg->peers[off].connect_peers);
7037     if (pg->peers[off].blacklisted_peers != NULL)
7038       GNUNET_CONTAINER_multihashmap_destroy (pg->peers[off].blacklisted_peers);
7039 #endif
7040   }
7041 }
7042
7043 /* end of testing_group.c */