code clean up
[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 2, 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 Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_arm_service.h"
28 #include "gnunet_testing_lib.h"
29
30 #define VERBOSE_TESTING GNUNET_YES
31
32 /**
33  * Lowest port used for GNUnet testing.  Should be high enough to not
34  * conflict with other applications running on the hosts but be low
35  * enough to not conflict with client-ports (typically starting around
36  * 32k).
37  */
38 #define LOW_PORT 10000
39
40 /**
41  * Highest port used for GNUnet testing.  Should be low enough to not
42  * conflict with the port range for "local" ports (client apps; see
43  * /proc/sys/net/ipv4/ip_local_port_range on Linux for example).
44  */
45 #define HIGH_PORT 32000
46
47 #define CONNECT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 180)
48
49 struct PeerConnection
50 {
51   /*
52    * Linked list
53    */
54   struct PeerConnection *next;
55
56   /*
57    * Pointer to daemon handle
58    */
59   struct GNUNET_TESTING_Daemon *daemon;
60
61 };
62
63 /**
64  * Data we keep per peer.
65  */
66 struct PeerData
67 {
68   /**
69    * (Initial) configuration of the host.
70    * (initial because clients could change
71    *  it and we would not know about those
72    *  updates).
73    */
74   struct GNUNET_CONFIGURATION_Handle *cfg;
75
76   /**
77    * Handle for controlling the daemon.
78    */
79   struct GNUNET_TESTING_Daemon *daemon;
80
81   /*
82    * Linked list of peer connections (simply indexes of PeerGroup)
83    * FIXME: Question, store pointer or integer?  Pointer for now...
84    */
85   struct PeerConnection *connected_peers;
86 };
87
88
89 /**
90  * Data we keep per host.
91  */
92 struct HostData
93 {
94   /**
95    * Name of the host.
96    */
97   char *hostname;
98
99   /**
100    * Lowest port that we have not yet used
101    * for GNUnet.
102    */
103   uint16_t minport;
104 };
105
106
107 /**
108  * Handle to a group of GNUnet peers.
109  */
110 struct GNUNET_TESTING_PeerGroup
111 {
112   /**
113    * Our scheduler.
114    */
115   struct GNUNET_SCHEDULER_Handle *sched;
116
117   /**
118    * Configuration template.
119    */
120   const struct GNUNET_CONFIGURATION_Handle *cfg;
121
122   /**
123    * Function to call on each started daemon.
124    */
125   GNUNET_TESTING_NotifyDaemonRunning cb;
126
127   /**
128    * Closure for cb.
129    */
130   void *cb_cls;
131
132   /*
133    * Function to call on each topology connection created
134    */
135   GNUNET_TESTING_NotifyConnection notify_connection;
136
137   /*
138    * Callback for notify_connection
139    */
140   void *notify_connection_cls;
141
142   /**
143    * NULL-terminated array of information about
144    * hosts.
145    */
146   struct HostData *hosts;
147
148   /**
149    * Array of "total" peers.
150    */
151   struct PeerData *peers;
152
153   /**
154    * Number of peers in this group.
155    */
156   unsigned int total;
157
158 };
159
160
161 struct UpdateContext
162 {
163   struct GNUNET_CONFIGURATION_Handle *ret;
164   unsigned int nport;
165 };
166
167 /**
168  * Function to iterate over options.  Copies
169  * the options to the target configuration,
170  * updating PORT values as needed.
171  *
172  * @param cls closure
173  * @param section name of the section
174  * @param option name of the option
175  * @param value value of the option
176  */
177 static void
178 update_config (void *cls,
179                const char *section, const char *option, const char *value)
180 {
181   struct UpdateContext *ctx = cls;
182   unsigned int ival;
183   char cval[12];
184
185   if ((0 == strcmp (option, "PORT")) && (1 == sscanf (value, "%u", &ival)))
186     {
187       GNUNET_snprintf (cval, sizeof (cval), "%u", ctx->nport++);
188       value = cval;
189     }
190   GNUNET_CONFIGURATION_set_value_string (ctx->ret, section, option, value);
191 }
192
193
194 /**
195  * Create a new configuration using the given configuration
196  * as a template; however, each PORT in the existing cfg
197  * must be renumbered by incrementing "*port".  If we run
198  * out of "*port" numbers, return NULL. 
199  * 
200  * @param cfg template configuration
201  * @param port port numbers to use, update to reflect
202  *             port numbers that were used
203  * @return new configuration, NULL on error
204  */
205 static struct GNUNET_CONFIGURATION_Handle *
206 make_config (const struct GNUNET_CONFIGURATION_Handle *cfg, uint16_t * port)
207 {
208   struct UpdateContext uc;
209   uint16_t orig;
210
211   orig = *port;
212   uc.nport = *port;
213   uc.ret = GNUNET_CONFIGURATION_create ();
214   GNUNET_CONFIGURATION_iterate (cfg, &update_config, &uc);
215   if (uc.nport >= HIGH_PORT)
216     {
217       *port = orig;
218       GNUNET_CONFIGURATION_destroy (uc.ret);
219       return NULL;
220     }
221   *port = (uint16_t) uc.nport;
222   return uc.ret;
223 }
224
225 /*
226  * Add entries to the peers connected list
227  *
228  * @param pg the peer group we are working with
229  * @param first index of the first peer
230  * @param second index of the second peer
231  *
232  * @return the number of connections added (can be 0, 1 or 2)
233  *
234  * FIXME: add both, or only add one?
235  *      - if both are added, then we have to keep track
236  *        when connecting so we don't double connect
237  *      - if only one is added, we need to iterate over
238  *        both lists to find out if connection already exists
239  *      - having both allows the whitelisting/friend file
240  *        creation to be easier
241  *
242  *      -- For now, add both, we have to iterate over each to
243  *         check for duplicates anyways, so we'll take the performance
244  *         hit assuming we don't have __too__ many connections
245  *
246  */
247 static int
248 add_connections(struct GNUNET_TESTING_PeerGroup *pg, unsigned int first, unsigned int second)
249 {
250   int added;
251   struct PeerConnection *first_iter;
252   struct PeerConnection *second_iter;
253   int add_first;
254   int add_second;
255   struct PeerConnection *new_first;
256   struct PeerConnection *new_second;
257
258   first_iter = pg->peers[first].connected_peers;
259   add_first = GNUNET_YES;
260   while (first_iter != NULL)
261     {
262       if (first_iter->daemon == pg->peers[second].daemon)
263         add_first = GNUNET_NO;
264       first_iter = first_iter->next;
265     }
266
267   second_iter = pg->peers[second].connected_peers;
268   add_second = GNUNET_YES;
269   while (second_iter != NULL)
270     {
271       if (second_iter->daemon == pg->peers[first].daemon)
272         add_second = GNUNET_NO;
273       second_iter = second_iter->next;
274     }
275
276   added = 0;
277   if (add_first)
278     {
279       new_first = GNUNET_malloc(sizeof(struct PeerConnection));
280       new_first->daemon = pg->peers[second].daemon;
281       new_first->next = pg->peers[first].connected_peers;
282       pg->peers[first].connected_peers = new_first;
283       added++;
284     }
285
286   if (add_second)
287     {
288       new_second = GNUNET_malloc(sizeof(struct PeerConnection));
289       new_second->daemon = pg->peers[first].daemon;
290       new_second->next = pg->peers[second].connected_peers;
291       pg->peers[second].connected_peers = new_second;
292       added++;
293     }
294
295   return added;
296 }
297
298 int
299 create_small_world_ring(struct GNUNET_TESTING_PeerGroup *pg)
300 {
301   unsigned int i, j;
302   int nodeToConnect;
303   unsigned int natLog;
304   unsigned int randomPeer;
305   double random, logNModifier, percentage;
306   unsigned int smallWorldConnections;
307   int connsPerPeer;
308   char *p_string;
309   int max;
310   int min;
311   unsigned int useAnd;
312   int connect_attempts;
313
314   logNModifier = 0.5; /* FIXME: default value? */
315   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg, 
316                                                          "TESTING",
317                                                          "LOGNMODIFIER", 
318                                                          &p_string))
319     {
320       if (sscanf(p_string, "%lf", &logNModifier) != 1)
321         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
322                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
323                     p_string,
324                     "LOGNMODIFIER",
325                     "TESTING");
326       GNUNET_free (p_string);
327     }
328   percentage = 0.5; /* FIXME: default percentage? */
329   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
330                                                          "TESTING",
331                                                          "PERCENTAGE",
332                                                          &p_string))
333     {
334       if (sscanf(p_string, "%lf", &percentage) != 1)
335         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
336                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
337                     p_string,
338                     "PERCENTAGE",
339                     "TESTING");
340       GNUNET_free (p_string);
341     }
342   natLog = log (pg->total);
343   connsPerPeer = ceil (natLog * logNModifier);
344
345   if (connsPerPeer % 2 == 1)
346     connsPerPeer += 1;
347
348   smallWorldConnections = 0;
349   connect_attempts = 0;
350   for (i = 0; i < pg->total; i++)
351     {
352       useAnd = 0;
353       max = i + connsPerPeer / 2;
354       min = i - connsPerPeer / 2;
355
356       if (max > pg->total - 1)
357         {
358           max = max - pg->total;
359           useAnd = 1;
360         }
361
362       if (min < 0)
363         {
364           min = pg->total - 1 + min;
365           useAnd = 1;
366         }
367
368       for (j = 0; j < connsPerPeer / 2; j++)
369         {
370           random = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
371                                                       (uint64_t)-1LL)) / ( (double) (uint64_t) -1LL);
372           if (random < percentage)
373             {
374               /* Connect to uniformly selected random peer */
375               randomPeer =
376                 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
377                                    pg->total);
378               while ((((randomPeer < max) && (randomPeer > min))
379                       && (useAnd == 0)) || (((randomPeer > min)
380                                              || (randomPeer < max))
381                                             && (useAnd == 1)))
382                 {
383                   randomPeer =
384                       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
385                                                          pg->total);
386                 }
387               smallWorldConnections +=
388                 add_connections (pg, i, randomPeer);
389             }
390           else
391             {
392               nodeToConnect = i + j + 1;
393               if (nodeToConnect > pg->total - 1)
394                 {
395                   nodeToConnect = nodeToConnect - pg->total;
396                 }
397               connect_attempts +=
398                 add_connections (pg, i, nodeToConnect);
399             }
400         }
401
402     }
403
404   connect_attempts += smallWorldConnections;
405
406   return connect_attempts;
407 }
408
409
410 static int
411 create_nated_internet (struct GNUNET_TESTING_PeerGroup *pg)
412 {
413   unsigned int outer_count, inner_count;
414   unsigned int cutoff;
415   int connect_attempts;
416   double nat_percentage;
417   char *p_string;
418
419   nat_percentage = 0.6; /* FIXME: default percentage? */
420   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
421                                                          "TESTING",
422                                                          "NATPERCENTAGE",
423                                                          &p_string))
424     {
425       if (sscanf(p_string, "%lf", &nat_percentage) != 1)
426         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
427                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
428                     p_string,
429                     "NATPERCENTAGE",
430                     "TESTING");
431       GNUNET_free (p_string);
432     }
433
434
435
436   cutoff = (unsigned int) (nat_percentage * pg->total);
437
438   connect_attempts = 0;
439
440   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
441     {
442       for (inner_count = outer_count + 1; inner_count < pg->total;
443            inner_count++)
444         {
445           if ((outer_count > cutoff) || (inner_count > cutoff))
446             {
447 #if VERBOSE_TESTING
448               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
449                           "Connecting peer %d to peer %d\n",
450                           outer_count, inner_count);
451 #endif
452               connect_attempts += add_connections(pg, outer_count, inner_count);
453             }
454         }
455     }
456
457   return connect_attempts;
458
459 }
460
461
462
463 static int
464 create_small_world (struct GNUNET_TESTING_PeerGroup *pg)
465 {
466   unsigned int i, j, k;
467   unsigned int square;
468   unsigned int rows;
469   unsigned int cols;
470   unsigned int toggle = 1;
471   unsigned int nodeToConnect;
472   unsigned int natLog;
473   unsigned int node1Row;
474   unsigned int node1Col;
475   unsigned int node2Row;
476   unsigned int node2Col;
477   unsigned int distance;
478   double probability, random, percentage;
479   unsigned int smallWorldConnections;
480   char *p_string;
481   int connect_attempts;
482   square = floor (sqrt (pg->total));
483   rows = square;
484   cols = square;
485   
486   percentage = 0.5; /* FIXME: default percentage? */
487   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
488                                                          "TESTING",
489                                                          "PERCENTAGE",
490                                                          &p_string))
491     {
492       if (sscanf(p_string, "%lf", &percentage) != 1)
493         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
494                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
495                     p_string,
496                     "PERCENTAGE",
497                     "TESTING");
498       GNUNET_free (p_string);
499     }
500   probability = 0.5; /* FIXME: default percentage? */
501   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(pg->cfg,
502                                                          "TESTING",
503                                                          "PROBABILITY",
504                                                          &p_string))
505     {
506       if (sscanf(p_string, "%lf", &probability) != 1)
507         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
508                     _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
509                     p_string,
510                     "PROBABILITY",
511                     "TESTING");
512       GNUNET_free (p_string);
513     }
514   if (square * square != pg->total)
515     {
516       while (rows * cols < pg->total)
517         {
518           if (toggle % 2 == 0)
519             rows++;
520           else
521             cols++;
522
523           toggle++;
524         }
525     }
526 #if VERBOSE_TESTING
527       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
528                   _("Connecting nodes in 2d torus topology: %u rows %u columns\n"),
529                   rows, cols);
530 #endif
531
532   connect_attempts = 0;
533   /* Rows and columns are all sorted out, now iterate over all nodes and connect each
534    * to the node to its right and above.  Once this is over, we'll have our torus!
535    * Special case for the last node (if the rows and columns are not equal), connect
536    * to the first in the row to maintain topology.
537    */
538   for (i = 0; i < pg->total; i++)
539     {
540       /* First connect to the node to the right */
541       if (((i + 1) % cols != 0) && (i + 1 != pg->total))
542         nodeToConnect = i + 1;
543       else if (i + 1 == pg->total)
544         nodeToConnect = rows * cols - cols;
545       else
546         nodeToConnect = i - cols + 1;
547
548       connect_attempts += add_connections (pg, i, nodeToConnect);
549
550       if (i < cols)
551         nodeToConnect = (rows * cols) - cols + i;
552       else
553         nodeToConnect = i - cols;
554
555       if (nodeToConnect < pg->total)
556         connect_attempts += add_connections (pg, i, nodeToConnect);
557     }
558   natLog = log (pg->total);
559 #if VERBOSE_TESTING
560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
561               _("natural log of %d is %d, will run %d iterations\n"),
562              pg->total, natLog, (int) (natLog * percentage));
563   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Total connections added thus far: %u!\n"), connect_attempts);
564 #endif
565   smallWorldConnections = 0;
566   for (i = 0; i < (int) (natLog * percentage); i++)
567     {
568       for (j = 0; j < pg->total; j++)
569         {
570           /* Determine the row and column of node at position j on the 2d torus */
571           node1Row = j / cols;
572           node1Col = j - (node1Row * cols);
573           for (k = 0; k < pg->total; k++)
574             {
575               /* Determine the row and column of node at position k on the 2d torus */
576               node2Row = k / cols;
577               node2Col = k - (node2Row * cols);
578               /* Simple Cartesian distance */
579               distance = abs (node1Row - node2Row) + abs (node1Col - node2Col);
580               if (distance > 1)
581                 {
582                   /* Calculate probability as 1 over the square of the distance */
583                   probability = 1.0 / (distance * distance);
584                   /* Choose a random value between 0 and 1 */
585                   random = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
586                                                               (uint64_t)-1LL)) / ( (double) (uint64_t) -1LL);
587                   /* If random < probability, then connect the two nodes */
588                   if (random < probability)
589                     smallWorldConnections += add_connections (pg, j, k);
590
591                 }
592             }
593         }
594     }
595   connect_attempts += smallWorldConnections;
596 #if VERBOSE_TESTING
597           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
598                       _("Total connections added for small world: %d!\n"),
599                       smallWorldConnections);
600 #endif
601   return connect_attempts;
602 }
603
604
605
606 static int
607 create_erdos_renyi (struct GNUNET_TESTING_PeerGroup *pg)
608 {
609   double temp_rand;
610   unsigned int outer_count;
611   unsigned int inner_count;
612   int connect_attempts;
613   double probability;
614   char *p_string;
615   connect_attempts = 0;
616
617   GNUNET_CONFIGURATION_get_value_string(pg->cfg, "TESTING", "PROBABILITY", &p_string);
618   if ((p_string == NULL) || (sscanf(p_string, "%lf", &probability) != 1))
619     probability = 0.5; /* FIXME: default probability? */
620
621   GNUNET_free_non_null (p_string);
622   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
623     {
624       for (inner_count = outer_count + 1; inner_count < pg->total;
625            inner_count++)
626         {
627           temp_rand = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
628                                                          (uint64_t)-1LL)) / ( (double) (uint64_t) -1LL);
629 #if VERBOSE_TESTING
630           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
631                       _("rand is %f probability is %f\n"), temp_rand,
632                       probability);
633 #endif
634           if (temp_rand < probability)
635             {
636               connect_attempts += add_connections (pg, outer_count, inner_count);
637             }
638         }
639     }
640
641   return connect_attempts;
642 }
643
644 static int
645 create_2d_torus (struct GNUNET_TESTING_PeerGroup *pg)
646 {
647   unsigned int i;
648   unsigned int square;
649   unsigned int rows;
650   unsigned int cols;
651   unsigned int toggle = 1;
652   unsigned int nodeToConnect;
653   int connect_attempts;
654
655   connect_attempts = 0;
656
657   square = floor (sqrt (pg->total));
658   rows = square;
659   cols = square;
660
661   if (square * square != pg->total)
662     {
663       while (rows * cols < pg->total)
664         {
665           if (toggle % 2 == 0)
666             rows++;
667           else
668             cols++;
669
670           toggle++;
671         }
672     }
673 #if VERBOSE_TESTING
674       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
675                   _("Connecting nodes in 2d torus topology: %u rows %u columns\n"),
676                   rows, cols);
677 #endif
678   /* Rows and columns are all sorted out, now iterate over all nodes and connect each
679    * to the node to its right and above.  Once this is over, we'll have our torus!
680    * Special case for the last node (if the rows and columns are not equal), connect
681    * to the first in the row to maintain topology.
682    */
683   for (i = 0; i < pg->total; i++)
684     {
685       /* First connect to the node to the right */
686       if (((i + 1) % cols != 0) && (i + 1 != pg->total))
687         nodeToConnect = i + 1;
688       else if (i + 1 == pg->total)
689         nodeToConnect = rows * cols - cols;
690       else
691         nodeToConnect = i - cols + 1;
692 #if VERBOSE_TESTING
693           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
694                       "Connecting peer %d to peer %d\n",
695                       i, nodeToConnect);
696 #endif
697       connect_attempts += add_connections(pg, i, nodeToConnect);
698
699       /* Second connect to the node immediately above */
700       if (i < cols)
701         nodeToConnect = (rows * cols) - cols + i;
702       else
703         nodeToConnect = i - cols;
704
705       if (nodeToConnect < pg->total)
706         {
707 #if VERBOSE_TESTING
708           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
709                       "Connecting peer %d to peer %d\n",
710                       i, nodeToConnect);
711 #endif
712           connect_attempts += add_connections(pg, i, nodeToConnect);
713         }
714
715     }
716
717   return connect_attempts;
718 }
719
720
721
722 static int
723 create_clique (struct GNUNET_TESTING_PeerGroup *pg)
724 {
725   unsigned int outer_count;
726   unsigned int inner_count;
727   int connect_attempts;
728
729   connect_attempts = 0;
730
731   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
732     {
733       for (inner_count = outer_count + 1; inner_count < pg->total;
734            inner_count++)
735         {
736 #if VERBOSE_TESTING
737           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
738                       "Connecting peer %d to peer %d\n",
739                       outer_count, inner_count);
740 #endif
741           connect_attempts += add_connections(pg, outer_count, inner_count);
742         }
743     }
744
745   return connect_attempts;
746 }
747
748
749 static int
750 create_ring (struct GNUNET_TESTING_PeerGroup *pg)
751 {
752   unsigned int count;
753   int connect_attempts;
754
755   connect_attempts = 0;
756
757   /* Connect each peer to the next highest numbered peer */
758   for (count = 0; count < pg->total - 1; count++)
759     {
760 #if VERBOSE_TESTING
761           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
762                       "Connecting peer %d to peer %d\n",
763                       count, count + 1);
764 #endif
765       connect_attempts += add_connections(pg, count, count + 1);
766     }
767
768   /* Connect the last peer to the first peer */
769   connect_attempts += add_connections(pg, pg->total - 1, 0);
770
771   return connect_attempts;
772 }
773
774
775 /*
776  * Create the friend files based on the PeerConnection's
777  * of each peer in the peer group, and copy the files
778  * to the appropriate place
779  *
780  * @param pg the peer group we are dealing with
781  */
782 static int
783 create_and_copy_friend_files (struct GNUNET_TESTING_PeerGroup *pg)
784 {
785   FILE *temp_friend_handle;
786   unsigned int pg_iter;
787   struct PeerConnection *connection_iter;
788   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
789   char *temp_service_path;
790   pid_t *pidarr;
791   char *arg;
792   struct GNUNET_PeerIdentity *temppeer;
793   char * mytemp;
794   enum GNUNET_OS_ProcessStatusType type;
795   unsigned long return_code;
796   int count;
797   int ret;
798   int max_wait = 10;
799
800   pidarr = GNUNET_malloc(sizeof(pid_t) * pg->total);
801   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
802     {
803       mytemp = GNUNET_DISK_mktemp("friends");
804       temp_friend_handle = fopen (mytemp, "wt");
805       connection_iter = pg->peers[pg_iter].connected_peers;
806       while (connection_iter != NULL)
807         {
808           temppeer = &connection_iter->daemon->id;
809           GNUNET_CRYPTO_hash_to_enc(&temppeer->hashPubKey, &peer_enc);
810           fprintf(temp_friend_handle, "%s\n", (char *)&peer_enc);
811           connection_iter = connection_iter->next;
812         }
813
814       fclose(temp_friend_handle);
815
816       if (GNUNET_OK !=
817           GNUNET_CONFIGURATION_get_value_string(pg->peers[pg_iter].daemon->cfg, "PATHS", "SERVICEHOME", &temp_service_path))
818         {         
819           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
820                       _("No `%s' specified in peer configuration in section `%s', cannot copy friends file!\n"),
821                       "SERVICEHOME",
822                       "PATHS");
823           if (UNLINK (mytemp) != 0)
824             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", mytemp);
825           GNUNET_free (mytemp);
826           break;
827         }
828
829       if (pg->peers[pg_iter].daemon->hostname == NULL) /* Local, just copy the file */
830         {
831           GNUNET_asprintf (&arg, "%s/friends", temp_service_path);
832           pidarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "mv",
833                                          "mv", mytemp, arg, NULL);
834 #if VERBOSE_TESTING
835           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
836                       _("Copying file with command cp %s %s\n"), mytemp, arg);
837 #endif
838
839           GNUNET_free(arg);
840         }
841       else /* Remote, scp the file to the correct place */
842         {
843           if (NULL != pg->peers[pg_iter].daemon->username)
844             GNUNET_asprintf (&arg, "%s@%s:%s/friends", pg->peers[pg_iter].daemon->username, pg->peers[pg_iter].daemon->hostname, temp_service_path);
845           else
846             GNUNET_asprintf (&arg, "%s:%s/friends", pg->peers[pg_iter].daemon->hostname, temp_service_path);
847           pidarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "scp",
848                                          "scp", mytemp, arg, NULL);
849
850 #if VERBOSE_TESTING
851           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
852                       _("Copying file with command scp %s %s\n"), mytemp, arg);
853 #endif
854           GNUNET_free(arg);
855         }
856       GNUNET_free (temp_service_path);
857       GNUNET_free (mytemp);
858     }
859
860   count = 0;
861   ret = GNUNET_SYSERR;
862   while ((count < max_wait) && (ret != GNUNET_OK))
863     {
864       ret = GNUNET_OK;
865       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
866         {
867 #if VERBOSE_TESTING
868           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
869                       _("Checking copy status of file %d\n"), pg_iter);
870 #endif
871           if (pidarr[pg_iter] != 0) /* Check for already completed! */
872             {
873               if (GNUNET_OS_process_status(pidarr[pg_iter], &type, &return_code) != GNUNET_OK)
874                 {
875                   ret = GNUNET_SYSERR;
876                 }
877               else if ((type != GNUNET_OS_PROCESS_EXITED) || (return_code != 0))
878                 {
879                   ret = GNUNET_SYSERR;
880                 }
881               else
882                 {
883                   pidarr[pg_iter] = 0;
884 #if VERBOSE_TESTING
885             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
886                       _("File %d copied\n"), pg_iter);
887 #endif
888                 }
889             }
890         }
891       count++;
892       if (ret == GNUNET_SYSERR)
893         {
894           sleep(1);
895         }
896     }
897
898   GNUNET_free(pidarr);
899   return ret;
900 }
901
902
903
904 /*
905  * Connect the topology as specified by the PeerConnection's
906  * of each peer in the peer group
907  *
908  * @param pg the peer group we are dealing with
909  */
910 static void
911 connect_topology (struct GNUNET_TESTING_PeerGroup *pg)
912 {
913   unsigned int pg_iter;
914   struct PeerConnection *connection_iter;
915   int connect_count;
916
917   connect_count = 0;
918   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
919     {
920       connection_iter = pg->peers[pg_iter].connected_peers;
921       while (connection_iter != NULL)
922         {
923           GNUNET_TESTING_daemons_connect (pg->peers[pg_iter].daemon,
924                                           connection_iter->daemon,
925                                           CONNECT_TIMEOUT,
926                                           pg->notify_connection,
927                                           pg->notify_connection_cls);
928           connection_iter = connection_iter->next;
929           connect_count++;
930           if (connect_count % 50 == 0)
931             {
932 #if VERBOSE_TESTING
933               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
934                           _("Sleeping to give peers a chance to connect!\n"));
935 #endif
936               sleep(2);
937             }
938         }
939     }
940 }
941
942
943 /*
944  * Takes a peer group and attempts to create a topology based on the
945  * one specified in the configuration file.  Returns the number of connections
946  * that will attempt to be created, but this will happen asynchronously(?) so
947  * the caller will have to keep track (via the callback) of whether or not
948  * the connection actually happened.
949  *
950  * @param pg the peer group struct representing the running peers
951  *
952  * @return the number of connections should be created by the topology, so the
953  * caller knows how many to wait for (if it so chooses)
954  *
955  */
956 int
957 GNUNET_TESTING_create_topology (struct GNUNET_TESTING_PeerGroup *pg)
958 {
959   unsigned long long topology_num;
960   int ret;
961   int num_connections;
962
963   GNUNET_assert (pg->notify_connection != NULL);
964   ret = GNUNET_OK;
965   if (GNUNET_YES ==
966       GNUNET_CONFIGURATION_get_value_number (pg->cfg, "testing", "topology",
967                                              &topology_num))
968     {
969       switch (topology_num)
970         {
971         case GNUNET_TESTING_TOPOLOGY_CLIQUE:
972 #if VERBOSE_TESTING
973           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
974                       _("Creating clique topology (may take a bit!)\n"));
975 #endif
976           num_connections = create_clique (pg);
977           break;
978         case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
979 #if VERBOSE_TESTING
980           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
981                       _("Creating small world (ring) topology (may take a bit!)\n"));
982 #endif
983           num_connections = create_small_world_ring (pg);
984           break;
985         case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
986 #if VERBOSE_TESTING
987           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
988                       _("Creating small world (2d-torus) topology (may take a bit!)\n"));
989 #endif
990           num_connections = create_small_world (pg);
991           break;
992         case GNUNET_TESTING_TOPOLOGY_RING:
993 #if VERBOSE_TESTING
994           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
995                       _("Creating ring topology (may take a bit!)\n"));
996 #endif
997           num_connections = create_ring (pg);
998           break;
999         case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
1000 #if VERBOSE_TESTING
1001           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1002                       _("Creating 2d torus topology (may take a bit!)\n"));
1003 #endif
1004           num_connections = create_2d_torus (pg);
1005           break;
1006         case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
1007 #if VERBOSE_TESTING
1008           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1009                       _("Creating Erdos-Renyi topology (may take a bit!)\n"));
1010 #endif
1011           num_connections = create_erdos_renyi (pg);
1012           break;
1013         case GNUNET_TESTING_TOPOLOGY_INTERNAT:
1014 #if VERBOSE_TESTING
1015           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1016                       _("Creating InterNAT topology (may take a bit!)\n"));
1017 #endif
1018           num_connections = create_nated_internet (pg);
1019           break;
1020         case GNUNET_TESTING_TOPOLOGY_NONE:
1021           num_connections = 0;
1022           break;
1023         default:
1024           num_connections = 0;
1025           break;
1026         }
1027       if (num_connections < 1)
1028         return GNUNET_SYSERR;
1029
1030       if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "TESTING", "F2F"))
1031         ret = create_and_copy_friend_files(pg);
1032       if (ret == GNUNET_OK)
1033         connect_topology(pg);
1034       else
1035         {
1036 #if VERBOSE_TESTING
1037           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1038                       _("Failed during friend file copying!\n"));
1039 #endif
1040           return GNUNET_SYSERR;
1041         }
1042     }
1043   else
1044     {
1045       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1046                   _("No topology specified, was one intended?\n"));
1047     }
1048
1049   return num_connections;
1050 }
1051
1052 /**
1053  * Start count gnunetd processes with the same set of transports and
1054  * applications.  The port numbers (any option called "PORT") will be
1055  * adjusted to ensure that no two peers running on the same system
1056  * have the same port(s) in their respective configurations.
1057  *
1058  * @param sched scheduler to use 
1059  * @param cfg configuration template to use
1060  * @param total number of daemons to start
1061  * @param cb function to call on each daemon that was started
1062  * @param cb_cls closure for cb
1063  * @param connect_callback function to call each time two hosts are connected
1064  * @param connect_callback_cls closure for connect_callback
1065  * @param hostnames space-separated list of hostnames to use; can be NULL (to run
1066  *        everything on localhost).
1067  * @return NULL on error, otherwise handle to control peer group
1068  */
1069 struct GNUNET_TESTING_PeerGroup *
1070 GNUNET_TESTING_daemons_start (struct GNUNET_SCHEDULER_Handle *sched,
1071                               const struct GNUNET_CONFIGURATION_Handle *cfg,
1072                               unsigned int total,
1073                               GNUNET_TESTING_NotifyDaemonRunning cb,
1074                               void *cb_cls,
1075                               GNUNET_TESTING_NotifyConnection
1076                               connect_callback, void *connect_callback_cls,
1077                               const char *hostnames)
1078 {
1079   struct GNUNET_TESTING_PeerGroup *pg;
1080   const char *rpos;
1081   char *pos;
1082   char *start;
1083   const char *hostname;
1084   char *baseservicehome;
1085   char *newservicehome;
1086   char *tmpdir;
1087   struct GNUNET_CONFIGURATION_Handle *pcfg;
1088   unsigned int off;
1089   unsigned int hostcnt;
1090   uint16_t minport;
1091
1092   if (0 == total)
1093     {
1094       GNUNET_break (0);
1095       return NULL;
1096     }
1097   pg = GNUNET_malloc (sizeof (struct GNUNET_TESTING_PeerGroup));
1098   pg->sched = sched;
1099   pg->cfg = cfg;
1100   pg->cb = cb;
1101   pg->cb_cls = cb_cls;
1102   pg->notify_connection = connect_callback;
1103   pg->notify_connection_cls = connect_callback_cls;
1104   pg->total = total;
1105   pg->peers = GNUNET_malloc (total * sizeof (struct PeerData));
1106   if (NULL != hostnames)
1107     {
1108       off = 2;
1109       /* skip leading spaces */
1110       while ((0 != *hostnames) && (isspace (*hostnames)))
1111         hostnames++;
1112       rpos = hostnames;
1113       while ('\0' != *rpos)
1114         {
1115           if (isspace (*rpos))
1116             off++;
1117           rpos++;
1118         }
1119       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
1120       off = 0;
1121       start = GNUNET_strdup (hostnames);
1122       pos = start;
1123       while ('\0' != *pos)
1124         {
1125           if (isspace (*pos))
1126             {
1127               *pos = '\0';
1128               if (strlen (start) > 0)
1129                 {
1130                   pg->hosts[off].minport = LOW_PORT;
1131                   pg->hosts[off++].hostname = start;
1132                 }
1133               start = pos + 1;
1134             }
1135           pos++;
1136         }
1137       if (strlen (start) > 0)
1138         {
1139           pg->hosts[off].minport = LOW_PORT;
1140           pg->hosts[off++].hostname = start;
1141         }
1142       if (off == 0)
1143         {
1144           GNUNET_free (start);
1145           GNUNET_free (pg->hosts);
1146           pg->hosts = NULL;
1147         }
1148       hostcnt = off;
1149       minport = 0;              /* make gcc happy */
1150     }
1151   else
1152     {
1153       hostcnt = 0;
1154       minport = LOW_PORT;
1155     }
1156   for (off = 0; off < total; off++)
1157     {
1158       if (hostcnt > 0)
1159         {
1160           hostname = pg->hosts[off % hostcnt].hostname;
1161           pcfg = make_config (cfg, &pg->hosts[off % hostcnt].minport);
1162         }
1163       else
1164         {
1165           hostname = NULL;
1166           pcfg = make_config (cfg, &minport);
1167         }
1168       if (NULL == pcfg)
1169         {
1170           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1171                       _
1172                       ("Could not create configuration for peer number %u on `%s'!\n"),
1173                       off, hostname == NULL ? "localhost" : hostname);
1174           continue;
1175         }
1176
1177       if (GNUNET_YES ==
1178           GNUNET_CONFIGURATION_get_value_string (pcfg, "PATHS", "SERVICEHOME",
1179                                                  &baseservicehome))
1180         {
1181           GNUNET_asprintf (&newservicehome,
1182                            "%s/%d/", baseservicehome, off);
1183           GNUNET_free (baseservicehome);
1184         }
1185       else
1186         {
1187           tmpdir = getenv ("TMPDIR");
1188           tmpdir = tmpdir ? tmpdir : "/tmp";
1189           GNUNET_asprintf (&newservicehome,
1190                            "%s/%s/%d/",
1191                            tmpdir,
1192                            "gnunet-testing-test-test", off);
1193         }
1194       GNUNET_CONFIGURATION_set_value_string (pcfg,
1195                                              "PATHS",
1196                                              "SERVICEHOME", newservicehome);
1197       GNUNET_free (newservicehome);
1198       pg->peers[off].cfg = pcfg;
1199       pg->peers[off].daemon = GNUNET_TESTING_daemon_start (sched,
1200                                                            pcfg,
1201                                                            hostname,
1202                                                            cb, cb_cls);
1203       if (NULL == pg->peers[off].daemon)
1204         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1205                     _("Could not start peer number %u!\n"), off);
1206     }
1207   return pg;
1208 }
1209
1210 /*
1211  * Get a daemon by number, so callers don't have to do nasty
1212  * offsetting operation.
1213  */
1214 struct GNUNET_TESTING_Daemon *
1215 GNUNET_TESTING_daemon_get (struct GNUNET_TESTING_PeerGroup *pg, unsigned int position)
1216 {
1217   if (position < pg->total)
1218     return pg->peers[position].daemon;
1219   else
1220     return NULL;
1221 }
1222
1223 /**
1224  * Shutdown all peers started in the given group.
1225  * 
1226  * @param pg handle to the peer group
1227  */
1228 void
1229 GNUNET_TESTING_daemons_stop (struct GNUNET_TESTING_PeerGroup *pg)
1230 {
1231   unsigned int off;
1232   struct PeerConnection *pos;
1233   struct PeerConnection *next;
1234
1235   for (off = 0; off < pg->total; off++)
1236     {
1237       /* FIXME: should we wait for our
1238          continuations to be called here? This
1239          would require us to take a continuation
1240          as well... */
1241
1242       if (NULL != pg->peers[off].daemon)
1243         GNUNET_TESTING_daemon_stop (pg->peers[off].daemon, NULL, NULL);
1244       if (NULL != pg->peers[off].cfg)
1245         GNUNET_CONFIGURATION_destroy (pg->peers[off].cfg);
1246
1247       pos = pg->peers[off].connected_peers;
1248       while (pos != NULL)
1249         {
1250           next = pos->next;
1251           GNUNET_free(pos);
1252           pos = next;
1253         }
1254
1255     }
1256   GNUNET_free (pg->peers);
1257   if (NULL != pg->hosts)
1258     {
1259       GNUNET_free (pg->hosts[0].hostname);
1260       GNUNET_free (pg->hosts);
1261     }
1262   GNUNET_free (pg);
1263 }
1264
1265
1266 /* end of testing_group.c */