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