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