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