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