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