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