(no commit message)
[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_peer_index = 0;
2556   /* First line should contain a single integer, specifying the number of peers */
2557   /* Each subsequent line should contain this format PEER_INDEX:OTHER_PEER_INDEX[,...] */
2558   curr_state = NUM_PEERS;
2559   while (count < frstat.st_size - 1)
2560     {
2561       if ((buf[count] == '\n') || (buf[count] == ' '))
2562         {
2563           count++;
2564           continue;
2565         }
2566
2567       switch (curr_state)
2568         {
2569       case NUM_PEERS:
2570         errno = 0;
2571         total_peers = strtoul(&buf[count], NULL, 10);
2572         if (errno != 0)
2573           {
2574             GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2575                         "Failed to read number of peers from topology file!\n");
2576             GNUNET_free_non_null(data);
2577             return connect_attempts;
2578           }
2579         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2580                     "Read %u total peers in topology\n", total_peers);
2581         GNUNET_assert(total_peers == pg->total);
2582         curr_state = PEER_INDEX;
2583         while ((buf[count] != '\n') && (count < frstat.st_size - 1))
2584           count++;
2585         count++;
2586         break;
2587       case PEER_INDEX:
2588         errno = 0;
2589         first_peer_index = strtoul(&buf[count], NULL, 10);
2590         if (errno != 0)
2591           {
2592             GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2593                         "Failed to read peer index from topology file!\n");
2594             GNUNET_free_non_null(data);
2595             return connect_attempts;
2596           }
2597         while ((buf[count] != ':') && (count < frstat.st_size - 1))
2598           count++;
2599         count++;
2600         curr_state = OTHER_PEER_INDEX;
2601         break;
2602       case COLON:
2603         if (1 == sscanf (&buf[count], ":"))
2604           curr_state = OTHER_PEER_INDEX;
2605         count++;
2606         break;
2607       case OTHER_PEER_INDEX:
2608         errno = 0;
2609         second_peer_index = strtoul(&buf[count], NULL, 10);
2610         if (errno != 0)
2611           {
2612             GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2613                         "Failed to peer index from topology file!\n");
2614             GNUNET_free_non_null(data);
2615             return connect_attempts;
2616           }
2617         /* Assume file is written with first peer 1, but array index is 0 */
2618         connect_attempts += proc (pg, first_peer_index - 1, second_peer_index
2619                                   - 1, list, GNUNET_YES);
2620         while ((buf[count] != '\n') && (buf[count] != ',') && (count
2621             < frstat.st_size - 1))
2622           count++;
2623         if (buf[count] == '\n')
2624           {
2625             curr_state = PEER_INDEX;
2626           }
2627         else if (buf[count] != ',')
2628           {
2629             curr_state = OTHER_PEER_INDEX;
2630           }
2631         count++;
2632         break;
2633       default:
2634         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2635                     "Found bad data in topology file while in state %d!\n",
2636                     curr_state);
2637         GNUNET_break(0);
2638         return connect_attempts;
2639         }
2640
2641     }
2642 #if 0
2643   /* Connect each peer to the next highest numbered peer */
2644   for (count = 0; count < pg->total - 1; count++)
2645     {
2646 #if VERBOSE_TESTING
2647       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2648           "Connecting peer %d to peer %d\n", first_peer_index, second_peer_index);
2649 #endif
2650       connect_attempts += proc (pg, first_peer_index, second_peer_index);
2651     }
2652 #endif
2653   return connect_attempts;
2654 }
2655
2656 /**
2657  * Create a topology given a peer group (set of running peers)
2658  * and a connection processor.
2659  *
2660  * @param pg the peergroup to create the topology on
2661  * @param proc the connection processor to call to actually set
2662  *        up connections between two peers
2663  * @param list the peer list to use
2664  *
2665  * @return the number of connections that were set up
2666  *
2667  */
2668 static unsigned int
2669 create_ring(struct GNUNET_TESTING_PeerGroup *pg,
2670             GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
2671 {
2672   unsigned int count;
2673   int connect_attempts;
2674
2675   connect_attempts = 0;
2676
2677   /* Connect each peer to the next highest numbered peer */
2678   for (count = 0; count < pg->total - 1; count++)
2679     {
2680 #if VERBOSE_TESTING
2681       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2682           "Connecting peer %d to peer %d\n", count, count + 1);
2683 #endif
2684       connect_attempts += proc (pg, count, count + 1, list, GNUNET_YES);
2685     }
2686
2687   /* Connect the last peer to the first peer */
2688   connect_attempts += proc (pg, pg->total - 1, 0, list, GNUNET_YES);
2689
2690   return connect_attempts;
2691 }
2692
2693 #if !OLD
2694 /**
2695  * Iterator for writing friends of a peer to a file.
2696  *
2697  * @param cls closure, an open writable file handle
2698  * @param key the key the daemon was stored under
2699  * @param value the GNUNET_TESTING_Daemon that needs to be written.
2700  *
2701  * @return GNUNET_YES to continue iteration
2702  *
2703  * TODO: Could replace friend_file_iterator and blacklist_file_iterator
2704  *       with a single file_iterator that takes a closure which contains
2705  *       the prefix to write before the peer.  Then this could be used
2706  *       for blacklisting multiple transports and writing the friend
2707  *       file.  I'm sure *someone* will complain loudly about other
2708  *       things that negate these functions even existing so no point in
2709  *       "fixing" now.
2710  */
2711 static int
2712 friend_file_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2713   {
2714     FILE *temp_friend_handle = cls;
2715     struct GNUNET_TESTING_Daemon *peer = value;
2716     struct GNUNET_PeerIdentity *temppeer;
2717     struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2718
2719     temppeer = &peer->id;
2720     GNUNET_CRYPTO_hash_to_enc (&temppeer->hashPubKey, &peer_enc);
2721     fprintf (temp_friend_handle, "%s\n", (char *) &peer_enc);
2722
2723     return GNUNET_YES;
2724   }
2725
2726 struct BlacklistContext
2727   {
2728     /*
2729      * The (open) file handle to write to
2730      */
2731     FILE *temp_file_handle;
2732
2733     /*
2734      * The transport that this peer will be blacklisted on.
2735      */
2736     char *transport;
2737   };
2738
2739 /**
2740  * Iterator for writing blacklist data to appropriate files.
2741  *
2742  * @param cls closure, an open writable file handle
2743  * @param key the key the daemon was stored under
2744  * @param value the GNUNET_TESTING_Daemon that needs to be written.
2745  *
2746  * @return GNUNET_YES to continue iteration
2747  */
2748 static int
2749 blacklist_file_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2750   {
2751     struct BlacklistContext *blacklist_ctx = cls;
2752     struct GNUNET_TESTING_Daemon *peer = value;
2753     struct GNUNET_PeerIdentity *temppeer;
2754     struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2755
2756     temppeer = &peer->id;
2757     GNUNET_CRYPTO_hash_to_enc (&temppeer->hashPubKey, &peer_enc);
2758     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Writing entry %s:%s to file\n", blacklist_ctx->transport, (char *) &peer_enc);
2759     fprintf (blacklist_ctx->temp_file_handle, "%s:%s\n",
2760         blacklist_ctx->transport, (char *) &peer_enc);
2761
2762     return GNUNET_YES;
2763   }
2764 #endif
2765
2766 /*
2767  * Create the friend files based on the PeerConnection's
2768  * of each peer in the peer group, and copy the files
2769  * to the appropriate place
2770  *
2771  * @param pg the peer group we are dealing with
2772  */
2773 static int
2774 create_and_copy_friend_files(struct GNUNET_TESTING_PeerGroup *pg)
2775 {
2776   FILE *temp_friend_handle;
2777   unsigned int pg_iter;
2778   char *temp_service_path;
2779   struct GNUNET_OS_Process **procarr;
2780   char *arg;
2781   char *mytemp;
2782 #if NOT_STUPID
2783   enum GNUNET_OS_ProcessStatusType type;
2784   unsigned long return_code;
2785   int count;
2786   int max_wait = 10;
2787 #endif
2788   int ret;
2789
2790   ret = GNUNET_OK;
2791 #if OLD
2792   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2793   struct PeerConnection *conn_iter;
2794 #endif
2795   procarr = GNUNET_malloc (sizeof (struct GNUNET_OS_Process *) * pg->total);
2796   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2797     {
2798       mytemp = GNUNET_DISK_mktemp ("friends");
2799       GNUNET_assert (mytemp != NULL);
2800       temp_friend_handle = fopen (mytemp, "wt");
2801       GNUNET_assert (temp_friend_handle != NULL);
2802 #if OLD
2803       conn_iter = pg->peers[pg_iter].allowed_peers_head;
2804       while (conn_iter != NULL)
2805         {
2806           GNUNET_CRYPTO_hash_to_enc (
2807                                      &pg->peers[conn_iter->index].daemon->id.hashPubKey,
2808                                      &peer_enc);
2809           fprintf (temp_friend_handle, "%s\n", (char *) &peer_enc);
2810           conn_iter = conn_iter->next;
2811         }
2812 #else
2813       GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].allowed_peers,
2814           &friend_file_iterator,
2815           temp_friend_handle);
2816 #endif
2817       fclose (temp_friend_handle);
2818
2819       if (GNUNET_OK
2820           != GNUNET_CONFIGURATION_get_value_string (
2821                                                     pg->peers[pg_iter]. daemon->cfg,
2822                                                     "PATHS", "SERVICEHOME",
2823                                                     &temp_service_path))
2824         {
2825           GNUNET_log (
2826                       GNUNET_ERROR_TYPE_WARNING,
2827                       _
2828                       ("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
2829                       "SERVICEHOME", "PATHS");
2830           if (UNLINK (mytemp) != 0)
2831             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
2832                 mytemp);
2833           GNUNET_free (mytemp);
2834           break;
2835         }
2836
2837       if (pg->peers[pg_iter].daemon->hostname == NULL) /* Local, just copy the file */
2838         {
2839           GNUNET_asprintf (&arg, "%s/friends", temp_service_path);
2840           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "mv", "mv",
2841                                                       mytemp, arg, NULL);
2842 #if VERBOSE_TESTING
2843           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2844               _("Copying file with command cp %s %s\n"), mytemp, arg);
2845 #endif
2846           ret = GNUNET_OS_process_wait (procarr[pg_iter]); /* FIXME: schedule this, throttle! */
2847           GNUNET_OS_process_close (procarr[pg_iter]);
2848           GNUNET_free (arg);
2849         }
2850       else /* Remote, scp the file to the correct place */
2851         {
2852           if (NULL != pg->peers[pg_iter].daemon->username)
2853             GNUNET_asprintf (&arg, "%s@%s:%s/friends",
2854                              pg->peers[pg_iter].daemon->username,
2855                              pg->peers[pg_iter].daemon->hostname,
2856                              temp_service_path);
2857           else
2858             GNUNET_asprintf (&arg, "%s:%s/friends",
2859                              pg->peers[pg_iter].daemon->hostname,
2860                              temp_service_path);
2861           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "scp", "scp",
2862                                                       mytemp, arg, NULL);
2863
2864           ret = GNUNET_OS_process_wait (procarr[pg_iter]); /* FIXME: schedule this, throttle! */
2865           GNUNET_OS_process_close (procarr[pg_iter]);
2866           if (ret != GNUNET_OK)
2867             return ret;
2868           procarr[pg_iter] = NULL;
2869 #if VERBOSE_TESTING
2870           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2871               _("Copying file with command scp %s %s\n"), mytemp,
2872               arg);
2873 #endif
2874           GNUNET_free (arg);
2875         }
2876       GNUNET_free (temp_service_path);
2877       GNUNET_free (mytemp);
2878     }
2879
2880 #if NOT_STUPID
2881   count = 0;
2882   ret = GNUNET_SYSERR;
2883   while ((count < max_wait) && (ret != GNUNET_OK))
2884     {
2885       ret = GNUNET_OK;
2886       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2887         {
2888 #if VERBOSE_TESTING
2889           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2890               _("Checking copy status of file %d\n"), pg_iter);
2891 #endif
2892           if (procarr[pg_iter] != NULL) /* Check for already completed! */
2893             {
2894               if (GNUNET_OS_process_status
2895                   (procarr[pg_iter], &type, &return_code) != GNUNET_OK)
2896                 {
2897                   ret = GNUNET_SYSERR;
2898                 }
2899               else if ((type != GNUNET_OS_PROCESS_EXITED)
2900                   || (return_code != 0))
2901                 {
2902                   ret = GNUNET_SYSERR;
2903                 }
2904               else
2905                 {
2906                   GNUNET_OS_process_close (procarr[pg_iter]);
2907                   procarr[pg_iter] = NULL;
2908 #if VERBOSE_TESTING
2909                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2910                       _("File %d copied\n"), pg_iter);
2911 #endif
2912                 }
2913             }
2914         }
2915       count++;
2916       if (ret == GNUNET_SYSERR)
2917         {
2918           /* FIXME: why sleep here? -CG */
2919           sleep (1);
2920         }
2921     }
2922
2923 #if VERBOSE_TESTING
2924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2925       _("Finished copying all friend files!\n"));
2926 #endif
2927 #endif
2928   GNUNET_free (procarr);
2929   return ret;
2930 }
2931
2932 /*
2933  * Create the blacklist files based on the PeerConnection's
2934  * of each peer in the peer group, and copy the files
2935  * to the appropriate place.
2936  *
2937  * @param pg the peer group we are dealing with
2938  * @param transports space delimited list of transports to blacklist
2939  */
2940 static int
2941 create_and_copy_blacklist_files(struct GNUNET_TESTING_PeerGroup *pg,
2942                                 const char *transports)
2943 {
2944   FILE *temp_file_handle;
2945   unsigned int pg_iter;
2946   char *temp_service_path;
2947   struct GNUNET_OS_Process **procarr;
2948   char *arg;
2949   char *mytemp;
2950   enum GNUNET_OS_ProcessStatusType type;
2951   unsigned long return_code;
2952   int count;
2953   int ret;
2954   int max_wait = 10;
2955   int transport_len;
2956   unsigned int i;
2957   char *pos;
2958   char *temp_transports;
2959   int entry_count;
2960 #if OLD
2961   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
2962   struct PeerConnection *conn_iter;
2963 #else
2964   static struct BlacklistContext blacklist_ctx;
2965 #endif
2966
2967   procarr = GNUNET_malloc (sizeof (struct GNUNET_OS_Process *) * pg->total);
2968   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2969     {
2970       mytemp = GNUNET_DISK_mktemp ("blacklist");
2971       GNUNET_assert (mytemp != NULL);
2972       temp_file_handle = fopen (mytemp, "wt");
2973       GNUNET_assert (temp_file_handle != NULL);
2974       temp_transports = GNUNET_strdup (transports);
2975 #if !OLD
2976       blacklist_ctx.temp_file_handle = temp_file_handle;
2977 #endif
2978       transport_len = strlen (temp_transports) + 1;
2979       pos = NULL;
2980
2981       for (i = 0; i < transport_len; i++)
2982         {
2983           if ((temp_transports[i] == ' ') && (pos == NULL))
2984             continue; /* At start of string (whitespace) */
2985           else if ((temp_transports[i] == ' ') || (temp_transports[i] == '\0')) /* At end of string */
2986             {
2987               temp_transports[i] = '\0';
2988 #if OLD
2989               conn_iter = pg->peers[pg_iter].blacklisted_peers_head;
2990               while (conn_iter != NULL)
2991                 {
2992                   GNUNET_CRYPTO_hash_to_enc (
2993                                              &pg->peers[conn_iter->index].daemon->id.hashPubKey,
2994                                              &peer_enc);
2995                   fprintf (temp_file_handle, "%s:%s\n", pos, (char *) &peer_enc);
2996                   conn_iter = conn_iter->next;
2997                   entry_count++;
2998                 }
2999 #else
3000               blacklist_ctx.transport = pos;
3001               entry_count = GNUNET_CONTAINER_multihashmap_iterate (pg->
3002                   peers
3003                   [pg_iter].blacklisted_peers,
3004                   &blacklist_file_iterator,
3005                   &blacklist_ctx);
3006 #endif
3007               pos = NULL;
3008             } /* At beginning of actual string */
3009           else if (pos == NULL)
3010             {
3011               pos = &temp_transports[i];
3012             }
3013         }
3014
3015       GNUNET_free (temp_transports);
3016       fclose (temp_file_handle);
3017
3018       if (GNUNET_OK
3019           != GNUNET_CONFIGURATION_get_value_string (
3020                                                     pg->peers[pg_iter]. daemon->cfg,
3021                                                     "PATHS", "SERVICEHOME",
3022                                                     &temp_service_path))
3023         {
3024           GNUNET_log (
3025                       GNUNET_ERROR_TYPE_WARNING,
3026                       _
3027                       ("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
3028                       "SERVICEHOME", "PATHS");
3029           if (UNLINK (mytemp) != 0)
3030             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
3031                 mytemp);
3032           GNUNET_free (mytemp);
3033           break;
3034         }
3035
3036       if (pg->peers[pg_iter].daemon->hostname == NULL) /* Local, just copy the file */
3037         {
3038           GNUNET_asprintf (&arg, "%s/blacklist", temp_service_path);
3039           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "mv", "mv",
3040                                                       mytemp, arg, NULL);
3041 #if VERBOSE_TESTING
3042           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3043               _("Copying file with command cp %s %s\n"), mytemp, arg);
3044 #endif
3045
3046           GNUNET_free (arg);
3047         }
3048       else /* Remote, scp the file to the correct place */
3049         {
3050           if (NULL != pg->peers[pg_iter].daemon->username)
3051             GNUNET_asprintf (&arg, "%s@%s:%s/blacklist",
3052                              pg->peers[pg_iter].daemon->username,
3053                              pg->peers[pg_iter].daemon->hostname,
3054                              temp_service_path);
3055           else
3056             GNUNET_asprintf (&arg, "%s:%s/blacklist",
3057                              pg->peers[pg_iter].daemon->hostname,
3058                              temp_service_path);
3059           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "scp", "scp",
3060                                                       mytemp, arg, NULL);
3061
3062           GNUNET_OS_process_wait (procarr[pg_iter]); /* FIXME: add scheduled blacklist file copy that parallelizes file copying! */
3063
3064 #if VERBOSE_TESTING
3065           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3066               _("Copying file with command scp %s %s\n"), mytemp,
3067               arg);
3068 #endif
3069           GNUNET_free (arg);
3070         }
3071       GNUNET_free (temp_service_path);
3072       GNUNET_free (mytemp);
3073     }
3074
3075   count = 0;
3076   ret = GNUNET_SYSERR;
3077   while ((count < max_wait) && (ret != GNUNET_OK))
3078     {
3079       ret = GNUNET_OK;
3080       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3081         {
3082 #if VERBOSE_TESTING
3083           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3084               _("Checking copy status of file %d\n"), pg_iter);
3085 #endif
3086           if (procarr[pg_iter] != NULL) /* Check for already completed! */
3087             {
3088               if (GNUNET_OS_process_status (procarr[pg_iter], &type,
3089                                             &return_code) != GNUNET_OK)
3090                 {
3091                   ret = GNUNET_SYSERR;
3092                 }
3093               else if ((type != GNUNET_OS_PROCESS_EXITED) || (return_code != 0))
3094                 {
3095                   ret = GNUNET_SYSERR;
3096                 }
3097               else
3098                 {
3099                   GNUNET_OS_process_close (procarr[pg_iter]);
3100                   procarr[pg_iter] = NULL;
3101 #if VERBOSE_TESTING
3102                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3103                       _("File %d copied\n"), pg_iter);
3104 #endif
3105                 }
3106             }
3107         }
3108       count++;
3109       if (ret == GNUNET_SYSERR)
3110         {
3111           /* FIXME: why sleep here? -CG */
3112           sleep (1);
3113         }
3114     }
3115
3116 #if VERBOSE_TESTING
3117   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3118       _("Finished copying all blacklist files!\n"));
3119 #endif
3120   GNUNET_free (procarr);
3121   return ret;
3122 }
3123
3124 /* Forward Declaration */
3125 static void
3126 schedule_connect(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
3127
3128 /**
3129  * Choose a random peer's next connection to create, and
3130  * call schedule_connect to set up the connect task.
3131  *
3132  * @param ct_ctx the overall connection context
3133  */
3134 static void
3135 preschedule_connect(struct GNUNET_TESTING_PeerGroup *pg)
3136 {
3137   struct ConnectTopologyContext *ct_ctx = &pg->ct_ctx;
3138   struct PeerConnection *connection_iter;
3139   struct ConnectContext *connect_context;
3140   uint32_t random_peer;
3141
3142   if (ct_ctx->remaining_connections == 0)
3143     return;
3144   random_peer
3145       = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, pg->total);
3146   while (pg->peers[random_peer].connect_peers_head == NULL)
3147     random_peer = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3148                                             pg->total);
3149
3150   connection_iter = pg->peers[random_peer].connect_peers_head;
3151   connect_context = GNUNET_malloc (sizeof (struct ConnectContext));
3152   connect_context->first_index = random_peer;
3153   connect_context->second_index = connection_iter->index;
3154   connect_context->ct_ctx = ct_ctx;
3155   GNUNET_SCHEDULER_add_now (&schedule_connect, connect_context);
3156   GNUNET_CONTAINER_DLL_remove(pg->peers[random_peer].connect_peers_head, pg->peers[random_peer].connect_peers_tail, connection_iter);
3157   GNUNET_free(connection_iter);
3158   ct_ctx->remaining_connections--;
3159 }
3160
3161 #if USE_SEND_HELLOS
3162 /* Forward declaration */
3163 static void schedule_send_hellos (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
3164
3165 /**
3166  * Close connections and free the hello context.
3167  *
3168  * @param cls the 'struct SendHelloContext *'
3169  * @param tc scheduler context
3170  */
3171 static void
3172 free_hello_context (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3173   {
3174     struct SendHelloContext *send_hello_context = cls;
3175     if (send_hello_context->peer->daemon->server != NULL)
3176       {
3177         GNUNET_CORE_disconnect(send_hello_context->peer->daemon->server);
3178         send_hello_context->peer->daemon->server = NULL;
3179       }
3180     if (send_hello_context->peer->daemon->th != NULL)
3181       {
3182         GNUNET_TRANSPORT_disconnect(send_hello_context->peer->daemon->th);
3183         send_hello_context->peer->daemon->th = NULL;
3184       }
3185     if (send_hello_context->core_connect_task != GNUNET_SCHEDULER_NO_TASK)
3186       {
3187         GNUNET_SCHEDULER_cancel(send_hello_context->core_connect_task);
3188         send_hello_context->core_connect_task = GNUNET_SCHEDULER_NO_TASK;
3189       }
3190     send_hello_context->pg->outstanding_connects--;
3191     GNUNET_free(send_hello_context);
3192   }
3193
3194 /**
3195  * For peers that haven't yet connected, notify
3196  * the caller that they have failed (timeout).
3197  *
3198  * @param cls the 'struct SendHelloContext *'
3199  * @param tc scheduler context
3200  */
3201 static void
3202 notify_remaining_connections_failed (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3203   {
3204     struct SendHelloContext *send_hello_context = cls;
3205     struct GNUNET_TESTING_PeerGroup *pg = send_hello_context->pg;
3206     struct PeerConnection *connection;
3207
3208     GNUNET_CORE_disconnect(send_hello_context->peer->daemon->server);
3209     send_hello_context->peer->daemon->server = NULL;
3210
3211     connection = send_hello_context->peer->connect_peers_head;
3212
3213     while (connection != NULL)
3214       {
3215         if (pg->notify_connection != NULL)
3216           {
3217             pg->notify_connection(pg->notify_connection_cls,
3218                 &send_hello_context->peer->daemon->id,
3219                 &pg->peers[connection->index].daemon->id,
3220                 0, /* FIXME */
3221                 send_hello_context->peer->daemon->cfg,
3222                 pg->peers[connection->index].daemon->cfg,
3223                 send_hello_context->peer->daemon,
3224                 pg->peers[connection->index].daemon,
3225                 "Peers failed to connect (timeout)");
3226           }
3227         GNUNET_CONTAINER_DLL_remove(send_hello_context->peer->connect_peers_head, send_hello_context->peer->connect_peers_tail, connection);
3228         GNUNET_free(connection);
3229         connection = connection->next;
3230       }
3231     GNUNET_SCHEDULER_add_now(&free_hello_context, send_hello_context);
3232 #if BAD
3233     other_peer = &pg->peers[connection->index];
3234 #endif
3235   }
3236
3237 /**
3238  * For peers that haven't yet connected, send
3239  * CORE connect requests.
3240  *
3241  * @param cls the 'struct SendHelloContext *'
3242  * @param tc scheduler context
3243  */
3244 static void
3245 send_core_connect_requests (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3246   {
3247     struct SendHelloContext *send_hello_context = cls;
3248     struct PeerConnection *conn;
3249     GNUNET_assert(send_hello_context->peer->daemon->server != NULL);
3250
3251     send_hello_context->core_connect_task = GNUNET_SCHEDULER_NO_TASK;
3252
3253     send_hello_context->connect_attempts++;
3254     if (send_hello_context->connect_attempts < send_hello_context->pg->ct_ctx.connect_attempts)
3255       {
3256         conn = send_hello_context->peer->connect_peers_head;
3257         while (conn != NULL)
3258           {
3259             GNUNET_CORE_peer_request_connect(send_hello_context->peer->daemon->server,
3260                 GNUNET_TIME_relative_get_forever(),
3261                 &send_hello_context->pg->peers[conn->index].daemon->id,
3262                 NULL,
3263                 NULL);
3264             conn = conn->next;
3265           }
3266         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) ,
3267             &send_core_connect_requests,
3268             send_hello_context);
3269       }
3270     else
3271       {
3272         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Timeout before all connections created, marking rest as failed!\n");
3273         GNUNET_SCHEDULER_add_now(&notify_remaining_connections_failed, send_hello_context);
3274       }
3275
3276   }
3277
3278 /**
3279  * Success, connection is up.  Signal client our success.
3280  *
3281  * @param cls our "struct SendHelloContext"
3282  * @param peer identity of the peer that has connected
3283  * @param atsi performance information
3284  *
3285  * FIXME: remove peers from BOTH lists, call notify twice, should
3286  * double the speed of connections as long as the list iteration
3287  * doesn't take too long!
3288  */
3289 static void
3290 core_connect_notify (void *cls,
3291     const struct GNUNET_PeerIdentity *peer,
3292     const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3293   {
3294     struct SendHelloContext *send_hello_context = cls;
3295     struct PeerConnection *connection;
3296     struct GNUNET_TESTING_PeerGroup *pg = send_hello_context->pg;
3297 #if BAD
3298     struct PeerData *other_peer;
3299 #endif
3300 #if DEBUG_TESTING
3301     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3302         "Connected peer %s to peer %s\n",
3303         ctx->d1->shortname, GNUNET_i2s(peer));
3304 #endif
3305
3306     if (0 == memcmp(&send_hello_context->peer->daemon->id, peer, sizeof(struct GNUNET_PeerIdentity)))
3307     return;
3308
3309     connection = send_hello_context->peer->connect_peers_head;
3310 #if BAD
3311     other_peer = NULL;
3312 #endif
3313
3314     while ((connection != NULL) &&
3315         (0 != memcmp(&pg->peers[connection->index].daemon->id, peer, sizeof(struct GNUNET_PeerIdentity))))
3316       {
3317         connection = connection->next;
3318       }
3319
3320     if (connection == NULL)
3321       {
3322         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);
3323       }
3324     else
3325       {
3326 #if BAD
3327         other_peer = &pg->peers[connection->index];
3328 #endif
3329         if (pg->notify_connection != NULL)
3330           {
3331             pg->notify_connection(pg->notify_connection_cls,
3332                 &send_hello_context->peer->daemon->id,
3333                 peer,
3334                 0, /* FIXME */
3335                 send_hello_context->peer->daemon->cfg,
3336                 pg->peers[connection->index].daemon->cfg,
3337                 send_hello_context->peer->daemon,
3338                 pg->peers[connection->index].daemon,
3339                 NULL);
3340           }
3341         GNUNET_CONTAINER_DLL_remove(send_hello_context->peer->connect_peers_head, send_hello_context->peer->connect_peers_tail, connection);
3342         GNUNET_free(connection);
3343       }
3344
3345 #if BAD
3346     /* Notify of reverse connection and remove from other peers list of outstanding */
3347     if (other_peer != NULL)
3348       {
3349         connection = other_peer->connect_peers_head;
3350         while ((connection != NULL) &&
3351             (0 != memcmp(&send_hello_context->peer->daemon->id, &pg->peers[connection->index].daemon->id, sizeof(struct GNUNET_PeerIdentity))))
3352           {
3353             connection = connection->next;
3354           }
3355         if (connection != NULL)
3356           {
3357             if (pg->notify_connection != NULL)
3358               {
3359                 pg->notify_connection(pg->notify_connection_cls,
3360                     peer,
3361                     &send_hello_context->peer->daemon->id,
3362                     0, /* FIXME */
3363                     pg->peers[connection->index].daemon->cfg,
3364                     send_hello_context->peer->daemon->cfg,
3365                     pg->peers[connection->index].daemon,
3366                     send_hello_context->peer->daemon,
3367                     NULL);
3368               }
3369
3370             GNUNET_CONTAINER_DLL_remove(other_peer->connect_peers_head, other_peer->connect_peers_tail, connection);
3371             GNUNET_free(connection);
3372           }
3373       }
3374 #endif
3375
3376     if (send_hello_context->peer->connect_peers_head == NULL)
3377       {
3378         GNUNET_SCHEDULER_add_now(&free_hello_context, send_hello_context);
3379       }
3380   }
3381
3382 /**
3383  * Notify of a successful connection to the core service.
3384  *
3385  * @param cls a struct SendHelloContext *
3386  * @param server handle to the core service
3387  * @param my_identity the peer identity of this peer
3388  * @param publicKey the public key of the peer
3389  */
3390 void
3391 core_init (void *cls,
3392     struct GNUNET_CORE_Handle * server,
3393     const struct GNUNET_PeerIdentity *
3394     my_identity,
3395     const struct
3396     GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
3397     publicKey)
3398   {
3399     struct SendHelloContext *send_hello_context = cls;
3400     send_hello_context->core_ready = GNUNET_YES;
3401   }
3402
3403 /**
3404  * Function called once a hello has been sent
3405  * to the transport, move on to the next one
3406  * or go away forever.
3407  *
3408  * @param cls the 'struct SendHelloContext *'
3409  * @param tc scheduler context
3410  */
3411 static void
3412 hello_sent_callback (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3413   {
3414     struct SendHelloContext *send_hello_context = cls;
3415     //unsigned int pg_iter;
3416     if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3417       {
3418         GNUNET_free(send_hello_context);
3419         return;
3420       }
3421
3422     send_hello_context->pg->remaining_hellos--;
3423 #if DEBUG_TESTING
3424     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sent HELLO, have %d remaining!\n", send_hello_context->pg->remaining_hellos);
3425 #endif
3426     if (send_hello_context->peer_pos == NULL) /* All HELLOs (for this peer!) have been transmitted! */
3427       {
3428 #if DEBUG_TESTING
3429         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "All hellos for this peer sent, disconnecting transport!\n");
3430 #endif
3431         GNUNET_assert(send_hello_context->peer->daemon->th != NULL);
3432         GNUNET_TRANSPORT_disconnect(send_hello_context->peer->daemon->th);
3433         send_hello_context->peer->daemon->th = NULL;
3434
3435         /*if (send_hello_context->pg->remaining_hellos == 0)
3436          {
3437          for (pg_iter = 0; pg_iter < send_hello_context->pg->max_outstanding_connections; pg_iter++)
3438          {
3439          preschedule_connect(&send_hello_context->pg->ct_ctx);
3440          }
3441          }
3442          */
3443         GNUNET_assert (send_hello_context->peer->daemon->server == NULL);
3444         send_hello_context->peer->daemon->server = GNUNET_CORE_connect(send_hello_context->peer->cfg,
3445             1,
3446             send_hello_context,
3447             &core_init,
3448             &core_connect_notify,
3449             NULL,
3450             NULL,
3451             NULL, GNUNET_NO,
3452             NULL, GNUNET_NO,
3453             no_handlers);
3454
3455         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),
3456             &send_core_connect_requests,
3457             send_hello_context);
3458       }
3459     else
3460     GNUNET_SCHEDULER_add_now(&schedule_send_hellos, send_hello_context);
3461   }
3462
3463 /**
3464  * Connect to a peer, give it all the HELLO's of those peers
3465  * we will later ask it to connect to.
3466  *
3467  * @param ct_ctx the overall connection context
3468  */
3469 static void schedule_send_hellos (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3470   {
3471     struct SendHelloContext *send_hello_context = cls;
3472     struct GNUNET_TESTING_PeerGroup *pg = send_hello_context->pg;
3473
3474     if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3475       {
3476         GNUNET_free(send_hello_context);
3477         return;
3478       }
3479
3480     GNUNET_assert(send_hello_context->peer_pos != NULL); /* All of the HELLO sends to be scheduled have been scheduled! */
3481
3482     if (((send_hello_context->peer->daemon->th == NULL) &&
3483             (pg->outstanding_connects > pg->max_outstanding_connections)) ||
3484         (pg->stop_connects == GNUNET_YES))
3485       {
3486 #if VERBOSE_TESTING > 2
3487         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3488             _
3489             ("Delaying connect, we have too many outstanding connections!\n"));
3490 #endif
3491         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3492             (GNUNET_TIME_UNIT_MILLISECONDS, 100),
3493             &schedule_send_hellos, send_hello_context);
3494       }
3495     else
3496       {
3497 #if VERBOSE_TESTING > 2
3498         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3499             _("Creating connection, outstanding_connections is %d\n"),
3500             outstanding_connects);
3501 #endif
3502         if (send_hello_context->peer->daemon->th == NULL)
3503           {
3504             pg->outstanding_connects++; /* Actual TRANSPORT, CORE connections! */
3505             send_hello_context->peer->daemon->th = GNUNET_TRANSPORT_connect(send_hello_context->peer->cfg,
3506                 NULL,
3507                 send_hello_context,
3508                 NULL,
3509                 NULL,
3510                 NULL);
3511           }
3512 #if DEBUG_TESTING
3513         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3514             _("Offering Hello of peer %s to peer %s\n"),
3515             send_hello_context->peer->daemon->shortname, pg->peers[send_hello_context->peer_pos->index].daemon->shortname);
3516 #endif
3517         GNUNET_TRANSPORT_offer_hello(send_hello_context->peer->daemon->th,
3518             (const struct GNUNET_MessageHeader *)pg->peers[send_hello_context->peer_pos->index].daemon->hello,
3519             &hello_sent_callback,
3520             send_hello_context);
3521         send_hello_context->peer_pos = send_hello_context->peer_pos->next;
3522         GNUNET_assert(send_hello_context->peer->daemon->th != NULL);
3523       }
3524   }
3525 #endif
3526
3527 /**
3528  * Internal notification of a connection, kept so that we can ensure some connections
3529  * happen instead of flooding all testing daemons with requests to connect.
3530  */
3531 static void
3532 internal_connect_notify(void *cls, const struct GNUNET_PeerIdentity *first,
3533                         const struct GNUNET_PeerIdentity *second,
3534                         uint32_t distance,
3535                         const struct GNUNET_CONFIGURATION_Handle *first_cfg,
3536                         const struct GNUNET_CONFIGURATION_Handle *second_cfg,
3537                         struct GNUNET_TESTING_Daemon *first_daemon,
3538                         struct GNUNET_TESTING_Daemon *second_daemon,
3539                         const char *emsg)
3540 {
3541   struct ConnectContext *connect_ctx = cls;
3542   struct ConnectTopologyContext *ct_ctx = connect_ctx->ct_ctx;
3543   struct GNUNET_TESTING_PeerGroup *pg = ct_ctx->pg;
3544   struct PeerConnection *connection;
3545   pg->outstanding_connects--;
3546
3547   /*
3548    * Check whether the inverse connection has been scheduled yet,
3549    * if not, we can remove it from the other peers list and avoid
3550    * even trying to connect them again!
3551    */
3552   connection = pg->peers[connect_ctx->second_index].connect_peers_head;
3553 #if BAD
3554   other_peer = NULL;
3555 #endif
3556
3557   while ((connection != NULL) && (0
3558       != memcmp (first, &pg->peers[connection->index].daemon->id,
3559                  sizeof(struct GNUNET_PeerIdentity))))
3560     {
3561       connection = connection->next;
3562     }
3563
3564   if (connection != NULL) /* Can safely remove! */
3565     {
3566       ct_ctx->remaining_connections--;
3567       if (pg->notify_connection != NULL) /* Notify of reverse connection */
3568         pg->notify_connection (pg->notify_connection_cls, second, first,
3569                                distance, second_cfg, first_cfg, second_daemon,
3570                                first_daemon, emsg);
3571
3572       GNUNET_CONTAINER_DLL_remove(pg->peers[connect_ctx->second_index].connect_peers_head, pg->peers[connect_ctx->second_index].connect_peers_tail, connection);
3573       GNUNET_free(connection);
3574     }
3575
3576   if (ct_ctx->remaining_connections == 0)
3577     {
3578       if (ct_ctx->notify_connections_done != NULL)
3579         ct_ctx->notify_connections_done (ct_ctx->notify_cls, NULL);
3580     }
3581   else
3582     preschedule_connect (pg);
3583
3584   if (pg->notify_connection != NULL)
3585     pg->notify_connection (pg->notify_connection_cls, first, second, distance,
3586                            first_cfg, second_cfg, first_daemon, second_daemon,
3587                            emsg);
3588
3589   GNUNET_free(connect_ctx);
3590 }
3591
3592 /**
3593  * Either delay a connection (because there are too many outstanding)
3594  * or schedule it for right now.
3595  *
3596  * @param cls a connection context
3597  * @param tc the task runtime context
3598  */
3599 static void
3600 schedule_connect(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3601 {
3602   struct ConnectContext *connect_context = cls;
3603   struct GNUNET_TESTING_PeerGroup *pg = connect_context->ct_ctx->pg;
3604
3605   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3606     return;
3607
3608   if ((pg->outstanding_connects > pg->max_outstanding_connections)
3609       || (pg->stop_connects == GNUNET_YES))
3610     {
3611 #if VERBOSE_TESTING
3612       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3613           _
3614           ("Delaying connect, we have too many outstanding connections!\n"));
3615 #endif
3616       GNUNET_SCHEDULER_add_delayed (
3617                                     GNUNET_TIME_relative_multiply (
3618                                                                    GNUNET_TIME_UNIT_MILLISECONDS,
3619                                                                    100),
3620                                     &schedule_connect, connect_context);
3621     }
3622   else
3623     {
3624 #if VERBOSE_TESTING
3625       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3626           _("Creating connection, outstanding_connections is %d (max %d)\n"),
3627           pg->outstanding_connects, pg->max_outstanding_connections);
3628 #endif
3629       pg->outstanding_connects++;
3630       pg->total_connects_scheduled++;
3631       GNUNET_TESTING_daemons_connect (
3632                                       pg->peers[connect_context->first_index].daemon,
3633                                       pg->peers[connect_context->second_index].daemon,
3634                                       connect_context->ct_ctx->connect_timeout,
3635                                       connect_context->ct_ctx->connect_attempts,
3636 #if USE_SEND_HELLOS
3637                                        GNUNET_NO,
3638 #else
3639                                       GNUNET_YES,
3640 #endif
3641                                       &internal_connect_notify, connect_context); /* FIXME: free connect context! */
3642     }
3643 }
3644
3645 #if !OLD
3646 /**
3647  * Iterator for actually scheduling connections to be created
3648  * between two peers.
3649  *
3650  * @param cls closure, a GNUNET_TESTING_Daemon
3651  * @param key the key the second Daemon was stored under
3652  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
3653  *
3654  * @return GNUNET_YES to continue iteration
3655  */
3656 static int
3657 connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
3658   {
3659     struct ConnectTopologyContext *ct_ctx = cls;
3660     struct PeerData *first = ct_ctx->first;
3661     struct GNUNET_TESTING_Daemon *second = value;
3662     struct ConnectContext *connect_context;
3663
3664     connect_context = GNUNET_malloc (sizeof (struct ConnectContext));
3665     connect_context->first = first->daemon;
3666     connect_context->second = second;
3667     connect_context->ct_ctx = ct_ctx;
3668     GNUNET_SCHEDULER_add_now (&schedule_connect, connect_context);
3669
3670     return GNUNET_YES;
3671   }
3672 #endif
3673
3674 #if !OLD
3675 /**
3676  * Iterator for copying all entries in the allowed hashmap to the
3677  * connect hashmap.
3678  *
3679  * @param cls closure, a GNUNET_TESTING_Daemon
3680  * @param key the key the second Daemon was stored under
3681  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
3682  *
3683  * @return GNUNET_YES to continue iteration
3684  */
3685 static int
3686 copy_topology_iterator (void *cls, const GNUNET_HashCode * key, void *value)
3687   {
3688     struct PeerData *first = cls;
3689
3690     GNUNET_assert (GNUNET_OK ==
3691         GNUNET_CONTAINER_multihashmap_put (first->connect_peers, key,
3692             value,
3693             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3694
3695     return GNUNET_YES;
3696   }
3697 #endif
3698
3699 /**
3700  * Make the peers to connect the same as those that are allowed to be
3701  * connected.
3702  *
3703  * @param pg the peer group
3704  */
3705 static int
3706 copy_allowed_topology(struct GNUNET_TESTING_PeerGroup *pg)
3707 {
3708   unsigned int pg_iter;
3709   int ret;
3710   int total;
3711 #if OLD
3712   struct PeerConnection *iter;
3713 #endif
3714   total = 0;
3715   ret = 0;
3716   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3717     {
3718 #if OLD
3719       iter = pg->peers[pg_iter].allowed_peers_head;
3720       while (iter != NULL)
3721         {
3722           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3723                       "Creating connection between %d and %d\n", pg_iter,
3724                       iter->index);
3725           total += add_connections (pg, pg_iter, iter->index, CONNECT,
3726                                     GNUNET_NO);
3727           //total += add_actual_connections(pg, pg_iter, iter->index);
3728           iter = iter->next;
3729         }
3730 #else
3731       ret =
3732       GNUNET_CONTAINER_multihashmap_iterate (pg->
3733           peers[pg_iter].allowed_peers,
3734           &copy_topology_iterator,
3735           &pg->peers[pg_iter]);
3736 #endif
3737       if (GNUNET_SYSERR == ret)
3738         return GNUNET_SYSERR;
3739
3740       total = total + ret;
3741     }
3742
3743   return total;
3744 }
3745
3746 /**
3747  * Connect the topology as specified by the PeerConnection's
3748  * of each peer in the peer group
3749  *
3750  * @param pg the peer group we are dealing with
3751  * @param connect_timeout how long try connecting two peers
3752  * @param connect_attempts how many times (max) to attempt
3753  * @param notify_callback callback to notify when finished
3754  * @param notify_cls closure for notify callback
3755  *
3756  * @return the number of connections that will be attempted
3757  */
3758 static int
3759 connect_topology(struct GNUNET_TESTING_PeerGroup *pg,
3760                  struct GNUNET_TIME_Relative connect_timeout,
3761                  unsigned int connect_attempts,
3762                  GNUNET_TESTING_NotifyCompletion notify_callback,
3763                  void *notify_cls)
3764 {
3765   unsigned int pg_iter;
3766   unsigned int total;
3767
3768 #if OLD
3769   struct PeerConnection *connection_iter;
3770 #endif
3771 #if USE_SEND_HELLOS
3772   struct SendHelloContext *send_hello_context
3773 #endif
3774
3775   total = 0;
3776   pg->ct_ctx.notify_connections_done = notify_callback;
3777   pg->ct_ctx.notify_cls = notify_cls;
3778   pg->ct_ctx.pg = pg;
3779
3780   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3781     {
3782 #if OLD
3783       connection_iter = pg->peers[pg_iter].connect_peers_head;
3784       while (connection_iter != NULL)
3785         {
3786           connection_iter = connection_iter->next;
3787           total++;
3788         }
3789 #else
3790       total +=
3791       GNUNET_CONTAINER_multihashmap_size (pg->peers[pg_iter].connect_peers);
3792 #endif
3793     }
3794
3795   if (total == 0)
3796     return total;
3797
3798   pg->ct_ctx.connect_timeout = connect_timeout;
3799   pg->ct_ctx.connect_attempts = connect_attempts;
3800   pg->ct_ctx.remaining_connections = total;
3801
3802 #if USE_SEND_HELLOS
3803   /* First give all peers the HELLO's of other peers (connect to first peer's transport service, give HELLO's of other peers, continue...) */
3804   pg->remaining_hellos = total;
3805   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3806     {
3807       send_hello_context = GNUNET_malloc(sizeof(struct SendHelloContext));
3808       send_hello_context->peer = &pg->peers[pg_iter];
3809       send_hello_context->peer_pos = pg->peers[pg_iter].connect_peers_head;
3810       send_hello_context->pg = pg;
3811       GNUNET_SCHEDULER_add_now(&schedule_send_hellos, send_hello_context);
3812     }
3813 #else
3814   for (pg_iter = 0; pg_iter < pg->max_outstanding_connections; pg_iter++)
3815     {
3816       preschedule_connect (pg);
3817     }
3818 #endif
3819   return total;
3820
3821 }
3822
3823 /**
3824  * Takes a peer group and creates a topology based on the
3825  * one specified.  Creates a topology means generates friend
3826  * files for the peers so they can only connect to those allowed
3827  * by the topology.  This will only have an effect once peers
3828  * are started if the FRIENDS_ONLY option is set in the base
3829  * config.  Also takes an optional restrict topology which
3830  * disallows connections based on particular transports
3831  * UNLESS they are specified in the restricted topology.
3832  *
3833  * @param pg the peer group struct representing the running peers
3834  * @param topology which topology to connect the peers in
3835  * @param restrict_topology disallow restrict_transports transport
3836  *                          connections to peers NOT in this topology
3837  *                          use GNUNET_TESTING_TOPOLOGY_NONE for no restrictions
3838  * @param restrict_transports space delimited list of transports to blacklist
3839  *                            to create restricted topology
3840  *
3841  * @return the maximum number of connections were all allowed peers
3842  *         connected to each other
3843  */
3844 unsigned int
3845 GNUNET_TESTING_create_topology(struct GNUNET_TESTING_PeerGroup *pg,
3846                                enum GNUNET_TESTING_Topology topology,
3847                                enum GNUNET_TESTING_Topology restrict_topology,
3848                                const char *restrict_transports)
3849 {
3850   int ret;
3851
3852   unsigned int num_connections;
3853   int unblacklisted_connections;
3854   char *filename;
3855   struct PeerConnection *conn_iter;
3856   struct PeerConnection *temp_conn;
3857   unsigned int off;
3858
3859 #if !OLD
3860   unsigned int i;
3861   for (i = 0; i < pg->total; i++)
3862     {
3863       pg->peers[i].allowed_peers =
3864       GNUNET_CONTAINER_multihashmap_create (100);
3865       pg->peers[i].connect_peers =
3866       GNUNET_CONTAINER_multihashmap_create (100);
3867       pg->peers[i].blacklisted_peers =
3868       GNUNET_CONTAINER_multihashmap_create (100);
3869       pg->peers[i].pg = pg;
3870     }
3871 #endif
3872
3873   switch (topology)
3874     {
3875   case GNUNET_TESTING_TOPOLOGY_CLIQUE:
3876 #if VERBOSE_TESTING
3877     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating clique topology\n"));
3878 #endif
3879     num_connections = create_clique (pg, &add_connections, ALLOWED, GNUNET_NO);
3880     break;
3881   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
3882 #if VERBOSE_TESTING
3883     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3884         _("Creating small world (ring) topology\n"));
3885 #endif
3886     num_connections = create_small_world_ring (pg, &add_connections, ALLOWED);
3887     break;
3888   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
3889 #if VERBOSE_TESTING
3890     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3891         _("Creating small world (2d-torus) topology\n"));
3892 #endif
3893     num_connections = create_small_world (pg, &add_connections, ALLOWED);
3894     break;
3895   case GNUNET_TESTING_TOPOLOGY_RING:
3896 #if VERBOSE_TESTING
3897     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating ring topology\n"));
3898 #endif
3899     num_connections = create_ring (pg, &add_connections, ALLOWED);
3900     break;
3901   case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
3902 #if VERBOSE_TESTING
3903     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating 2d torus topology\n"));
3904 #endif
3905     num_connections = create_2d_torus (pg, &add_connections, ALLOWED);
3906     break;
3907   case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
3908 #if VERBOSE_TESTING
3909     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3910         _("Creating Erdos-Renyi topology\n"));
3911 #endif
3912     num_connections = create_erdos_renyi (pg, &add_connections, ALLOWED);
3913     break;
3914   case GNUNET_TESTING_TOPOLOGY_INTERNAT:
3915 #if VERBOSE_TESTING
3916     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating InterNAT topology\n"));
3917 #endif
3918     num_connections = create_nated_internet (pg, &add_connections, ALLOWED);
3919     break;
3920   case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
3921 #if VERBOSE_TESTING
3922     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3923         _("Creating Scale Free topology\n"));
3924 #endif
3925     num_connections = create_scale_free (pg, &add_connections, ALLOWED);
3926     break;
3927   case GNUNET_TESTING_TOPOLOGY_LINE:
3928 #if VERBOSE_TESTING
3929     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3930         _("Creating straight line topology\n"));
3931 #endif
3932     num_connections = create_line (pg, &add_connections, ALLOWED);
3933     break;
3934   case GNUNET_TESTING_TOPOLOGY_FROM_FILE:
3935 #if VERBOSE_TESTING
3936     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3937         _("Creating topology from file!\n"));
3938 #endif
3939     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (pg->cfg, "testing",
3940                                                             "topology_file",
3941                                                             &filename))
3942       num_connections = create_from_file (pg, filename, &add_connections,
3943                                           ALLOWED);
3944     else
3945       {
3946         GNUNET_log (
3947                     GNUNET_ERROR_TYPE_WARNING,
3948                     "Missing configuration option TESTING:TOPOLOGY_FILE for creating topology from file!\n");
3949         num_connections = 0;
3950       }
3951     break;
3952   case GNUNET_TESTING_TOPOLOGY_NONE:
3953 #if VERBOSE_TESTING
3954     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3955         _
3956         ("Creating no allowed topology (all peers can connect at core level)\n"));
3957 #endif
3958     num_connections = pg->total * pg->total; /* Clique is allowed! */
3959     break;
3960   default:
3961     num_connections = 0;
3962     break;
3963     }
3964
3965   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "TESTING",
3966                                                           "F2F"))
3967     {
3968       ret = create_and_copy_friend_files (pg);
3969       if (ret != GNUNET_OK)
3970         {
3971 #if VERBOSE_TESTING
3972           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3973               _("Failed during friend file copying!\n"));
3974 #endif
3975           return GNUNET_SYSERR;
3976         }
3977       else
3978         {
3979 #if VERBOSE_TESTING
3980           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3981               _("Friend files created/copied successfully!\n"));
3982 #endif
3983         }
3984     }
3985
3986   /* Use the create clique method to initially set all connections as blacklisted. */
3987   if ((restrict_topology != GNUNET_TESTING_TOPOLOGY_NONE) && (restrict_topology
3988       != GNUNET_TESTING_TOPOLOGY_FROM_FILE))
3989     create_clique (pg, &add_connections, BLACKLIST, GNUNET_NO);
3990
3991   unblacklisted_connections = 0;
3992   /* Un-blacklist connections as per the topology specified */
3993   switch (restrict_topology)
3994     {
3995   case GNUNET_TESTING_TOPOLOGY_CLIQUE:
3996 #if VERBOSE_TESTING
3997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3998         _("Blacklisting all but clique topology\n"));
3999 #endif
4000     unblacklisted_connections = create_clique (pg, &remove_connections,
4001                                                BLACKLIST, GNUNET_NO);
4002     break;
4003   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
4004 #if VERBOSE_TESTING
4005     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4006         _("Blacklisting all but small world (ring) topology\n"));
4007 #endif
4008     unblacklisted_connections = create_small_world_ring (pg,
4009                                                          &remove_connections,
4010                                                          BLACKLIST);
4011     break;
4012   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
4013 #if VERBOSE_TESTING
4014     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4015         _
4016         ("Blacklisting all but small world (2d-torus) topology\n"));
4017 #endif
4018     unblacklisted_connections = create_small_world (pg, &remove_connections,
4019                                                     BLACKLIST);
4020     break;
4021   case GNUNET_TESTING_TOPOLOGY_RING:
4022 #if VERBOSE_TESTING
4023     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4024         _("Blacklisting all but ring topology\n"));
4025 #endif
4026     unblacklisted_connections
4027         = create_ring (pg, &remove_connections, BLACKLIST);
4028     break;
4029   case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
4030 #if VERBOSE_TESTING
4031     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4032         _("Blacklisting all but 2d torus topology\n"));
4033 #endif
4034     unblacklisted_connections = create_2d_torus (pg, &remove_connections,
4035                                                  BLACKLIST);
4036     break;
4037   case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
4038 #if VERBOSE_TESTING
4039     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4040         _("Blacklisting all but Erdos-Renyi topology\n"));
4041 #endif
4042     unblacklisted_connections = create_erdos_renyi (pg, &remove_connections,
4043                                                     BLACKLIST);
4044     break;
4045   case GNUNET_TESTING_TOPOLOGY_INTERNAT:
4046 #if VERBOSE_TESTING
4047     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4048         _("Blacklisting all but InterNAT topology\n"));
4049 #endif
4050
4051 #if TOPOLOGY_HACK
4052     for (off = 0; off < pg->total; off++)
4053       {
4054         conn_iter = pg->peers[off].allowed_peers_head;
4055         while (conn_iter != NULL)
4056           {
4057             temp_conn = conn_iter->next;
4058             GNUNET_free(conn_iter);
4059             conn_iter = temp_conn;
4060           }
4061         pg->peers[off].allowed_peers_head = NULL;
4062         pg->peers[off].allowed_peers_tail = NULL;
4063
4064         conn_iter = pg->peers[off].connect_peers_head;
4065         while (conn_iter != NULL)
4066           {
4067             temp_conn = conn_iter->next;
4068             GNUNET_free(conn_iter);
4069             conn_iter = temp_conn;
4070           }
4071         pg->peers[off].connect_peers_head = NULL;
4072         pg->peers[off].connect_peers_tail = NULL;
4073       }
4074     unblacklisted_connections
4075         = create_nated_internet_copy (pg, &remove_connections, BLACKLIST);
4076 #else
4077     unblacklisted_connections =
4078     create_nated_internet (pg, &remove_connections, BLACKLIST);
4079 #endif
4080
4081     break;
4082   case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
4083 #if VERBOSE_TESTING
4084     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4085         _("Blacklisting all but Scale Free topology\n"));
4086 #endif
4087     unblacklisted_connections = create_scale_free (pg, &remove_connections,
4088                                                    BLACKLIST);
4089     break;
4090   case GNUNET_TESTING_TOPOLOGY_LINE:
4091 #if VERBOSE_TESTING
4092     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4093         _("Blacklisting all but straight line topology\n"));
4094 #endif
4095     unblacklisted_connections
4096         = create_line (pg, &remove_connections, BLACKLIST);
4097     break;
4098   case GNUNET_TESTING_TOPOLOGY_NONE: /* Fall through */
4099   case GNUNET_TESTING_TOPOLOGY_FROM_FILE:
4100 #if VERBOSE_TESTING
4101     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4102         _
4103         ("Creating no blacklist topology (all peers can connect at transport level)\n"));
4104 #endif
4105     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _
4106     ("Creating blacklist topology from allowed\n"));
4107     unblacklisted_connections = copy_allowed (pg, &remove_connections);
4108   default:
4109     break;
4110     }
4111
4112   if ((unblacklisted_connections > 0) && (restrict_transports != NULL))
4113     {
4114       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Creating blacklist with `%s'\n",
4115                   restrict_transports);
4116       ret = create_and_copy_blacklist_files (pg, restrict_transports);
4117       if (ret != GNUNET_OK)
4118         {
4119 #if VERBOSE_TESTING
4120           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4121               _("Failed during blacklist file copying!\n"));
4122 #endif
4123           return 0;
4124         }
4125       else
4126         {
4127 #if VERBOSE_TESTING
4128           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4129               _("Blacklist files created/copied successfully!\n"));
4130 #endif
4131         }
4132     }
4133   return num_connections;
4134 }
4135
4136 #if !OLD
4137 /**
4138  * Iterator for choosing random peers to connect.
4139  *
4140  * @param cls closure, a RandomContext
4141  * @param key the key the second Daemon was stored under
4142  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
4143  *
4144  * @return GNUNET_YES to continue iteration
4145  */
4146 static int
4147 random_connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
4148   {
4149     struct RandomContext *random_ctx = cls;
4150     double random_number;
4151     uint32_t second_pos;
4152     GNUNET_HashCode first_hash;
4153     random_number =
4154     ((double)
4155         GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
4156             UINT64_MAX)) / ((double) UINT64_MAX);
4157     if (random_number < random_ctx->percentage)
4158       {
4159         GNUNET_assert (GNUNET_OK ==
4160             GNUNET_CONTAINER_multihashmap_put (random_ctx->
4161                 first->connect_peers_working_set,
4162                 key, value,
4163                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4164       }
4165
4166     /* Now we have considered this particular connection, remove it from the second peer so it's not double counted */
4167     uid_from_hash (key, &second_pos);
4168     hash_from_uid (random_ctx->first_uid, &first_hash);
4169     GNUNET_assert (random_ctx->pg->total > second_pos);
4170     GNUNET_assert (GNUNET_YES ==
4171         GNUNET_CONTAINER_multihashmap_remove (random_ctx->
4172             pg->peers
4173             [second_pos].connect_peers,
4174             &first_hash,
4175             random_ctx->
4176             first->daemon));
4177
4178     return GNUNET_YES;
4179   }
4180
4181 /**
4182  * Iterator for adding at least X peers to a peers connection set.
4183  *
4184  * @param cls closure, MinimumContext
4185  * @param key the key the second Daemon was stored under
4186  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
4187  *
4188  * @return GNUNET_YES to continue iteration
4189  */
4190 static int
4191 minimum_connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
4192   {
4193     struct MinimumContext *min_ctx = cls;
4194     uint32_t second_pos;
4195     GNUNET_HashCode first_hash;
4196     unsigned int i;
4197
4198     if (GNUNET_CONTAINER_multihashmap_size
4199         (min_ctx->first->connect_peers_working_set) < min_ctx->num_to_add)
4200       {
4201         for (i = 0; i < min_ctx->num_to_add; i++)
4202           {
4203             if (min_ctx->pg_array[i] == min_ctx->current)
4204               {
4205                 GNUNET_assert (GNUNET_OK ==
4206                     GNUNET_CONTAINER_multihashmap_put
4207                     (min_ctx->first->connect_peers_working_set, key,
4208                         value,
4209                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4210                 uid_from_hash (key, &second_pos);
4211                 hash_from_uid (min_ctx->first_uid, &first_hash);
4212                 GNUNET_assert (min_ctx->pg->total > second_pos);
4213                 GNUNET_assert (GNUNET_OK ==
4214                     GNUNET_CONTAINER_multihashmap_put (min_ctx->
4215                         pg->peers
4216                         [second_pos].connect_peers_working_set,
4217                         &first_hash,
4218                         min_ctx->first->
4219                         daemon,
4220                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4221                 /* Now we have added this particular connection, remove it from the second peer's map so it's not double counted */
4222                 GNUNET_assert (GNUNET_YES ==
4223                     GNUNET_CONTAINER_multihashmap_remove
4224                     (min_ctx->pg->peers[second_pos].connect_peers,
4225                         &first_hash, min_ctx->first->daemon));
4226               }
4227           }
4228         min_ctx->current++;
4229         return GNUNET_YES;
4230       }
4231     else
4232     return GNUNET_NO; /* We can stop iterating, we have enough peers! */
4233
4234   }
4235
4236 /**
4237  * Iterator for adding peers to a connection set based on a depth first search.
4238  *
4239  * @param cls closure, MinimumContext
4240  * @param key the key the second daemon was stored under
4241  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
4242  *
4243  * @return GNUNET_YES to continue iteration
4244  */
4245 static int
4246 dfs_connect_iterator (void *cls, const GNUNET_HashCode * key, void *value)
4247   {
4248     struct DFSContext *dfs_ctx = cls;
4249     GNUNET_HashCode first_hash;
4250
4251     if (dfs_ctx->current == dfs_ctx->chosen)
4252       {
4253         GNUNET_assert (GNUNET_OK ==
4254             GNUNET_CONTAINER_multihashmap_put (dfs_ctx->
4255                 first->connect_peers_working_set,
4256                 key, value,
4257                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4258         uid_from_hash (key, &dfs_ctx->second_uid);
4259         hash_from_uid (dfs_ctx->first_uid, &first_hash);
4260         GNUNET_assert (GNUNET_OK ==
4261             GNUNET_CONTAINER_multihashmap_put (dfs_ctx->
4262                 pg->peers
4263                 [dfs_ctx->second_uid].connect_peers_working_set,
4264                 &first_hash,
4265                 dfs_ctx->
4266                 first->daemon,
4267                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
4268         GNUNET_assert (GNUNET_YES ==
4269             GNUNET_CONTAINER_multihashmap_remove (dfs_ctx->
4270                 pg->peers
4271                 [dfs_ctx->second_uid].connect_peers,
4272                 &first_hash,
4273                 dfs_ctx->
4274                 first->daemon));
4275         /* Can't remove second from first yet because we are currently iterating, hence the return value in the DFSContext! */
4276         return GNUNET_NO; /* We have found our peer, don't iterate more */
4277       }
4278
4279     dfs_ctx->current++;
4280     return GNUNET_YES;
4281   }
4282 #endif
4283
4284 /**
4285  * From the set of connections possible, choose percentage percent of connections
4286  * to actually connect.
4287  *
4288  * @param pg the peergroup we are dealing with
4289  * @param percentage what percent of total connections to make
4290  */
4291 void
4292 choose_random_connections(struct GNUNET_TESTING_PeerGroup *pg,
4293                           double percentage)
4294 {
4295   struct RandomContext random_ctx;
4296   uint32_t pg_iter;
4297 #if OLD
4298   struct PeerConnection *temp_peers;
4299   struct PeerConnection *conn_iter;
4300   double random_number;
4301 #endif
4302
4303   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4304     {
4305       random_ctx.first_uid = pg_iter;
4306       random_ctx.first = &pg->peers[pg_iter];
4307       random_ctx.percentage = percentage;
4308       random_ctx.pg = pg;
4309 #if OLD
4310       temp_peers = NULL;
4311       conn_iter = pg->peers[pg_iter].connect_peers_head;
4312       while (conn_iter != NULL)
4313         {
4314           random_number
4315               = ((double) GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
4316                                                     UINT64_MAX))
4317                   / ((double) UINT64_MAX);
4318           if (random_number < percentage)
4319             {
4320               add_connections (pg, pg_iter, conn_iter->index, WORKING_SET,
4321                                GNUNET_YES);
4322             }
4323           conn_iter = conn_iter->next;
4324         }
4325 #else
4326       pg->peers[pg_iter].connect_peers_working_set =
4327       GNUNET_CONTAINER_multihashmap_create (pg->total);
4328       GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].connect_peers,
4329           &random_connect_iterator,
4330           &random_ctx);
4331       /* Now remove the old connections */
4332       GNUNET_CONTAINER_multihashmap_destroy (pg->
4333           peers[pg_iter].connect_peers);
4334       /* And replace with the random set */
4335       pg->peers[pg_iter].connect_peers =
4336       pg->peers[pg_iter].connect_peers_working_set;
4337 #endif
4338     }
4339
4340   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4341     {
4342       conn_iter = pg->peers[pg_iter].connect_peers_head;
4343       while (pg->peers[pg_iter].connect_peers_head != NULL)
4344         remove_connections (pg, pg_iter,
4345                             pg->peers[pg_iter].connect_peers_head->index,
4346                             CONNECT, GNUNET_YES);
4347
4348       pg->peers[pg_iter].connect_peers_head
4349           = pg->peers[pg_iter].connect_peers_working_set_head;
4350       pg->peers[pg_iter].connect_peers_tail
4351           = pg->peers[pg_iter].connect_peers_working_set_tail;
4352       pg->peers[pg_iter].connect_peers_working_set_head = NULL;
4353       pg->peers[pg_iter].connect_peers_working_set_tail = NULL;
4354     }
4355 }
4356
4357 /**
4358  * Count the number of connections in a linked list of connections.
4359  *
4360  * @param conn_list the connection list to get the count of
4361  *
4362  * @return the number of elements in the list
4363  */
4364 static unsigned int
4365 count_connections(struct PeerConnection *conn_list)
4366 {
4367   struct PeerConnection *iter;
4368   unsigned int count;
4369   count = 0;
4370   iter = conn_list;
4371   while (iter != NULL)
4372     {
4373       iter = iter->next;
4374       count++;
4375     }
4376   return count;
4377 }
4378
4379 static unsigned int
4380 count_workingset_connections(struct GNUNET_TESTING_PeerGroup *pg)
4381 {
4382   unsigned int count;
4383   unsigned int pg_iter;
4384 #if OLD
4385   struct PeerConnection *conn_iter;
4386 #endif
4387   count = 0;
4388
4389   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4390     {
4391 #if OLD
4392       conn_iter = pg->peers[pg_iter].connect_peers_working_set_head;
4393       while (conn_iter != NULL)
4394         {
4395           count++;
4396           conn_iter = conn_iter->next;
4397         }
4398 #else
4399       count +=
4400       GNUNET_CONTAINER_multihashmap_size (pg->
4401           peers
4402           [pg_iter].connect_peers_working_set);
4403 #endif
4404     }
4405
4406   return count;
4407 }
4408
4409 static unsigned int
4410 count_allowed_connections(struct GNUNET_TESTING_PeerGroup *pg)
4411 {
4412   unsigned int count;
4413   unsigned int pg_iter;
4414 #if OLD
4415   struct PeerConnection *conn_iter;
4416 #endif
4417
4418   count = 0;
4419   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4420     {
4421 #if OLD
4422       conn_iter = pg->peers[pg_iter].allowed_peers_head;
4423       while (conn_iter != NULL)
4424         {
4425           count++;
4426           conn_iter = conn_iter->next;
4427         }
4428 #else
4429       count +=
4430       GNUNET_CONTAINER_multihashmap_size (pg->
4431           peers
4432           [pg_iter].allowed_peers);
4433 #endif
4434     }
4435
4436   return count;
4437 }
4438
4439 /**
4440  * From the set of connections possible, choose at least num connections per
4441  * peer.
4442  *
4443  * @param pg the peergroup we are dealing with
4444  * @param num how many connections at least should each peer have (if possible)?
4445  */
4446 static void
4447 choose_minimum(struct GNUNET_TESTING_PeerGroup *pg, unsigned int num)
4448 {
4449 #if !OLD
4450   struct MinimumContext minimum_ctx;
4451 #else
4452   struct PeerConnection *conn_iter;
4453   unsigned int temp_list_size;
4454   unsigned int i;
4455   unsigned int count;
4456   uint32_t random; /* Random list entry to connect peer to */
4457 #endif
4458   uint32_t pg_iter;
4459
4460 #if OLD
4461   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4462     {
4463       temp_list_size
4464           = count_connections (pg->peers[pg_iter].connect_peers_head);
4465       if (temp_list_size == 0)
4466         {
4467           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4468                       "Peer %d has 0 connections!?!?\n", pg_iter);
4469           break;
4470         }
4471       for (i = 0; i < num; i++)
4472         {
4473           random = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4474                                              temp_list_size);
4475           conn_iter = pg->peers[pg_iter].connect_peers_head;
4476           for (count = 0; count < random; count++)
4477             conn_iter = conn_iter->next;
4478           /* We now have a random connection, connect it! */
4479           GNUNET_assert(conn_iter != NULL);
4480           add_connections (pg, pg_iter, conn_iter->index, WORKING_SET,
4481                            GNUNET_YES);
4482         }
4483     }
4484 #else
4485   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4486     {
4487       pg->peers[pg_iter].connect_peers_working_set =
4488       GNUNET_CONTAINER_multihashmap_create (num);
4489     }
4490
4491   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4492     {
4493       minimum_ctx.first_uid = pg_iter;
4494       minimum_ctx.pg_array =
4495       GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
4496           GNUNET_CONTAINER_multihashmap_size
4497           (pg->peers[pg_iter].connect_peers));
4498       minimum_ctx.first = &pg->peers[pg_iter];
4499       minimum_ctx.pg = pg;
4500       minimum_ctx.num_to_add = num;
4501       minimum_ctx.current = 0;
4502       GNUNET_CONTAINER_multihashmap_iterate (pg->peers[pg_iter].connect_peers,
4503           &minimum_connect_iterator,
4504           &minimum_ctx);
4505     }
4506
4507   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4508     {
4509       /* Remove the "old" connections */
4510       GNUNET_CONTAINER_multihashmap_destroy (pg->
4511           peers[pg_iter].connect_peers);
4512       /* And replace with the working set */
4513       pg->peers[pg_iter].connect_peers =
4514       pg->peers[pg_iter].connect_peers_working_set;
4515     }
4516 #endif
4517   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4518     {
4519       while (pg->peers[pg_iter].connect_peers_head != NULL)
4520         {
4521           conn_iter = pg->peers[pg_iter].connect_peers_head;
4522           GNUNET_CONTAINER_DLL_remove(pg->peers[pg_iter].connect_peers_head,
4523               pg->peers[pg_iter].connect_peers_tail,
4524               conn_iter);
4525           GNUNET_free(conn_iter);
4526           /*remove_connections(pg, pg_iter, pg->peers[pg_iter].connect_peers_head->index, CONNECT, GNUNET_YES);*/
4527         }
4528
4529       pg->peers[pg_iter].connect_peers_head
4530           = pg->peers[pg_iter].connect_peers_working_set_head;
4531       pg->peers[pg_iter].connect_peers_tail
4532           = pg->peers[pg_iter].connect_peers_working_set_tail;
4533       pg->peers[pg_iter].connect_peers_working_set_head = NULL;
4534       pg->peers[pg_iter].connect_peers_working_set_tail = NULL;
4535     }
4536 }
4537
4538 #if !OLD
4539 struct FindClosestContext
4540   {
4541     /**
4542      * The currently known closest peer.
4543      */
4544     struct GNUNET_TESTING_Daemon *closest;
4545
4546     /**
4547      * The info for the peer we are adding connections for.
4548      */
4549     struct PeerData *curr_peer;
4550
4551     /**
4552      * The distance (bits) between the current
4553      * peer and the currently known closest.
4554      */
4555     unsigned int closest_dist;
4556
4557     /**
4558      * The offset of the closest known peer in
4559      * the peer group.
4560      */
4561     unsigned int closest_num;
4562   };
4563
4564 /**
4565  * Iterator over hash map entries of the allowed
4566  * peer connections.  Find the closest, not already
4567  * connected peer and return it.
4568  *
4569  * @param cls closure (struct FindClosestContext)
4570  * @param key current key code (hash of offset in pg)
4571  * @param value value in the hash map - a GNUNET_TESTING_Daemon
4572  * @return GNUNET_YES if we should continue to
4573  *         iterate,
4574  *         GNUNET_NO if not.
4575  */
4576 static int
4577 find_closest_peers (void *cls, const GNUNET_HashCode * key, void *value)
4578   {
4579     struct FindClosestContext *closest_ctx = cls;
4580     struct GNUNET_TESTING_Daemon *daemon = value;
4581
4582     if (((closest_ctx->closest == NULL) ||
4583             (GNUNET_CRYPTO_hash_matching_bits
4584                 (&daemon->id.hashPubKey,
4585                     &closest_ctx->curr_peer->daemon->id.hashPubKey) >
4586                 closest_ctx->closest_dist))
4587         && (GNUNET_YES !=
4588             GNUNET_CONTAINER_multihashmap_contains (closest_ctx->
4589                 curr_peer->connect_peers,
4590                 key)))
4591       {
4592         closest_ctx->closest_dist =
4593         GNUNET_CRYPTO_hash_matching_bits (&daemon->id.hashPubKey,
4594             &closest_ctx->curr_peer->daemon->
4595             id.hashPubKey);
4596         closest_ctx->closest = daemon;
4597         uid_from_hash (key, &closest_ctx->closest_num);
4598       }
4599     return GNUNET_YES;
4600   }
4601
4602 /**
4603  * From the set of connections possible, choose at num connections per
4604  * peer based on depth which are closest out of those allowed.  Guaranteed
4605  * to add num peers to connect to, provided there are that many peers
4606  * in the underlay topology to connect to.
4607  *
4608  * @param pg the peergroup we are dealing with
4609  * @param num how many connections at least should each peer have (if possible)?
4610  * @param proc processor to actually add the connections
4611  * @param list the peer list to use
4612  */
4613 void
4614 add_closest (struct GNUNET_TESTING_PeerGroup *pg, unsigned int num,
4615     GNUNET_TESTING_ConnectionProcessor proc, enum PeerLists list)
4616   {
4617 #if OLD
4618
4619 #else
4620     struct FindClosestContext closest_ctx;
4621 #endif
4622     uint32_t pg_iter;
4623     uint32_t i;
4624
4625     for (i = 0; i < num; i++) /* Each time find a closest peer (from those available) */
4626       {
4627         for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4628           {
4629             closest_ctx.curr_peer = &pg->peers[pg_iter];
4630             closest_ctx.closest = NULL;
4631             closest_ctx.closest_dist = 0;
4632             closest_ctx.closest_num = 0;
4633             GNUNET_CONTAINER_multihashmap_iterate (pg->
4634                 peers[pg_iter].allowed_peers,
4635                 &find_closest_peers,
4636                 &closest_ctx);
4637             if (closest_ctx.closest != NULL)
4638               {
4639                 GNUNET_assert (closest_ctx.closest_num < pg->total);
4640                 proc (pg, pg_iter, closest_ctx.closest_num, list);
4641               }
4642           }
4643       }
4644   }
4645 #endif
4646
4647 /**
4648  * From the set of connections possible, choose at least num connections per
4649  * peer based on depth first traversal of peer connections.  If DFS leaves
4650  * peers unconnected, ensure those peers get connections.
4651  *
4652  * @param pg the peergroup we are dealing with
4653  * @param num how many connections at least should each peer have (if possible)?
4654  */
4655 void
4656 perform_dfs(struct GNUNET_TESTING_PeerGroup *pg, unsigned int num)
4657 {
4658   uint32_t pg_iter;
4659   uint32_t dfs_count;
4660   uint32_t starting_peer;
4661   uint32_t least_connections;
4662   uint32_t random_connection;
4663 #if OLD
4664   unsigned int temp_count;
4665   struct PeerConnection *peer_iter;
4666 #else
4667   struct DFSContext dfs_ctx;
4668   GNUNET_HashCode second_hash;
4669 #endif
4670
4671 #if OLD
4672   starting_peer = 0;
4673   dfs_count = 0;
4674   while ((count_workingset_connections (pg) < num * pg->total)
4675       && (count_allowed_connections (pg) > 0))
4676     {
4677       if (dfs_count % pg->total == 0) /* Restart the DFS at some weakly connected peer */
4678         {
4679           least_connections = -1; /* Set to very high number */
4680           for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4681             {
4682               temp_count
4683                   = count_connections (
4684                                        pg->peers[pg_iter].connect_peers_working_set_head);
4685               if (temp_count < least_connections)
4686                 {
4687                   starting_peer = pg_iter;
4688                   least_connections = temp_count;
4689                 }
4690             }
4691         }
4692
4693       temp_count
4694           = count_connections (pg->peers[starting_peer].connect_peers_head);
4695       if (temp_count == 0)
4696         continue; /* FIXME: infinite loop? */
4697
4698       random_connection = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4699                                                     temp_count);
4700       temp_count = 0;
4701       peer_iter = pg->peers[starting_peer].connect_peers_head;
4702       while (temp_count < random_connection)
4703         {
4704           peer_iter = peer_iter->next;
4705           temp_count++;
4706         }
4707       GNUNET_assert(peer_iter != NULL);
4708       add_connections (pg, starting_peer, peer_iter->index, WORKING_SET,
4709                        GNUNET_NO);
4710       remove_connections (pg, starting_peer, peer_iter->index, CONNECT,
4711                           GNUNET_YES);
4712       starting_peer = peer_iter->index;
4713       dfs_count++;
4714     }
4715
4716 #else
4717   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4718     {
4719       pg->peers[pg_iter].connect_peers_working_set =
4720       GNUNET_CONTAINER_multihashmap_create (num);
4721     }
4722
4723   starting_peer = 0;
4724   dfs_count = 0;
4725   while ((count_workingset_connections (pg) < num * pg->total)
4726       && (count_allowed_connections (pg) > 0))
4727     {
4728       if (dfs_count % pg->total == 0) /* Restart the DFS at some weakly connected peer */
4729         {
4730           least_connections = -1; /* Set to very high number */
4731           for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4732             {
4733               if (GNUNET_CONTAINER_multihashmap_size
4734                   (pg->peers[pg_iter].connect_peers_working_set) <
4735                   least_connections)
4736                 {
4737                   starting_peer = pg_iter;
4738                   least_connections =
4739                   GNUNET_CONTAINER_multihashmap_size (pg->
4740                       peers
4741                       [pg_iter].connect_peers_working_set);
4742                 }
4743             }
4744         }
4745
4746       if (GNUNET_CONTAINER_multihashmap_size (pg->peers[starting_peer].connect_peers) == 0) /* Ensure there is at least one peer left to connect! */
4747         {
4748           dfs_count = 0;
4749           continue;
4750         }
4751
4752       /* Choose a random peer from the chosen peers set of connections to add */
4753       dfs_ctx.chosen =
4754       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4755           GNUNET_CONTAINER_multihashmap_size
4756           (pg->peers[starting_peer].connect_peers));
4757       dfs_ctx.first_uid = starting_peer;
4758       dfs_ctx.first = &pg->peers[starting_peer];
4759       dfs_ctx.pg = pg;
4760       dfs_ctx.current = 0;
4761
4762       GNUNET_CONTAINER_multihashmap_iterate (pg->
4763           peers
4764           [starting_peer].connect_peers,
4765           &dfs_connect_iterator, &dfs_ctx);
4766       /* Remove the second from the first, since we will be continuing the search and may encounter the first peer again! */
4767       hash_from_uid (dfs_ctx.second_uid, &second_hash);
4768       GNUNET_assert (GNUNET_YES ==
4769           GNUNET_CONTAINER_multihashmap_remove (pg->peers
4770               [starting_peer].connect_peers,
4771               &second_hash,
4772               pg->
4773               peers
4774               [dfs_ctx.second_uid].daemon));
4775       starting_peer = dfs_ctx.second_uid;
4776     }
4777
4778   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
4779     {
4780       /* Remove the "old" connections */
4781       GNUNET_CONTAINER_multihashmap_destroy (pg->
4782           peers[pg_iter].connect_peers);
4783       /* And replace with the working set */
4784       pg->peers[pg_iter].connect_peers =
4785       pg->peers[pg_iter].connect_peers_working_set;
4786     }
4787 #endif
4788 }
4789
4790 /**
4791  * Internal callback for topology information for a particular peer.
4792  */
4793 static void
4794 internal_topology_callback(void *cls, const struct GNUNET_PeerIdentity *peer,
4795                            const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4796 {
4797   struct CoreContext *core_ctx = cls;
4798   struct TopologyIterateContext *iter_ctx = core_ctx->iter_context;
4799
4800   if (peer == NULL) /* Either finished, or something went wrong */
4801     {
4802       iter_ctx->completed++;
4803       iter_ctx->connected--;
4804       /* One core context allocated per iteration, must free! */
4805       GNUNET_free (core_ctx);
4806     }
4807   else
4808     {
4809       iter_ctx->topology_cb (iter_ctx->cls, &core_ctx->daemon->id, peer, NULL);
4810     }
4811
4812   if (iter_ctx->completed == iter_ctx->total)
4813     {
4814       iter_ctx->topology_cb (iter_ctx->cls, NULL, NULL, NULL);
4815       /* Once all are done, free the iteration context */
4816       GNUNET_free (iter_ctx);
4817     }
4818 }
4819
4820 /**
4821  * Check running topology iteration tasks, if below max start a new one, otherwise
4822  * schedule for some time in the future.
4823  */
4824 static void
4825 schedule_get_topology(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4826 {
4827   struct CoreContext *core_context = cls;
4828   struct TopologyIterateContext *topology_context =
4829       (struct TopologyIterateContext *) core_context->iter_context;
4830   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
4831     return;
4832
4833   if (topology_context->connected
4834       > topology_context->pg->max_outstanding_connections)
4835     {
4836 #if VERBOSE_TESTING > 2
4837       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4838           _
4839           ("Delaying connect, we have too many outstanding connections!\n"));
4840 #endif
4841       GNUNET_SCHEDULER_add_delayed (
4842                                     GNUNET_TIME_relative_multiply (
4843                                                                    GNUNET_TIME_UNIT_MILLISECONDS,
4844                                                                    100),
4845                                     &schedule_get_topology, core_context);
4846     }
4847   else
4848     {
4849 #if VERBOSE_TESTING > 2
4850       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4851           _("Creating connection, outstanding_connections is %d\n"),
4852           outstanding_connects);
4853 #endif
4854       topology_context->connected++;
4855
4856       if (GNUNET_OK != GNUNET_CORE_iterate_peers (core_context->daemon->cfg,
4857                                                   &internal_topology_callback,
4858                                                   core_context))
4859         {
4860           GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Topology iteration failed.\n");
4861           internal_topology_callback (core_context, NULL, NULL);
4862         }
4863     }
4864 }
4865
4866 /**
4867  * Iterate over all (running) peers in the peer group, retrieve
4868  * all connections that each currently has.
4869  */
4870 void
4871 GNUNET_TESTING_get_topology(struct GNUNET_TESTING_PeerGroup *pg,
4872                             GNUNET_TESTING_NotifyTopology cb, void *cls)
4873 {
4874   struct TopologyIterateContext *topology_context;
4875   struct CoreContext *core_ctx;
4876   unsigned int i;
4877   unsigned int total_count;
4878
4879   /* Allocate a single topology iteration context */
4880   topology_context = GNUNET_malloc (sizeof (struct TopologyIterateContext));
4881   topology_context->topology_cb = cb;
4882   topology_context->cls = cls;
4883   topology_context->pg = pg;
4884   total_count = 0;
4885   for (i = 0; i < pg->total; i++)
4886     {
4887       if (pg->peers[i].daemon->running == GNUNET_YES)
4888         {
4889           /* Allocate one core context per core we need to connect to */
4890           core_ctx = GNUNET_malloc (sizeof (struct CoreContext));
4891           core_ctx->daemon = pg->peers[i].daemon;
4892           /* Set back pointer to topology iteration context */
4893           core_ctx->iter_context = topology_context;
4894           GNUNET_SCHEDULER_add_now (&schedule_get_topology, core_ctx);
4895           total_count++;
4896         }
4897     }
4898   if (total_count == 0)
4899     {
4900       cb (cls, NULL, NULL, "Cannot iterate over topology, no running peers!");
4901       GNUNET_free (topology_context);
4902     }
4903   else
4904     topology_context->total = total_count;
4905   return;
4906 }
4907
4908 /**
4909  * Callback function to process statistic values.
4910  * This handler is here only really to insert a peer
4911  * identity (or daemon) so the statistics can be uniquely
4912  * tied to a single running peer.
4913  *
4914  * @param cls closure
4915  * @param subsystem name of subsystem that created the statistic
4916  * @param name the name of the datum
4917  * @param value the current value
4918  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
4919  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
4920  */
4921 static int
4922 internal_stats_callback(void *cls, const char *subsystem, const char *name,
4923                         uint64_t value, int is_persistent)
4924 {
4925   struct StatsCoreContext *core_context = cls;
4926   struct StatsIterateContext *stats_context =
4927       (struct StatsIterateContext *) core_context->iter_context;
4928
4929   return stats_context->proc (stats_context->cls, &core_context->daemon->id,
4930                               subsystem, name, value, is_persistent);
4931 }
4932
4933 /**
4934  * Internal continuation call for statistics iteration.
4935  *
4936  * @param cls closure, the CoreContext for this iteration
4937  * @param success whether or not the statistics iterations
4938  *        was canceled or not (we don't care)
4939  */
4940 static void
4941 internal_stats_cont(void *cls, int success)
4942 {
4943   struct StatsCoreContext *core_context = cls;
4944   struct StatsIterateContext *stats_context =
4945       (struct StatsIterateContext *) core_context->iter_context;
4946
4947   stats_context->connected--;
4948   stats_context->completed++;
4949
4950   if (stats_context->completed == stats_context->total)
4951     {
4952       stats_context->cont (stats_context->cls, GNUNET_YES);
4953       GNUNET_free (stats_context);
4954     }
4955
4956   if (core_context->stats_handle != NULL)
4957     GNUNET_STATISTICS_destroy (core_context->stats_handle, GNUNET_NO);
4958
4959   GNUNET_free (core_context);
4960 }
4961
4962 /**
4963  * Check running topology iteration tasks, if below max start a new one, otherwise
4964  * schedule for some time in the future.
4965  */
4966 static void
4967 schedule_get_statistics(void *cls,
4968                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4969 {
4970   struct StatsCoreContext *core_context = cls;
4971   struct StatsIterateContext *stats_context =
4972       (struct StatsIterateContext *) core_context->iter_context;
4973
4974   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
4975     return;
4976
4977   if (stats_context->connected > stats_context->pg->max_outstanding_connections)
4978     {
4979 #if VERBOSE_TESTING > 2
4980       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4981           _
4982           ("Delaying connect, we have too many outstanding connections!\n"));
4983 #endif
4984       GNUNET_SCHEDULER_add_delayed (
4985                                     GNUNET_TIME_relative_multiply (
4986                                                                    GNUNET_TIME_UNIT_MILLISECONDS,
4987                                                                    100),
4988                                     &schedule_get_statistics, core_context);
4989     }
4990   else
4991     {
4992 #if VERBOSE_TESTING > 2
4993       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4994           _("Creating connection, outstanding_connections is %d\n"),
4995           outstanding_connects);
4996 #endif
4997
4998       stats_context->connected++;
4999       core_context->stats_handle
5000           = GNUNET_STATISTICS_create ("testing", core_context->daemon->cfg);
5001       if (core_context->stats_handle == NULL)
5002         {
5003           internal_stats_cont (core_context, GNUNET_NO);
5004           return;
5005         }
5006
5007       core_context->stats_get_handle
5008           = GNUNET_STATISTICS_get (core_context->stats_handle, NULL, NULL,
5009                                    GNUNET_TIME_relative_get_forever (),
5010                                    &internal_stats_cont,
5011                                    &internal_stats_callback, core_context);
5012       if (core_context->stats_get_handle == NULL)
5013         internal_stats_cont (core_context, GNUNET_NO);
5014
5015     }
5016 }
5017
5018 struct DuplicateStats
5019 {
5020   /**
5021    * Next item in the list
5022    */
5023   struct DuplicateStats *next;
5024
5025   /**
5026    * Nasty string, concatenation of relevant information.
5027    */
5028   char *unique_string;
5029 };
5030
5031 /**
5032  * Check whether the combination of port/host/unix domain socket
5033  * already exists in the list of peers being checked for statistics.
5034  *
5035  * @param pg the peergroup in question
5036  * @param specific_peer the peer we're concerned with
5037  * @param stats_list the list to return to the caller
5038  *
5039  * @return GNUNET_YES if the statistics instance has been seen already,
5040  *         GNUNET_NO if not (and we may have added it to the list)
5041  */
5042 static int
5043 stats_check_existing(struct GNUNET_TESTING_PeerGroup *pg,
5044                      struct PeerData *specific_peer,
5045                      struct DuplicateStats **stats_list)
5046 {
5047   struct DuplicateStats *pos;
5048   char *unix_domain_socket;
5049   unsigned long long port;
5050   char *to_match;
5051   if (GNUNET_YES
5052       != GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "testing",
5053                                                "single_statistics_per_host"))
5054     return GNUNET_NO; /* Each peer has its own statistics instance, do nothing! */
5055
5056   pos = *stats_list;
5057   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (specific_peer->cfg,
5058                                                           "statistics",
5059                                                           "unixpath",
5060                                                           &unix_domain_socket))
5061     return GNUNET_NO;
5062
5063   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (specific_peer->cfg,
5064                                                           "statistics", "port",
5065                                                           &port))
5066     {
5067       GNUNET_free(unix_domain_socket);
5068       return GNUNET_NO;
5069     }
5070
5071   if (specific_peer->daemon->hostname != NULL)
5072     GNUNET_asprintf (&to_match, "%s%s%llu", specific_peer->daemon->hostname,
5073                      unix_domain_socket, port);
5074   else
5075     GNUNET_asprintf (&to_match, "%s%llu", unix_domain_socket, port);
5076
5077   while (pos != NULL)
5078     {
5079       if (0 == strcmp (to_match, pos->unique_string))
5080         {
5081           GNUNET_free (unix_domain_socket);
5082           GNUNET_free (to_match);
5083           return GNUNET_YES;
5084         }
5085       pos = pos->next;
5086     }
5087   pos = GNUNET_malloc (sizeof (struct DuplicateStats));
5088   pos->unique_string = to_match;
5089   pos->next = *stats_list;
5090   *stats_list = pos;
5091   GNUNET_free (unix_domain_socket);
5092   return GNUNET_NO;
5093 }
5094
5095 /**
5096  * Iterate over all (running) peers in the peer group, retrieve
5097  * all statistics from each.
5098  */
5099 void
5100 GNUNET_TESTING_get_statistics(struct GNUNET_TESTING_PeerGroup *pg,
5101                               GNUNET_STATISTICS_Callback cont,
5102                               GNUNET_TESTING_STATISTICS_Iterator proc,
5103                               void *cls)
5104 {
5105   struct StatsIterateContext *stats_context;
5106   struct StatsCoreContext *core_ctx;
5107   unsigned int i;
5108   unsigned int total_count;
5109   struct DuplicateStats *stats_list;
5110   struct DuplicateStats *pos;
5111   stats_list = NULL;
5112
5113   /* Allocate a single stats iteration context */
5114   stats_context = GNUNET_malloc (sizeof (struct StatsIterateContext));
5115   stats_context->cont = cont;
5116   stats_context->proc = proc;
5117   stats_context->cls = cls;
5118   stats_context->pg = pg;
5119   total_count = 0;
5120
5121   for (i = 0; i < pg->total; i++)
5122     {
5123       if ((pg->peers[i].daemon->running == GNUNET_YES) && (GNUNET_NO
5124           == stats_check_existing (pg, &pg->peers[i], &stats_list)))
5125         {
5126           /* Allocate one core context per core we need to connect to */
5127           core_ctx = GNUNET_malloc (sizeof (struct StatsCoreContext));
5128           core_ctx->daemon = pg->peers[i].daemon;
5129           /* Set back pointer to topology iteration context */
5130           core_ctx->iter_context = stats_context;
5131           GNUNET_SCHEDULER_add_now (&schedule_get_statistics, core_ctx);
5132           total_count++;
5133         }
5134     }
5135
5136   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5137               "Retrieving stats from %u total instances.\n", total_count);
5138   stats_context->total = total_count;
5139   if (stats_list != NULL)
5140     {
5141       pos = stats_list;
5142       while (pos != NULL)
5143         {
5144           GNUNET_free (pos->unique_string);
5145           stats_list = pos->next;
5146           GNUNET_free (pos);
5147           pos = stats_list->next;
5148         }
5149     }
5150   return;
5151 }
5152
5153 /**
5154  * Stop the connection process temporarily.
5155  *
5156  * @param pg the peer group to stop connecting
5157  */
5158 void
5159 GNUNET_TESTING_stop_connections(struct GNUNET_TESTING_PeerGroup *pg)
5160 {
5161   pg->stop_connects = GNUNET_YES;
5162 }
5163
5164 /**
5165  * Resume the connection process temporarily.
5166  *
5167  * @param pg the peer group to resume connecting
5168  */
5169 void
5170 GNUNET_TESTING_resume_connections(struct GNUNET_TESTING_PeerGroup *pg)
5171 {
5172   pg->stop_connects = GNUNET_NO;
5173 }
5174
5175 /**
5176  * There are many ways to connect peers that are supported by this function.
5177  * To connect peers in the same topology that was created via the
5178  * GNUNET_TESTING_create_topology, the topology variable must be set to
5179  * GNUNET_TESTING_TOPOLOGY_NONE.  If the topology variable is specified,
5180  * a new instance of that topology will be generated and attempted to be
5181  * connected.  This could result in some connections being impossible,
5182  * because some topologies are non-deterministic.
5183  *
5184  * @param pg the peer group struct representing the running peers
5185  * @param topology which topology to connect the peers in
5186  * @param options options for connecting the topology
5187  * @param option_modifier modifier for options that take a parameter
5188  * @param connect_timeout how long to wait before giving up on connecting
5189  *                        two peers
5190  * @param connect_attempts how many times to attempt to connect two peers
5191  *                         over the connect_timeout duration
5192  * @param notify_callback notification to be called once all connections completed
5193  * @param notify_cls closure for notification callback
5194  *
5195  * @return the number of connections that will be attempted, GNUNET_SYSERR on error
5196  */
5197 int
5198 GNUNET_TESTING_connect_topology(
5199                                 struct GNUNET_TESTING_PeerGroup *pg,
5200                                 enum GNUNET_TESTING_Topology topology,
5201                                 enum GNUNET_TESTING_TopologyOption options,
5202                                 double option_modifier,
5203                                 struct GNUNET_TIME_Relative connect_timeout,
5204                                 unsigned int connect_attempts,
5205                                 GNUNET_TESTING_NotifyCompletion notify_callback,
5206                                 void *notify_cls)
5207 {
5208   switch (topology)
5209     {
5210   case GNUNET_TESTING_TOPOLOGY_CLIQUE:
5211 #if VERBOSE_TOPOLOGY
5212     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5213                 _("Creating clique CONNECT topology\n"));
5214 #endif
5215     create_clique (pg, &add_connections, CONNECT, GNUNET_NO);
5216     break;
5217   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
5218 #if VERBOSE_TOPOLOGY
5219     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5220                 _("Creating small world (ring) CONNECT topology\n"));
5221 #endif
5222     create_small_world_ring (pg, &add_connections, CONNECT);
5223     break;
5224   case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
5225 #if VERBOSE_TOPOLOGY
5226     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5227                 _("Creating small world (2d-torus) CONNECT topology\n"));
5228 #endif
5229     create_small_world (pg, &add_connections, CONNECT);
5230     break;
5231   case GNUNET_TESTING_TOPOLOGY_RING:
5232 #if VERBOSE_TOPOLOGY
5233     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating ring CONNECT topology\n"));
5234 #endif
5235     create_ring (pg, &add_connections, CONNECT);
5236     break;
5237   case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
5238 #if VERBOSE_TOPOLOGY
5239     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5240                 _("Creating 2d torus CONNECT topology\n"));
5241 #endif
5242     create_2d_torus (pg, &add_connections, CONNECT);
5243     break;
5244   case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
5245 #if VERBOSE_TOPOLOGY
5246     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5247                 _("Creating Erdos-Renyi CONNECT topology\n"));
5248 #endif
5249     create_erdos_renyi (pg, &add_connections, CONNECT);
5250     break;
5251   case GNUNET_TESTING_TOPOLOGY_INTERNAT:
5252 #if VERBOSE_TOPOLOGY
5253     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5254                 _("Creating InterNAT CONNECT topology\n"));
5255 #endif
5256     create_nated_internet (pg, &add_connections, CONNECT);
5257     break;
5258   case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
5259 #if VERBOSE_TOPOLOGY
5260     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5261                 _("Creating Scale Free CONNECT topology\n"));
5262 #endif
5263     create_scale_free (pg, &add_connections, CONNECT);
5264     break;
5265   case GNUNET_TESTING_TOPOLOGY_LINE:
5266 #if VERBOSE_TOPOLOGY
5267     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5268                 _("Creating straight line CONNECT topology\n"));
5269 #endif
5270     create_line (pg, &add_connections, CONNECT);
5271     break;
5272   case GNUNET_TESTING_TOPOLOGY_NONE:
5273 #if VERBOSE_TOPOLOGY
5274     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Creating no CONNECT topology\n"));
5275 #endif
5276     copy_allowed_topology (pg);
5277     break;
5278   default:
5279     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _
5280     ("Unknown topology specification, can't connect peers!\n"));
5281     return GNUNET_SYSERR;
5282     }
5283
5284   switch (options)
5285     {
5286   case GNUNET_TESTING_TOPOLOGY_OPTION_RANDOM:
5287 #if VERBOSE_TOPOLOGY
5288     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _
5289     ("Connecting random subset (%'.2f percent) of possible peers\n"), 100
5290         * option_modifier);
5291 #endif
5292     choose_random_connections (pg, option_modifier);
5293     break;
5294   case GNUNET_TESTING_TOPOLOGY_OPTION_MINIMUM:
5295 #if VERBOSE_TOPOLOGY
5296     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5297                 _("Connecting a minimum of %u peers each (if possible)\n"),
5298                 (unsigned int) option_modifier);
5299 #endif
5300     choose_minimum (pg, (unsigned int) option_modifier);
5301     break;
5302   case GNUNET_TESTING_TOPOLOGY_OPTION_DFS:
5303 #if VERBOSE_TOPOLOGY
5304     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _
5305     ("Using DFS to connect a minimum of %u peers each (if possible)\n"),
5306                 (unsigned int) option_modifier);
5307 #endif
5308 #if FIXME
5309     perform_dfs (pg, (int) option_modifier);
5310 #endif
5311     break;
5312   case GNUNET_TESTING_TOPOLOGY_OPTION_ADD_CLOSEST:
5313 #if VERBOSE_TOPOLOGY
5314     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _
5315     ("Finding additional %u closest peers each (if possible)\n"),
5316                 (unsigned int) option_modifier);
5317 #endif
5318 #if FIXME
5319     add_closest (pg, (unsigned int) option_modifier,
5320         &add_connections, CONNECT);
5321 #endif
5322     break;
5323   case GNUNET_TESTING_TOPOLOGY_OPTION_NONE:
5324     break;
5325   case GNUNET_TESTING_TOPOLOGY_OPTION_ALL:
5326     break;
5327   default:
5328     break;
5329     }
5330
5331   return connect_topology (pg, connect_timeout, connect_attempts,
5332                            notify_callback, notify_cls);
5333 }
5334
5335 /**
5336  * Lookup and return the number of SSH connections to a host.
5337  *
5338  * @param hostname the hostname to lookup in the list
5339  * @param pg the peergroup that the host belongs to
5340  *
5341  * @return the number of current ssh connections to the host
5342  */
5343 static unsigned int
5344 count_outstanding_at_host(const char *hostname,
5345                           struct GNUNET_TESTING_PeerGroup *pg)
5346 {
5347   struct OutstandingSSH *pos;
5348   pos = pg->ssh_head;
5349   while ((pos != NULL) && (strcmp (pos->hostname, hostname) != 0))
5350     pos = pos->next;
5351   GNUNET_assert(pos != NULL);
5352   return pos->outstanding;
5353 }
5354
5355 /**
5356  * Increment the number of SSH connections to a host by one.
5357  *
5358  * @param hostname the hostname to lookup in the list
5359  * @param pg the peergroup that the host belongs to
5360  *
5361  */
5362 static void
5363 increment_outstanding_at_host(const char *hostname,
5364                               struct GNUNET_TESTING_PeerGroup *pg)
5365 {
5366   struct OutstandingSSH *pos;
5367   pos = pg->ssh_head;
5368   while ((pos != NULL) && (strcmp (pos->hostname, hostname) != 0))
5369     pos = pos->next;
5370   GNUNET_assert(pos != NULL);
5371   pos->outstanding++;
5372 }
5373
5374 /**
5375  * Decrement the number of SSH connections to a host by one.
5376  *
5377  * @param hostname the hostname to lookup in the list
5378  * @param pg the peergroup that the host belongs to
5379  *
5380  */
5381 static void
5382 decrement_outstanding_at_host(const char *hostname,
5383                               struct GNUNET_TESTING_PeerGroup *pg)
5384 {
5385   struct OutstandingSSH *pos;
5386   pos = pg->ssh_head;
5387   while ((pos != NULL) && (strcmp (pos->hostname, hostname) != 0))
5388     pos = pos->next;
5389   GNUNET_assert(pos != NULL);
5390   pos->outstanding--;
5391 }
5392
5393 /**
5394  * Callback that is called whenever a hostkey is generated
5395  * for a peer.  Call the real callback and decrement the
5396  * starting counter for the peergroup.
5397  *
5398  * @param cls closure
5399  * @param id identifier for the daemon, NULL on error
5400  * @param d handle for the daemon
5401  * @param emsg error message (NULL on success)
5402  */
5403 static void
5404 internal_hostkey_callback(void *cls, const struct GNUNET_PeerIdentity *id,
5405                           struct GNUNET_TESTING_Daemon *d, const char *emsg)
5406 {
5407   struct InternalStartContext *internal_context = cls;
5408   internal_context->peer->pg->starting--;
5409   internal_context->peer->pg->started++;
5410   if (internal_context->hostname != NULL)
5411     decrement_outstanding_at_host (internal_context->hostname,
5412                                    internal_context->peer->pg);
5413   if (internal_context->hostkey_callback != NULL)
5414     internal_context->hostkey_callback (internal_context->hostkey_cls, id, d,
5415                                         emsg);
5416   else if (internal_context->peer->pg->started
5417       == internal_context->peer->pg->total)
5418     {
5419       internal_context->peer->pg->started = 0; /* Internal startup may use this counter! */
5420       GNUNET_TESTING_daemons_continue_startup (internal_context->peer->pg);
5421     }
5422 }
5423
5424 /**
5425  * Callback that is called whenever a peer has finished starting.
5426  * Call the real callback and decrement the starting counter
5427  * for the peergroup.
5428  *
5429  * @param cls closure
5430  * @param id identifier for the daemon, NULL on error
5431  * @param cfg config
5432  * @param d handle for the daemon
5433  * @param emsg error message (NULL on success)
5434  */
5435 static void
5436 internal_startup_callback(void *cls, const struct GNUNET_PeerIdentity *id,
5437                           const struct GNUNET_CONFIGURATION_Handle *cfg,
5438                           struct GNUNET_TESTING_Daemon *d, const char *emsg)
5439 {
5440   struct InternalStartContext *internal_context = cls;
5441   internal_context->peer->pg->starting--;
5442   if (internal_context->hostname != NULL)
5443     decrement_outstanding_at_host (internal_context->hostname,
5444                                    internal_context->peer->pg);
5445   if (internal_context->start_cb != NULL)
5446     internal_context->start_cb (internal_context->start_cb_cls, id, cfg, d,
5447                                 emsg);
5448 }
5449
5450 static void
5451 internal_continue_startup(void *cls,
5452                           const struct GNUNET_SCHEDULER_TaskContext *tc)
5453 {
5454   struct InternalStartContext *internal_context = cls;
5455
5456   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
5457     {
5458       return;
5459     }
5460
5461   if ((internal_context->peer->pg->starting
5462       < internal_context->peer->pg->max_concurrent_ssh)
5463       || ((internal_context->hostname != NULL)
5464           && (count_outstanding_at_host (internal_context->hostname,
5465                                          internal_context->peer->pg)
5466               < internal_context->peer->pg->max_concurrent_ssh)))
5467     {
5468       if (internal_context->hostname != NULL)
5469         increment_outstanding_at_host (internal_context->hostname,
5470                                        internal_context->peer->pg);
5471       internal_context->peer->pg->starting++;
5472       GNUNET_TESTING_daemon_continue_startup (internal_context->peer->daemon);
5473     }
5474   else
5475     {
5476       GNUNET_SCHEDULER_add_delayed (
5477                                     GNUNET_TIME_relative_multiply (
5478                                                                    GNUNET_TIME_UNIT_MILLISECONDS,
5479                                                                    100),
5480                                     &internal_continue_startup,
5481                                     internal_context);
5482     }
5483 }
5484
5485 /**
5486  * Callback for informing us about a successful
5487  * or unsuccessful churn start call.
5488  *
5489  * @param cls a ChurnContext
5490  * @param id the peer identity of the started peer
5491  * @param cfg the handle to the configuration of the peer
5492  * @param d handle to the daemon for the peer
5493  * @param emsg NULL on success, non-NULL on failure
5494  *
5495  */
5496 void
5497 churn_start_callback(void *cls, const struct GNUNET_PeerIdentity *id,
5498                      const struct GNUNET_CONFIGURATION_Handle *cfg,
5499                      struct GNUNET_TESTING_Daemon *d, const char *emsg)
5500 {
5501   struct ChurnRestartContext *startup_ctx = cls;
5502   struct ChurnContext *churn_ctx = startup_ctx->churn_ctx;
5503
5504   unsigned int total_left;
5505   char *error_message;
5506
5507   error_message = NULL;
5508   if (emsg != NULL)
5509     {
5510       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5511                   "Churn stop callback failed with error `%s'\n", emsg);
5512       churn_ctx->num_failed_start++;
5513     }
5514   else
5515     {
5516       churn_ctx->num_to_start--;
5517     }
5518
5519 #if DEBUG_CHURN
5520   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5521       "Started peer, %d left.\n", churn_ctx->num_to_start);
5522 #endif
5523
5524   total_left = (churn_ctx->num_to_stop - churn_ctx->num_failed_stop)
5525       + (churn_ctx->num_to_start - churn_ctx->num_failed_start);
5526
5527   if (total_left == 0)
5528     {
5529       if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
5530         GNUNET_asprintf (
5531                          &error_message,
5532                          "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!",
5533                          churn_ctx->num_failed_start,
5534                          churn_ctx->num_failed_stop);
5535       churn_ctx->cb (churn_ctx->cb_cls, error_message);
5536       GNUNET_free_non_null (error_message);
5537       GNUNET_free (churn_ctx);
5538       GNUNET_free (startup_ctx);
5539     }
5540 }
5541
5542 static void
5543 schedule_churn_restart(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5544 {
5545   struct PeerRestartContext *peer_restart_ctx = cls;
5546   struct ChurnRestartContext *startup_ctx = peer_restart_ctx->churn_restart_ctx;
5547
5548   if (startup_ctx->outstanding > startup_ctx->pg->max_concurrent_ssh)
5549     GNUNET_SCHEDULER_add_delayed (
5550                                   GNUNET_TIME_relative_multiply (
5551                                                                  GNUNET_TIME_UNIT_MILLISECONDS,
5552                                                                  100),
5553                                   &schedule_churn_restart, peer_restart_ctx);
5554   else
5555     {
5556       GNUNET_TESTING_daemon_start_stopped (peer_restart_ctx->daemon,
5557                                            startup_ctx->timeout,
5558                                            &churn_start_callback, startup_ctx);
5559       GNUNET_free (peer_restart_ctx);
5560     }
5561 }
5562
5563 static void
5564 internal_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5565 {
5566   struct InternalStartContext *internal_context = cls;
5567
5568   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
5569     {
5570       return;
5571     }
5572
5573   if ((internal_context->peer->pg->starting
5574       < internal_context->peer->pg->max_concurrent_ssh)
5575       || ((internal_context->hostname != NULL)
5576           && (count_outstanding_at_host (internal_context->hostname,
5577                                          internal_context->peer->pg)
5578               < internal_context->peer->pg->max_concurrent_ssh)))
5579     {
5580       if (internal_context->hostname != NULL)
5581         increment_outstanding_at_host (internal_context->hostname,
5582                                        internal_context->peer->pg);
5583       internal_context->peer->pg->starting++;
5584       internal_context->peer->daemon
5585           = GNUNET_TESTING_daemon_start (internal_context->peer->cfg,
5586                                          internal_context->timeout,
5587                                          internal_context->hostname,
5588                                          internal_context->username,
5589                                          internal_context->sshport,
5590                                          internal_context->hostkey,
5591                                          &internal_hostkey_callback,
5592                                          internal_context,
5593                                          &internal_startup_callback,
5594                                          internal_context);
5595     }
5596   else
5597     {
5598       GNUNET_SCHEDULER_add_delayed (
5599                                     GNUNET_TIME_relative_multiply (
5600                                                                    GNUNET_TIME_UNIT_MILLISECONDS,
5601                                                                    100),
5602                                     &internal_start, internal_context);
5603     }
5604 }
5605
5606 /**
5607  * Function which continues a peer group starting up
5608  * after successfully generating hostkeys for each peer.
5609  *
5610  * @param pg the peer group to continue starting
5611  *
5612  */
5613 void
5614 GNUNET_TESTING_daemons_continue_startup(struct GNUNET_TESTING_PeerGroup *pg)
5615 {
5616   unsigned int i;
5617
5618   pg->starting = 0;
5619   for (i = 0; i < pg->total; i++)
5620     {
5621       GNUNET_SCHEDULER_add_now (&internal_continue_startup,
5622                                 &pg->peers[i].internal_context);
5623       //GNUNET_TESTING_daemon_continue_startup(pg->peers[i].daemon);
5624     }
5625 }
5626
5627 /**
5628  * Start count gnunet instances with the same set of transports and
5629  * applications.  The port numbers (any option called "PORT") will be
5630  * adjusted to ensure that no two peers running on the same system
5631  * have the same port(s) in their respective configurations.
5632  *
5633  * @param cfg configuration template to use
5634  * @param total number of daemons to start
5635  * @param max_concurrent_connections for testing, how many peers can
5636  *                                   we connect to simultaneously
5637  * @param max_concurrent_ssh when starting with ssh, how many ssh
5638  *        connections will we allow at once (based on remote hosts allowed!)
5639  * @param timeout total time allowed for peers to start
5640  * @param hostkey_callback function to call on each peers hostkey generation
5641  *        if NULL, peers will be started by this call, if non-null,
5642  *        GNUNET_TESTING_daemons_continue_startup must be called after
5643  *        successful hostkey generation
5644  * @param hostkey_cls closure for hostkey callback
5645  * @param cb function to call on each daemon that was started
5646  * @param cb_cls closure for cb
5647  * @param connect_callback function to call each time two hosts are connected
5648  * @param connect_callback_cls closure for connect_callback
5649  * @param hostnames linked list of host structs to use to start peers on
5650  *                  (NULL to run on localhost only)
5651  *
5652  * @return NULL on error, otherwise handle to control peer group
5653  */
5654 struct GNUNET_TESTING_PeerGroup *
5655 GNUNET_TESTING_daemons_start(
5656                              const struct GNUNET_CONFIGURATION_Handle *cfg,
5657                              unsigned int total,
5658                              unsigned int max_concurrent_connections,
5659                              unsigned int max_concurrent_ssh,
5660                              struct GNUNET_TIME_Relative timeout,
5661                              GNUNET_TESTING_NotifyHostkeyCreated hostkey_callback,
5662                              void *hostkey_cls,
5663                              GNUNET_TESTING_NotifyDaemonRunning cb,
5664                              void *cb_cls,
5665                              GNUNET_TESTING_NotifyConnection connect_callback,
5666                              void *connect_callback_cls,
5667                              const struct GNUNET_TESTING_Host *hostnames)
5668 {
5669   struct GNUNET_TESTING_PeerGroup *pg;
5670   const struct GNUNET_TESTING_Host *hostpos;
5671 #if 0
5672   char *pos;
5673   const char *rpos;
5674   char *start;
5675 #endif
5676   const char *hostname;
5677   const char *username;
5678   char *baseservicehome;
5679   char *newservicehome;
5680   char *tmpdir;
5681   char *hostkeys_file;
5682   char *arg;
5683   char *ssh_port_str;
5684   struct GNUNET_DISK_FileHandle *fd;
5685   struct GNUNET_CONFIGURATION_Handle *pcfg;
5686   unsigned int off;
5687   struct OutstandingSSH *ssh_entry;
5688   unsigned int hostcnt;
5689   unsigned int i;
5690   uint16_t minport;
5691   uint16_t sshport;
5692   uint32_t upnum;
5693   uint32_t fdnum;
5694   uint64_t fs;
5695   uint64_t total_hostkeys;
5696   struct GNUNET_OS_Process *proc;
5697
5698   if (0 == total)
5699     {
5700       GNUNET_break (0);
5701       return NULL;
5702     }
5703
5704   upnum = 0;
5705   fdnum = 0;
5706   pg = GNUNET_malloc (sizeof (struct GNUNET_TESTING_PeerGroup));
5707   pg->cfg = cfg;
5708   pg->notify_connection = connect_callback;
5709   pg->notify_connection_cls = connect_callback_cls;
5710   pg->total = total;
5711   pg->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
5712   pg->peers = GNUNET_malloc (total * sizeof (struct PeerData));
5713   pg->max_outstanding_connections = max_concurrent_connections;
5714   pg->max_concurrent_ssh = max_concurrent_ssh;
5715   if (NULL != hostnames)
5716     {
5717       off = 0;
5718       hostpos = hostnames;
5719       while (hostpos != NULL)
5720         {
5721           hostpos = hostpos->next;
5722           off++;
5723         }
5724       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
5725       off = 0;
5726
5727       hostpos = hostnames;
5728       while (hostpos != NULL)
5729         {
5730           pg->hosts[off].minport = LOW_PORT;
5731           pg->hosts[off].hostname = GNUNET_strdup (hostpos->hostname);
5732           if (hostpos->username != NULL)
5733             pg->hosts[off].username = GNUNET_strdup (hostpos->username);
5734           pg->hosts[off].sshport = hostpos->port;
5735           hostpos = hostpos->next;
5736           off++;
5737         }
5738
5739       if (off == 0)
5740         {
5741           pg->hosts = NULL;
5742         }
5743       hostcnt = off;
5744       minport = 0;
5745       pg->num_hosts = off;
5746
5747 #if NO_LL
5748       off = 2;
5749       /* skip leading spaces */
5750       while ((0 != *hostnames) && (isspace ((unsigned char) *hostnames)))
5751       hostnames++;
5752       rpos = hostnames;
5753       while ('\0' != *rpos)
5754         {
5755           if (isspace ((unsigned char) *rpos))
5756           off++;
5757           rpos++;
5758         }
5759       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
5760       off = 0;
5761       start = GNUNET_strdup (hostnames);
5762       pos = start;
5763       while ('\0' != *pos)
5764         {
5765           if (isspace ((unsigned char) *pos))
5766             {
5767               *pos = '\0';
5768               if (strlen (start) > 0)
5769                 {
5770                   pg->hosts[off].minport = LOW_PORT;
5771                   pg->hosts[off++].hostname = start;
5772                 }
5773               start = pos + 1;
5774             }
5775           pos++;
5776         }
5777       if (strlen (start) > 0)
5778         {
5779           pg->hosts[off].minport = LOW_PORT;
5780           pg->hosts[off++].hostname = start;
5781         }
5782       if (off == 0)
5783         {
5784           GNUNET_free (start);
5785           GNUNET_free (pg->hosts);
5786           pg->hosts = NULL;
5787         }
5788       hostcnt = off;
5789       minport = 0; /* make gcc happy */
5790 #endif
5791     }
5792   else
5793     {
5794       hostcnt = 0;
5795       minport = LOW_PORT;
5796     }
5797
5798   /* Create the servicehome directory for each remote peer */
5799   GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS", "SERVICEHOME",
5800                                                                     &baseservicehome));
5801   for (i = 0; i < pg->num_hosts; i++)
5802     {
5803       ssh_entry = GNUNET_malloc(sizeof(struct OutstandingSSH));
5804       ssh_entry->hostname = pg->hosts[i].hostname; /* Don't free! */
5805       GNUNET_CONTAINER_DLL_insert(pg->ssh_head, pg->ssh_tail, ssh_entry);
5806       GNUNET_asprintf(&tmpdir, "%s/%s", baseservicehome, pg->hosts[i].hostname);
5807       if (NULL != pg->hosts[i].username)
5808         GNUNET_asprintf (&arg, "%s@%s", pg->hosts[i].username,
5809                          pg->hosts[i].hostname);
5810       else
5811         GNUNET_asprintf (&arg, "%s", pg->hosts[i].hostname);
5812       if (pg->hosts[i].sshport != 0)
5813         {
5814           GNUNET_asprintf (&ssh_port_str, "%d", pg->hosts[i].sshport);
5815           proc = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh", "-P",
5816                                           ssh_port_str,
5817 #if !DEBUG_TESTING
5818                                           "-q",
5819 #endif
5820                                           arg, "mkdir -p", tmpdir,
5821                                           NULL);
5822         }
5823       else
5824         proc = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh", arg,
5825                                         "mkdir -p", tmpdir, NULL);
5826       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5827                   "Creating remote dir with command ssh %s %s %s\n", arg,
5828                   " mkdir -p ", tmpdir);
5829       GNUNET_free(tmpdir);
5830       GNUNET_free(arg);
5831       GNUNET_OS_process_wait (proc);
5832       GNUNET_OS_process_close(proc);
5833     }
5834   GNUNET_free(baseservicehome);
5835
5836   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (cfg, "TESTING",
5837                                                            "HOSTKEYSFILE",
5838                                                            &hostkeys_file))
5839     {
5840       if (GNUNET_YES != GNUNET_DISK_file_test (hostkeys_file))
5841         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Couldn't read hostkeys file!\n");
5842       else
5843         {
5844           /* Check hostkey file size, read entire thing into memory */
5845           fd = GNUNET_DISK_file_open (hostkeys_file, GNUNET_DISK_OPEN_READ,
5846                                       GNUNET_DISK_PERM_NONE);
5847           if (NULL == fd)
5848             {
5849               GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", hostkeys_file);
5850               return NULL;
5851             }
5852
5853           if (GNUNET_YES != GNUNET_DISK_file_size (hostkeys_file, &fs,
5854                                                    GNUNET_YES))
5855             fs = 0;
5856
5857           GNUNET_log (
5858                       GNUNET_ERROR_TYPE_WARNING,
5859                       "Found file size %llu for hostkeys, expect hostkeys to be size %d\n",
5860                       fs, HOSTKEYFILESIZE);
5861
5862           if (fs % HOSTKEYFILESIZE != 0)
5863             {
5864               GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5865                           "File size %llu seems incorrect for hostkeys...\n",
5866                           fs);
5867             }
5868           else
5869             {
5870               total_hostkeys = fs / HOSTKEYFILESIZE;
5871               GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5872                           "Will read %llu hostkeys from file\n", total_hostkeys);
5873               pg->hostkey_data = GNUNET_malloc_large (fs);
5874               GNUNET_assert (fs == GNUNET_DISK_file_read (fd, pg->hostkey_data, fs));
5875               GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fd));
5876             }
5877         }
5878       GNUNET_free(hostkeys_file);
5879     }
5880
5881   for (off = 0; off < total; off++)
5882     {
5883       if (hostcnt > 0)
5884         {
5885           hostname = pg->hosts[off % hostcnt].hostname;
5886           username = pg->hosts[off % hostcnt].username;
5887           sshport = pg->hosts[off % hostcnt].sshport;
5888           pcfg = make_config (cfg, off, &pg->hosts[off % hostcnt].minport,
5889                               &upnum, hostname, &fdnum);
5890         }
5891       else
5892         {
5893           hostname = NULL;
5894           username = NULL;
5895           sshport = 0;
5896           pcfg = make_config (cfg, off, &minport, &upnum, hostname, &fdnum);
5897         }
5898
5899       if (NULL == pcfg)
5900         {
5901           GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _
5902           ("Could not create configuration for peer number %u on `%s'!\n"),
5903                       off, hostname == NULL ? "localhost" : hostname);
5904           continue;
5905         }
5906
5907       if (GNUNET_YES
5908           == GNUNET_CONFIGURATION_get_value_string (pcfg, "PATHS",
5909                                                     "SERVICEHOME",
5910                                                     &baseservicehome))
5911         {
5912           if (hostname != NULL)
5913             GNUNET_asprintf (&newservicehome, "%s/%s/%d/", baseservicehome, hostname, off);
5914           else
5915             GNUNET_asprintf (&newservicehome, "%s/%d/", baseservicehome, off);
5916           GNUNET_free (baseservicehome);
5917         }
5918       else
5919         {
5920           tmpdir = getenv ("TMPDIR");
5921           tmpdir = tmpdir ? tmpdir : "/tmp";
5922           if (hostname != NULL)
5923             GNUNET_asprintf (&newservicehome, "%s/%s/%s/%d/", tmpdir, hostname,
5924                              "gnunet-testing-test-test", off);
5925           else
5926             GNUNET_asprintf (&newservicehome, "%s/%s/%d/", tmpdir,
5927                              "gnunet-testing-test-test", off);
5928         }
5929       GNUNET_CONFIGURATION_set_value_string (pcfg, "PATHS", "SERVICEHOME",
5930                                              newservicehome);
5931       GNUNET_free (newservicehome);
5932       pg->peers[off].cfg = pcfg;
5933 #if DEFER
5934       /* Can we do this later? */
5935       pg->peers[off].allowed_peers =
5936       GNUNET_CONTAINER_multihashmap_create (total);
5937       pg->peers[off].connect_peers =
5938       GNUNET_CONTAINER_multihashmap_create (total);
5939       pg->peers[off].blacklisted_peers =
5940       GNUNET_CONTAINER_multihashmap_create (total);
5941
5942 #endif
5943       pg->peers[off].pg = pg;
5944       pg->peers[off].internal_context.peer = &pg->peers[off];
5945       pg->peers[off].internal_context.timeout = timeout;
5946       pg->peers[off].internal_context.hostname = hostname;
5947       pg->peers[off].internal_context.username = username;
5948       pg->peers[off].internal_context.sshport = sshport;
5949       if (pg->hostkey_data != NULL)
5950         pg->peers[off].internal_context.hostkey = &pg->hostkey_data[off
5951             * HOSTKEYFILESIZE];
5952       pg->peers[off].internal_context.hostkey_callback = hostkey_callback;
5953       pg->peers[off].internal_context.hostkey_cls = hostkey_cls;
5954       pg->peers[off].internal_context.start_cb = cb;
5955       pg->peers[off].internal_context.start_cb_cls = cb_cls;
5956
5957       GNUNET_SCHEDULER_add_now (&internal_start,
5958                                 &pg->peers[off].internal_context);
5959
5960     }
5961   return pg;
5962 }
5963
5964 /*
5965  * Get a daemon by number, so callers don't have to do nasty
5966  * offsetting operation.
5967  */
5968 struct GNUNET_TESTING_Daemon *
5969 GNUNET_TESTING_daemon_get(struct GNUNET_TESTING_PeerGroup *pg,
5970                           unsigned int position)
5971 {
5972   if (position < pg->total)
5973     return pg->peers[position].daemon;
5974   else
5975     return NULL;
5976 }
5977
5978 /*
5979  * Get a daemon by peer identity, so callers can
5980  * retrieve the daemon without knowing it's offset.
5981  *
5982  * @param pg the peer group to retrieve the daemon from
5983  * @param peer_id the peer identity of the daemon to retrieve
5984  *
5985  * @return the daemon on success, or NULL if no such peer identity is found
5986  */
5987 struct GNUNET_TESTING_Daemon *
5988 GNUNET_TESTING_daemon_get_by_id(struct GNUNET_TESTING_PeerGroup *pg,
5989                                 struct GNUNET_PeerIdentity *peer_id)
5990 {
5991   unsigned int i;
5992
5993   for (i = 0; i < pg->total; i++)
5994     {
5995       if (0 == memcmp (&pg->peers[i].daemon->id, peer_id,
5996                        sizeof(struct GNUNET_PeerIdentity)))
5997         return pg->peers[i].daemon;
5998     }
5999
6000   return NULL;
6001 }
6002
6003 /**
6004  * Prototype of a function that will be called when a
6005  * particular operation was completed the testing library.
6006  *
6007  * @param cls closure (a struct RestartContext)
6008  * @param id id of the peer that was restarted
6009  * @param cfg handle to the configuration of the peer
6010  * @param d handle to the daemon that was restarted
6011  * @param emsg NULL on success
6012  */
6013 void
6014 restart_callback(void *cls, const struct GNUNET_PeerIdentity *id,
6015                  const struct GNUNET_CONFIGURATION_Handle *cfg,
6016                  struct GNUNET_TESTING_Daemon *d, const char *emsg)
6017 {
6018   struct RestartContext *restart_context = cls;
6019
6020   if (emsg == NULL)
6021     {
6022       restart_context->peers_restarted++;
6023     }
6024   else
6025     {
6026       restart_context->peers_restart_failed++;
6027     }
6028
6029   if (restart_context->peers_restarted == restart_context->peer_group->total)
6030     {
6031       restart_context->callback (restart_context->callback_cls, NULL);
6032       GNUNET_free (restart_context);
6033     }
6034   else if (restart_context->peers_restart_failed
6035       + restart_context->peers_restarted == restart_context->peer_group->total)
6036     {
6037       restart_context->callback (restart_context->callback_cls,
6038                                  "Failed to restart peers!");
6039       GNUNET_free (restart_context);
6040     }
6041
6042 }
6043
6044 /**
6045  * Callback for informing us about a successful
6046  * or unsuccessful churn stop call.
6047  *
6048  * @param cls a ChurnContext
6049  * @param emsg NULL on success, non-NULL on failure
6050  *
6051  */
6052 void
6053 churn_stop_callback(void *cls, const char *emsg)
6054 {
6055   struct ShutdownContext *shutdown_ctx = cls;
6056   struct ChurnContext *churn_ctx = shutdown_ctx->cb_cls;
6057   unsigned int total_left;
6058   char *error_message;
6059
6060   error_message = NULL;
6061   shutdown_ctx->outstanding--;
6062
6063   if (emsg != NULL)
6064     {
6065       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6066                   "Churn stop callback failed with error `%s'\n", emsg);
6067       churn_ctx->num_failed_stop++;
6068     }
6069   else
6070     {
6071       churn_ctx->num_to_stop--;
6072     }
6073
6074 #if DEBUG_CHURN
6075   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6076       "Stopped peer, %d left.\n", churn_ctx->num_to_stop);
6077 #endif
6078   total_left = (churn_ctx->num_to_stop - churn_ctx->num_failed_stop)
6079       + (churn_ctx->num_to_start - churn_ctx->num_failed_start);
6080
6081   if (total_left == 0)
6082     {
6083       if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
6084         {
6085           GNUNET_asprintf (
6086                            &error_message,
6087                            "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!",
6088                            churn_ctx->num_failed_start,
6089                            churn_ctx->num_failed_stop);
6090         }
6091       churn_ctx->cb (churn_ctx->cb_cls, error_message);
6092       GNUNET_free_non_null (error_message);
6093       GNUNET_free (churn_ctx);
6094       GNUNET_free (shutdown_ctx);
6095     }
6096 }
6097
6098 /**
6099  * Count the number of running peers.
6100  *
6101  * @param pg handle for the peer group
6102  *
6103  * @return the number of currently running peers in the peer group
6104  */
6105 unsigned int
6106 GNUNET_TESTING_daemons_running(struct GNUNET_TESTING_PeerGroup *pg)
6107 {
6108   unsigned int i;
6109   unsigned int running = 0;
6110   for (i = 0; i < pg->total; i++)
6111     {
6112       if (pg->peers[i].daemon->running == GNUNET_YES)
6113         {
6114           GNUNET_assert (running != -1);
6115           running++;
6116         }
6117     }
6118   return running;
6119 }
6120
6121 /**
6122  * Task to rate limit the number of outstanding peer shutdown
6123  * requests.  This is necessary for making sure we don't do
6124  * too many ssh connections at once, but is generally nicer
6125  * to any system as well (graduated task starts, as opposed
6126  * to calling gnunet-arm N times all at once).
6127  */
6128 static void
6129 schedule_churn_shutdown_task(void *cls,
6130                              const struct GNUNET_SCHEDULER_TaskContext *tc)
6131 {
6132   struct PeerShutdownContext *peer_shutdown_ctx = cls;
6133   struct ShutdownContext *shutdown_ctx;
6134   struct ChurnContext *churn_ctx;
6135   GNUNET_assert (peer_shutdown_ctx != NULL);
6136   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
6137   GNUNET_assert (shutdown_ctx != NULL);
6138   churn_ctx = (struct ChurnContext *) shutdown_ctx->cb_cls;
6139   if (shutdown_ctx->outstanding > churn_ctx->pg->max_concurrent_ssh)
6140     GNUNET_SCHEDULER_add_delayed (
6141                                   GNUNET_TIME_relative_multiply (
6142                                                                  GNUNET_TIME_UNIT_MILLISECONDS,
6143                                                                  100),
6144                                   &schedule_churn_shutdown_task,
6145                                   peer_shutdown_ctx);
6146   else
6147     {
6148       shutdown_ctx->outstanding++;
6149       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon,
6150                                   shutdown_ctx->timeout, shutdown_ctx->cb,
6151                                   shutdown_ctx, GNUNET_NO, GNUNET_YES);
6152       GNUNET_free (peer_shutdown_ctx);
6153     }
6154 }
6155
6156 /**
6157  * Simulate churn by stopping some peers (and possibly
6158  * re-starting others if churn is called multiple times).  This
6159  * function can only be used to create leave-join churn (peers "never"
6160  * leave for good).  First "voff" random peers that are currently
6161  * online will be taken offline; then "von" random peers that are then
6162  * offline will be put back online.  No notifications will be
6163  * generated for any of these operations except for the callback upon
6164  * completion.
6165  *
6166  * @param pg handle for the peer group
6167  * @param voff number of peers that should go offline
6168  * @param von number of peers that should come back online;
6169  *            must be zero on first call (since "testbed_start"
6170  *            always starts all of the peers)
6171  * @param timeout how long to wait for operations to finish before
6172  *        giving up
6173  * @param cb function to call at the end
6174  * @param cb_cls closure for cb
6175  */
6176 void
6177 GNUNET_TESTING_daemons_churn(struct GNUNET_TESTING_PeerGroup *pg,
6178                              unsigned int voff, unsigned int von,
6179                              struct GNUNET_TIME_Relative timeout,
6180                              GNUNET_TESTING_NotifyCompletion cb, void *cb_cls)
6181 {
6182   struct ChurnContext *churn_ctx;
6183   struct ShutdownContext *shutdown_ctx;
6184   struct PeerShutdownContext *peer_shutdown_ctx;
6185   struct PeerRestartContext *peer_restart_ctx;
6186   struct ChurnRestartContext *churn_startup_ctx;
6187
6188   unsigned int running;
6189   unsigned int stopped;
6190   unsigned int total_running;
6191   unsigned int total_stopped;
6192   unsigned int i;
6193   unsigned int *running_arr;
6194   unsigned int *stopped_arr;
6195   unsigned int *running_permute;
6196   unsigned int *stopped_permute;
6197
6198   running = 0;
6199   stopped = 0;
6200
6201   if ((von == 0) && (voff == 0)) /* No peers at all? */
6202     {
6203       cb (cb_cls, NULL);
6204       return;
6205     }
6206
6207   for (i = 0; i < pg->total; i++)
6208     {
6209       if (pg->peers[i].daemon->running == GNUNET_YES)
6210         {
6211           GNUNET_assert (running != -1);
6212           running++;
6213         }
6214       else
6215         {
6216           GNUNET_assert (stopped != -1);
6217           stopped++;
6218         }
6219     }
6220
6221   if (voff > running)
6222     {
6223       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6224                   "Trying to stop more peers than are currently running!\n");
6225       cb (cb_cls, "Trying to stop more peers than are currently running!");
6226       return;
6227     }
6228
6229   if (von > stopped)
6230     {
6231       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6232                   "Trying to start more peers than are currently stopped!\n");
6233       cb (cb_cls, "Trying to start more peers than are currently stopped!");
6234       return;
6235     }
6236
6237   churn_ctx = GNUNET_malloc (sizeof (struct ChurnContext));
6238
6239   running_arr = NULL;
6240   if (running > 0)
6241     running_arr = GNUNET_malloc (running * sizeof (unsigned int));
6242
6243   stopped_arr = NULL;
6244   if (stopped > 0)
6245     stopped_arr = GNUNET_malloc (stopped * sizeof (unsigned int));
6246
6247   running_permute = NULL;
6248   stopped_permute = NULL;
6249
6250   if (running > 0)
6251     running_permute = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
6252                                                     running);
6253   if (stopped > 0)
6254     stopped_permute = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
6255                                                     stopped);
6256
6257   total_running = running;
6258   total_stopped = stopped;
6259   running = 0;
6260   stopped = 0;
6261
6262   churn_ctx->num_to_start = von;
6263   churn_ctx->num_to_stop = voff;
6264   churn_ctx->cb = cb;
6265   churn_ctx->cb_cls = cb_cls;
6266   churn_ctx->pg = pg;
6267
6268   for (i = 0; i < pg->total; i++)
6269     {
6270       if (pg->peers[i].daemon->running == GNUNET_YES)
6271         {
6272           GNUNET_assert ((running_arr != NULL) && (total_running > running));
6273           running_arr[running] = i;
6274           running++;
6275         }
6276       else
6277         {
6278           GNUNET_assert ((stopped_arr != NULL) && (total_stopped > stopped));
6279           stopped_arr[stopped] = i;
6280           stopped++;
6281         }
6282     }
6283
6284   GNUNET_assert (running >= voff);
6285   if (voff > 0)
6286     {
6287       shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
6288       shutdown_ctx->cb = &churn_stop_callback;
6289       shutdown_ctx->cb_cls = churn_ctx;
6290       shutdown_ctx->total_peers = voff;
6291       shutdown_ctx->timeout = timeout;
6292     }
6293
6294   for (i = 0; i < voff; i++)
6295     {
6296 #if DEBUG_CHURN
6297       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Stopping peer %d!\n",
6298           running_permute[i]);
6299 #endif
6300       GNUNET_assert (running_arr != NULL);
6301       peer_shutdown_ctx = GNUNET_malloc (sizeof (struct PeerShutdownContext));
6302       peer_shutdown_ctx->daemon
6303           = pg->peers[running_arr[running_permute[i]]].daemon;
6304       peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
6305       GNUNET_SCHEDULER_add_now (&schedule_churn_shutdown_task,
6306                                 peer_shutdown_ctx);
6307
6308       /*
6309        GNUNET_TESTING_daemon_stop (pg->peers[running_arr[running_permute[i]]].daemon,
6310        timeout,
6311        &churn_stop_callback, churn_ctx,
6312        GNUNET_NO, GNUNET_YES); */
6313     }
6314
6315   GNUNET_assert (stopped >= von);
6316   if (von > 0)
6317     {
6318       churn_startup_ctx = GNUNET_malloc (sizeof (struct ChurnRestartContext));
6319       churn_startup_ctx->churn_ctx = churn_ctx;
6320       churn_startup_ctx->timeout = timeout;
6321       churn_startup_ctx->pg = pg;
6322     }
6323   for (i = 0; i < von; i++)
6324     {
6325 #if DEBUG_CHURN
6326       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Starting up peer %d!\n",
6327           stopped_permute[i]);
6328 #endif
6329       GNUNET_assert (stopped_arr != NULL);
6330       peer_restart_ctx = GNUNET_malloc (sizeof (struct PeerRestartContext));
6331       peer_restart_ctx->churn_restart_ctx = churn_startup_ctx;
6332       peer_restart_ctx->daemon
6333           = pg->peers[stopped_arr[stopped_permute[i]]].daemon;
6334       GNUNET_SCHEDULER_add_now (&schedule_churn_restart, peer_restart_ctx);
6335       /*
6336        GNUNET_TESTING_daemon_start_stopped(pg->peers[stopped_arr[stopped_permute[i]]].daemon,
6337        timeout, &churn_start_callback, churn_ctx); */
6338     }
6339
6340   GNUNET_free_non_null (running_arr);
6341   GNUNET_free_non_null (stopped_arr);
6342   GNUNET_free_non_null (running_permute);
6343   GNUNET_free_non_null (stopped_permute);
6344 }
6345
6346 /**
6347  * Restart all peers in the given group.
6348  *
6349  * @param pg the handle to the peer group
6350  * @param callback function to call on completion (or failure)
6351  * @param callback_cls closure for the callback function
6352  */
6353 void
6354 GNUNET_TESTING_daemons_restart(struct GNUNET_TESTING_PeerGroup *pg,
6355                                GNUNET_TESTING_NotifyCompletion callback,
6356                                void *callback_cls)
6357 {
6358   struct RestartContext *restart_context;
6359   unsigned int off;
6360
6361   if (pg->total > 0)
6362     {
6363       restart_context = GNUNET_malloc (sizeof (struct RestartContext));
6364       restart_context->peer_group = pg;
6365       restart_context->peers_restarted = 0;
6366       restart_context->callback = callback;
6367       restart_context->callback_cls = callback_cls;
6368
6369       for (off = 0; off < pg->total; off++)
6370         {
6371           GNUNET_TESTING_daemon_restart (pg->peers[off].daemon,
6372                                          &restart_callback, restart_context);
6373         }
6374     }
6375 }
6376
6377 /**
6378  * Start or stop an individual peer from the given group.
6379  *
6380  * @param pg handle to the peer group
6381  * @param offset which peer to start or stop
6382  * @param desired_status GNUNET_YES to have it running, GNUNET_NO to stop it
6383  * @param timeout how long to wait for shutdown
6384  * @param cb function to call at the end
6385  * @param cb_cls closure for cb
6386  */
6387 void
6388 GNUNET_TESTING_daemons_vary(struct GNUNET_TESTING_PeerGroup *pg,
6389                             unsigned int offset, int desired_status,
6390                             struct GNUNET_TIME_Relative timeout,
6391                             GNUNET_TESTING_NotifyCompletion cb, void *cb_cls)
6392 {
6393   struct ShutdownContext *shutdown_ctx;
6394   struct ChurnRestartContext *startup_ctx;
6395   struct ChurnContext *churn_ctx;
6396
6397   if (GNUNET_NO == desired_status)
6398     {
6399       if (NULL != pg->peers[offset].daemon)
6400         {
6401           shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
6402           churn_ctx = GNUNET_malloc (sizeof (struct ChurnContext));
6403           churn_ctx->num_to_start = 0;
6404           churn_ctx->num_to_stop = 1;
6405           churn_ctx->cb = cb;
6406           churn_ctx->cb_cls = cb_cls;
6407           shutdown_ctx->cb_cls = churn_ctx;
6408           GNUNET_TESTING_daemon_stop (pg->peers[offset].daemon, timeout,
6409                                       &churn_stop_callback, shutdown_ctx,
6410                                       GNUNET_NO, GNUNET_YES);
6411         }
6412     }
6413   else if (GNUNET_YES == desired_status)
6414     {
6415       if (NULL == pg->peers[offset].daemon)
6416         {
6417           startup_ctx = GNUNET_malloc (sizeof (struct ChurnRestartContext));
6418           churn_ctx = GNUNET_malloc (sizeof (struct ChurnContext));
6419           churn_ctx->num_to_start = 1;
6420           churn_ctx->num_to_stop = 0;
6421           churn_ctx->cb = cb;
6422           churn_ctx->cb_cls = cb_cls;
6423           startup_ctx->churn_ctx = churn_ctx;
6424           GNUNET_TESTING_daemon_start_stopped (pg->peers[offset].daemon,
6425                                                timeout, &churn_start_callback,
6426                                                startup_ctx);
6427         }
6428     }
6429   else
6430     GNUNET_break (0);
6431 }
6432
6433 /**
6434  * Callback for shutting down peers in a peer group.
6435  *
6436  * @param cls closure (struct ShutdownContext)
6437  * @param emsg NULL on success
6438  */
6439 void
6440 internal_shutdown_callback(void *cls, const char *emsg)
6441 {
6442   struct PeerShutdownContext *peer_shutdown_ctx = cls;
6443   struct ShutdownContext *shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
6444   unsigned int off;
6445   struct OutstandingSSH *ssh_pos;
6446
6447   shutdown_ctx->outstanding--;
6448   if (peer_shutdown_ctx->daemon->hostname != NULL)
6449     decrement_outstanding_at_host (peer_shutdown_ctx->daemon->hostname,
6450                                    shutdown_ctx->pg);
6451
6452   if (emsg == NULL)
6453     {
6454       shutdown_ctx->peers_down++;
6455     }
6456   else
6457     {
6458       shutdown_ctx->peers_failed++;
6459     }
6460
6461   if ((shutdown_ctx->cb != NULL) && (shutdown_ctx->peers_down
6462       + shutdown_ctx->peers_failed == shutdown_ctx->total_peers))
6463     {
6464       if (shutdown_ctx->peers_failed > 0)
6465         shutdown_ctx->cb (shutdown_ctx->cb_cls,
6466                           "Not all peers successfully shut down!");
6467       else
6468         shutdown_ctx->cb (shutdown_ctx->cb_cls, NULL);
6469
6470       GNUNET_free (shutdown_ctx->pg->peers);
6471       GNUNET_free_non_null(shutdown_ctx->pg->hostkey_data);
6472       for (off = 0; off < shutdown_ctx->pg->num_hosts; off++)
6473         {
6474           GNUNET_free (shutdown_ctx->pg->hosts[off].hostname);
6475           GNUNET_free_non_null (shutdown_ctx->pg->hosts[off].username);
6476         }
6477       GNUNET_free_non_null (shutdown_ctx->pg->hosts);
6478       while (NULL != (ssh_pos = shutdown_ctx->pg->ssh_head))
6479         {
6480           GNUNET_CONTAINER_DLL_remove(shutdown_ctx->pg->ssh_head, shutdown_ctx->pg->ssh_tail, ssh_pos);
6481           GNUNET_free(ssh_pos);
6482         }
6483       GNUNET_free (shutdown_ctx->pg);
6484       GNUNET_free (shutdown_ctx);
6485     }
6486   GNUNET_free(peer_shutdown_ctx);
6487 }
6488
6489 /**
6490  * Task to rate limit the number of outstanding peer shutdown
6491  * requests.  This is necessary for making sure we don't do
6492  * too many ssh connections at once, but is generally nicer
6493  * to any system as well (graduated task starts, as opposed
6494  * to calling gnunet-arm N times all at once).
6495  */
6496 static void
6497 schedule_shutdown_task(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6498 {
6499   struct PeerShutdownContext *peer_shutdown_ctx = cls;
6500   struct ShutdownContext *shutdown_ctx;
6501
6502   GNUNET_assert (peer_shutdown_ctx != NULL);
6503   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
6504   GNUNET_assert (shutdown_ctx != NULL);
6505
6506   if ((shutdown_ctx->outstanding < shutdown_ctx->pg->max_concurrent_ssh)
6507       || ((peer_shutdown_ctx->daemon->hostname != NULL)
6508           && (count_outstanding_at_host (peer_shutdown_ctx->daemon->hostname,
6509                                          shutdown_ctx->pg)
6510               < shutdown_ctx->pg->max_concurrent_ssh)))
6511     {
6512       if (peer_shutdown_ctx->daemon->hostname != NULL)
6513         increment_outstanding_at_host (peer_shutdown_ctx->daemon->hostname,
6514                                        shutdown_ctx->pg);
6515       shutdown_ctx->outstanding++;
6516       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon,
6517                                   shutdown_ctx->timeout,
6518                                   &internal_shutdown_callback, peer_shutdown_ctx,
6519                                   GNUNET_YES, GNUNET_NO);
6520     }
6521   else
6522     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
6523                                                                  100),
6524                                   &schedule_shutdown_task, peer_shutdown_ctx);
6525
6526 }
6527
6528 /**
6529  * Shutdown all peers started in the given group.
6530  *
6531  * @param pg handle to the peer group
6532  * @param timeout how long to wait for shutdown
6533  * @param cb callback to notify upon success or failure
6534  * @param cb_cls closure for cb
6535  */
6536 void
6537 GNUNET_TESTING_daemons_stop(struct GNUNET_TESTING_PeerGroup *pg,
6538                             struct GNUNET_TIME_Relative timeout,
6539                             GNUNET_TESTING_NotifyCompletion cb, void *cb_cls)
6540 {
6541   unsigned int off;
6542   struct ShutdownContext *shutdown_ctx;
6543   struct PeerShutdownContext *peer_shutdown_ctx;
6544 #if OLD
6545   struct PeerConnection *conn_iter;
6546   struct PeerConnection *temp_conn;
6547 #endif
6548
6549   GNUNET_assert (pg->total > 0);
6550
6551   shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
6552   shutdown_ctx->cb = cb;
6553   shutdown_ctx->cb_cls = cb_cls;
6554   shutdown_ctx->total_peers = pg->total;
6555   shutdown_ctx->timeout = timeout;
6556   shutdown_ctx->pg = pg;
6557   /* shtudown_ctx->outstanding = 0; */
6558
6559   for (off = 0; off < pg->total; off++)
6560     {
6561       GNUNET_assert (NULL != pg->peers[off].daemon);
6562       peer_shutdown_ctx = GNUNET_malloc (sizeof (struct PeerShutdownContext));
6563       peer_shutdown_ctx->daemon = pg->peers[off].daemon;
6564       peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
6565       GNUNET_SCHEDULER_add_now (&schedule_shutdown_task, peer_shutdown_ctx);
6566
6567       if (NULL != pg->peers[off].cfg)
6568         GNUNET_CONFIGURATION_destroy (pg->peers[off].cfg);
6569 #if OLD
6570       conn_iter = pg->peers[off].allowed_peers_head;
6571       while (conn_iter != NULL)
6572         {
6573           temp_conn = conn_iter->next;
6574           GNUNET_free(conn_iter);
6575           conn_iter = temp_conn;
6576         }
6577
6578       conn_iter = pg->peers[off].connect_peers_head;
6579       while (conn_iter != NULL)
6580         {
6581           temp_conn = conn_iter->next;
6582           GNUNET_free(conn_iter);
6583           conn_iter = temp_conn;
6584         }
6585
6586       conn_iter = pg->peers[off].blacklisted_peers_head;
6587       while (conn_iter != NULL)
6588         {
6589           temp_conn = conn_iter->next;
6590           GNUNET_free(conn_iter);
6591           conn_iter = temp_conn;
6592         }
6593
6594       conn_iter = pg->peers[off].connect_peers_working_set_head;
6595       while (conn_iter != NULL)
6596         {
6597           temp_conn = conn_iter->next;
6598           GNUNET_free(conn_iter);
6599           conn_iter = temp_conn;
6600         }
6601 #else
6602       if (pg->peers[off].allowed_peers != NULL)
6603       GNUNET_CONTAINER_multihashmap_destroy (pg->peers[off].allowed_peers);
6604       if (pg->peers[off].connect_peers != NULL)
6605       GNUNET_CONTAINER_multihashmap_destroy (pg->peers[off].connect_peers);
6606       if (pg->peers[off].blacklisted_peers != NULL)
6607       GNUNET_CONTAINER_multihashmap_destroy (pg->
6608           peers[off].blacklisted_peers);
6609 #endif
6610     }
6611 }
6612
6613 /* end of testing_group.c */