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