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