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