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