big scheduler refactoring, expect some issues
[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 /**
40  * Lowest port used for GNUnet testing.  Should be high enough to not
41  * conflict with other applications running on the hosts but be low
42  * enough to not conflict with client-ports (typically starting around
43  * 32k).
44  */
45 #define LOW_PORT 10000
46
47 /**
48  * Highest port used for GNUnet testing.  Should be low enough to not
49  * conflict with the port range for "local" ports (client apps; see
50  * /proc/sys/net/ipv4/ip_local_port_range on Linux for example).
51  */
52 #define HIGH_PORT 56000
53
54 #define MAX_OUTSTANDING_CONNECTIONS 40
55
56 #define MAX_CONCURRENT_HOSTKEYS 10
57
58 #define MAX_CONCURRENT_STARTING 10
59
60 #define MAX_CONCURRENT_SHUTDOWN 10
61
62 #define CONNECT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300)
63
64 #define CONNECT_ATTEMPTS 8
65
66 /**
67  * Prototype of a function called whenever two peers would be connected
68  * in a certain topology.
69  */
70 typedef unsigned int (*GNUNET_TESTING_ConnectionProcessor)(struct GNUNET_TESTING_PeerGroup *pg,
71                                                   unsigned int first,
72                                                   unsigned int second);
73
74
75 /**
76  * Context for handling churning a peer group
77  */
78 struct ChurnContext
79 {
80   /**
81    * Callback used to notify of churning finished
82    */
83   GNUNET_TESTING_NotifyCompletion cb;
84
85   /**
86    * Closure for callback
87    */
88   void *cb_cls;
89
90   /**
91    * Number of peers that still need to be started
92    */
93   unsigned int num_to_start;
94
95   /**
96    * Number of peers that still need to be stopped
97    */
98   unsigned int num_to_stop;
99  
100   /**
101    * Number of peers that failed to start
102    */
103   unsigned int num_failed_start;
104
105   /**
106    * Number of peers that failed to stop
107    */
108   unsigned int num_failed_stop;
109 };
110
111 struct RestartContext
112 {
113   /**
114    * The group of peers being restarted
115    */
116   struct GNUNET_TESTING_PeerGroup *peer_group;
117
118   /**
119    * How many peers have been restarted thus far
120    */
121   unsigned int peers_restarted;
122
123   /**
124    * How many peers got an error when restarting
125    */
126   unsigned int peers_restart_failed;
127
128   /**
129    * The function to call once all peers have been restarted
130    */
131   GNUNET_TESTING_NotifyCompletion callback;
132
133   /**
134    * Closure for callback function
135    */
136   void *callback_cls;
137
138 };
139
140
141 struct ShutdownContext
142 {
143   /**
144    * Total peers to wait for
145    */
146   unsigned int total_peers;
147
148   /**
149    * Number of peers successfully shut down
150    */
151   unsigned int peers_down;
152
153   /**
154    * Number of peers failed to shut down
155    */
156   unsigned int peers_failed;
157
158   /**
159    * Number of peers we have started shutting
160    * down.  If too many, wait on them.
161    */
162   unsigned int outstanding;
163
164   /**
165    * Timeout for shutdown.
166    */
167   struct GNUNET_TIME_Relative timeout;
168
169   /**
170    * Callback to call when all peers either
171    * shutdown or failed to shutdown
172    */
173   GNUNET_TESTING_NotifyCompletion cb;
174
175   /**
176    * Closure for cb
177    */
178   void *cb_cls;
179 };
180
181 /**
182  * Individual shutdown context for a particular peer.
183  */
184 struct PeerShutdownContext
185 {
186   /**
187    * Pointer to the high level shutdown context.
188    */
189   struct ShutdownContext *shutdown_ctx;
190
191   /**
192    * The daemon handle for the peer to shut down.
193    */
194   struct GNUNET_TESTING_Daemon *daemon;
195 };
196
197 /**
198  * Individual shutdown context for a particular peer.
199  */
200 struct PeerRestartContext
201 {
202   /**
203    * Pointer to the high level restart context.
204    */
205   struct ChurnRestartContext *churn_restart_ctx;
206
207   /**
208    * The daemon handle for the peer to shut down.
209    */
210   struct GNUNET_TESTING_Daemon *daemon;
211 };
212
213
214 struct CreateTopologyContext
215 {
216
217   /**
218    * Function to call with number of connections
219    */
220   GNUNET_TESTING_NotifyConnections cont;
221
222   /**
223    * Closure for connection notification
224    */
225   void *cls;
226 };
227
228 #if OLD
229 struct PeerConnection
230 {
231   /*
232    * Linked list
233    */
234   struct PeerConnection *next;
235
236   /*
237    * Pointer to daemon handle
238    */
239   struct GNUNET_TESTING_Daemon *daemon;
240
241 };
242 #endif
243
244 struct InternalStartContext
245 {
246   /**
247    * Pointer to peerdata
248    */
249   struct PeerData *peer;
250
251   /**
252    * Timeout for peer startup
253    */
254   struct GNUNET_TIME_Relative timeout;
255
256   /**
257    * Client callback for hostkey notification
258    */
259   GNUNET_TESTING_NotifyHostkeyCreated hostkey_callback;
260
261   /**
262    * Closure for hostkey_callback
263    */
264   void *hostkey_cls;
265
266   /**
267    * Client callback for peer start notification
268    */
269   GNUNET_TESTING_NotifyDaemonRunning start_cb;
270
271   /**
272    * Closure for cb
273    */
274   void *start_cb_cls;
275
276   /**
277    * Hostname, where to start the peer
278    */
279   const char *hostname;
280
281   /**
282    * Username to use when connecting to the
283    * host via ssh.
284    */
285   const char *username;
286
287   /**
288    * Port to use for ssh.
289    */
290   uint16_t sshport;
291
292 };
293
294 struct ChurnRestartContext
295 {
296   /**
297    * Number of restarts currently in flight.
298    */
299   unsigned int outstanding;
300
301   /**
302    * Handle to the underlying churn context.
303    */
304   struct ChurnContext *churn_ctx;
305
306   /**
307    * How long to allow the operation to take.
308    */
309   struct GNUNET_TIME_Relative timeout;
310 };
311
312 /**
313  * Data we keep per peer.
314  */
315 struct PeerData
316 {
317   /**
318    * (Initial) configuration of the host.
319    * (initial because clients could change
320    *  it and we would not know about those
321    *  updates).
322    */
323   struct GNUNET_CONFIGURATION_Handle *cfg;
324
325   /**
326    * Handle for controlling the daemon.
327    */
328   struct GNUNET_TESTING_Daemon *daemon;
329
330   /**
331    * The peergroup this peer belongs to.
332    */
333   struct GNUNET_TESTING_PeerGroup *pg;
334
335   /**
336    * Hash map of allowed peer connections (F2F created topology)
337    */
338   struct GNUNET_CONTAINER_MultiHashMap *allowed_peers;
339
340   /**
341    * Hash map of blacklisted peers
342    */
343   struct GNUNET_CONTAINER_MultiHashMap *blacklisted_peers;
344
345   /**
346    * Hash map of peer connections
347    */
348   struct GNUNET_CONTAINER_MultiHashMap *connect_peers;
349
350   /**
351    * Temporary hash map of peer connections
352    */
353   struct GNUNET_CONTAINER_MultiHashMap *connect_peers_working_set;
354
355   /**
356    * Temporary variable for topology creation, should be reset before
357    * creating any topology so the count is valid once finished.
358    */
359   int num_connections;
360
361   /**
362    * Context to keep track of peers being started, to
363    * stagger hostkey generation and peer startup.
364    */
365   struct InternalStartContext internal_context;
366 };
367
368
369 /**
370  * Linked list of per-host data.
371  */
372 struct HostData
373 {
374   /**
375    * Name of the host.
376    */
377   char *hostname;
378
379   /**
380    * SSH username to use when connecting to this host.
381    */
382   char *username;
383
384   /**
385    * SSH port to use when connecting to this host.
386    */
387   uint16_t sshport;
388
389   /**
390    * Lowest port that we have not yet used
391    * for GNUnet.
392    */
393   uint16_t minport;
394 };
395
396 struct TopologyIterateContext
397 {
398   /**
399    * Callback for notifying of two connected peers.
400    */
401   GNUNET_TESTING_NotifyTopology topology_cb;
402
403   /**
404    * Closure for topology_cb
405    */
406   void *cls;
407
408   /**
409    * Number of peers currently connected to.
410    */
411   unsigned int connected;
412
413   /**
414    * Number of peers we have finished iterating.
415    */
416   unsigned int completed;
417
418   /**
419    * Number of peers total.
420    */
421   unsigned int total;
422 };
423
424 struct StatsIterateContext
425 {
426   /**
427    * Continuation to call once all stats information has been retrieved.
428    */
429   GNUNET_STATISTICS_Callback cont;
430
431   /**
432    * Proc function to call on each value received.
433    */
434   GNUNET_TESTING_STATISTICS_Iterator proc;
435
436   /**
437    * Closure for topology_cb
438    */
439   void *cls;
440
441   /**
442    * Number of peers currently connected to.
443    */
444   unsigned int connected;
445
446   /**
447    * Number of peers we have finished iterating.
448    */
449   unsigned int completed;
450
451   /**
452    * Number of peers total.
453    */
454   unsigned int total;
455 };
456
457 struct CoreContext
458 {
459   void *iter_context;
460   struct GNUNET_TESTING_Daemon *daemon;
461 };
462
463 struct StatsCoreContext
464 {
465   void *iter_context;
466   struct GNUNET_TESTING_Daemon *daemon;
467   /**
468    * Handle to the statistics service.
469    */
470   struct GNUNET_STATISTICS_Handle *stats_handle;
471
472   /**
473    * Handle for getting statistics.
474    */
475   struct GNUNET_STATISTICS_GetHandle *stats_get_handle;
476 };
477
478 /**
479  * Handle to a group of GNUnet peers.
480  */
481 struct GNUNET_TESTING_PeerGroup
482 {
483   /**
484    * Configuration template.
485    */
486   const struct GNUNET_CONFIGURATION_Handle *cfg;
487
488   /**
489    * Function to call on each started daemon.
490    */
491   //GNUNET_TESTING_NotifyDaemonRunning cb;
492
493   /**
494    * Closure for cb.
495    */
496   //void *cb_cls;
497
498   /*
499    * Function to call on each topology connection created
500    */
501   GNUNET_TESTING_NotifyConnection notify_connection;
502
503   /*
504    * Callback for notify_connection
505    */
506   void *notify_connection_cls;
507
508   /**
509    * Array of information about hosts.
510    */
511   struct HostData *hosts;
512
513   /**
514    * Number of hosts (size of HostData)
515    */
516   unsigned int num_hosts;
517
518   /**
519    * Array of "total" peers.
520    */
521   struct PeerData *peers;
522
523   /**
524    * Number of peers in this group.
525    */
526   unsigned int total;
527
528   /**
529    * At what time should we fail the peer startup process?
530    */
531   struct GNUNET_TIME_Absolute max_timeout;
532
533   /**
534    * How many peers are being started right now?
535    */
536   unsigned int starting;
537
538   /**
539    * How many peers have already been started?
540    */
541   unsigned int started;
542 };
543
544 struct UpdateContext
545 {
546   struct GNUNET_CONFIGURATION_Handle *ret;
547   const struct GNUNET_CONFIGURATION_Handle *orig;
548   const char *hostname;
549   unsigned int nport;
550   unsigned int upnum;
551   unsigned int fdnum;
552 };
553
554 struct ConnectTopologyContext
555 {
556   /**
557    * How many connections are left to create.
558    */
559   unsigned int remaining_connections;
560
561   /**
562    * Handle to group of peers.
563    */
564   struct GNUNET_TESTING_PeerGroup *pg;
565
566   /**
567    * Temp value set for each iteration.
568    */
569   struct PeerData *first;
570
571   /**
572    * Notification that all peers are connected.
573    */
574   GNUNET_TESTING_NotifyCompletion notify_connections_done;
575
576   /**
577    * Closure for notify.
578    */
579   void *notify_cls;
580 };
581
582 struct ConnectContext
583 {
584   /**
585    * Peer to connect second to.
586    */
587   struct GNUNET_TESTING_Daemon *first;
588
589   /**
590    * Peer to connect first to.
591    */
592   struct GNUNET_TESTING_Daemon *second;
593
594   /**
595    * Higher level topology connection context.
596    */
597   struct ConnectTopologyContext *ct_ctx;
598 };
599
600 /**
601  * Convert unique ID to hash code.
602  *
603  * @param uid unique ID to convert
604  * @param hash set to uid (extended with zeros)
605  */
606 static void
607 hash_from_uid (uint32_t uid,
608                GNUNET_HashCode *hash)
609 {
610   memset (hash, 0, sizeof(GNUNET_HashCode));
611   *((uint32_t*)hash) = uid;
612 }
613
614 /**
615  * Convert hash code to unique ID.
616  *
617  * @param uid unique ID to convert
618  * @param hash set to uid (extended with zeros)
619  */
620 static void
621 uid_from_hash (const GNUNET_HashCode *hash, uint32_t *uid)
622 {
623   memcpy (uid, hash, sizeof(uint32_t));
624 }
625
626 /**
627  * Number of connects we are waiting on, allows us to rate limit
628  * connect attempts.
629  */
630 static int outstanding_connects;
631
632 /**
633  * Get a topology from a string input.
634  *
635  * @param topology where to write the retrieved topology
636  * @param topology_string The string to attempt to
637  *        get a configuration value from
638  * @return GNUNET_YES if topology string matched a
639  *         known topology, GNUNET_NO if not
640  */
641 int
642 GNUNET_TESTING_topology_get(enum GNUNET_TESTING_Topology *topology, const char * topology_string)
643 {
644   /**
645    * Strings representing topologies in enum
646    */
647   static const char * topology_strings[] =
648     {
649       /**
650        * A clique (everyone connected to everyone else).
651        */
652       "CLIQUE",
653       
654       /**
655        * Small-world network (2d torus plus random links).
656        */
657       "SMALL_WORLD",
658       
659       /**
660        * Small-world network (ring plus random links).
661        */
662       "SMALL_WORLD_RING",
663       
664       /**
665        * Ring topology.
666        */
667       "RING",
668       
669       /**
670        * 2-d torus.
671        */
672       "2D_TORUS",
673       
674       /**
675        * Random graph.
676        */
677       "ERDOS_RENYI",
678       
679       /**
680        * Certain percentage of peers are unable to communicate directly
681        * replicating NAT conditions
682        */
683       "INTERNAT",
684       
685       /**
686        * Scale free topology.
687        */
688       "SCALE_FREE",
689       
690       /**
691        * Straight line topology.
692        */
693       "LINE",
694       
695       /**
696        * All peers are disconnected.
697        */
698       "NONE",
699
700       NULL
701     };
702
703   int curr = 0;
704   if (topology_string == NULL)
705     return GNUNET_NO;
706   while (topology_strings[curr] != NULL)
707     {
708       if (strcasecmp(topology_strings[curr], topology_string) == 0)
709         {
710           *topology = curr;
711           return GNUNET_YES;
712         }
713       curr++;
714     }
715   *topology = GNUNET_TESTING_TOPOLOGY_NONE;
716   return GNUNET_NO;
717 }
718
719
720 /**
721  * Get connect topology option from string input.
722  *
723  * @param topology_option where to write the retrieved topology
724  * @param topology_string The string to attempt to
725  *        get a configuration value from
726  * @return GNUNET_YES if string matched a known
727  *         topology option, GNUNET_NO if not
728  */
729 int
730 GNUNET_TESTING_topology_option_get (enum GNUNET_TESTING_TopologyOption *topology_option,
731                                     const char * topology_string)
732 {
733   /**
734    * Options for connecting a topology as strings.
735    */
736   static const char * topology_option_strings[] =
737     {
738       /**
739        * Try to connect all peers specified in the topology.
740        */
741       "CONNECT_ALL",
742       
743       /**
744        * Choose a random subset of connections to create.
745        */
746       "CONNECT_RANDOM_SUBSET",
747       
748       /**
749        * Create at least X connections for each peer.
750        */
751       "CONNECT_MINIMUM",
752       
753       /**
754        * Using a depth first search, create one connection
755        * per peer.  If any are missed (graph disconnected)
756        * start over at those peers until all have at least one
757        * connection.
758        */
759       "CONNECT_DFS",
760       
761       /**
762        * Find the N closest peers to each allowed peer in the
763        * topology and make sure a connection to those peers
764        * exists in the connect topology.
765        */
766       "CONNECT_CLOSEST",
767
768       /**
769        * No options specified.
770        */
771       "CONNECT_NONE",
772
773       NULL
774     };
775   int curr = 0;
776
777   if (topology_string == NULL)
778     return GNUNET_NO;
779   while (NULL != topology_option_strings[curr])
780     {
781       if (strcasecmp(topology_option_strings[curr], topology_string) == 0)
782         {
783           *topology_option = curr;
784           return GNUNET_YES;
785         }
786       curr++;
787     } 
788   *topology_option = GNUNET_TESTING_TOPOLOGY_OPTION_NONE;
789   return GNUNET_NO;
790 }
791
792 /**
793  * Function to iterate over options.  Copies
794  * the options to the target configuration,
795  * updating PORT values as needed.
796  *
797  * @param cls closure
798  * @param section name of the section
799  * @param option name of the option
800  * @param value value of the option
801  */
802 static void
803 update_config (void *cls,
804                const char *section, const char *option, const char *value)
805 {
806   struct UpdateContext *ctx = cls;
807   unsigned int ival;
808   char cval[12];
809   char uval[128];
810   char *single_variable;
811   char *per_host_variable;
812   unsigned long long num_per_host;
813
814   if ((0 == strcmp (option, "PORT")) && (1 == sscanf (value, "%u", &ival)))
815     {
816       GNUNET_asprintf(&single_variable, "single_%s_per_host", section);
817       if ((ival != 0) && (GNUNET_YES != GNUNET_CONFIGURATION_get_value_yesno(ctx->orig, "testing", single_variable)))
818         {
819           GNUNET_snprintf (cval, sizeof (cval), "%u", ctx->nport++);
820           value = cval;
821         }
822
823       GNUNET_free(single_variable);
824     }
825
826   if (0 == strcmp (option, "UNIXPATH"))
827     {
828       GNUNET_asprintf(&single_variable, "single_%s_per_host", section);
829       GNUNET_asprintf(&per_host_variable, "num_%s_per_host", section);
830       if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_yesno(ctx->orig, "testing", single_variable))
831         {
832           GNUNET_snprintf (uval,
833                            sizeof (uval),
834                            "/tmp/test-service-%s-%u",
835                            section,
836                            ctx->upnum++);
837           value = uval;
838         }
839       else if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_number(ctx->orig, "testing", per_host_variable, &num_per_host))
840         {
841           GNUNET_snprintf (uval,
842                            sizeof (uval),
843                            "/tmp/test-service-%s-%u",
844                            section,
845                            ctx->fdnum % num_per_host);
846           value = uval;
847         }
848       GNUNET_free(single_variable);
849       GNUNET_free(per_host_variable);
850
851     }
852
853   if ((0 == strcmp (option, "HOSTNAME")) && (ctx->hostname != NULL))
854     {
855       value = ctx->hostname;
856     }
857
858   GNUNET_CONFIGURATION_set_value_string (ctx->ret, section, option, value);
859 }
860
861
862 /**
863  * Create a new configuration using the given configuration
864  * as a template; however, each PORT in the existing cfg
865  * must be renumbered by incrementing "*port".  If we run
866  * out of "*port" numbers, return NULL.
867  *
868  * @param cfg template configuration
869  * @param port port numbers to use, update to reflect
870  *             port numbers that were used
871  * @param upnum number to make unix domain socket names unique
872  * @param hostname hostname of the controlling host, to allow control connections from
873  * @param fdnum number used to offset the unix domain socket for grouped processes
874  *              (such as statistics or peerinfo, which can be shared among others)
875  *
876  * @return new configuration, NULL on error
877  */
878 static struct GNUNET_CONFIGURATION_Handle *
879 make_config (const struct GNUNET_CONFIGURATION_Handle *cfg, 
880              uint16_t * port,
881              uint32_t * upnum,
882              const char *hostname, uint32_t * fdnum)
883 {
884   struct UpdateContext uc;
885   uint16_t orig;
886   char *control_host;
887   char *allowed_hosts;
888
889   orig = *port;
890   uc.nport = *port;
891   uc.upnum = *upnum;
892   uc.fdnum = *fdnum;
893   uc.ret = GNUNET_CONFIGURATION_create ();
894   uc.hostname = hostname;
895   uc.orig = cfg;
896
897   GNUNET_CONFIGURATION_iterate (cfg, &update_config, &uc);
898   if (uc.nport >= HIGH_PORT)
899     {
900       *port = orig;
901       GNUNET_CONFIGURATION_destroy (uc.ret);
902       return NULL;
903     }
904
905   if (GNUNET_CONFIGURATION_get_value_string(cfg, "testing", "control_host", &control_host) == GNUNET_OK)
906     {
907       if (hostname != NULL)
908         GNUNET_asprintf(&allowed_hosts, "%s; 127.0.0.1; %s;", control_host, hostname);
909       else
910         GNUNET_asprintf(&allowed_hosts, "%s; 127.0.0.1;", control_host);
911
912       GNUNET_CONFIGURATION_set_value_string(uc.ret, "core", "ACCEPT_FROM", allowed_hosts);
913       GNUNET_CONFIGURATION_set_value_string(uc.ret, "transport", "ACCEPT_FROM", allowed_hosts);
914       GNUNET_CONFIGURATION_set_value_string(uc.ret, "dht", "ACCEPT_FROM", allowed_hosts);
915       GNUNET_CONFIGURATION_set_value_string(uc.ret, "statistics", "ACCEPT_FROM", allowed_hosts);
916       GNUNET_free_non_null(control_host);
917       GNUNET_free(allowed_hosts);
918     }
919
920
921   /* arm needs to know to allow connections from the host on which it is running,
922    * otherwise gnunet-arm is unable to connect to it in some instances */
923   if (hostname != NULL)
924     {
925       GNUNET_asprintf(&allowed_hosts, "%s; 127.0.0.1;", hostname);
926       GNUNET_CONFIGURATION_set_value_string(uc.ret, "transport-udp", "BINDTO", hostname);
927       GNUNET_CONFIGURATION_set_value_string(uc.ret, "transport-tcp", "BINDTO", hostname);
928       GNUNET_CONFIGURATION_set_value_string(uc.ret, "arm", "ACCEPT_FROM", allowed_hosts);
929       GNUNET_free(allowed_hosts);
930     }
931   else
932     {
933       GNUNET_CONFIGURATION_set_value_string(uc.ret, "transport-tcp", "BINDTO", "127.0.0.1");
934       GNUNET_CONFIGURATION_set_value_string(uc.ret, "transport-udp", "BINDTO", "127.0.0.1");
935     }
936
937   *port = (uint16_t) uc.nport;
938   *upnum = uc.upnum;
939   uc.fdnum++;
940   *fdnum = uc.fdnum;
941   return uc.ret;
942 }
943
944
945 /*
946  * Add entries to the peers connect list
947  *
948  * @param pg the peer group we are working with
949  * @param first index of the first peer
950  * @param second index of the second peer
951  *
952  * @return the number of connections added
953  *         technically should only be 0 or 2
954  *
955  */
956 static unsigned int
957 add_actual_connections(struct GNUNET_TESTING_PeerGroup *pg, unsigned int first, unsigned int second)
958 {
959   int added;
960   int add_first;
961   int add_second;
962
963   GNUNET_HashCode hash_first;
964   GNUNET_HashCode hash_second;
965
966   hash_from_uid(first, &hash_first);
967   hash_from_uid(second, &hash_second);
968
969   add_first = GNUNET_NO;
970   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[first].connect_peers, &hash_second))
971     {
972       add_first = GNUNET_YES;
973     }
974
975   add_second = GNUNET_NO;
976   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[second].connect_peers, &hash_first))
977     {
978       add_second = GNUNET_YES;
979     }
980
981   added = 0;
982   if (add_first)
983     {
984       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[first].connect_peers, &hash_second, pg->peers[second].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
985       pg->peers[first].num_connections++;
986       added++;
987     }
988
989   if (add_second)
990     {
991       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[second].connect_peers, &hash_first, pg->peers[first].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
992       pg->peers[second].num_connections++;
993       added++;
994     }
995
996   return added;
997 }
998
999
1000 /*
1001  * Add entries to the peers allowed connections list
1002  *
1003  * @param pg the peer group we are working with
1004  * @param first index of the first peer
1005  * @param second index of the second peer
1006  *
1007  * @return the number of connections added (can be 0, 1 or 2)
1008  *         technically should only be 0 or 2, but the small price
1009  *         of iterating over the lists (hashmaps in the future)
1010  *         for being sure doesn't bother me!
1011  *
1012  */
1013 static unsigned int
1014 add_allowed_connections(struct GNUNET_TESTING_PeerGroup *pg, unsigned int first, unsigned int second)
1015 {
1016   int added;
1017 #if OLD
1018   struct PeerConnection *first_iter;
1019   struct PeerConnection *second_iter;
1020   struct PeerConnection *new_first;
1021   struct PeerConnection *new_second;
1022 #endif
1023   int add_first;
1024   int add_second;
1025
1026   GNUNET_HashCode hash_first;
1027   GNUNET_HashCode hash_second;
1028
1029   hash_from_uid(first, &hash_first);
1030   hash_from_uid(second, &hash_second);
1031
1032   add_first = GNUNET_NO;
1033   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[first].allowed_peers, &hash_second))
1034     {
1035       add_first = GNUNET_YES;
1036     }
1037
1038   add_second = GNUNET_NO;
1039   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[second].allowed_peers, &hash_first))
1040     {
1041       add_second = GNUNET_YES;
1042     }
1043 #if OLD
1044   first_iter = pg->peers[first].connected_peers;
1045   while (first_iter != NULL)
1046     {
1047       if (first_iter->daemon == pg->peers[second].daemon)
1048         add_first = GNUNET_NO;
1049       first_iter = first_iter->next;
1050     }
1051
1052   second_iter = pg->peers[second].connected_peers;
1053   add_second = GNUNET_YES;
1054   while (second_iter != NULL)
1055     {
1056       if (second_iter->daemon == pg->peers[first].daemon)
1057         add_second = GNUNET_NO;
1058       second_iter = second_iter->next;
1059     }
1060 #endif
1061
1062   added = 0;
1063   if (add_first)
1064     {
1065       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[first].allowed_peers, &hash_second, pg->peers[second].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1066 #if OLD
1067       new_first = GNUNET_malloc(sizeof(struct PeerConnection));
1068       new_first->daemon = pg->peers[second].daemon;
1069       new_first->next = pg->peers[first].connected_peers;
1070       pg->peers[first].connected_peers = new_first;
1071 #endif
1072       pg->peers[first].num_connections++;
1073       added++;
1074     }
1075
1076   if (add_second)
1077     {
1078       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[second].allowed_peers, &hash_first, pg->peers[first].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1079 #if OLD
1080       new_second = GNUNET_malloc(sizeof(struct PeerConnection));
1081       new_second->daemon = pg->peers[first].daemon;
1082       new_second->next = pg->peers[second].connected_peers;
1083       pg->peers[second].connected_peers = new_second;
1084       pg->peers[first].num_connections++;
1085 #endif
1086       pg->peers[second].num_connections++;
1087       added++;
1088     }
1089
1090   return added;
1091 }
1092
1093 /*
1094  * Add entries to the peers blacklisted list
1095  *
1096  * @param pg the peer group we are working with
1097  * @param first index of the first peer
1098  * @param second index of the second peer
1099  *
1100  * @return the number of connections added (can be 0, 1 or 2)
1101  *
1102  */
1103 static unsigned int
1104 blacklist_connections(struct GNUNET_TESTING_PeerGroup *pg, unsigned int first, unsigned int second)
1105 {
1106   int added;
1107   int add_first;
1108   int add_second;
1109   GNUNET_HashCode hash_first;
1110   GNUNET_HashCode hash_second;
1111
1112   hash_from_uid(first, &hash_first);
1113   hash_from_uid(second, &hash_second);
1114
1115   add_first = GNUNET_NO;
1116   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[first].blacklisted_peers, &hash_second))
1117     {
1118       add_first = GNUNET_YES;
1119     }
1120
1121   add_second = GNUNET_NO;
1122   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(pg->peers[second].blacklisted_peers, &hash_first))
1123     {
1124       add_second = GNUNET_YES;
1125     }
1126
1127   added = 0;
1128   if (add_first)
1129     {
1130       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[first].blacklisted_peers, &hash_second, pg->peers[second].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1131       pg->peers[first].num_connections++;
1132       added++;
1133     }
1134
1135   if (add_second)
1136     {
1137       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(pg->peers[second].blacklisted_peers, &hash_first, pg->peers[first].daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1138       pg->peers[second].num_connections++;
1139       added++;
1140     }
1141
1142   return added;
1143 }
1144
1145 /*
1146  * Remove entries from the peers blacklisted list
1147  *
1148  * @param pg the peer group we are working with
1149  * @param first index of the first peer
1150  * @param second index of the second peer
1151  *
1152  * @return the number of connections removed (can be 0, 1 or 2)
1153  *
1154  */
1155 static unsigned int
1156 unblacklist_connections(struct GNUNET_TESTING_PeerGroup *pg, unsigned int first, unsigned int second)
1157 {
1158   int removed;
1159   int remove_first;
1160   int remove_second;
1161   GNUNET_HashCode hash_first;
1162   GNUNET_HashCode hash_second;
1163
1164   hash_from_uid(first, &hash_first);
1165   hash_from_uid(second, &hash_second);
1166
1167   remove_first = GNUNET_CONTAINER_multihashmap_contains(pg->peers[first].blacklisted_peers, &hash_second);
1168   remove_second = GNUNET_CONTAINER_multihashmap_contains(pg->peers[second].blacklisted_peers, &hash_first);
1169
1170   removed = 0;
1171   if (remove_first)
1172     {
1173       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(pg->peers[first].blacklisted_peers, &hash_second, pg->peers[second].daemon));
1174       removed++;
1175     }
1176
1177   if (remove_second)
1178     {
1179       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(pg->peers[second].blacklisted_peers, &hash_first, pg->peers[first].daemon));
1180       removed++;
1181     }
1182
1183   return removed;
1184 }
1185
1186 /**
1187  * Scale free network construction as described in:
1188  *
1189  * "Emergence of Scaling in Random Networks." Science 286, 509-512, 1999.
1190  *
1191  * Start with a network of "one" peer, then progressively add
1192  * peers up to the total number.  At each step, iterate over
1193  * all possible peers and connect new peer based on number of
1194  * existing connections of the target peer.
1195  *
1196  * @param pg the peer group we are dealing with
1197  * @param proc the connection processor to use
1198  *
1199  * @return the number of connections created
1200  */
1201 static unsigned int
1202 create_scale_free (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1203 {
1204
1205   unsigned int total_connections;
1206   unsigned int outer_count;
1207   unsigned int i;
1208   unsigned int previous_total_connections;
1209   double random;
1210   double probability;
1211
1212   GNUNET_assert(pg->total > 1);
1213
1214   /* Add a connection between the first two nodes */
1215   total_connections = proc(pg, 0, 1);
1216
1217   for (outer_count = 1; outer_count < pg->total; outer_count++)
1218     {
1219       previous_total_connections = total_connections;
1220       for (i = 0; i < outer_count; i++)
1221         {
1222           probability = pg->peers[i].num_connections / (double)previous_total_connections;
1223           random = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
1224                                                       UINT64_MAX)) / ( (double) UINT64_MAX);
1225 #if VERBOSE_TESTING
1226           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1227                       "Considering connecting peer %d to peer %d\n",
1228                       outer_count, i);
1229 #endif
1230           if (random < probability)
1231             {
1232 #if VERBOSE_TESTING
1233               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1234                           "Connecting peer %d to peer %d\n",
1235                           outer_count, i);
1236 #endif
1237               total_connections += proc(pg, outer_count, i);
1238             }
1239         }
1240     }
1241
1242   return total_connections;
1243 }
1244
1245 /**
1246  * Create a topology given a peer group (set of running peers)
1247  * and a connection processor.
1248  *
1249  * @param pg the peergroup to create the topology on
1250  * @param proc the connection processor to call to actually set
1251  *        up connections between two peers
1252  *
1253  * @return the number of connections that were set up
1254  *
1255  */
1256 static unsigned int
1257 create_small_world_ring(struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1258 {
1259   unsigned int i, j;
1260   int nodeToConnect;
1261   unsigned int natLog;
1262   unsigned int randomPeer;
1263   double random, logNModifier, percentage;
1264   unsigned int smallWorldConnections;
1265   int connsPerPeer;
1266   char *p_string;
1267   int max;
1268   int min;
1269   unsigned int useAnd;
1270   int connect_attempts;
1271
1272   logNModifier = 0.5; /* FIXME: default value? */
1273   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1274                                                          "TESTING",
1275                                                          "LOGNMODIFIER",
1276                                                          &p_string))
1277     {
1278       if (sscanf(p_string, "%lf", &logNModifier) != 1)
1279         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1280                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1281                     p_string,
1282                     "LOGNMODIFIER",
1283                     "TESTING");
1284       GNUNET_free (p_string);
1285     }
1286   percentage = 0.5; /* FIXME: default percentage? */
1287   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1288                                                          "TESTING",
1289                                                          "PERCENTAGE",
1290                                                          &p_string))
1291     {
1292       if (sscanf(p_string, "%lf", &percentage) != 1)
1293         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1294                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1295                     p_string,
1296                     "PERCENTAGE",
1297                     "TESTING");
1298       GNUNET_free (p_string);
1299     }
1300   natLog = log (pg->total);
1301   connsPerPeer = ceil (natLog * logNModifier);
1302
1303   if (connsPerPeer % 2 == 1)
1304     connsPerPeer += 1;
1305
1306   smallWorldConnections = 0;
1307   connect_attempts = 0;
1308   for (i = 0; i < pg->total; i++)
1309     {
1310       useAnd = 0;
1311       max = i + connsPerPeer / 2;
1312       min = i - connsPerPeer / 2;
1313
1314       if (max > pg->total - 1)
1315         {
1316           max = max - pg->total;
1317           useAnd = 1;
1318         }
1319
1320       if (min < 0)
1321         {
1322           min = pg->total - 1 + min;
1323           useAnd = 1;
1324         }
1325
1326       for (j = 0; j < connsPerPeer / 2; j++)
1327         {
1328           random = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
1329                                                       UINT64_MAX) / ( (double) UINT64_MAX));
1330           if (random < percentage)
1331             {
1332               /* Connect to uniformly selected random peer */
1333               randomPeer =
1334                 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1335                                    pg->total);
1336               while ((((randomPeer < max) && (randomPeer > min))
1337                       && (useAnd == 0)) || (((randomPeer > min)
1338                                              || (randomPeer < max))
1339                                             && (useAnd == 1)))
1340                 {
1341                   randomPeer =
1342                       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1343                                                          pg->total);
1344                 }
1345               smallWorldConnections +=
1346                 proc (pg, i, randomPeer);
1347             }
1348           else
1349             {
1350               nodeToConnect = i + j + 1;
1351               if (nodeToConnect > pg->total - 1)
1352                 {
1353                   nodeToConnect = nodeToConnect - pg->total;
1354                 }
1355               connect_attempts +=
1356                 proc (pg, i, nodeToConnect);
1357             }
1358         }
1359
1360     }
1361
1362   connect_attempts += smallWorldConnections;
1363
1364   return connect_attempts;
1365 }
1366
1367 /**
1368  * Create a topology given a peer group (set of running peers)
1369  * and a connection processor.
1370  *
1371  * @param pg the peergroup to create the topology on
1372  * @param proc the connection processor to call to actually set
1373  *        up connections between two peers
1374  *
1375  * @return the number of connections that were set up
1376  *
1377  */
1378 static unsigned int
1379 create_nated_internet (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1380 {
1381   unsigned int outer_count, inner_count;
1382   unsigned int cutoff;
1383   int connect_attempts;
1384   double nat_percentage;
1385   char *p_string;
1386
1387   nat_percentage = 0.6; /* FIXME: default percentage? */
1388   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1389                                                          "TESTING",
1390                                                          "NATPERCENTAGE",
1391                                                          &p_string))
1392     {
1393       if (sscanf(p_string, "%lf", &nat_percentage) != 1)
1394         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1395                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1396                     p_string,
1397                     "NATPERCENTAGE",
1398                     "TESTING");
1399       GNUNET_free (p_string);
1400     }
1401
1402
1403
1404   cutoff = (unsigned int) (nat_percentage * pg->total);
1405
1406   connect_attempts = 0;
1407
1408   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
1409     {
1410       for (inner_count = outer_count + 1; inner_count < pg->total;
1411            inner_count++)
1412         {
1413           if ((outer_count > cutoff) || (inner_count > cutoff))
1414             {
1415 #if VERBOSE_TESTING
1416               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1417                           "Connecting peer %d to peer %d\n",
1418                           outer_count, inner_count);
1419 #endif
1420               connect_attempts += proc(pg, outer_count, inner_count);
1421             }
1422         }
1423     }
1424
1425   return connect_attempts;
1426
1427 }
1428
1429 /**
1430  * Create a topology given a peer group (set of running peers)
1431  * and a connection processor.
1432  *
1433  * @param pg the peergroup to create the topology on
1434  * @param proc the connection processor to call to actually set
1435  *        up connections between two peers
1436  *
1437  * @return the number of connections that were set up
1438  *
1439  */
1440 static unsigned int
1441 create_small_world (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1442 {
1443   unsigned int i, j, k;
1444   unsigned int square;
1445   unsigned int rows;
1446   unsigned int cols;
1447   unsigned int toggle = 1;
1448   unsigned int nodeToConnect;
1449   unsigned int natLog;
1450   unsigned int node1Row;
1451   unsigned int node1Col;
1452   unsigned int node2Row;
1453   unsigned int node2Col;
1454   unsigned int distance;
1455   double probability, random, percentage;
1456   unsigned int smallWorldConnections;
1457   unsigned int small_world_it;
1458   char *p_string;
1459   int connect_attempts;
1460   square = floor (sqrt (pg->total));
1461   rows = square;
1462   cols = square;
1463
1464   percentage = 0.5; /* FIXME: default percentage? */
1465   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1466                                                          "TESTING",
1467                                                          "PERCENTAGE",
1468                                                          &p_string))
1469     {
1470       if (sscanf(p_string, "%lf", &percentage) != 1)
1471         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1472                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1473                     p_string,
1474                     "PERCENTAGE",
1475                     "TESTING");
1476       GNUNET_free (p_string);
1477     }
1478   if (percentage < 0.0)
1479     {
1480       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1481                   _("Invalid value `%s' for option `%s' in section `%s': got %f, needed value greater than 0\n"),
1482                   "PERCENTAGE", "TESTING", percentage);
1483       percentage = 0.5;
1484     }
1485   probability = 0.5; /* FIXME: default percentage? */
1486   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1487                                                          "TESTING",
1488                                                          "PROBABILITY",
1489                                                          &p_string))
1490     {
1491       if (sscanf(p_string, "%lf", &probability) != 1)
1492         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1493                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1494                     p_string,
1495                     "PROBABILITY",
1496                     "TESTING");
1497       GNUNET_free (p_string);
1498     }
1499   if (square * square != pg->total)
1500     {
1501       while (rows * cols < pg->total)
1502         {
1503           if (toggle % 2 == 0)
1504             rows++;
1505           else
1506             cols++;
1507
1508           toggle++;
1509         }
1510     }
1511 #if VERBOSE_TESTING
1512       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1513                   _("Connecting nodes in 2d torus topology: %u rows %u columns\n"),
1514                   rows, cols);
1515 #endif
1516
1517   connect_attempts = 0;
1518   /* Rows and columns are all sorted out, now iterate over all nodes and connect each
1519    * to the node to its right and above.  Once this is over, we'll have our torus!
1520    * Special case for the last node (if the rows and columns are not equal), connect
1521    * to the first in the row to maintain topology.
1522    */
1523   for (i = 0; i < pg->total; i++)
1524     {
1525       /* First connect to the node to the right */
1526       if (((i + 1) % cols != 0) && (i + 1 != pg->total))
1527         nodeToConnect = i + 1;
1528       else if (i + 1 == pg->total)
1529         nodeToConnect = rows * cols - cols;
1530       else
1531         nodeToConnect = i - cols + 1;
1532
1533       connect_attempts += proc (pg, i, nodeToConnect);
1534
1535       if (i < cols)
1536         nodeToConnect = (rows * cols) - cols + i;
1537       else
1538         nodeToConnect = i - cols;
1539
1540       if (nodeToConnect < pg->total)
1541         connect_attempts += proc (pg, i, nodeToConnect);
1542     }
1543   natLog = log (pg->total);
1544 #if VERBOSE_TESTING > 2
1545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1546               _("natural log of %d is %d, will run %d iterations\n"),
1547              pg->total, natLog, (int) (natLog * percentage));
1548   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Total connections added thus far: %u!\n"), connect_attempts);
1549 #endif
1550   smallWorldConnections = 0;
1551   small_world_it = (unsigned int)(natLog * percentage);
1552   if (small_world_it < 1)
1553     small_world_it = 1;
1554   GNUNET_assert(small_world_it > 0 && small_world_it < (unsigned int)-1);
1555   for (i = 0; i < small_world_it; i++)
1556     {
1557       for (j = 0; j < pg->total; j++)
1558         {
1559           /* Determine the row and column of node at position j on the 2d torus */
1560           node1Row = j / cols;
1561           node1Col = j - (node1Row * cols);
1562           for (k = 0; k < pg->total; k++)
1563             {
1564               /* Determine the row and column of node at position k on the 2d torus */
1565               node2Row = k / cols;
1566               node2Col = k - (node2Row * cols);
1567               /* Simple Cartesian distance */
1568               distance = abs (node1Row - node2Row) + abs (node1Col - node2Col);
1569               if (distance > 1)
1570                 {
1571                   /* Calculate probability as 1 over the square of the distance */
1572                   probability = 1.0 / (distance * distance);
1573                   /* Choose a random value between 0 and 1 */
1574                   random = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
1575                                                               UINT64_MAX)) / ( (double) UINT64_MAX);
1576                   /* If random < probability, then connect the two nodes */
1577                   if (random < probability)
1578                     smallWorldConnections += proc (pg, j, k);
1579
1580                 }
1581             }
1582         }
1583     }
1584   connect_attempts += smallWorldConnections;
1585 #if VERBOSE_TESTING > 2
1586           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1587                       _("Total connections added for small world: %d!\n"),
1588                       smallWorldConnections);
1589 #endif
1590   return connect_attempts;
1591 }
1592
1593 /**
1594  * Create a topology given a peer group (set of running peers)
1595  * and a connection processor.
1596  *
1597  * @param pg the peergroup to create the topology on
1598  * @param proc the connection processor to call to actually set
1599  *        up connections between two peers
1600  *
1601  * @return the number of connections that were set up
1602  *
1603  */
1604 static unsigned int
1605 create_erdos_renyi (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1606 {
1607   double temp_rand;
1608   unsigned int outer_count;
1609   unsigned int inner_count;
1610   int connect_attempts;
1611   double probability;
1612   char *p_string;
1613
1614   probability = 0.5; /* FIXME: default percentage? */
1615   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
1616                                                          "TESTING",
1617                                                          "PROBABILITY",
1618                                                          &p_string))
1619     {
1620       if (sscanf(p_string, "%lf", &probability) != 1)
1621         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1622                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1623                     p_string,
1624                     "PROBABILITY",
1625                     "TESTING");
1626       GNUNET_free (p_string);
1627     }
1628   connect_attempts = 0;
1629   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
1630     {
1631       for (inner_count = outer_count + 1; inner_count < pg->total;
1632            inner_count++)
1633         {
1634           temp_rand = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
1635                                                          UINT64_MAX)) / ( (double) UINT64_MAX);
1636 #if VERBOSE_TESTING
1637           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1638                       _("rand is %f probability is %f\n"), temp_rand,
1639                       probability);
1640 #endif
1641           if (temp_rand < probability)
1642             {
1643               connect_attempts += proc (pg, outer_count, inner_count);
1644             }
1645         }
1646     }
1647
1648   return connect_attempts;
1649 }
1650
1651 /**
1652  * Create a topology given a peer group (set of running peers)
1653  * and a connection processor.  This particular function creates
1654  * the connections for a 2d-torus, plus additional "closest"
1655  * connections per peer.
1656  *
1657  * @param pg the peergroup to create the topology on
1658  * @param proc the connection processor to call to actually set
1659  *        up connections between two peers
1660  *
1661  * @return the number of connections that were set up
1662  *
1663  */
1664 static unsigned int
1665 create_2d_torus (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1666 {
1667   unsigned int i;
1668   unsigned int square;
1669   unsigned int rows;
1670   unsigned int cols;
1671   unsigned int toggle = 1;
1672   unsigned int nodeToConnect;
1673   int connect_attempts;
1674
1675   connect_attempts = 0;
1676
1677   square = floor (sqrt (pg->total));
1678   rows = square;
1679   cols = square;
1680
1681   if (square * square != pg->total)
1682     {
1683       while (rows * cols < pg->total)
1684         {
1685           if (toggle % 2 == 0)
1686             rows++;
1687           else
1688             cols++;
1689
1690           toggle++;
1691         }
1692     }
1693 #if VERBOSE_TESTING
1694       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1695                   _("Connecting nodes in 2d torus topology: %u rows %u columns\n"),
1696                   rows, cols);
1697 #endif
1698   /* Rows and columns are all sorted out, now iterate over all nodes and connect each
1699    * to the node to its right and above.  Once this is over, we'll have our torus!
1700    * Special case for the last node (if the rows and columns are not equal), connect
1701    * to the first in the row to maintain topology.
1702    */
1703   for (i = 0; i < pg->total; i++)
1704     {
1705       /* First connect to the node to the right */
1706       if (((i + 1) % cols != 0) && (i + 1 != pg->total))
1707         nodeToConnect = i + 1;
1708       else if (i + 1 == pg->total)
1709         nodeToConnect = rows * cols - cols;
1710       else
1711         nodeToConnect = i - cols + 1;
1712 #if VERBOSE_TESTING
1713           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714                       "Connecting peer %d to peer %d\n",
1715                       i, nodeToConnect);
1716 #endif
1717       connect_attempts += proc(pg, i, nodeToConnect);
1718
1719       /* Second connect to the node immediately above */
1720       if (i < cols)
1721         nodeToConnect = (rows * cols) - cols + i;
1722       else
1723         nodeToConnect = i - cols;
1724
1725       if (nodeToConnect < pg->total)
1726         {
1727 #if VERBOSE_TESTING
1728           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1729                       "Connecting peer %d to peer %d\n",
1730                       i, nodeToConnect);
1731 #endif
1732           connect_attempts += proc(pg, i, nodeToConnect);
1733         }
1734
1735     }
1736
1737   return connect_attempts;
1738 }
1739
1740
1741 /**
1742  * Create a topology given a peer group (set of running peers)
1743  * and a connection processor.
1744  *
1745  * @param pg the peergroup to create the topology on
1746  * @param proc the connection processor to call to actually set
1747  *        up connections between two peers
1748  *
1749  * @return the number of connections that were set up
1750  *
1751  */
1752 static unsigned int
1753 create_clique (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1754 {
1755   unsigned int outer_count;
1756   unsigned int inner_count;
1757   int connect_attempts;
1758
1759   connect_attempts = 0;
1760
1761   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
1762     {
1763       for (inner_count = outer_count + 1; inner_count < pg->total;
1764            inner_count++)
1765         {
1766 #if VERBOSE_TESTING
1767           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1768                       "Connecting peer %d to peer %d\n",
1769                       outer_count, inner_count);
1770 #endif
1771           connect_attempts += proc(pg, outer_count, inner_count);
1772         }
1773     }
1774
1775   return connect_attempts;
1776 }
1777
1778 /**
1779  * Create a topology given a peer group (set of running peers)
1780  * and a connection processor.
1781  *
1782  * @param pg the peergroup to create the topology on
1783  * @param proc the connection processor to call to actually set
1784  *        up connections between two peers
1785  *
1786  * @return the number of connections that were set up
1787  *
1788  */
1789 static unsigned int
1790 create_line (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1791 {
1792   unsigned int count;
1793   int connect_attempts;
1794
1795   connect_attempts = 0;
1796
1797   /* Connect each peer to the next highest numbered peer */
1798   for (count = 0; count < pg->total - 1; count++)
1799     {
1800 #if VERBOSE_TESTING
1801           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1802                       "Connecting peer %d to peer %d\n",
1803                       count, count + 1);
1804 #endif
1805       connect_attempts += proc(pg, count, count + 1);
1806     }
1807
1808   return connect_attempts;
1809 }
1810
1811 /**
1812  * Create a topology given a peer group (set of running peers)
1813  * and a connection processor.
1814  *
1815  * @param pg the peergroup to create the topology on
1816  * @param proc the connection processor to call to actually set
1817  *        up connections between two peers
1818  *
1819  * @return the number of connections that were set up
1820  *
1821  */
1822 static unsigned int
1823 create_ring (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_ConnectionProcessor proc)
1824 {
1825   unsigned int count;
1826   int connect_attempts;
1827
1828   connect_attempts = 0;
1829
1830   /* Connect each peer to the next highest numbered peer */
1831   for (count = 0; count < pg->total - 1; count++)
1832     {
1833 #if VERBOSE_TESTING
1834           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1835                       "Connecting peer %d to peer %d\n",
1836                       count, count + 1);
1837 #endif
1838       connect_attempts += proc(pg, count, count + 1);
1839     }
1840
1841   /* Connect the last peer to the first peer */
1842   connect_attempts += proc(pg, pg->total - 1, 0);
1843
1844   return connect_attempts;
1845 }
1846
1847
1848 /**
1849  * Iterator for writing friends of a peer to a file.
1850  *
1851  * @param cls closure, an open writable file handle
1852  * @param key the key the daemon was stored under
1853  * @param value the GNUNET_TESTING_Daemon that needs to be written.
1854  *
1855  * @return GNUNET_YES to continue iteration
1856  *
1857  * TODO: Could replace friend_file_iterator and blacklist_file_iterator
1858  *       with a single file_iterator that takes a closure which contains
1859  *       the prefix to write before the peer.  Then this could be used
1860  *       for blacklisting multiple transports and writing the friend
1861  *       file.  I'm sure *someone* will complain loudly about other
1862  *       things that negate these functions even existing so no point in
1863  *       "fixing" now.
1864  */
1865 static int
1866 friend_file_iterator (void *cls,
1867                   const GNUNET_HashCode * key,
1868                   void *value)
1869 {
1870   FILE *temp_friend_handle = cls;
1871   struct GNUNET_TESTING_Daemon *peer = value;
1872   struct GNUNET_PeerIdentity *temppeer;
1873   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
1874
1875   temppeer = &peer->id;
1876   GNUNET_CRYPTO_hash_to_enc(&temppeer->hashPubKey, &peer_enc);
1877   fprintf(temp_friend_handle, "%s\n", (char *)&peer_enc);
1878
1879   return GNUNET_YES;
1880 }
1881
1882 struct BlacklistContext
1883 {
1884   /*
1885    * The (open) file handle to write to
1886    */
1887   FILE *temp_file_handle;
1888
1889   /*
1890    * The transport that this peer will be blacklisted on.
1891    */
1892   char *transport;
1893 };
1894
1895 /**
1896  * Iterator for writing blacklist data to appropriate files.
1897  *
1898  * @param cls closure, an open writable file handle
1899  * @param key the key the daemon was stored under
1900  * @param value the GNUNET_TESTING_Daemon that needs to be written.
1901  *
1902  * @return GNUNET_YES to continue iteration
1903  */
1904 static int
1905 blacklist_file_iterator (void *cls,
1906                          const GNUNET_HashCode * key,
1907                          void *value)
1908 {
1909   struct BlacklistContext *blacklist_ctx = cls;
1910   //FILE *temp_blacklist_handle = cls;
1911   struct GNUNET_TESTING_Daemon *peer = value;
1912   struct GNUNET_PeerIdentity *temppeer;
1913   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
1914
1915   temppeer = &peer->id;
1916   GNUNET_CRYPTO_hash_to_enc(&temppeer->hashPubKey, &peer_enc);
1917   fprintf(blacklist_ctx->temp_file_handle, "%s:%s\n", blacklist_ctx->transport, (char *)&peer_enc);
1918
1919   return GNUNET_YES;
1920 }
1921
1922 /*
1923  * Create the friend files based on the PeerConnection's
1924  * of each peer in the peer group, and copy the files
1925  * to the appropriate place
1926  *
1927  * @param pg the peer group we are dealing with
1928  */
1929 static int
1930 create_and_copy_friend_files (struct GNUNET_TESTING_PeerGroup *pg)
1931 {
1932   FILE *temp_friend_handle;
1933   unsigned int pg_iter;
1934   char *temp_service_path;
1935   struct GNUNET_OS_Process **procarr;
1936   char *arg;
1937   char * mytemp;
1938   enum GNUNET_OS_ProcessStatusType type;
1939   unsigned long return_code;
1940   int count;
1941   int ret;
1942   int max_wait = 10;
1943
1944   procarr = GNUNET_malloc(sizeof(struct GNUNET_OS_Process *) * pg->total);
1945   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
1946     {
1947       mytemp = GNUNET_DISK_mktemp("friends");
1948       GNUNET_assert(mytemp != NULL);
1949       temp_friend_handle = fopen (mytemp, "wt");
1950       GNUNET_assert(temp_friend_handle != NULL);
1951       GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].allowed_peers, &friend_file_iterator, temp_friend_handle);
1952       fclose(temp_friend_handle);
1953
1954       if (GNUNET_OK !=
1955           GNUNET_CONFIGURATION_get_value_string(pg->peers[pg_iter].daemon->cfg, "PATHS", "SERVICEHOME", &temp_service_path))
1956         {
1957           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1958                       _("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
1959                       "SERVICEHOME",
1960                       "PATHS");
1961           if (UNLINK (mytemp) != 0)
1962             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", mytemp);
1963           GNUNET_free (mytemp);
1964           break;
1965         }
1966
1967       if (pg->peers[pg_iter].daemon->hostname == NULL) /* Local, just copy the file */
1968         {
1969           GNUNET_asprintf (&arg, "%s/friends", temp_service_path);
1970           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "mv",
1971                                          "mv", mytemp, arg, NULL);
1972 #if VERBOSE_TESTING
1973           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1974                       _("Copying file with command cp %s %s\n"), mytemp, arg);
1975 #endif
1976
1977           GNUNET_free(arg);
1978         }
1979       else /* Remote, scp the file to the correct place */
1980         {
1981           if (NULL != pg->peers[pg_iter].daemon->username)
1982             GNUNET_asprintf (&arg, "%s@%s:%s/friends", pg->peers[pg_iter].daemon->username, pg->peers[pg_iter].daemon->hostname, temp_service_path);
1983           else
1984             GNUNET_asprintf (&arg, "%s:%s/friends", pg->peers[pg_iter].daemon->hostname, temp_service_path);
1985           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "scp",
1986                                          "scp", mytemp, arg, NULL);
1987
1988 #if VERBOSE_TESTING
1989           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1990                       _("Copying file with command scp %s %s\n"), mytemp, arg);
1991 #endif
1992           GNUNET_free(arg);
1993         }
1994       GNUNET_free (temp_service_path);
1995       GNUNET_free (mytemp);
1996     }
1997
1998   count = 0;
1999   ret = GNUNET_SYSERR;
2000   while ((count < max_wait) && (ret != GNUNET_OK))
2001     {
2002       ret = GNUNET_OK;
2003       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2004         {
2005 #if VERBOSE_TESTING
2006           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2007                       _("Checking copy status of file %d\n"), pg_iter);
2008 #endif
2009           if (procarr[pg_iter] != NULL) /* Check for already completed! */
2010             {
2011               if (GNUNET_OS_process_status(procarr[pg_iter], &type, &return_code) != GNUNET_OK)
2012                 {
2013                   ret = GNUNET_SYSERR;
2014                 }
2015               else if ((type != GNUNET_OS_PROCESS_EXITED) || (return_code != 0))
2016                 {
2017                   ret = GNUNET_SYSERR;
2018                 }
2019               else
2020                 {
2021                   GNUNET_OS_process_close (procarr[pg_iter]);
2022                   procarr[pg_iter] = NULL;
2023 #if VERBOSE_TESTING
2024             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2025                       _("File %d copied\n"), pg_iter);
2026 #endif
2027                 }
2028             }
2029         }
2030       count++;
2031       if (ret == GNUNET_SYSERR)
2032         {
2033           /* FIXME: why sleep here? -CG */
2034           sleep(1);
2035         }
2036     }
2037
2038 #if VERBOSE_TESTING
2039     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2040                 _("Finished copying all friend files!\n"));
2041 #endif
2042   GNUNET_free(procarr);
2043   return ret;
2044 }
2045
2046
2047 /*
2048  * Create the blacklist files based on the PeerConnection's
2049  * of each peer in the peer group, and copy the files
2050  * to the appropriate place.
2051  *
2052  * @param pg the peer group we are dealing with
2053  * @param transports space delimited list of transports to blacklist
2054  */
2055 static int
2056 create_and_copy_blacklist_files (struct GNUNET_TESTING_PeerGroup *pg, const char *transports)
2057 {
2058   FILE *temp_file_handle;
2059   static struct BlacklistContext blacklist_ctx;
2060   unsigned int pg_iter;
2061   char *temp_service_path;
2062   struct GNUNET_OS_Process **procarr;
2063   char *arg;
2064   char *mytemp;
2065   enum GNUNET_OS_ProcessStatusType type;
2066   unsigned long return_code;
2067   int count;
2068   int ret;
2069   int max_wait = 10;
2070   int transport_len;
2071   unsigned int i;
2072   char *pos;
2073   char *temp_transports;
2074
2075   procarr = GNUNET_malloc(sizeof(struct GNUNET_OS_Process *) * pg->total);
2076   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2077     {
2078       mytemp = GNUNET_DISK_mktemp("blacklist");
2079       GNUNET_assert(mytemp != NULL);
2080       temp_file_handle = fopen (mytemp, "wt");
2081       GNUNET_assert(temp_file_handle != NULL);
2082       temp_transports = GNUNET_strdup(transports);
2083       blacklist_ctx.temp_file_handle = temp_file_handle;
2084       transport_len = strlen(temp_transports) + 1;
2085       pos = NULL;
2086
2087       for (i = 0; i < transport_len; i++)
2088       {
2089         if ((temp_transports[i] == ' ') && (pos == NULL))
2090           continue; /* At start of string (whitespace) */
2091         else if ((temp_transports[i] == ' ') || (temp_transports[i] == '\0')) /* At end of string */
2092         {
2093           temp_transports[i] = '\0';
2094           blacklist_ctx.transport = pos;
2095           GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].blacklisted_peers, &blacklist_file_iterator, &blacklist_ctx);
2096           pos = NULL;
2097         } /* At beginning of actual string */
2098         else if (pos == NULL)
2099         {
2100           pos = &temp_transports[i];
2101         }
2102       }
2103
2104       GNUNET_free (temp_transports);
2105       fclose(temp_file_handle);
2106
2107       if (GNUNET_OK !=
2108           GNUNET_CONFIGURATION_get_value_string(pg->peers[pg_iter].daemon->cfg, "PATHS", "SERVICEHOME", &temp_service_path))
2109         {
2110           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2111                       _("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
2112                       "SERVICEHOME",
2113                       "PATHS");
2114           if (UNLINK (mytemp) != 0)
2115             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", mytemp);
2116           GNUNET_free (mytemp);
2117           break;
2118         }
2119
2120       if (pg->peers[pg_iter].daemon->hostname == NULL) /* Local, just copy the file */
2121         {
2122           GNUNET_asprintf (&arg, "%s/blacklist", temp_service_path);
2123           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "mv",
2124                                          "mv", mytemp, arg, NULL);
2125 #if VERBOSE_TESTING
2126           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2127                       _("Copying file with command cp %s %s\n"), mytemp, arg);
2128 #endif
2129
2130           GNUNET_free(arg);
2131         }
2132       else /* Remote, scp the file to the correct place */
2133         {
2134           if (NULL != pg->peers[pg_iter].daemon->username)
2135             GNUNET_asprintf (&arg, "%s@%s:%s/blacklist", pg->peers[pg_iter].daemon->username, pg->peers[pg_iter].daemon->hostname, temp_service_path);
2136           else
2137             GNUNET_asprintf (&arg, "%s:%s/blacklist", pg->peers[pg_iter].daemon->hostname, temp_service_path);
2138           procarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "scp",
2139                                          "scp", mytemp, arg, NULL);
2140
2141 #if VERBOSE_TESTING
2142           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2143                       _("Copying file with command scp %s %s\n"), mytemp, arg);
2144 #endif
2145           GNUNET_free(arg);
2146         }
2147       GNUNET_free (temp_service_path);
2148       GNUNET_free (mytemp);
2149     }
2150
2151   count = 0;
2152   ret = GNUNET_SYSERR;
2153   while ((count < max_wait) && (ret != GNUNET_OK))
2154     {
2155       ret = GNUNET_OK;
2156       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2157         {
2158 #if VERBOSE_TESTING
2159           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2160                       _("Checking copy status of file %d\n"), pg_iter);
2161 #endif
2162           if (procarr[pg_iter] != NULL) /* Check for already completed! */
2163             {
2164               if (GNUNET_OS_process_status(procarr[pg_iter], &type, &return_code) != GNUNET_OK)
2165                 {
2166                   ret = GNUNET_SYSERR;
2167                 }
2168               else if ((type != GNUNET_OS_PROCESS_EXITED) || (return_code != 0))
2169                 {
2170                   ret = GNUNET_SYSERR;
2171                 }
2172               else
2173                 {
2174                   GNUNET_OS_process_close (procarr[pg_iter]);
2175                   procarr[pg_iter] = NULL;
2176 #if VERBOSE_TESTING
2177             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2178                       _("File %d copied\n"), pg_iter);
2179 #endif
2180                 }
2181             }
2182         }
2183       count++;
2184       if (ret == GNUNET_SYSERR)
2185         {
2186           /* FIXME: why sleep here? -CG */
2187           sleep(1);
2188         }
2189     }
2190
2191 #if VERBOSE_TESTING
2192     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2193                 _("Finished copying all blacklist files!\n"));
2194 #endif
2195   GNUNET_free(procarr);
2196   return ret;
2197 }
2198
2199
2200 /**
2201  * Internal notification of a connection, kept so that we can ensure some connections
2202  * happen instead of flooding all testing daemons with requests to connect.
2203  */
2204 static void internal_connect_notify (void *cls,
2205                                      const struct GNUNET_PeerIdentity *first,
2206                                      const struct GNUNET_PeerIdentity *second,
2207                                      uint32_t distance,
2208                                      const struct GNUNET_CONFIGURATION_Handle *first_cfg,
2209                                      const struct GNUNET_CONFIGURATION_Handle *second_cfg,
2210                                      struct GNUNET_TESTING_Daemon *first_daemon,
2211                                      struct GNUNET_TESTING_Daemon *second_daemon,
2212                                      const char *emsg)
2213 {
2214   struct ConnectTopologyContext *ct_ctx = cls;
2215   struct GNUNET_TESTING_PeerGroup *pg = ct_ctx->pg;
2216   outstanding_connects--;
2217   ct_ctx->remaining_connections--;
2218   if (ct_ctx->remaining_connections == 0)
2219     {
2220       if (ct_ctx->notify_connections_done != NULL)
2221         ct_ctx->notify_connections_done(ct_ctx->notify_cls, NULL);
2222       GNUNET_free(ct_ctx);
2223     }
2224
2225   if (pg->notify_connection != NULL)
2226     pg->notify_connection (pg->notify_connection_cls, first, second, distance, first_cfg, second_cfg, first_daemon, second_daemon, emsg);
2227 }
2228
2229
2230 /**
2231  * Either delay a connection (because there are too many outstanding)
2232  * or schedule it for right now.
2233  *
2234  * @param cls a connection context
2235  * @param tc the task runtime context
2236  */
2237 static void schedule_connect(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2238 {
2239   struct ConnectContext *connect_context = cls;
2240
2241   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2242     return;
2243
2244   if (outstanding_connects > MAX_OUTSTANDING_CONNECTIONS)
2245     {
2246 #if VERBOSE_TESTING > 2
2247           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2248                       _("Delaying connect, we have too many outstanding connections!\n"));
2249 #endif
2250       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_connect, connect_context);
2251     }
2252   else
2253     {
2254 #if VERBOSE_TESTING > 2
2255           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2256                       _("Creating connection, outstanding_connections is %d\n"), outstanding_connects);
2257 #endif
2258       outstanding_connects++;
2259       GNUNET_TESTING_daemons_connect (connect_context->first,
2260                                       connect_context->second,
2261                                       CONNECT_TIMEOUT,
2262                                       CONNECT_ATTEMPTS,
2263                                       &internal_connect_notify,
2264                                       connect_context->ct_ctx);
2265       GNUNET_free(connect_context);
2266     }
2267 }
2268
2269
2270 /**
2271  * Iterator for actually scheduling connections to be created
2272  * between two peers.
2273  *
2274  * @param cls closure, a GNUNET_TESTING_Daemon
2275  * @param key the key the second Daemon was stored under
2276  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
2277  *
2278  * @return GNUNET_YES to continue iteration
2279  */
2280 static int
2281 connect_iterator (void *cls,
2282                   const GNUNET_HashCode * key,
2283                   void *value)
2284 {
2285   struct ConnectTopologyContext *ct_ctx = cls;
2286   struct PeerData *first = ct_ctx->first;
2287   struct GNUNET_TESTING_Daemon *second = value;
2288   struct ConnectContext *connect_context;
2289
2290   connect_context = GNUNET_malloc(sizeof(struct ConnectContext));
2291   connect_context->first = first->daemon;
2292   connect_context->second = second;
2293   connect_context->ct_ctx = ct_ctx;
2294   GNUNET_SCHEDULER_add_now(&schedule_connect, connect_context);
2295
2296   return GNUNET_YES;
2297 }
2298
2299
2300 /**
2301  * Iterator for copying all entries in the allowed hashmap to the
2302  * connect hashmap.
2303  *
2304  * @param cls closure, a GNUNET_TESTING_Daemon
2305  * @param key the key the second Daemon was stored under
2306  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
2307  *
2308  * @return GNUNET_YES to continue iteration
2309  */
2310 static int
2311 copy_topology_iterator (void *cls,
2312                   const GNUNET_HashCode * key,
2313                   void *value)
2314 {
2315   struct PeerData *first = cls;
2316
2317   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(first->connect_peers, key, value, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2318
2319   return GNUNET_YES;
2320 }
2321
2322 /**
2323  * Make the peers to connect the same as those that are allowed to be
2324  * connected.
2325  *
2326  * @param pg the peer group
2327  */
2328 static int
2329 copy_allowed_topology (struct GNUNET_TESTING_PeerGroup *pg)
2330 {
2331   unsigned int pg_iter;
2332   int ret;
2333   int total;
2334
2335   total = 0;
2336   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2337     {
2338       ret = GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].allowed_peers, &copy_topology_iterator, &pg->peers[pg_iter]);
2339       if (GNUNET_SYSERR == ret)
2340         return GNUNET_SYSERR;
2341
2342       total = total + ret;
2343     }
2344
2345   return total;
2346 }
2347
2348
2349 /**
2350  * Connect the topology as specified by the PeerConnection's
2351  * of each peer in the peer group
2352  *
2353  * @param pg the peer group we are dealing with
2354  * @return the number of connections that will be attempted
2355  */
2356 static int
2357 connect_topology (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_NotifyCompletion notify_callback, void *notify_cls)
2358 {
2359   unsigned int pg_iter;
2360   int ret;
2361   unsigned int total;
2362   struct ConnectTopologyContext *ct_ctx;
2363 #if OLD
2364   struct PeerConnection *connection_iter;
2365   struct ConnectContext *connect_context;
2366 #endif
2367
2368   total = 0;
2369   ct_ctx = GNUNET_malloc(sizeof(struct ConnectTopologyContext));
2370   ct_ctx->notify_connections_done = notify_callback;
2371   ct_ctx->notify_cls = notify_cls;
2372   ct_ctx->pg = pg;
2373
2374   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2375     {
2376       total += GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers);
2377     }
2378
2379   if (total == 0)
2380     {
2381       GNUNET_free(ct_ctx);
2382       return total;
2383     }
2384   ct_ctx->remaining_connections = total;
2385   total = 0;
2386
2387   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2388     {
2389       ct_ctx->first = &pg->peers[pg_iter];
2390       ret = GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].connect_peers, &connect_iterator, ct_ctx);
2391       GNUNET_assert(GNUNET_SYSERR != ret && ret >= 0);
2392       total = total + ret;
2393
2394 #if OLD
2395       connection_iter = FIXME;
2396       while (connection_iter != NULL)
2397         {
2398           connect_context = GNUNET_malloc(sizeof(struct ConnectContext));
2399           connect_context->pg = pg;
2400           connect_context->first = FIXME;
2401           connect_context->second = connection_iter->daemon;
2402           GNUNET_SCHEDULER_add_now(&schedule_connect, connect_context);
2403           connection_iter = connection_iter->next;
2404         }
2405 #endif
2406     }
2407   return total;
2408 }
2409
2410
2411 /**
2412  * Takes a peer group and creates a topology based on the
2413  * one specified.  Creates a topology means generates friend
2414  * files for the peers so they can only connect to those allowed
2415  * by the topology.  This will only have an effect once peers
2416  * are started if the FRIENDS_ONLY option is set in the base
2417  * config.  Also takes an optional restrict topology which
2418  * disallows connections based on a particular transport
2419  * UNLESS they are specified in the restricted topology.
2420  *
2421  * @param pg the peer group struct representing the running peers
2422  * @param topology which topology to connect the peers in
2423  * @param restrict_topology allow only direct TCP connections in this topology
2424  *                          use GNUNET_TESTING_TOPOLOGY_NONE for no restrictions
2425  * @param restrict_transports space delimited list of transports to blacklist
2426  *                            to create restricted topology
2427  *
2428  * @return the maximum number of connections were all allowed peers
2429  *         connected to each other
2430  */
2431 unsigned int
2432 GNUNET_TESTING_create_topology (struct GNUNET_TESTING_PeerGroup *pg,
2433                                 enum GNUNET_TESTING_Topology topology,
2434                                 enum GNUNET_TESTING_Topology restrict_topology,
2435                                 const char *restrict_transports)
2436 {
2437   int ret;
2438   unsigned int num_connections;
2439   int unblacklisted_connections;
2440
2441   switch (topology)
2442     {
2443     case GNUNET_TESTING_TOPOLOGY_CLIQUE:
2444 #if VERBOSE_TESTING
2445       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2446                   _("Creating clique topology\n"));
2447 #endif
2448       num_connections = create_clique (pg, &add_allowed_connections);
2449       break;
2450     case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
2451 #if VERBOSE_TESTING
2452       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2453                   _("Creating small world (ring) topology\n"));
2454 #endif
2455       num_connections = create_small_world_ring (pg, &add_allowed_connections);
2456       break;
2457     case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
2458 #if VERBOSE_TESTING
2459       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2460                   _("Creating small world (2d-torus) topology\n"));
2461 #endif
2462       num_connections = create_small_world (pg, &add_allowed_connections);
2463       break;
2464     case GNUNET_TESTING_TOPOLOGY_RING:
2465 #if VERBOSE_TESTING
2466       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2467                   _("Creating ring topology\n"));
2468 #endif
2469       num_connections = create_ring (pg, &add_allowed_connections);
2470       break;
2471     case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
2472 #if VERBOSE_TESTING
2473       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2474                   _("Creating 2d torus topology\n"));
2475 #endif
2476       num_connections = create_2d_torus (pg, &add_allowed_connections);
2477       break;
2478     case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
2479 #if VERBOSE_TESTING
2480       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2481                   _("Creating Erdos-Renyi topology\n"));
2482 #endif
2483       num_connections = create_erdos_renyi (pg, &add_allowed_connections);
2484       break;
2485     case GNUNET_TESTING_TOPOLOGY_INTERNAT:
2486 #if VERBOSE_TESTING
2487       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488                   _("Creating InterNAT topology\n"));
2489 #endif
2490       num_connections = create_nated_internet (pg, &add_allowed_connections);
2491       break;
2492     case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
2493 #if VERBOSE_TESTING
2494       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495                   _("Creating Scale Free topology\n"));
2496 #endif
2497       num_connections = create_scale_free (pg, &add_allowed_connections);
2498       break;
2499     case GNUNET_TESTING_TOPOLOGY_LINE:
2500 #if VERBOSE_TESTING
2501       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2502                   _("Creating straight line topology\n"));
2503 #endif
2504       num_connections = create_line (pg, &add_allowed_connections);
2505       break;
2506     case GNUNET_TESTING_TOPOLOGY_NONE:
2507 #if VERBOSE_TESTING
2508       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2509                   _("Creating no allowed topology (all peers can connect at core level)\n"));
2510 #endif
2511       num_connections = 0;
2512       break;
2513     default:
2514       num_connections = 0;
2515       break;
2516     }
2517
2518   if (num_connections < 0)
2519     return GNUNET_SYSERR;
2520
2521   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "TESTING", "F2F"))
2522     {
2523       ret = create_and_copy_friend_files(pg);
2524       if (ret != GNUNET_OK)
2525         {
2526 #if VERBOSE_TESTING
2527           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2528                       _("Failed during friend file copying!\n"));
2529 #endif
2530           return GNUNET_SYSERR;
2531         }
2532       else
2533         {
2534 #if VERBOSE_TESTING
2535               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2536                           _("Friend files created/copied successfully!\n"));
2537 #endif
2538         }
2539     }
2540
2541   /* Use the create clique method to initially set all connections as blacklisted. */
2542   if (restrict_topology != GNUNET_TESTING_TOPOLOGY_NONE)
2543     create_clique (pg, &blacklist_connections);
2544
2545   unblacklisted_connections = 0;
2546   /* Un-blacklist connections as per the topology specified */
2547   switch (restrict_topology)
2548     {
2549     case GNUNET_TESTING_TOPOLOGY_CLIQUE:
2550 #if VERBOSE_TESTING
2551       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2552                   _("Blacklisting all but clique topology\n"));
2553 #endif
2554       unblacklisted_connections = create_clique (pg, &unblacklist_connections);
2555       break;
2556     case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
2557 #if VERBOSE_TESTING
2558       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2559                   _("Blacklisting all but small world (ring) topology\n"));
2560 #endif
2561       unblacklisted_connections = create_small_world_ring (pg, &unblacklist_connections);
2562       break;
2563     case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
2564 #if VERBOSE_TESTING
2565       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2566                   _("Blacklisting all but small world (2d-torus) topology\n"));
2567 #endif
2568       unblacklisted_connections = create_small_world (pg, &unblacklist_connections);
2569       break;
2570     case GNUNET_TESTING_TOPOLOGY_RING:
2571 #if VERBOSE_TESTING
2572       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2573                   _("Blacklisting all but ring topology\n"));
2574 #endif
2575       unblacklisted_connections = create_ring (pg, &unblacklist_connections);
2576       break;
2577     case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
2578 #if VERBOSE_TESTING
2579       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2580                   _("Blacklisting all but 2d torus topology\n"));
2581 #endif
2582       unblacklisted_connections = create_2d_torus (pg, &unblacklist_connections);
2583       break;
2584     case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
2585 #if VERBOSE_TESTING
2586       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2587                   _("Blacklisting all but Erdos-Renyi topology\n"));
2588 #endif
2589       unblacklisted_connections = create_erdos_renyi (pg, &unblacklist_connections);
2590       break;
2591     case GNUNET_TESTING_TOPOLOGY_INTERNAT:
2592 #if VERBOSE_TESTING
2593       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2594                   _("Blacklisting all but InterNAT topology\n"));
2595 #endif
2596       unblacklisted_connections = create_nated_internet (pg, &unblacklist_connections);
2597       break;
2598     case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
2599 #if VERBOSE_TESTING
2600       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2601                   _("Blacklisting all but Scale Free topology\n"));
2602 #endif
2603       unblacklisted_connections = create_scale_free (pg, &unblacklist_connections);
2604       break;
2605     case GNUNET_TESTING_TOPOLOGY_LINE:
2606 #if VERBOSE_TESTING
2607       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2608                   _("Blacklisting all but straight line topology\n"));
2609 #endif
2610       unblacklisted_connections = create_line (pg, &unblacklist_connections);
2611       break;
2612     case GNUNET_TESTING_TOPOLOGY_NONE:
2613 #if VERBOSE_TESTING
2614       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2615                   _("Creating no blacklist topology (all peers can connect at transport level)\n"));
2616 #endif
2617     default:
2618       break;
2619     }
2620
2621   if ((unblacklisted_connections > 0) && (restrict_transports != NULL))
2622   {
2623     ret = create_and_copy_blacklist_files(pg, restrict_transports);
2624     if (ret != GNUNET_OK)
2625       {
2626 #if VERBOSE_TESTING
2627         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2628                     _("Failed during blacklist file copying!\n"));
2629 #endif
2630         return 0;
2631       }
2632     else
2633       {
2634 #if VERBOSE_TESTING
2635         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2636                     _("Blacklist files created/copied successfully!\n"));
2637 #endif
2638       }
2639   }
2640   return num_connections;
2641 }
2642
2643 struct RandomContext
2644 {
2645   /**
2646    * The peergroup
2647    */
2648   struct GNUNET_TESTING_PeerGroup *pg;
2649
2650   /**
2651    * uid of the first peer
2652    */
2653   uint32_t first_uid;
2654
2655   /**
2656    * Peer data for first peer.
2657    */
2658   struct PeerData *first;
2659
2660   /**
2661    * Random percentage to use
2662    */
2663   double percentage;
2664 };
2665
2666 struct MinimumContext
2667 {
2668   /**
2669    * The peergroup
2670    */
2671   struct GNUNET_TESTING_PeerGroup *pg;
2672
2673   /**
2674    * uid of the first peer
2675    */
2676   uint32_t first_uid;
2677
2678   /**
2679    * Peer data for first peer.
2680    */
2681   struct PeerData *first;
2682
2683   /**
2684    * Number of conns per peer
2685    */
2686   unsigned int num_to_add;
2687
2688   /**
2689    * Permuted array of all possible connections.  Only add the Nth
2690    * peer if it's in the Nth position.
2691    */
2692   unsigned int *pg_array;
2693
2694   /**
2695    * What number is the current element we are iterating over?
2696    */
2697   unsigned int current;
2698 };
2699
2700 struct DFSContext
2701 {
2702   /**
2703    * The peergroup
2704    */
2705   struct GNUNET_TESTING_PeerGroup *pg;
2706
2707   /**
2708    * uid of the first peer
2709    */
2710   uint32_t first_uid;
2711
2712   /**
2713    * uid of the second peer
2714    */
2715   uint32_t second_uid;
2716
2717   /**
2718    * Peer data for first peer.
2719    */
2720   struct PeerData *first;
2721
2722   /**
2723    * Which peer has been chosen as the one to add?
2724    */
2725   unsigned int chosen;
2726
2727   /**
2728    * What number is the current element we are iterating over?
2729    */
2730   unsigned int current;
2731 };
2732
2733 /**
2734  * Iterator for choosing random peers to connect.
2735  *
2736  * @param cls closure, a RandomContext
2737  * @param key the key the second Daemon was stored under
2738  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
2739  *
2740  * @return GNUNET_YES to continue iteration
2741  */
2742 static int
2743 random_connect_iterator (void *cls,
2744                          const GNUNET_HashCode * key,
2745                          void *value)
2746 {
2747   struct RandomContext *random_ctx = cls;
2748   double random_number;
2749   uint32_t second_pos;
2750   GNUNET_HashCode first_hash;
2751   random_number = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
2752                                                      UINT64_MAX)) / ( (double) UINT64_MAX);
2753   if (random_number < random_ctx->percentage)
2754   {
2755     GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(random_ctx->first->connect_peers_working_set, key, value, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2756   }
2757   /* Now we have considered this particular connection, remove it from the second peer so it's not double counted */
2758   uid_from_hash(key, &second_pos);
2759   hash_from_uid(random_ctx->first_uid, &first_hash);
2760   GNUNET_assert(random_ctx->pg->total > second_pos);
2761   GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(random_ctx->pg->peers[second_pos].connect_peers, &first_hash, random_ctx->first->daemon));
2762
2763   return GNUNET_YES;
2764 }
2765
2766 /**
2767  * Iterator for adding at least X peers to a peers connection set.
2768  *
2769  * @param cls closure, MinimumContext
2770  * @param key the key the second Daemon was stored under
2771  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
2772  *
2773  * @return GNUNET_YES to continue iteration
2774  */
2775 static int
2776 minimum_connect_iterator (void *cls,
2777                   const GNUNET_HashCode * key,
2778                   void *value)
2779 {
2780   struct MinimumContext *min_ctx = cls;
2781   uint32_t second_pos;
2782   GNUNET_HashCode first_hash;
2783   unsigned int i;
2784
2785   if (GNUNET_CONTAINER_multihashmap_size(min_ctx->first->connect_peers_working_set) < min_ctx->num_to_add)
2786   {
2787     for (i = 0; i < min_ctx->num_to_add; i++)
2788     {
2789       if (min_ctx->pg_array[i] == min_ctx->current)
2790       {
2791         GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(min_ctx->first->connect_peers_working_set, key, value, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2792         uid_from_hash(key, &second_pos);
2793         hash_from_uid(min_ctx->first_uid, &first_hash);
2794         GNUNET_assert(min_ctx->pg->total > second_pos);
2795         GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(min_ctx->pg->peers[second_pos].connect_peers_working_set, &first_hash, min_ctx->first->daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2796         /* Now we have added this particular connection, remove it from the second peer's map so it's not double counted */
2797         GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(min_ctx->pg->peers[second_pos].connect_peers, &first_hash, min_ctx->first->daemon));
2798       }
2799     }
2800     min_ctx->current++;
2801     return GNUNET_YES;
2802   }
2803   else
2804     return GNUNET_NO; /* We can stop iterating, we have enough peers! */
2805
2806 }
2807
2808
2809 /**
2810  * Iterator for adding peers to a connection set based on a depth first search.
2811  *
2812  * @param cls closure, MinimumContext
2813  * @param key the key the second daemon was stored under
2814  * @param value the GNUNET_TESTING_Daemon that the first is to connect to
2815  *
2816  * @return GNUNET_YES to continue iteration
2817  */
2818 static int
2819 dfs_connect_iterator (void *cls,
2820                   const GNUNET_HashCode * key,
2821                   void *value)
2822 {
2823   struct DFSContext *dfs_ctx = cls;
2824   GNUNET_HashCode first_hash;
2825
2826   if (dfs_ctx->current == dfs_ctx->chosen)
2827     {
2828       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(dfs_ctx->first->connect_peers_working_set, key, value, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2829       uid_from_hash(key, &dfs_ctx->second_uid);
2830       hash_from_uid(dfs_ctx->first_uid, &first_hash);
2831       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(dfs_ctx->pg->peers[dfs_ctx->second_uid].connect_peers_working_set, &first_hash, dfs_ctx->first->daemon, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2832       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(dfs_ctx->pg->peers[dfs_ctx->second_uid].connect_peers, &first_hash, dfs_ctx->first->daemon));
2833       /* Can't remove second from first yet because we are currently iterating, hence the return value in the DFSContext! */
2834       return GNUNET_NO; /* We have found our peer, don't iterate more */
2835     }
2836
2837   dfs_ctx->current++;
2838   return GNUNET_YES;
2839 }
2840
2841
2842 /**
2843  * From the set of connections possible, choose percentage percent of connections
2844  * to actually connect.
2845  *
2846  * @param pg the peergroup we are dealing with
2847  * @param percentage what percent of total connections to make
2848  */
2849 void
2850 choose_random_connections(struct GNUNET_TESTING_PeerGroup *pg, double percentage)
2851 {
2852   struct RandomContext random_ctx;
2853   uint32_t pg_iter;
2854
2855   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2856     {
2857       random_ctx.first_uid = pg_iter;
2858       random_ctx.first = &pg->peers[pg_iter];
2859       random_ctx.percentage = percentage;
2860       random_ctx.pg = pg;
2861       pg->peers[pg_iter].connect_peers_working_set = GNUNET_CONTAINER_multihashmap_create(pg->total);
2862       GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].connect_peers, &random_connect_iterator, &random_ctx);
2863       /* Now remove the old connections */
2864       GNUNET_CONTAINER_multihashmap_destroy(pg->peers[pg_iter].connect_peers);
2865       /* And replace with the random set */
2866       pg->peers[pg_iter].connect_peers = pg->peers[pg_iter].connect_peers_working_set;
2867     }
2868 }
2869
2870 /**
2871  * From the set of connections possible, choose at least num connections per
2872  * peer.
2873  *
2874  * @param pg the peergroup we are dealing with
2875  * @param num how many connections at least should each peer have (if possible)?
2876  */
2877 static void
2878 choose_minimum(struct GNUNET_TESTING_PeerGroup *pg, unsigned int num)
2879 {
2880   struct MinimumContext minimum_ctx;
2881   uint32_t pg_iter;
2882
2883   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2884    {
2885      pg->peers[pg_iter].connect_peers_working_set = GNUNET_CONTAINER_multihashmap_create(num);
2886    }
2887
2888   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2889     {
2890       minimum_ctx.first_uid = pg_iter;
2891       minimum_ctx.pg_array = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_WEAK, 
2892                                                           GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers));
2893       minimum_ctx.first = &pg->peers[pg_iter];
2894       minimum_ctx.pg = pg;
2895       minimum_ctx.num_to_add = num;
2896       minimum_ctx.current = 0;
2897       GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].connect_peers,
2898                                             &minimum_connect_iterator, 
2899                                             &minimum_ctx);
2900     }
2901
2902   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2903     {
2904       /* Remove the "old" connections */
2905       GNUNET_CONTAINER_multihashmap_destroy(pg->peers[pg_iter].connect_peers);
2906       /* And replace with the working set */
2907       pg->peers[pg_iter].connect_peers = pg->peers[pg_iter].connect_peers_working_set;
2908     }
2909
2910 }
2911
2912
2913 static unsigned int
2914 count_workingset_connections(struct GNUNET_TESTING_PeerGroup *pg)
2915 {
2916   unsigned int count;
2917   unsigned int pg_iter;
2918
2919   count = 0;
2920
2921   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2922     {
2923       count += GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers_working_set);
2924     }
2925
2926   return count;
2927 }
2928
2929
2930 static unsigned int count_allowed_connections(struct GNUNET_TESTING_PeerGroup *pg)
2931 {
2932   unsigned int count;
2933   unsigned int pg_iter;
2934
2935   count = 0;
2936
2937   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
2938     {
2939       count += GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers);
2940     }
2941
2942   return count;
2943 }
2944
2945
2946 struct FindClosestContext
2947 {
2948   /**
2949    * The currently known closest peer.
2950    */
2951   struct GNUNET_TESTING_Daemon *closest;
2952
2953   /**
2954    * The info for the peer we are adding connections for.
2955    */
2956   struct PeerData *curr_peer;
2957
2958   /**
2959    * The distance (bits) between the current
2960    * peer and the currently known closest.
2961    */
2962   unsigned int closest_dist;
2963
2964   /**
2965    * The offset of the closest known peer in
2966    * the peer group.
2967    */
2968   unsigned int closest_num;
2969 };
2970
2971 /**
2972  * Iterator over hash map entries of the allowed
2973  * peer connections.  Find the closest, not already
2974  * connected peer and return it.
2975  *
2976  * @param cls closure (struct FindClosestContext)
2977  * @param key current key code (hash of offset in pg)
2978  * @param value value in the hash map - a GNUNET_TESTING_Daemon
2979  * @return GNUNET_YES if we should continue to
2980  *         iterate,
2981  *         GNUNET_NO if not.
2982  */
2983 static
2984 int find_closest_peers (void *cls, const GNUNET_HashCode * key, void *value)
2985 {
2986   struct FindClosestContext *closest_ctx = cls;
2987   struct GNUNET_TESTING_Daemon *daemon = value;
2988
2989   if (((closest_ctx->closest == NULL) ||
2990        (GNUNET_CRYPTO_hash_matching_bits(&daemon->id.hashPubKey, &closest_ctx->curr_peer->daemon->id.hashPubKey) > closest_ctx->closest_dist))
2991       && (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(closest_ctx->curr_peer->connect_peers, key)))
2992     {
2993       closest_ctx->closest_dist = GNUNET_CRYPTO_hash_matching_bits(&daemon->id.hashPubKey, &closest_ctx->curr_peer->daemon->id.hashPubKey);
2994       closest_ctx->closest = daemon;
2995       uid_from_hash(key, &closest_ctx->closest_num);
2996     }
2997   return GNUNET_YES;
2998 }
2999
3000 /**
3001  * From the set of connections possible, choose at num connections per
3002  * peer based on depth which are closest out of those allowed.  Guaranteed
3003  * to add num peers to connect to, provided there are that many peers
3004  * in the underlay topology to connect to.
3005  *
3006  * @param pg the peergroup we are dealing with
3007  * @param num how many connections at least should each peer have (if possible)?
3008  * @param proc processor to actually add the connections
3009  */
3010 void
3011 add_closest (struct GNUNET_TESTING_PeerGroup *pg, unsigned int num, GNUNET_TESTING_ConnectionProcessor proc)
3012 {
3013   struct FindClosestContext closest_ctx;
3014   uint32_t pg_iter;
3015   uint32_t i;
3016
3017   for (i = 0; i < num; i++) /* Each time find a closest peer (from those available) */
3018     {
3019       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3020         {
3021           closest_ctx.curr_peer = &pg->peers[pg_iter];
3022           closest_ctx.closest = NULL;
3023           closest_ctx.closest_dist = 0;
3024           closest_ctx.closest_num = 0;
3025           GNUNET_CONTAINER_multihashmap_iterate(pg->peers[pg_iter].allowed_peers, &find_closest_peers, &closest_ctx);
3026           if (closest_ctx.closest != NULL)
3027             {
3028               GNUNET_assert((0 <= closest_ctx.closest_num) && (closest_ctx.closest_num < pg->total));
3029               proc(pg, pg_iter, closest_ctx.closest_num);
3030             }
3031         }
3032     }
3033 }
3034
3035 /**
3036  * From the set of connections possible, choose at least num connections per
3037  * peer based on depth first traversal of peer connections.  If DFS leaves
3038  * peers unconnected, ensure those peers get connections.
3039  *
3040  * @param pg the peergroup we are dealing with
3041  * @param num how many connections at least should each peer have (if possible)?
3042  */
3043 void
3044 perform_dfs (struct GNUNET_TESTING_PeerGroup *pg, unsigned int num)
3045 {
3046   struct DFSContext dfs_ctx;
3047   uint32_t pg_iter;
3048   uint32_t dfs_count;
3049   uint32_t starting_peer;
3050   uint32_t least_connections;
3051   GNUNET_HashCode second_hash;
3052
3053   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3054     {
3055       pg->peers[pg_iter].connect_peers_working_set = GNUNET_CONTAINER_multihashmap_create(num);
3056     }
3057
3058   starting_peer = 0;
3059   dfs_count = 0;
3060   while ((count_workingset_connections(pg) < num * pg->total) && (count_allowed_connections(pg) > 0))
3061     {
3062       if (dfs_count % pg->total == 0) /* Restart the DFS at some weakly connected peer */
3063         {
3064           least_connections = -1; /* Set to very high number */
3065           for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3066             {
3067               if (GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers_working_set) < least_connections)
3068                 {
3069                   starting_peer = pg_iter;
3070                   least_connections = GNUNET_CONTAINER_multihashmap_size(pg->peers[pg_iter].connect_peers_working_set);
3071                 }
3072             }
3073         }
3074
3075       if (GNUNET_CONTAINER_multihashmap_size(pg->peers[starting_peer].connect_peers) == 0)  /* Ensure there is at least one peer left to connect! */
3076         {
3077           dfs_count = 0;
3078           continue;
3079         }
3080
3081       /* Choose a random peer from the chosen peers set of connections to add */
3082       dfs_ctx.chosen = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, GNUNET_CONTAINER_multihashmap_size(pg->peers[starting_peer].connect_peers));
3083       dfs_ctx.first_uid = starting_peer;
3084       dfs_ctx.first = &pg->peers[starting_peer];
3085       dfs_ctx.pg = pg;
3086       dfs_ctx.current = 0;
3087
3088       GNUNET_CONTAINER_multihashmap_iterate(pg->peers[starting_peer].connect_peers, &dfs_connect_iterator, &dfs_ctx);
3089       /* Remove the second from the first, since we will be continuing the search and may encounter the first peer again! */
3090       hash_from_uid(dfs_ctx.second_uid, &second_hash);
3091       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(pg->peers[starting_peer].connect_peers, &second_hash, pg->peers[dfs_ctx.second_uid].daemon));
3092       starting_peer = dfs_ctx.second_uid;
3093     }
3094
3095   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
3096     {
3097       /* Remove the "old" connections */
3098       GNUNET_CONTAINER_multihashmap_destroy(pg->peers[pg_iter].connect_peers);
3099       /* And replace with the working set */
3100       pg->peers[pg_iter].connect_peers = pg->peers[pg_iter].connect_peers_working_set;
3101     }
3102 }
3103
3104 /**
3105  * Internal callback for topology information for a particular peer.
3106  */
3107 static void
3108 internal_topology_callback(void *cls,
3109                            const struct GNUNET_PeerIdentity *peer,
3110                            struct GNUNET_TIME_Relative latency, uint32_t distance)
3111 {
3112   struct CoreContext *core_ctx = cls;
3113   struct TopologyIterateContext *iter_ctx = core_ctx->iter_context;
3114
3115   if (peer == NULL) /* Either finished, or something went wrong */
3116     {
3117       iter_ctx->completed++;
3118       iter_ctx->connected--;
3119       /* One core context allocated per iteration, must free! */
3120       GNUNET_free(core_ctx);
3121     }
3122   else
3123     {
3124       iter_ctx->topology_cb(iter_ctx->cls, &core_ctx->daemon->id, peer, latency, distance, NULL);
3125     }
3126
3127   if (iter_ctx->completed == iter_ctx->total)
3128     {
3129       iter_ctx->topology_cb(iter_ctx->cls, NULL, NULL, GNUNET_TIME_relative_get_zero(), 0, NULL);
3130       /* Once all are done, free the iteration context */
3131       GNUNET_free(iter_ctx);
3132     }
3133 }
3134
3135
3136 /**
3137  * Check running topology iteration tasks, if below max start a new one, otherwise
3138  * schedule for some time in the future.
3139  */
3140 static void
3141 schedule_get_topology(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3142 {
3143   struct CoreContext *core_context = cls;
3144   struct TopologyIterateContext *topology_context = (struct TopologyIterateContext *)core_context->iter_context;
3145   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3146     return;
3147
3148   if (topology_context->connected > MAX_OUTSTANDING_CONNECTIONS)
3149     {
3150 #if VERBOSE_TESTING > 2
3151           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3152                       _("Delaying connect, we have too many outstanding connections!\n"));
3153 #endif
3154       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_get_topology, core_context);
3155     }
3156   else
3157     {
3158 #if VERBOSE_TESTING > 2
3159           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3160                       _("Creating connection, outstanding_connections is %d\n"), outstanding_connects);
3161 #endif
3162       topology_context->connected++;
3163       if (GNUNET_OK != GNUNET_CORE_iterate_peers (core_context->daemon->cfg, &internal_topology_callback, core_context))
3164         internal_topology_callback(core_context, NULL, GNUNET_TIME_relative_get_zero(), 0);
3165
3166     }
3167 }
3168
3169 /**
3170  * Iterate over all (running) peers in the peer group, retrieve
3171  * all connections that each currently has.
3172  */
3173 void
3174 GNUNET_TESTING_get_topology (struct GNUNET_TESTING_PeerGroup *pg, GNUNET_TESTING_NotifyTopology cb, void *cls)
3175 {
3176   struct TopologyIterateContext *topology_context;
3177   struct CoreContext *core_ctx;
3178   unsigned int i;
3179   unsigned int total_count;
3180
3181   /* Allocate a single topology iteration context */
3182   topology_context = GNUNET_malloc(sizeof(struct TopologyIterateContext));
3183   topology_context->topology_cb = cb;
3184   topology_context->cls = cls;
3185   total_count = 0;
3186   for (i = 0; i < pg->total; i++)
3187     {
3188       if (pg->peers[i].daemon->running == GNUNET_YES)
3189         {
3190           /* Allocate one core context per core we need to connect to */
3191           core_ctx = GNUNET_malloc(sizeof(struct CoreContext));
3192           core_ctx->daemon = pg->peers[i].daemon;
3193           /* Set back pointer to topology iteration context */
3194           core_ctx->iter_context = topology_context;
3195           GNUNET_SCHEDULER_add_now(&schedule_get_topology, core_ctx);
3196           total_count++;
3197         }
3198     }
3199   topology_context->total = total_count;
3200   return;
3201 }
3202
3203 /**
3204  * Callback function to process statistic values.
3205  * This handler is here only really to insert a peer
3206  * identity (or daemon) so the statistics can be uniquely
3207  * tied to a single running peer.
3208  *
3209  * @param cls closure
3210  * @param subsystem name of subsystem that created the statistic
3211  * @param name the name of the datum
3212  * @param value the current value
3213  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
3214  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
3215  */
3216 static int internal_stats_callback (void *cls,
3217                                     const char *subsystem,
3218                                     const char *name,
3219                                     uint64_t value,
3220                                     int is_persistent)
3221 {
3222   struct StatsCoreContext *core_context = cls;
3223   struct StatsIterateContext *stats_context = (struct StatsIterateContext *)core_context->iter_context;
3224
3225   return stats_context->proc(stats_context->cls, &core_context->daemon->id, subsystem, name, value, is_persistent);
3226 }
3227
3228 /**
3229  * Internal continuation call for statistics iteration.
3230  *
3231  * @param cls closure, the CoreContext for this iteration
3232  * @param success whether or not the statistics iterations
3233  *        was canceled or not (we don't care)
3234  */
3235 static void internal_stats_cont (void *cls, int success)
3236 {
3237   struct StatsCoreContext *core_context = cls;
3238   struct StatsIterateContext *stats_context = (struct StatsIterateContext *)core_context->iter_context;
3239
3240   stats_context->connected--;
3241   stats_context->completed++;
3242
3243   if (stats_context->completed == stats_context->total)
3244     {
3245       stats_context->cont(stats_context->cls, GNUNET_YES);
3246       GNUNET_free(stats_context);
3247     }
3248
3249   if (core_context->stats_handle != NULL)
3250     GNUNET_STATISTICS_destroy(core_context->stats_handle, GNUNET_NO);
3251
3252   GNUNET_free(core_context);
3253 }
3254
3255 /**
3256  * Check running topology iteration tasks, if below max start a new one, otherwise
3257  * schedule for some time in the future.
3258  */
3259 static void
3260 schedule_get_statistics(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3261 {
3262   struct StatsCoreContext *core_context = cls;
3263   struct StatsIterateContext *stats_context = (struct StatsIterateContext *)core_context->iter_context;
3264
3265   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3266     return;
3267
3268   if (stats_context->connected > MAX_OUTSTANDING_CONNECTIONS)
3269     {
3270 #if VERBOSE_TESTING > 2
3271           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3272                       _("Delaying connect, we have too many outstanding connections!\n"));
3273 #endif
3274       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_get_statistics, core_context);
3275     }
3276   else
3277     {
3278 #if VERBOSE_TESTING > 2
3279           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3280                       _("Creating connection, outstanding_connections is %d\n"), outstanding_connects);
3281 #endif
3282
3283       stats_context->connected++;
3284       core_context->stats_handle = GNUNET_STATISTICS_create("testing", core_context->daemon->cfg);
3285       if (core_context->stats_handle == NULL)
3286         {
3287           internal_stats_cont (core_context, GNUNET_NO);
3288           return;
3289         }
3290
3291       core_context->stats_get_handle = GNUNET_STATISTICS_get(core_context->stats_handle, NULL, NULL, GNUNET_TIME_relative_get_forever(), &internal_stats_cont, &internal_stats_callback, core_context);
3292       if (core_context->stats_get_handle == NULL)
3293         internal_stats_cont (core_context, GNUNET_NO);
3294
3295     }
3296 }
3297
3298 struct DuplicateStats
3299 {
3300   /**
3301    * Next item in the list
3302    */
3303   struct DuplicateStats *next;
3304
3305   /**
3306    * Nasty string, concatenation of relevant information.
3307    */
3308   char *unique_string;
3309 };
3310
3311 /**
3312  * Check whether the combination of port/host/unix domain socket
3313  * already exists in the list of peers being checked for statistics.
3314  *
3315  * @param pg the peergroup in question
3316  * @param specific_peer the peer we're concerned with
3317  * @param stats_list the list to return to the caller
3318  *
3319  * @return GNUNET_YES if the statistics instance has been seen already,
3320  *         GNUNET_NO if not (and we may have added it to the list)
3321  */
3322 static int
3323 stats_check_existing(struct GNUNET_TESTING_PeerGroup *pg, struct PeerData *specific_peer, struct DuplicateStats **stats_list)
3324 {
3325   struct DuplicateStats *pos;
3326   char *unix_domain_socket;
3327   unsigned long long port;
3328   char *to_match;
3329   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_yesno(pg->cfg, "testing", "single_statistics_per_host"))
3330     return GNUNET_NO; /* Each peer has its own statistics instance, do nothing! */
3331
3332   pos = *stats_list;
3333   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(specific_peer->cfg, "statistics", "unixpath", &unix_domain_socket))
3334     return GNUNET_NO;
3335
3336   GNUNET_CONFIGURATION_get_value_number(specific_peer->cfg, "statistics", "port", &port);
3337
3338   if (specific_peer->daemon->hostname != NULL)
3339     GNUNET_asprintf(&to_match, "%s%s%llu", specific_peer->daemon->hostname, unix_domain_socket, port);
3340   else
3341     GNUNET_asprintf(&to_match, "%s%llu", unix_domain_socket, port);
3342
3343   while (pos != NULL)
3344     {
3345       if (0 == strcmp(to_match, pos->unique_string))
3346         {
3347           GNUNET_free(to_match);
3348           return GNUNET_YES;
3349         }
3350       pos = pos->next;
3351     }
3352   pos = GNUNET_malloc(sizeof(struct DuplicateStats));
3353   pos->unique_string = to_match;
3354   pos->next = *stats_list;
3355   *stats_list = pos;
3356   return GNUNET_NO;
3357 }
3358
3359 /**
3360  * Iterate over all (running) peers in the peer group, retrieve
3361  * all statistics from each.
3362  */
3363 void
3364 GNUNET_TESTING_get_statistics (struct GNUNET_TESTING_PeerGroup *pg,
3365                                GNUNET_STATISTICS_Callback cont,
3366                                GNUNET_TESTING_STATISTICS_Iterator proc, void *cls)
3367 {
3368   struct StatsIterateContext *stats_context;
3369   struct StatsCoreContext *core_ctx;
3370   unsigned int i;
3371   unsigned int total_count;
3372   struct DuplicateStats *stats_list;
3373   struct DuplicateStats *pos;
3374   stats_list = NULL;
3375
3376   /* Allocate a single stats iteration context */
3377   stats_context = GNUNET_malloc(sizeof(struct StatsIterateContext));
3378   stats_context->cont = cont;
3379   stats_context->proc = proc;
3380   stats_context->cls = cls;
3381   total_count = 0;
3382
3383   for (i = 0; i < pg->total; i++)
3384     {
3385       if ((pg->peers[i].daemon->running == GNUNET_YES) && (GNUNET_NO == stats_check_existing(pg, &pg->peers[i], &stats_list)))
3386         {
3387           /* Allocate one core context per core we need to connect to */
3388           core_ctx = GNUNET_malloc(sizeof(struct StatsCoreContext));
3389           core_ctx->daemon = pg->peers[i].daemon;
3390           /* Set back pointer to topology iteration context */
3391           core_ctx->iter_context = stats_context;
3392           GNUNET_SCHEDULER_add_now(&schedule_get_statistics, core_ctx);
3393           total_count++;
3394         }
3395     }
3396
3397   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Retrieving stats from %u total instances.\n", total_count);
3398   stats_context->total = total_count;
3399   if (stats_list != NULL)
3400     {
3401       pos = stats_list;
3402       while(pos != NULL)
3403         {
3404           GNUNET_free(pos->unique_string);
3405           stats_list = pos->next;
3406           GNUNET_free(pos);
3407           pos = stats_list->next;
3408         }
3409     }
3410   return;
3411 }
3412
3413 /**
3414  * There are many ways to connect peers that are supported by this function.
3415  * To connect peers in the same topology that was created via the
3416  * GNUNET_TESTING_create_topology, the topology variable must be set to
3417  * GNUNET_TESTING_TOPOLOGY_NONE.  If the topology variable is specified,
3418  * a new instance of that topology will be generated and attempted to be
3419  * connected.  This could result in some connections being impossible,
3420  * because some topologies are non-deterministic.
3421  *
3422  * @param pg the peer group struct representing the running peers
3423  * @param topology which topology to connect the peers in
3424  * @param options options for connecting the topology
3425  * @param option_modifier modifier for options that take a parameter
3426  * @param notify_callback notification to be called once all connections completed
3427  * @param notify_cls closure for notification callback
3428  *
3429  * @return the number of connections that will be attempted, GNUNET_SYSERR on error
3430  */
3431 int
3432 GNUNET_TESTING_connect_topology (struct GNUNET_TESTING_PeerGroup *pg,
3433                                  enum GNUNET_TESTING_Topology topology,
3434                                  enum GNUNET_TESTING_TopologyOption options,
3435                                  double option_modifier,
3436                                  GNUNET_TESTING_NotifyCompletion notify_callback,
3437                                  void *notify_cls)
3438 {
3439   switch (topology)
3440       {
3441       case GNUNET_TESTING_TOPOLOGY_CLIQUE:
3442 #if VERBOSE_TOPOLOGY
3443       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3444                   _("Creating clique CONNECT topology\n"));
3445 #endif
3446         create_clique (pg, &add_actual_connections);
3447         break;
3448       case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
3449 #if VERBOSE_TOPOLOGY
3450       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3451                   _("Creating small world (ring) CONNECT topology\n"));
3452 #endif
3453         create_small_world_ring (pg, &add_actual_connections);
3454         break;
3455       case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
3456 #if VERBOSE_TOPOLOGY
3457       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3458                   _("Creating small world (2d-torus) CONNECT topology\n"));
3459 #endif
3460         create_small_world (pg, &add_actual_connections);
3461         break;
3462       case GNUNET_TESTING_TOPOLOGY_RING:
3463 #if VERBOSE_TOPOLOGY
3464       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3465                   _("Creating ring CONNECT topology\n"));
3466 #endif
3467         create_ring (pg, &add_actual_connections);
3468         break;
3469       case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
3470 #if VERBOSE_TOPOLOGY
3471       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3472                   _("Creating 2d torus CONNECT topology\n"));
3473 #endif
3474         create_2d_torus (pg, &add_actual_connections);
3475         break;
3476       case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
3477 #if VERBOSE_TOPOLOGY
3478       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3479                   _("Creating Erdos-Renyi CONNECT topology\n"));
3480 #endif
3481         create_erdos_renyi (pg, &add_actual_connections);
3482         break;
3483       case GNUNET_TESTING_TOPOLOGY_INTERNAT:
3484 #if VERBOSE_TOPOLOGY
3485       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3486                   _("Creating InterNAT CONNECT topology\n"));
3487 #endif
3488         create_nated_internet (pg, &add_actual_connections);
3489         break;
3490       case GNUNET_TESTING_TOPOLOGY_SCALE_FREE:
3491 #if VERBOSE_TOPOLOGY
3492       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3493                   _("Creating Scale Free CONNECT topology\n"));
3494 #endif
3495         create_scale_free (pg, &add_actual_connections);
3496         break;
3497       case GNUNET_TESTING_TOPOLOGY_LINE:
3498 #if VERBOSE_TOPOLOGY
3499       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3500                   _("Creating straight line CONNECT topology\n"));
3501 #endif
3502         create_line (pg, &add_actual_connections);
3503         break;
3504       case GNUNET_TESTING_TOPOLOGY_NONE:
3505 #if VERBOSE_TOPOLOGY
3506         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3507                   _("Creating no CONNECT topology\n"));
3508 #endif
3509         copy_allowed_topology(pg);
3510         break;
3511       default:
3512         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
3513                    _("Unknown topology specification, can't connect peers!\n"));
3514         return GNUNET_SYSERR;
3515       }
3516
3517   switch (options)
3518     {
3519     case GNUNET_TESTING_TOPOLOGY_OPTION_RANDOM:
3520 #if VERBOSE_TOPOLOGY
3521       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3522                   _("Connecting random subset (%'.2f percent) of possible peers\n"), 100 * option_modifier);
3523 #endif
3524       choose_random_connections(pg, option_modifier);
3525       break;
3526     case GNUNET_TESTING_TOPOLOGY_OPTION_MINIMUM:
3527 #if VERBOSE_TOPOLOGY
3528       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3529                   _("Connecting a minimum of %u peers each (if possible)\n"), (unsigned int)option_modifier);
3530 #endif
3531       choose_minimum(pg, (unsigned int)option_modifier);
3532       break;
3533     case GNUNET_TESTING_TOPOLOGY_OPTION_DFS:
3534 #if VERBOSE_TOPOLOGY
3535       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3536                   _("Using DFS to connect a minimum of %u peers each (if possible)\n"), (unsigned int)option_modifier);
3537 #endif
3538       perform_dfs(pg, (int)option_modifier);
3539       break;
3540     case GNUNET_TESTING_TOPOLOGY_OPTION_ADD_CLOSEST:
3541 #if VERBOSE_TOPOLOGY
3542       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3543                   _("Finding additional %u closest peers each (if possible)\n"), (unsigned int)option_modifier);
3544 #endif
3545       add_closest(pg, (unsigned int)option_modifier, &add_actual_connections);
3546       break;
3547     case GNUNET_TESTING_TOPOLOGY_OPTION_NONE:
3548       break;
3549     case GNUNET_TESTING_TOPOLOGY_OPTION_ALL:
3550       break;
3551     default:
3552       break;
3553     }
3554
3555   return connect_topology(pg, notify_callback, notify_cls);
3556 }
3557
3558 /**
3559  * Callback that is called whenever a hostkey is generated
3560  * for a peer.  Call the real callback and decrement the
3561  * starting counter for the peergroup.
3562  *
3563  * @param cls closure
3564  * @param id identifier for the daemon, NULL on error
3565  * @param d handle for the daemon
3566  * @param emsg error message (NULL on success)
3567  */
3568 static void internal_hostkey_callback (void *cls,
3569                                        const struct GNUNET_PeerIdentity *id,
3570                                        struct GNUNET_TESTING_Daemon *d,
3571                                        const char *emsg)
3572 {
3573   struct InternalStartContext *internal_context = cls;
3574   internal_context->peer->pg->starting--;
3575   internal_context->peer->pg->started++;
3576   if (internal_context->hostkey_callback != NULL)
3577     internal_context->hostkey_callback(internal_context->hostkey_cls, id, d, emsg);
3578   else if (internal_context->peer->pg->started == internal_context->peer->pg->total)
3579     {
3580       internal_context->peer->pg->started = 0; /* Internal startup may use this counter! */
3581       GNUNET_TESTING_daemons_continue_startup(internal_context->peer->pg);
3582     }
3583 }
3584
3585 /**
3586  * Callback that is called whenever a peer has finished starting.
3587  * Call the real callback and decrement the starting counter
3588  * for the peergroup.
3589  *
3590  * @param cls closure
3591  * @param id identifier for the daemon, NULL on error
3592  * @param d handle for the daemon
3593  * @param emsg error message (NULL on success)
3594  */
3595 static void internal_startup_callback (void *cls,
3596                                        const struct GNUNET_PeerIdentity *id,
3597                                        const struct GNUNET_CONFIGURATION_Handle *cfg,
3598                                        struct GNUNET_TESTING_Daemon *d,
3599                                        const char *emsg)
3600 {
3601   struct InternalStartContext *internal_context = cls;
3602   internal_context->peer->pg->starting--;
3603   if (internal_context->start_cb != NULL)
3604     internal_context->start_cb(internal_context->start_cb_cls, id, cfg, d, emsg);
3605 }
3606
3607 static void
3608 internal_continue_startup (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
3609 {
3610   struct InternalStartContext *internal_context = cls;
3611
3612   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3613     {
3614       return;
3615     }
3616
3617   if (internal_context->peer->pg->starting < MAX_CONCURRENT_STARTING)
3618     {
3619       internal_context->peer->pg->starting++;
3620       GNUNET_TESTING_daemon_continue_startup (internal_context->peer->daemon);
3621     }
3622   else
3623     {
3624       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &internal_continue_startup, internal_context);
3625     }
3626 }
3627
3628
3629 /**
3630  * Callback for informing us about a successful
3631  * or unsuccessful churn start call.
3632  *
3633  * @param cls a ChurnContext
3634  * @param id the peer identity of the started peer
3635  * @param cfg the handle to the configuration of the peer
3636  * @param d handle to the daemon for the peer
3637  * @param emsg NULL on success, non-NULL on failure
3638  *
3639  */
3640 void
3641 churn_start_callback (void *cls,
3642                       const struct GNUNET_PeerIdentity *id,
3643                       const struct GNUNET_CONFIGURATION_Handle *cfg,
3644                       struct GNUNET_TESTING_Daemon *d,
3645                       const char *emsg)
3646 {
3647   struct ChurnRestartContext *startup_ctx = cls;
3648   struct ChurnContext *churn_ctx = startup_ctx->churn_ctx;
3649
3650   unsigned int total_left;
3651   char *error_message;
3652
3653   error_message = NULL;
3654   if (emsg != NULL)
3655     {
3656       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3657                   "Churn stop callback failed with error `%s'\n",
3658                   emsg);
3659       churn_ctx->num_failed_start++;
3660     }
3661   else
3662     {
3663       churn_ctx->num_to_start--;
3664     }
3665
3666 #if DEBUG_CHURN
3667   GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
3668              "Started peer, %d left.\n",
3669              churn_ctx->num_to_start);
3670 #endif
3671
3672   total_left = (churn_ctx->num_to_stop - churn_ctx->num_failed_stop) + (churn_ctx->num_to_start - churn_ctx->num_failed_start);
3673
3674   if (total_left == 0)
3675   {
3676     if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
3677       GNUNET_asprintf(&error_message,
3678                       "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!",
3679                       churn_ctx->num_failed_start,
3680                       churn_ctx->num_failed_stop);
3681     churn_ctx->cb(churn_ctx->cb_cls, error_message);
3682     GNUNET_free_non_null(error_message);
3683     GNUNET_free(churn_ctx);
3684     GNUNET_free(startup_ctx);
3685   }
3686 }
3687
3688
3689 static void schedule_churn_restart(void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
3690 {
3691   struct PeerRestartContext *peer_restart_ctx = cls;
3692   struct ChurnRestartContext *startup_ctx = peer_restart_ctx->churn_restart_ctx;
3693
3694   if (startup_ctx->outstanding > MAX_CONCURRENT_STARTING)
3695     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_churn_restart, peer_restart_ctx);
3696   else
3697     {
3698       GNUNET_TESTING_daemon_start_stopped(peer_restart_ctx->daemon,
3699                                           startup_ctx->timeout,
3700                                           &churn_start_callback,
3701                                           startup_ctx);
3702       GNUNET_free(peer_restart_ctx);
3703     }
3704 }
3705
3706 static void
3707 internal_start (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
3708 {
3709   struct InternalStartContext *internal_context = cls;
3710
3711   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3712     {
3713       return;
3714     }
3715
3716   if (internal_context->peer->pg->starting < MAX_CONCURRENT_HOSTKEYS)
3717     {
3718       internal_context->peer->pg->starting++;
3719       internal_context->peer->daemon = GNUNET_TESTING_daemon_start (internal_context->peer->cfg,
3720                                                                     internal_context->timeout,
3721                                                                     internal_context->hostname,
3722                                                                     internal_context->username,
3723                                                                     internal_context->sshport,
3724                                                                     &internal_hostkey_callback,
3725                                                                     internal_context,
3726                                                                     &internal_startup_callback,
3727                                                                     internal_context);
3728     }
3729   else
3730     {
3731       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &internal_start, internal_context);
3732     }
3733 }
3734
3735 /**
3736  * Function which continues a peer group starting up
3737  * after successfully generating hostkeys for each peer.
3738  *
3739  * @param pg the peer group to continue starting
3740  *
3741  */
3742 void
3743 GNUNET_TESTING_daemons_continue_startup(struct GNUNET_TESTING_PeerGroup *pg)
3744 {
3745   unsigned int i;
3746
3747   pg->starting = 0;
3748   for (i = 0; i < pg->total; i++)
3749     {
3750       GNUNET_SCHEDULER_add_now (&internal_continue_startup, &pg->peers[i].internal_context);
3751       //GNUNET_TESTING_daemon_continue_startup(pg->peers[i].daemon);
3752     }
3753 }
3754
3755 /**
3756  * Start count gnunet instances with the same set of transports and
3757  * applications.  The port numbers (any option called "PORT") will be
3758  * adjusted to ensure that no two peers running on the same system
3759  * have the same port(s) in their respective configurations.
3760  *
3761  * @param cfg configuration template to use
3762  * @param total number of daemons to start
3763  * @param timeout total time allowed for peers to start
3764  * @param hostkey_callback function to call on each peers hostkey generation
3765  *        if NULL, peers will be started by this call, if non-null,
3766  *        GNUNET_TESTING_daemons_continue_startup must be called after
3767  *        successful hostkey generation
3768  * @param hostkey_cls closure for hostkey callback
3769  * @param cb function to call on each daemon that was started
3770  * @param cb_cls closure for cb
3771  * @param connect_callback function to call each time two hosts are connected
3772  * @param connect_callback_cls closure for connect_callback
3773  * @param hostnames linked list of hosts to use to start peers on (NULL to run on localhost only)
3774  *
3775  * @return NULL on error, otherwise handle to control peer group
3776  */
3777 struct GNUNET_TESTING_PeerGroup *
3778 GNUNET_TESTING_daemons_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
3779                               unsigned int total,
3780                               struct GNUNET_TIME_Relative timeout,
3781                               GNUNET_TESTING_NotifyHostkeyCreated hostkey_callback,
3782                               void *hostkey_cls,
3783                               GNUNET_TESTING_NotifyDaemonRunning cb,
3784                               void *cb_cls,
3785                               GNUNET_TESTING_NotifyConnection
3786                               connect_callback, void *connect_callback_cls,
3787                               const struct GNUNET_TESTING_Host *hostnames)
3788 {
3789   struct GNUNET_TESTING_PeerGroup *pg;
3790   const struct GNUNET_TESTING_Host *hostpos;
3791 #if 0
3792   char *pos;
3793   const char *rpos;
3794   char *start;
3795 #endif
3796   const char *hostname;
3797   const char *username;
3798   char *baseservicehome;
3799   char *newservicehome;
3800   char *tmpdir;
3801   struct GNUNET_CONFIGURATION_Handle *pcfg;
3802   unsigned int off;
3803   unsigned int hostcnt;
3804   uint16_t minport;
3805   uint16_t sshport;
3806   uint32_t upnum;
3807   uint32_t fdnum;
3808
3809   if (0 == total)
3810     {
3811       GNUNET_break (0);
3812       return NULL;
3813     }
3814   upnum = 0;
3815   fdnum = 0;
3816   pg = GNUNET_malloc (sizeof (struct GNUNET_TESTING_PeerGroup));
3817   pg->cfg = cfg;
3818   pg->notify_connection = connect_callback;
3819   pg->notify_connection_cls = connect_callback_cls;
3820   pg->total = total;
3821   pg->max_timeout = GNUNET_TIME_relative_to_absolute(timeout);
3822   pg->peers = GNUNET_malloc (total * sizeof (struct PeerData));
3823   if (NULL != hostnames)
3824     {
3825       off = 0;
3826       hostpos = hostnames;
3827       while (hostpos != NULL)
3828         {
3829           hostpos = hostpos->next;
3830           off++;
3831         }
3832       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
3833       off = 0;
3834
3835       hostpos = hostnames;
3836       while (hostpos != NULL)
3837         {
3838           pg->hosts[off].minport = LOW_PORT;
3839           pg->hosts[off].hostname = GNUNET_strdup(hostpos->hostname);
3840           if (hostpos->username != NULL)
3841             pg->hosts[off].username = GNUNET_strdup(hostpos->username);
3842           pg->hosts[off].sshport = hostpos->port;
3843           hostpos = hostpos->next;
3844           off++;
3845         }
3846
3847       if (off == 0)
3848         {
3849           pg->hosts = NULL;
3850         }
3851       hostcnt = off;
3852       minport = 0;
3853       pg->num_hosts = off;
3854
3855 #if NO_LL
3856       off = 2;
3857       /* skip leading spaces */
3858       while ((0 != *hostnames) && (isspace ( (unsigned char) *hostnames)))
3859         hostnames++;
3860       rpos = hostnames;
3861       while ('\0' != *rpos)
3862         {
3863           if (isspace ( (unsigned char) *rpos))
3864             off++;
3865           rpos++;
3866         }
3867       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
3868       off = 0;
3869       start = GNUNET_strdup (hostnames);
3870       pos = start;
3871       while ('\0' != *pos)
3872         {
3873           if (isspace ( (unsigned char) *pos))
3874             {
3875               *pos = '\0';
3876               if (strlen (start) > 0)
3877                 {
3878                   pg->hosts[off].minport = LOW_PORT;
3879                   pg->hosts[off++].hostname = start;
3880                 }
3881               start = pos + 1;
3882             }
3883           pos++;
3884         }
3885       if (strlen (start) > 0)
3886         {
3887           pg->hosts[off].minport = LOW_PORT;
3888           pg->hosts[off++].hostname = start;
3889         }
3890       if (off == 0)
3891         {
3892           GNUNET_free (start);
3893           GNUNET_free (pg->hosts);
3894           pg->hosts = NULL;
3895         }
3896       hostcnt = off;
3897       minport = 0;              /* make gcc happy */
3898 #endif
3899     }
3900   else
3901     {
3902       hostcnt = 0;
3903       minport = LOW_PORT;
3904     }
3905   for (off = 0; off < total; off++)
3906     {
3907       if (hostcnt > 0)
3908         {
3909           hostname = pg->hosts[off % hostcnt].hostname;
3910           username = pg->hosts[off % hostcnt].username;
3911           sshport = pg->hosts[off % hostcnt].sshport;
3912           pcfg = make_config (cfg, 
3913                               &pg->hosts[off % hostcnt].minport,
3914                               &upnum,
3915                               hostname, &fdnum);
3916         }
3917       else
3918         {
3919           hostname = NULL;
3920           username = NULL;
3921           sshport = 0;
3922           pcfg = make_config (cfg,
3923                               &minport,
3924                               &upnum,
3925                               hostname, &fdnum);
3926         }
3927
3928       if (NULL == pcfg)
3929         {
3930           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3931                       _
3932                       ("Could not create configuration for peer number %u on `%s'!\n"),
3933                       off, hostname == NULL ? "localhost" : hostname);
3934           continue;
3935         }
3936
3937       if (GNUNET_YES ==
3938           GNUNET_CONFIGURATION_get_value_string (pcfg, "PATHS", "SERVICEHOME",
3939                                                  &baseservicehome))
3940         {
3941           GNUNET_asprintf (&newservicehome,
3942                            "%s/%d/", baseservicehome, off);
3943           GNUNET_free (baseservicehome);
3944         }
3945       else
3946         {
3947           tmpdir = getenv ("TMPDIR");
3948           tmpdir = tmpdir ? tmpdir : "/tmp";
3949           GNUNET_asprintf (&newservicehome,
3950                            "%s/%s/%d/",
3951                            tmpdir,
3952                            "gnunet-testing-test-test", off);
3953         }
3954       GNUNET_CONFIGURATION_set_value_string (pcfg,
3955                                              "PATHS",
3956                                              "SERVICEHOME", newservicehome);
3957       GNUNET_free (newservicehome);
3958       pg->peers[off].cfg = pcfg;
3959       pg->peers[off].allowed_peers = GNUNET_CONTAINER_multihashmap_create(total);
3960       pg->peers[off].connect_peers = GNUNET_CONTAINER_multihashmap_create(total);
3961       pg->peers[off].blacklisted_peers = GNUNET_CONTAINER_multihashmap_create(total);
3962       pg->peers[off].pg = pg;
3963
3964       pg->peers[off].internal_context.peer = &pg->peers[off];
3965       pg->peers[off].internal_context.timeout = timeout;
3966       pg->peers[off].internal_context.hostname = hostname;
3967       pg->peers[off].internal_context.username = username;
3968       pg->peers[off].internal_context.sshport = sshport;
3969       pg->peers[off].internal_context.hostkey_callback = hostkey_callback;
3970       pg->peers[off].internal_context.hostkey_cls = hostkey_cls;
3971       pg->peers[off].internal_context.start_cb = cb;
3972       pg->peers[off].internal_context.start_cb_cls = cb_cls;
3973
3974       GNUNET_SCHEDULER_add_now (&internal_start, &pg->peers[off].internal_context);
3975
3976     }
3977   return pg;
3978 }
3979
3980 /*
3981  * Get a daemon by number, so callers don't have to do nasty
3982  * offsetting operation.
3983  */
3984 struct GNUNET_TESTING_Daemon *
3985 GNUNET_TESTING_daemon_get (struct GNUNET_TESTING_PeerGroup *pg, unsigned int position)
3986 {
3987   if (position < pg->total)
3988     return pg->peers[position].daemon;
3989   else
3990     return NULL;
3991 }
3992
3993 /*
3994  * Get a daemon by peer identity, so callers can
3995  * retrieve the daemon without knowing it's offset.
3996  *
3997  * @param pg the peer group to retrieve the daemon from
3998  * @param peer_id the peer identity of the daemon to retrieve
3999  *
4000  * @return the daemon on success, or NULL if no such peer identity is found
4001  */
4002 struct GNUNET_TESTING_Daemon *
4003 GNUNET_TESTING_daemon_get_by_id (struct GNUNET_TESTING_PeerGroup *pg, struct GNUNET_PeerIdentity *peer_id)
4004 {
4005   unsigned int i;
4006
4007   for (i = 0; i < pg->total; i ++)
4008     {
4009       if (0 == memcmp(&pg->peers[i].daemon->id, peer_id, sizeof(struct GNUNET_PeerIdentity)))
4010         return pg->peers[i].daemon;
4011     }
4012
4013   return NULL;
4014 }
4015
4016 /**
4017  * Prototype of a function that will be called when a
4018  * particular operation was completed the testing library.
4019  *
4020  * @param cls closure (a struct RestartContext)
4021  * @param id id of the peer that was restarted
4022  * @param cfg handle to the configuration of the peer
4023  * @param d handle to the daemon that was restarted
4024  * @param emsg NULL on success
4025  */
4026 void restart_callback (void *cls,
4027                        const struct GNUNET_PeerIdentity *id,
4028                        const struct GNUNET_CONFIGURATION_Handle *cfg,
4029                        struct GNUNET_TESTING_Daemon *d,
4030                        const char *emsg)
4031 {
4032   struct RestartContext *restart_context = cls;
4033
4034   if (emsg == NULL)
4035     {
4036       restart_context->peers_restarted++;
4037     }
4038   else
4039     {
4040       restart_context->peers_restart_failed++;
4041     }
4042
4043   if (restart_context->peers_restarted == restart_context->peer_group->total)
4044     {
4045       restart_context->callback(restart_context->callback_cls, NULL);
4046       GNUNET_free(restart_context);
4047     }
4048   else if (restart_context->peers_restart_failed + restart_context->peers_restarted == restart_context->peer_group->total)
4049     {
4050       restart_context->callback(restart_context->callback_cls, "Failed to restart peers!");
4051       GNUNET_free(restart_context);
4052     }
4053
4054 }
4055
4056 /**
4057  * Callback for informing us about a successful
4058  * or unsuccessful churn stop call.
4059  *
4060  * @param cls a ChurnContext
4061  * @param emsg NULL on success, non-NULL on failure
4062  *
4063  */
4064 void
4065 churn_stop_callback (void *cls, const char *emsg)
4066 {
4067   struct ShutdownContext *shutdown_ctx = cls;
4068   struct ChurnContext *churn_ctx = shutdown_ctx->cb_cls;
4069   unsigned int total_left;
4070   char *error_message;
4071
4072   error_message = NULL;
4073   shutdown_ctx->outstanding--;
4074
4075   if (emsg != NULL)
4076     {
4077       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4078                  "Churn stop callback failed with error `%s'\n", emsg);
4079       churn_ctx->num_failed_stop++;
4080     }
4081   else
4082     {
4083       churn_ctx->num_to_stop--;
4084     }
4085
4086 #if DEBUG_CHURN
4087   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4088              "Stopped peer, %d left.\n", 
4089              churn_ctx->num_to_stop);
4090 #endif
4091   total_left = (churn_ctx->num_to_stop - churn_ctx->num_failed_stop) + (churn_ctx->num_to_start - churn_ctx->num_failed_start);
4092
4093   if (total_left == 0)
4094   {
4095     if ((churn_ctx->num_failed_stop > 0) || (churn_ctx->num_failed_start > 0))
4096       {
4097         GNUNET_asprintf(&error_message, 
4098                         "Churn didn't complete successfully, %u peers failed to start %u peers failed to be stopped!", 
4099                         churn_ctx->num_failed_start, 
4100                         churn_ctx->num_failed_stop);
4101       }
4102     churn_ctx->cb(churn_ctx->cb_cls, error_message);
4103     GNUNET_free_non_null(error_message);
4104     GNUNET_free(churn_ctx);
4105     GNUNET_free(shutdown_ctx);
4106   }
4107 }
4108
4109 /**
4110  * Count the number of running peers.
4111  *
4112  * @param pg handle for the peer group
4113  *
4114  * @return the number of currently running peers in the peer group
4115  */
4116 unsigned int
4117 GNUNET_TESTING_daemons_running (struct GNUNET_TESTING_PeerGroup *pg)
4118 {
4119   unsigned int i;
4120   unsigned int running = 0;
4121   for (i = 0; i < pg->total; i++)
4122   {
4123     if (pg->peers[i].daemon->running == GNUNET_YES)
4124     {
4125       GNUNET_assert(running != -1);
4126       running++;
4127     }
4128   }
4129   return running;
4130 }
4131
4132 /**
4133  * Task to rate limit the number of outstanding peer shutdown
4134  * requests.  This is necessary for making sure we don't do
4135  * too many ssh connections at once, but is generally nicer
4136  * to any system as well (graduated task starts, as opposed
4137  * to calling gnunet-arm N times all at once).
4138  */
4139 static void
4140 schedule_churn_shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
4141 {
4142   struct PeerShutdownContext *peer_shutdown_ctx = cls;
4143   struct ShutdownContext *shutdown_ctx;
4144
4145   GNUNET_assert(peer_shutdown_ctx != NULL);
4146   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
4147   GNUNET_assert(shutdown_ctx != NULL);
4148
4149   if (shutdown_ctx->outstanding > MAX_CONCURRENT_SHUTDOWN)
4150     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_churn_shutdown_task, peer_shutdown_ctx);
4151   else
4152     {
4153       shutdown_ctx->outstanding++;
4154       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon, shutdown_ctx->timeout, shutdown_ctx->cb, shutdown_ctx, GNUNET_NO, GNUNET_YES);
4155       GNUNET_free(peer_shutdown_ctx);
4156     }
4157 }
4158
4159 /**
4160  * Simulate churn by stopping some peers (and possibly
4161  * re-starting others if churn is called multiple times).  This
4162  * function can only be used to create leave-join churn (peers "never"
4163  * leave for good).  First "voff" random peers that are currently
4164  * online will be taken offline; then "von" random peers that are then
4165  * offline will be put back online.  No notifications will be
4166  * generated for any of these operations except for the callback upon
4167  * completion.
4168  *
4169  * @param pg handle for the peer group
4170  * @param voff number of peers that should go offline
4171  * @param von number of peers that should come back online;
4172  *            must be zero on first call (since "testbed_start"
4173  *            always starts all of the peers)
4174  * @param timeout how long to wait for operations to finish before
4175  *        giving up
4176  * @param cb function to call at the end
4177  * @param cb_cls closure for cb
4178  */
4179 void
4180 GNUNET_TESTING_daemons_churn (struct GNUNET_TESTING_PeerGroup *pg,
4181                               unsigned int voff,
4182                               unsigned int von,
4183                               struct GNUNET_TIME_Relative timeout,
4184                               GNUNET_TESTING_NotifyCompletion cb,
4185                               void *cb_cls)
4186 {
4187   struct ChurnContext *churn_ctx;
4188   struct ShutdownContext *shutdown_ctx;
4189   struct PeerShutdownContext *peer_shutdown_ctx;
4190   struct PeerRestartContext *peer_restart_ctx;
4191   struct ChurnRestartContext *churn_startup_ctx;
4192
4193   unsigned int running;
4194   unsigned int stopped;
4195   unsigned int total_running;
4196   unsigned int total_stopped;
4197   unsigned int i;
4198   unsigned int *running_arr;
4199   unsigned int *stopped_arr;
4200   unsigned int *running_permute;
4201   unsigned int *stopped_permute;
4202
4203   running = 0;
4204   stopped = 0;
4205
4206   if ((von == 0) && (voff == 0)) /* No peers at all? */
4207     {
4208       cb(cb_cls, NULL);
4209       return;
4210     }
4211
4212   for (i = 0; i < pg->total; i++)
4213   {
4214     if (pg->peers[i].daemon->running == GNUNET_YES)
4215     {
4216       GNUNET_assert(running != -1);
4217       running++;
4218     }
4219     else
4220     {
4221       GNUNET_assert(stopped != -1);
4222       stopped++;
4223     }
4224   }
4225
4226   if (voff > running)
4227   {
4228     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Trying to stop more peers than are currently running!\n");
4229     cb(cb_cls, "Trying to stop more peers than are currently running!");
4230     return;
4231   }
4232
4233   if (von > stopped)
4234   {
4235     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Trying to start more peers than are currently stopped!\n");
4236     cb(cb_cls, "Trying to start more peers than are currently stopped!");
4237     return;
4238   }
4239
4240   churn_ctx = GNUNET_malloc(sizeof(struct ChurnContext));
4241
4242   running_arr = NULL;
4243   if (running > 0)
4244     running_arr = GNUNET_malloc(running * sizeof(unsigned int));
4245
4246   stopped_arr = NULL;
4247   if (stopped > 0)
4248     stopped_arr = GNUNET_malloc(stopped * sizeof(unsigned int));
4249
4250   running_permute = NULL;
4251   stopped_permute = NULL;
4252
4253   if (running > 0)
4254     running_permute = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_WEAK, running);
4255   if (stopped > 0)
4256     stopped_permute = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_WEAK, stopped);
4257
4258   total_running = running;
4259   total_stopped = stopped;
4260   running = 0;
4261   stopped = 0;
4262
4263   churn_ctx->num_to_start = von;
4264   churn_ctx->num_to_stop = voff;
4265   churn_ctx->cb = cb;
4266   churn_ctx->cb_cls = cb_cls;  
4267
4268   for (i = 0; i < pg->total; i++)
4269   {
4270     if (pg->peers[i].daemon->running == GNUNET_YES)
4271     {
4272       GNUNET_assert((running_arr != NULL) && (total_running > running));
4273       running_arr[running] = i;
4274       running++;
4275     }
4276     else
4277     {
4278       GNUNET_assert((stopped_arr != NULL) && (total_stopped > stopped));
4279       stopped_arr[stopped] = i;
4280       stopped++;
4281     }
4282   }
4283
4284   GNUNET_assert(running >= voff);
4285   if (voff > 0)
4286     {
4287       shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
4288       shutdown_ctx->cb = &churn_stop_callback;
4289       shutdown_ctx->cb_cls = churn_ctx;
4290       shutdown_ctx->total_peers = voff;
4291       shutdown_ctx->timeout = timeout;
4292     }
4293
4294   for (i = 0; i < voff; i++)
4295   {
4296 #if DEBUG_CHURN
4297     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Stopping peer %d!\n", running_permute[i]);
4298 #endif
4299     GNUNET_assert(running_arr != NULL);
4300     peer_shutdown_ctx = GNUNET_malloc(sizeof(struct PeerShutdownContext));
4301     peer_shutdown_ctx->daemon = pg->peers[running_arr[running_permute[i]]].daemon;
4302     peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
4303     GNUNET_SCHEDULER_add_now(&schedule_churn_shutdown_task, peer_shutdown_ctx);
4304
4305     /*
4306     GNUNET_TESTING_daemon_stop (pg->peers[running_arr[running_permute[i]]].daemon,
4307                                 timeout, 
4308                                 &churn_stop_callback, churn_ctx, 
4309                                 GNUNET_NO, GNUNET_YES); */
4310   }
4311
4312   GNUNET_assert(stopped >= von);
4313   if (von > 0)
4314     {
4315       churn_startup_ctx = GNUNET_malloc(sizeof(struct ChurnRestartContext));
4316       churn_startup_ctx->churn_ctx = churn_ctx;
4317       churn_startup_ctx->timeout = timeout;
4318     }
4319   for (i = 0; i < von; i++)
4320     {
4321 #if DEBUG_CHURN
4322       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Starting up peer %d!\n", stopped_permute[i]);
4323 #endif
4324       GNUNET_assert(stopped_arr != NULL);
4325       peer_restart_ctx = GNUNET_malloc(sizeof(struct PeerRestartContext));
4326       peer_restart_ctx->churn_restart_ctx = churn_startup_ctx;
4327       peer_restart_ctx->daemon = pg->peers[stopped_arr[stopped_permute[i]]].daemon;
4328       GNUNET_SCHEDULER_add_now(&schedule_churn_restart, peer_restart_ctx);
4329       /*
4330       GNUNET_TESTING_daemon_start_stopped(pg->peers[stopped_arr[stopped_permute[i]]].daemon, 
4331                                           timeout, &churn_start_callback, churn_ctx);*/
4332   }
4333
4334   GNUNET_free_non_null(running_arr);
4335   GNUNET_free_non_null(stopped_arr);
4336   GNUNET_free_non_null(running_permute);
4337   GNUNET_free_non_null(stopped_permute);
4338 }
4339
4340
4341 /**
4342  * Restart all peers in the given group.
4343  *
4344  * @param pg the handle to the peer group
4345  * @param callback function to call on completion (or failure)
4346  * @param callback_cls closure for the callback function
4347  */
4348 void
4349 GNUNET_TESTING_daemons_restart (struct GNUNET_TESTING_PeerGroup *pg,
4350                                 GNUNET_TESTING_NotifyCompletion callback,
4351                                 void *callback_cls)
4352 {
4353   struct RestartContext *restart_context;
4354   unsigned int off;
4355
4356   if (pg->total > 0)
4357     {
4358       restart_context = GNUNET_malloc(sizeof(struct RestartContext));
4359       restart_context->peer_group = pg;
4360       restart_context->peers_restarted = 0;
4361       restart_context->callback = callback;
4362       restart_context->callback_cls = callback_cls;
4363
4364       for (off = 0; off < pg->total; off++)
4365         {
4366           GNUNET_TESTING_daemon_restart (pg->peers[off].daemon, &restart_callback, restart_context);
4367         }
4368     }
4369 }
4370
4371 /**
4372  * Start or stop an individual peer from the given group.
4373  *
4374  * @param pg handle to the peer group
4375  * @param offset which peer to start or stop
4376  * @param desired_status GNUNET_YES to have it running, GNUNET_NO to stop it
4377  * @param timeout how long to wait for shutdown
4378  * @param cb function to call at the end
4379  * @param cb_cls closure for cb
4380  */
4381 void
4382 GNUNET_TESTING_daemons_vary (struct GNUNET_TESTING_PeerGroup *pg, 
4383                              unsigned int offset,
4384                              int desired_status,
4385                              struct GNUNET_TIME_Relative timeout,
4386                              GNUNET_TESTING_NotifyCompletion cb,
4387                              void *cb_cls)
4388 {
4389   struct ShutdownContext *shutdown_ctx;
4390   struct ChurnRestartContext *startup_ctx;
4391   struct ChurnContext *churn_ctx;
4392
4393   if (GNUNET_NO == desired_status)
4394     {
4395       if (NULL != pg->peers[offset].daemon)
4396         {
4397           shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
4398           churn_ctx = GNUNET_malloc(sizeof(struct ChurnContext));
4399           churn_ctx->num_to_start = 0;
4400           churn_ctx->num_to_stop = 1;
4401           churn_ctx->cb = cb;
4402           churn_ctx->cb_cls = cb_cls;
4403           shutdown_ctx->cb_cls = churn_ctx;
4404           GNUNET_TESTING_daemon_stop(pg->peers[offset].daemon, 
4405                                      timeout, &churn_stop_callback, shutdown_ctx,
4406                                      GNUNET_NO, GNUNET_YES);     
4407         }
4408     }
4409   else if (GNUNET_YES == desired_status)
4410     {
4411       if (NULL == pg->peers[offset].daemon)
4412         {
4413           startup_ctx = GNUNET_malloc(sizeof(struct ChurnRestartContext));
4414           churn_ctx = GNUNET_malloc(sizeof(struct ChurnContext));
4415           churn_ctx->num_to_start = 1;
4416           churn_ctx->num_to_stop = 0;
4417           churn_ctx->cb = cb;
4418           churn_ctx->cb_cls = cb_cls;  
4419           startup_ctx->churn_ctx = churn_ctx;
4420           GNUNET_TESTING_daemon_start_stopped(pg->peers[offset].daemon, 
4421                                               timeout, &churn_start_callback, startup_ctx);
4422         }
4423     }
4424   else
4425     GNUNET_break (0);
4426 }
4427
4428
4429 /**
4430  * Callback for shutting down peers in a peer group.
4431  *
4432  * @param cls closure (struct ShutdownContext)
4433  * @param emsg NULL on success
4434  */
4435 void internal_shutdown_callback (void *cls,
4436                                  const char *emsg)
4437 {
4438   struct ShutdownContext *shutdown_ctx = cls;
4439
4440   shutdown_ctx->outstanding--;
4441   if (emsg == NULL)
4442     {
4443       shutdown_ctx->peers_down++;
4444     }
4445   else
4446     {
4447       shutdown_ctx->peers_failed++;
4448     }
4449
4450   if ((shutdown_ctx->cb != NULL) && (shutdown_ctx->peers_down + shutdown_ctx->peers_failed == shutdown_ctx->total_peers))
4451     {
4452       if (shutdown_ctx->peers_failed > 0)
4453         shutdown_ctx->cb(shutdown_ctx->cb_cls, "Not all peers successfully shut down!");
4454       else
4455         shutdown_ctx->cb(shutdown_ctx->cb_cls, NULL);
4456       GNUNET_free(shutdown_ctx);
4457     }
4458 }
4459
4460
4461 /**
4462  * Task to rate limit the number of outstanding peer shutdown
4463  * requests.  This is necessary for making sure we don't do
4464  * too many ssh connections at once, but is generally nicer
4465  * to any system as well (graduated task starts, as opposed
4466  * to calling gnunet-arm N times all at once).
4467  */
4468 static void
4469 schedule_shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
4470 {
4471   struct PeerShutdownContext *peer_shutdown_ctx = cls;
4472   struct ShutdownContext *shutdown_ctx;
4473
4474   GNUNET_assert(peer_shutdown_ctx != NULL);
4475   shutdown_ctx = peer_shutdown_ctx->shutdown_ctx;
4476   GNUNET_assert(shutdown_ctx != NULL);
4477
4478   if (shutdown_ctx->outstanding > MAX_CONCURRENT_SHUTDOWN)
4479     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &schedule_shutdown_task, peer_shutdown_ctx);
4480   else
4481     {
4482       shutdown_ctx->outstanding++;
4483       GNUNET_TESTING_daemon_stop (peer_shutdown_ctx->daemon, shutdown_ctx->timeout, &internal_shutdown_callback, shutdown_ctx, GNUNET_YES, GNUNET_NO);
4484       GNUNET_free(peer_shutdown_ctx);
4485     }
4486 }
4487
4488 /**
4489  * Shutdown all peers started in the given group.
4490  *
4491  * @param pg handle to the peer group
4492  * @param timeout how long to wait for shutdown
4493  * @param cb callback to notify upon success or failure
4494  * @param cb_cls closure for cb
4495  */
4496 void
4497 GNUNET_TESTING_daemons_stop (struct GNUNET_TESTING_PeerGroup *pg, 
4498                              struct GNUNET_TIME_Relative timeout,
4499                              GNUNET_TESTING_NotifyCompletion cb,
4500                              void *cb_cls)
4501 {
4502   unsigned int off;
4503   struct ShutdownContext *shutdown_ctx;
4504   struct PeerShutdownContext *peer_shutdown_ctx;
4505
4506   GNUNET_assert(pg->total > 0);
4507
4508   shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
4509   shutdown_ctx->cb = cb;
4510   shutdown_ctx->cb_cls = cb_cls;
4511   shutdown_ctx->total_peers = pg->total;
4512   shutdown_ctx->timeout = timeout;
4513   /* shtudown_ctx->outstanding = 0; */
4514
4515   for (off = 0; off < pg->total; off++)
4516     {
4517       GNUNET_assert(NULL != pg->peers[off].daemon);
4518       peer_shutdown_ctx = GNUNET_malloc(sizeof(struct PeerShutdownContext));
4519       peer_shutdown_ctx->daemon = pg->peers[off].daemon;
4520       peer_shutdown_ctx->shutdown_ctx = shutdown_ctx;
4521       GNUNET_SCHEDULER_add_now(&schedule_shutdown_task, peer_shutdown_ctx);
4522       //GNUNET_TESTING_daemon_stop (pg->peers[off].daemon, timeout, shutdown_cb, shutdown_ctx, GNUNET_YES, GNUNET_NO);
4523       if (NULL != pg->peers[off].cfg)
4524         GNUNET_CONFIGURATION_destroy (pg->peers[off].cfg);
4525       if (pg->peers[off].allowed_peers != NULL)
4526         GNUNET_CONTAINER_multihashmap_destroy(pg->peers[off].allowed_peers);
4527       if (pg->peers[off].connect_peers != NULL)
4528         GNUNET_CONTAINER_multihashmap_destroy(pg->peers[off].connect_peers);
4529       if (pg->peers[off].blacklisted_peers != NULL)
4530         GNUNET_CONTAINER_multihashmap_destroy(pg->peers[off].blacklisted_peers);
4531     }
4532   GNUNET_free (pg->peers);
4533   for (off = 0; off < pg->num_hosts; off++)
4534     {
4535       GNUNET_free (pg->hosts[off].hostname);
4536       GNUNET_free_non_null (pg->hosts[off].username);
4537     }
4538   GNUNET_free_non_null (pg->hosts);
4539   GNUNET_free (pg);
4540 }
4541
4542
4543 /* end of testing_group.c */