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