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