dce
[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   GNUNET_CONFIGURATION_get_value_string(pg->cfg, "TESTING", "LOGNMODIFIER", &p_string);
315   if ((p_string == NULL) || (sscanf(p_string, "%lf", &logNModifier) != 1))
316     logNModifier = 0.5; /* FIXME: default modifier? */
317
318   GNUNET_free_non_null(p_string);
319
320   GNUNET_CONFIGURATION_get_value_string(pg->cfg, "TESTING", "PERCENTAGE", &p_string);
321   if ((p_string == NULL) || (sscanf(p_string, "%lf", &percentage) != 1))
322     percentage = 0.5; /* FIXME: default percentage? */
323
324   GNUNET_free_non_null(p_string);
325
326   natLog = log (pg->total);
327   connsPerPeer = ceil (natLog * logNModifier);
328
329   if (connsPerPeer % 2 == 1)
330     connsPerPeer += 1;
331
332   smallWorldConnections = 0;
333   connect_attempts = 0;
334   for (i = 0; i < pg->total; i++)
335     {
336       useAnd = 0;
337       max = i + connsPerPeer / 2;
338       min = i - connsPerPeer / 2;
339
340       if (max > pg->total - 1)
341         {
342           max = max - pg->total;
343           useAnd = 1;
344         }
345
346       if (min < 0)
347         {
348           min = pg->total - 1 + min;
349           useAnd = 1;
350         }
351
352       for (j = 0; j < connsPerPeer / 2; j++)
353         {
354           random = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
355                                                       (uint64_t)-1LL)) / ( (double) (uint64_t) -1LL);
356           if (random < percentage)
357             {
358               /* Connect to uniformly selected random peer */
359               randomPeer =
360                 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
361                                    pg->total);
362               while ((((randomPeer < max) && (randomPeer > min))
363                       && (useAnd == 0)) || (((randomPeer > min)
364                                              || (randomPeer < max))
365                                             && (useAnd == 1)))
366                 {
367                   randomPeer =
368                       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
369                                                          pg->total);
370                 }
371               smallWorldConnections +=
372                 add_connections (pg, i, randomPeer);
373             }
374           else
375             {
376               nodeToConnect = i + j + 1;
377               if (nodeToConnect > pg->total - 1)
378                 {
379                   nodeToConnect = nodeToConnect - pg->total;
380                 }
381               connect_attempts +=
382                 add_connections (pg, i, nodeToConnect);
383             }
384         }
385
386     }
387
388   connect_attempts += smallWorldConnections;
389
390   return connect_attempts;
391 }
392
393
394 static int
395 create_nated_internet (struct GNUNET_TESTING_PeerGroup *pg)
396 {
397   unsigned int outer_count, inner_count;
398   unsigned int cutoff;
399   int connect_attempts;
400   double nat_percentage;
401   char *p_string;
402
403   GNUNET_CONFIGURATION_get_value_string(pg->cfg, "TESTING", "NATPERCENTAGE", &p_string);
404   if ((p_string == NULL) || (sscanf(p_string, "%lf", &nat_percentage) != 1))
405     nat_percentage = 0.6; /* FIXME: default modifier? */
406
407   GNUNET_free_non_null(p_string);
408
409   cutoff = (unsigned int) (nat_percentage * pg->total);
410
411   connect_attempts = 0;
412
413   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
414     {
415       for (inner_count = outer_count + 1; inner_count < pg->total;
416            inner_count++)
417         {
418           if ((outer_count > cutoff) || (inner_count > cutoff))
419             {
420 #if VERBOSE_TESTING
421               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
422                           "Connecting peer %d to peer %d\n",
423                           outer_count, inner_count);
424 #endif
425               connect_attempts += add_connections(pg, outer_count, inner_count);
426             }
427         }
428     }
429
430   return connect_attempts;
431
432 }
433
434
435
436 static int
437 create_small_world (struct GNUNET_TESTING_PeerGroup *pg)
438 {
439   unsigned int i, j, k;
440   unsigned int square;
441   unsigned int rows;
442   unsigned int cols;
443   unsigned int toggle = 1;
444   unsigned int nodeToConnect;
445   unsigned int natLog;
446   unsigned int node1Row;
447   unsigned int node1Col;
448   unsigned int node2Row;
449   unsigned int node2Col;
450   unsigned int distance;
451   double probability, random, percentage;
452   unsigned int smallWorldConnections;
453   char *p_string;
454   int connect_attempts;
455   square = floor (sqrt (pg->total));
456   rows = square;
457   cols = square;
458
459   GNUNET_CONFIGURATION_get_value_string(pg->cfg, "TESTING", "PERCENTAGE", &p_string);
460   if ((p_string == NULL) || (sscanf(p_string, "%lf", &percentage) != 1))
461     percentage = 0.5; /* FIXME: default percentage? */
462
463   GNUNET_free_non_null(p_string);
464
465   GNUNET_CONFIGURATION_get_value_string(pg->cfg, "TESTING", "PROBABILITY", &p_string);
466   if ((p_string == NULL) || (sscanf(p_string, "%lf", &probability) != 1))
467     probability = 0.5; /* FIXME: default probability? */
468
469   GNUNET_free_non_null(p_string);
470
471   if (square * square != pg->total)
472     {
473       while (rows * cols < pg->total)
474         {
475           if (toggle % 2 == 0)
476             rows++;
477           else
478             cols++;
479
480           toggle++;
481         }
482     }
483 #if VERBOSE_TESTING
484       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
485                   _("Connecting nodes in 2d torus topology: %u rows %u columns\n"),
486                   rows, cols);
487 #endif
488
489   connect_attempts = 0;
490   /* Rows and columns are all sorted out, now iterate over all nodes and connect each
491    * to the node to its right and above.  Once this is over, we'll have our torus!
492    * Special case for the last node (if the rows and columns are not equal), connect
493    * to the first in the row to maintain topology.
494    */
495   for (i = 0; i < pg->total; i++)
496     {
497       /* First connect to the node to the right */
498       if (((i + 1) % cols != 0) && (i + 1 != pg->total))
499         nodeToConnect = i + 1;
500       else if (i + 1 == pg->total)
501         nodeToConnect = rows * cols - cols;
502       else
503         nodeToConnect = i - cols + 1;
504
505       connect_attempts += add_connections (pg, i, nodeToConnect);
506
507       if (i < cols)
508         nodeToConnect = (rows * cols) - cols + i;
509       else
510         nodeToConnect = i - cols;
511
512       if (nodeToConnect < pg->total)
513         connect_attempts += add_connections (pg, i, nodeToConnect);
514     }
515   natLog = log (pg->total);
516 #if VERBOSE_TESTING
517   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
518               _("natural log of %d is %d, will run %d iterations\n"),
519              pg->total, natLog, (int) (natLog * percentage));
520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Total connections added thus far: %u!\n"), connect_attempts);
521 #endif
522   smallWorldConnections = 0;
523   for (i = 0; i < (int) (natLog * percentage); i++)
524     {
525       for (j = 0; j < pg->total; j++)
526         {
527           /* Determine the row and column of node at position j on the 2d torus */
528           node1Row = j / cols;
529           node1Col = j - (node1Row * cols);
530           for (k = 0; k < pg->total; k++)
531             {
532               /* Determine the row and column of node at position k on the 2d torus */
533               node2Row = k / cols;
534               node2Col = k - (node2Row * cols);
535               /* Simple Cartesian distance */
536               distance = abs (node1Row - node2Row) + abs (node1Col - node2Col);
537               if (distance > 1)
538                 {
539                   /* Calculate probability as 1 over the square of the distance */
540                   probability = 1.0 / (distance * distance);
541                   /* Choose a random value between 0 and 1 */
542                   random = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
543                                                               (uint64_t)-1LL)) / ( (double) (uint64_t) -1LL);
544                   /* If random < probability, then connect the two nodes */
545                   if (random < probability)
546                     smallWorldConnections += add_connections (pg, j, k);
547
548                 }
549             }
550         }
551     }
552   connect_attempts += smallWorldConnections;
553 #if VERBOSE_TESTING
554           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
555                       _("Total connections added for small world: %d!\n"),
556                       smallWorldConnections);
557 #endif
558   return connect_attempts;
559 }
560
561
562
563 static int
564 create_erdos_renyi (struct GNUNET_TESTING_PeerGroup *pg)
565 {
566   double temp_rand;
567   unsigned int outer_count;
568   unsigned int inner_count;
569   int connect_attempts;
570   double probability;
571   char *p_string;
572   connect_attempts = 0;
573
574   GNUNET_CONFIGURATION_get_value_string(pg->cfg, "TESTING", "PROBABILITY", &p_string);
575   if ((p_string == NULL) || (sscanf(p_string, "%lf", &probability) != 1))
576     probability = 0.5; /* FIXME: default probability? */
577
578   GNUNET_free_non_null (p_string);
579   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
580     {
581       for (inner_count = outer_count + 1; inner_count < pg->total;
582            inner_count++)
583         {
584           temp_rand = ((double) GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
585                                                          (uint64_t)-1LL)) / ( (double) (uint64_t) -1LL);
586 #if VERBOSE_TESTING
587           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
588                       _("rand is %f probability is %f\n"), temp_rand,
589                       probability);
590 #endif
591           if (temp_rand < probability)
592             {
593               connect_attempts += add_connections (pg, outer_count, inner_count);
594             }
595         }
596     }
597
598   return connect_attempts;
599 }
600
601 static int
602 create_2d_torus (struct GNUNET_TESTING_PeerGroup *pg)
603 {
604   unsigned int i;
605   unsigned int square;
606   unsigned int rows;
607   unsigned int cols;
608   unsigned int toggle = 1;
609   unsigned int nodeToConnect;
610   int connect_attempts;
611
612   connect_attempts = 0;
613
614   square = floor (sqrt (pg->total));
615   rows = square;
616   cols = square;
617
618   if (square * square != pg->total)
619     {
620       while (rows * cols < pg->total)
621         {
622           if (toggle % 2 == 0)
623             rows++;
624           else
625             cols++;
626
627           toggle++;
628         }
629     }
630 #if VERBOSE_TESTING
631       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
632                   _("Connecting nodes in 2d torus topology: %u rows %u columns\n"),
633                   rows, cols);
634 #endif
635   /* Rows and columns are all sorted out, now iterate over all nodes and connect each
636    * to the node to its right and above.  Once this is over, we'll have our torus!
637    * Special case for the last node (if the rows and columns are not equal), connect
638    * to the first in the row to maintain topology.
639    */
640   for (i = 0; i < pg->total; i++)
641     {
642       /* First connect to the node to the right */
643       if (((i + 1) % cols != 0) && (i + 1 != pg->total))
644         nodeToConnect = i + 1;
645       else if (i + 1 == pg->total)
646         nodeToConnect = rows * cols - cols;
647       else
648         nodeToConnect = i - cols + 1;
649 #if VERBOSE_TESTING
650           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
651                       "Connecting peer %d to peer %d\n",
652                       i, nodeToConnect);
653 #endif
654       connect_attempts += add_connections(pg, i, nodeToConnect);
655
656       /* Second connect to the node immediately above */
657       if (i < cols)
658         nodeToConnect = (rows * cols) - cols + i;
659       else
660         nodeToConnect = i - cols;
661
662       if (nodeToConnect < pg->total)
663         {
664 #if VERBOSE_TESTING
665           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
666                       "Connecting peer %d to peer %d\n",
667                       i, nodeToConnect);
668 #endif
669           connect_attempts += add_connections(pg, i, nodeToConnect);
670         }
671
672     }
673
674   return connect_attempts;
675 }
676
677
678
679 static int
680 create_clique (struct GNUNET_TESTING_PeerGroup *pg)
681 {
682   unsigned int outer_count;
683   unsigned int inner_count;
684   int connect_attempts;
685
686   connect_attempts = 0;
687
688   for (outer_count = 0; outer_count < pg->total - 1; outer_count++)
689     {
690       for (inner_count = outer_count + 1; inner_count < pg->total;
691            inner_count++)
692         {
693 #if VERBOSE_TESTING
694           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
695                       "Connecting peer %d to peer %d\n",
696                       outer_count, inner_count);
697 #endif
698           connect_attempts += add_connections(pg, outer_count, inner_count);
699         }
700     }
701
702   return connect_attempts;
703 }
704
705
706 static int
707 create_ring (struct GNUNET_TESTING_PeerGroup *pg)
708 {
709   unsigned int count;
710   int connect_attempts;
711
712   connect_attempts = 0;
713
714   /* Connect each peer to the next highest numbered peer */
715   for (count = 0; count < pg->total - 1; count++)
716     {
717 #if VERBOSE_TESTING
718           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
719                       "Connecting peer %d to peer %d\n",
720                       count, count + 1);
721 #endif
722       connect_attempts += add_connections(pg, count, count + 1);
723     }
724
725   /* Connect the last peer to the first peer */
726   connect_attempts += add_connections(pg, pg->total - 1, 0);
727
728   return connect_attempts;
729 }
730
731
732 /*
733  * Create the friend files based on the PeerConnection's
734  * of each peer in the peer group, and copy the files
735  * to the appropriate place
736  *
737  * @param pg the peer group we are dealing with
738  */
739 static int
740 create_and_copy_friend_files (struct GNUNET_TESTING_PeerGroup *pg)
741 {
742   FILE *temp_friend_handle;
743   unsigned int pg_iter;
744   struct PeerConnection *connection_iter;
745   struct GNUNET_CRYPTO_HashAsciiEncoded peer_enc;
746   char *temp_service_path;
747   pid_t *pidarr;
748   char *arg;
749   struct GNUNET_PeerIdentity *temppeer;
750   char * mytemp;
751   enum GNUNET_OS_ProcessStatusType type;
752   unsigned long return_code;
753   int count;
754   int ret;
755   int max_wait = 10;
756
757   pidarr = GNUNET_malloc(sizeof(pid_t) * pg->total);
758   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
759     {
760       mytemp = GNUNET_DISK_mktemp("friends");
761       temp_friend_handle = fopen (mytemp, "wt");
762       connection_iter = pg->peers[pg_iter].connected_peers;
763       while (connection_iter != NULL)
764         {
765           temppeer = &connection_iter->daemon->id;
766           GNUNET_CRYPTO_hash_to_enc(&temppeer->hashPubKey, &peer_enc);
767           fprintf(temp_friend_handle, "%s\n", (char *)&peer_enc);
768           connection_iter = connection_iter->next;
769         }
770
771       fclose(temp_friend_handle);
772
773       GNUNET_CONFIGURATION_get_value_string(pg->peers[pg_iter].daemon->cfg, "PATHS", "SERVICEHOME", &temp_service_path);
774
775       if (temp_service_path == NULL)
776         {
777           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
778                     _("No SERVICEHOME specified in peer configuration, can't copy friends file!\n"));
779           if (unlink(mytemp) != 0)
780             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", mytemp);
781           GNUNET_free (mytemp);
782           break;
783         }
784
785       if (pg->peers[pg_iter].daemon->hostname == NULL) /* Local, just copy the file */
786         {
787           GNUNET_asprintf (&arg, "%s/friends", temp_service_path);
788           pidarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "mv",
789                                          "mv", mytemp, arg, NULL);
790 #if VERBOSE_TESTING
791           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
792                       _("Copying file with command cp %s %s\n"), mytemp, arg);
793 #endif
794
795           GNUNET_free(arg);
796         }
797       else /* Remote, scp the file to the correct place */
798         {
799           if (NULL != pg->peers[pg_iter].daemon->username)
800             GNUNET_asprintf (&arg, "%s@%s:%s/friends", pg->peers[pg_iter].daemon->username, pg->peers[pg_iter].daemon->hostname, temp_service_path);
801           else
802             GNUNET_asprintf (&arg, "%s:%s/friends", pg->peers[pg_iter].daemon->hostname, temp_service_path);
803           pidarr[pg_iter] = GNUNET_OS_start_process (NULL, NULL, "scp",
804                                          "scp", mytemp, arg, NULL);
805
806 #if VERBOSE_TESTING
807           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
808                       _("Copying file with command scp %s %s\n"), mytemp, arg);
809 #endif
810           GNUNET_free(arg);
811         }
812       GNUNET_free (temp_service_path);
813       GNUNET_free (mytemp);
814     }
815
816   count = 0;
817   ret = GNUNET_SYSERR;
818   while ((count < max_wait) && (ret != GNUNET_OK))
819     {
820       ret = GNUNET_OK;
821       for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
822         {
823 #if VERBOSE_TESTING
824           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
825                       _("Checking copy status of file %d\n"), pg_iter);
826 #endif
827           if (pidarr[pg_iter] != 0) /* Check for already completed! */
828             {
829               if (GNUNET_OS_process_status(pidarr[pg_iter], &type, &return_code) != GNUNET_OK)
830                 {
831                   ret = GNUNET_SYSERR;
832                 }
833               else if ((type != GNUNET_OS_PROCESS_EXITED) || (return_code != 0))
834                 {
835                   ret = GNUNET_SYSERR;
836                 }
837               else
838                 {
839                   pidarr[pg_iter] = 0;
840 #if VERBOSE_TESTING
841             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
842                       _("File %d copied\n"), pg_iter);
843 #endif
844                 }
845             }
846         }
847       count++;
848       if (ret == GNUNET_SYSERR)
849         {
850           sleep(1);
851         }
852     }
853
854   GNUNET_free(pidarr);
855   return ret;
856 }
857
858
859
860 /*
861  * Connect the topology as specified by the PeerConnection's
862  * of each peer in the peer group
863  *
864  * @param pg the peer group we are dealing with
865  */
866 static void
867 connect_topology (struct GNUNET_TESTING_PeerGroup *pg)
868 {
869   unsigned int pg_iter;
870   struct PeerConnection *connection_iter;
871   int connect_count;
872
873   connect_count = 0;
874   for (pg_iter = 0; pg_iter < pg->total; pg_iter++)
875     {
876       connection_iter = pg->peers[pg_iter].connected_peers;
877       while (connection_iter != NULL)
878         {
879           GNUNET_TESTING_daemons_connect (pg->peers[pg_iter].daemon,
880                                           connection_iter->daemon,
881                                           CONNECT_TIMEOUT,
882                                           pg->notify_connection,
883                                           pg->notify_connection_cls);
884           connection_iter = connection_iter->next;
885           connect_count++;
886           if (connect_count % 50 == 0)
887             {
888 #if VERBOSE_TESTING
889               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
890                           _("Sleeping to give peers a chance to connect!\n"));
891 #endif
892               sleep(2);
893             }
894         }
895     }
896 }
897
898
899 /*
900  * Takes a peer group and attempts to create a topology based on the
901  * one specified in the configuration file.  Returns the number of connections
902  * that will attempt to be created, but this will happen asynchronously(?) so
903  * the caller will have to keep track (via the callback) of whether or not
904  * the connection actually happened.
905  *
906  * @param pg the peer group struct representing the running peers
907  *
908  * @return the number of connections should be created by the topology, so the
909  * caller knows how many to wait for (if it so chooses)
910  *
911  */
912 int
913 GNUNET_TESTING_create_topology (struct GNUNET_TESTING_PeerGroup *pg)
914 {
915   unsigned long long topology_num;
916   int ret;
917   int num_connections;
918
919   GNUNET_assert (pg->notify_connection != NULL);
920   ret = 0;
921   if (GNUNET_YES ==
922       GNUNET_CONFIGURATION_get_value_number (pg->cfg, "testing", "topology",
923                                              &topology_num))
924     {
925       switch (topology_num)
926         {
927         case GNUNET_TESTING_TOPOLOGY_CLIQUE:
928 #if VERBOSE_TESTING
929           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930                       _("Creating clique topology (may take a bit!)\n"));
931 #endif
932           num_connections = create_clique (pg);
933           break;
934         case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING:
935 #if VERBOSE_TESTING
936           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
937                       _("Creating small world (ring) topology (may take a bit!)\n"));
938 #endif
939           num_connections = create_small_world_ring (pg);
940           break;
941         case GNUNET_TESTING_TOPOLOGY_SMALL_WORLD:
942 #if VERBOSE_TESTING
943           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
944                       _("Creating small world (2d-torus) topology (may take a bit!)\n"));
945 #endif
946           num_connections = create_small_world (pg);
947           break;
948         case GNUNET_TESTING_TOPOLOGY_RING:
949 #if VERBOSE_TESTING
950           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
951                       _("Creating ring topology (may take a bit!)\n"));
952 #endif
953           num_connections = create_ring (pg);
954           break;
955         case GNUNET_TESTING_TOPOLOGY_2D_TORUS:
956 #if VERBOSE_TESTING
957           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
958                       _("Creating 2d torus topology (may take a bit!)\n"));
959 #endif
960           num_connections = create_2d_torus (pg);
961           break;
962         case GNUNET_TESTING_TOPOLOGY_ERDOS_RENYI:
963 #if VERBOSE_TESTING
964           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
965                       _("Creating Erdos-Renyi topology (may take a bit!)\n"));
966 #endif
967           num_connections = create_erdos_renyi (pg);
968           break;
969         case GNUNET_TESTING_TOPOLOGY_INTERNAT:
970 #if VERBOSE_TESTING
971           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
972                       _("Creating InterNAT topology (may take a bit!)\n"));
973 #endif
974           num_connections = create_nated_internet (pg);
975           break;
976         case GNUNET_TESTING_TOPOLOGY_NONE:
977           num_connections = 0;
978           break;
979         default:
980           ret = GNUNET_SYSERR;
981           break;
982         }
983       if (num_connections < 1)
984         return GNUNET_SYSERR;
985
986       if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (pg->cfg, "TESTING", "F2F"))
987         ret = create_and_copy_friend_files(pg);
988       if (ret == GNUNET_OK)
989         connect_topology(pg);
990       else
991         {
992 #if VERBOSE_TESTING
993           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
994                       _("Failed during friend file copying!\n"));
995 #endif
996           return GNUNET_SYSERR;
997         }
998     }
999   else
1000     {
1001       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1002                   _("No topology specified, was one intended?\n"));
1003     }
1004
1005   return num_connections;
1006 }
1007
1008 /**
1009  * Start count gnunetd processes with the same set of transports and
1010  * applications.  The port numbers (any option called "PORT") will be
1011  * adjusted to ensure that no two peers running on the same system
1012  * have the same port(s) in their respective configurations.
1013  *
1014  * @param sched scheduler to use 
1015  * @param cfg configuration template to use
1016  * @param total number of daemons to start
1017  * @param cb function to call on each daemon that was started
1018  * @param cb_cls closure for cb
1019  * @param connect_callback function to call each time two hosts are connected
1020  * @param connect_callback_cls closure for connect_callback
1021  * @param hostnames space-separated list of hostnames to use; can be NULL (to run
1022  *        everything on localhost).
1023  * @return NULL on error, otherwise handle to control peer group
1024  */
1025 struct GNUNET_TESTING_PeerGroup *
1026 GNUNET_TESTING_daemons_start (struct GNUNET_SCHEDULER_Handle *sched,
1027                               const struct GNUNET_CONFIGURATION_Handle *cfg,
1028                               unsigned int total,
1029                               GNUNET_TESTING_NotifyDaemonRunning cb,
1030                               void *cb_cls,
1031                               GNUNET_TESTING_NotifyConnection
1032                               connect_callback, void *connect_callback_cls,
1033                               const char *hostnames)
1034 {
1035   struct GNUNET_TESTING_PeerGroup *pg;
1036   const char *rpos;
1037   char *pos;
1038   char *start;
1039   const char *hostname;
1040   char *baseservicehome;
1041   char *newservicehome;
1042   char *tmpdir;
1043   struct GNUNET_CONFIGURATION_Handle *pcfg;
1044   unsigned int off;
1045   unsigned int hostcnt;
1046   uint16_t minport;
1047
1048   if (0 == total)
1049     {
1050       GNUNET_break (0);
1051       return NULL;
1052     }
1053   pg = GNUNET_malloc (sizeof (struct GNUNET_TESTING_PeerGroup));
1054   pg->sched = sched;
1055   pg->cfg = cfg;
1056   pg->cb = cb;
1057   pg->cb_cls = cb_cls;
1058   pg->notify_connection = connect_callback;
1059   pg->notify_connection_cls = connect_callback_cls;
1060   pg->total = total;
1061   pg->peers = GNUNET_malloc (total * sizeof (struct PeerData));
1062   if (NULL != hostnames)
1063     {
1064       off = 2;
1065       /* skip leading spaces */
1066       while ((0 != *hostnames) && (isspace (*hostnames)))
1067         hostnames++;
1068       rpos = hostnames;
1069       while ('\0' != *rpos)
1070         {
1071           if (isspace (*rpos))
1072             off++;
1073           rpos++;
1074         }
1075       pg->hosts = GNUNET_malloc (off * sizeof (struct HostData));
1076       off = 0;
1077       start = GNUNET_strdup (hostnames);
1078       pos = start;
1079       while ('\0' != *pos)
1080         {
1081           if (isspace (*pos))
1082             {
1083               *pos = '\0';
1084               if (strlen (start) > 0)
1085                 {
1086                   pg->hosts[off].minport = LOW_PORT;
1087                   pg->hosts[off++].hostname = start;
1088                 }
1089               start = pos + 1;
1090             }
1091           pos++;
1092         }
1093       if (strlen (start) > 0)
1094         {
1095           pg->hosts[off].minport = LOW_PORT;
1096           pg->hosts[off++].hostname = start;
1097         }
1098       if (off == 0)
1099         {
1100           GNUNET_free (start);
1101           GNUNET_free (pg->hosts);
1102           pg->hosts = NULL;
1103         }
1104       hostcnt = off;
1105       minport = 0;              /* make gcc happy */
1106     }
1107   else
1108     {
1109       hostcnt = 0;
1110       minport = LOW_PORT;
1111     }
1112   for (off = 0; off < total; off++)
1113     {
1114       if (hostcnt > 0)
1115         {
1116           hostname = pg->hosts[off % hostcnt].hostname;
1117           pcfg = make_config (cfg, &pg->hosts[off % hostcnt].minport);
1118         }
1119       else
1120         {
1121           hostname = NULL;
1122           pcfg = make_config (cfg, &minport);
1123         }
1124       if (NULL == pcfg)
1125         {
1126           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1127                       _
1128                       ("Could not create configuration for peer number %u on `%s'!\n"),
1129                       off, hostname == NULL ? "localhost" : hostname);
1130           continue;
1131         }
1132
1133       if (GNUNET_YES ==
1134           GNUNET_CONFIGURATION_get_value_string (pcfg, "PATHS", "SERVICEHOME",
1135                                                  &baseservicehome))
1136         {
1137           GNUNET_asprintf (&newservicehome,
1138                            "%s/%d/", baseservicehome, off);
1139           GNUNET_free (baseservicehome);
1140         }
1141       else
1142         {
1143           tmpdir = getenv ("TMPDIR");
1144           tmpdir = tmpdir ? tmpdir : "/tmp";
1145           GNUNET_asprintf (&newservicehome,
1146                            "%s/%s/%d/",
1147                            tmpdir,
1148                            "gnunet-testing-test-test", off);
1149         }
1150       GNUNET_CONFIGURATION_set_value_string (pcfg,
1151                                              "PATHS",
1152                                              "SERVICEHOME", newservicehome);
1153       GNUNET_free (newservicehome);
1154       pg->peers[off].cfg = pcfg;
1155       pg->peers[off].daemon = GNUNET_TESTING_daemon_start (sched,
1156                                                            pcfg,
1157                                                            hostname,
1158                                                            cb, cb_cls);
1159       if (NULL == pg->peers[off].daemon)
1160         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1161                     _("Could not start peer number %u!\n"), off);
1162     }
1163   return pg;
1164 }
1165
1166 /*
1167  * Get a daemon by number, so callers don't have to do nasty
1168  * offsetting operation.
1169  */
1170 struct GNUNET_TESTING_Daemon *
1171 GNUNET_TESTING_daemon_get (struct GNUNET_TESTING_PeerGroup *pg, unsigned int position)
1172 {
1173   if (position < pg->total)
1174     return pg->peers[position].daemon;
1175   else
1176     return NULL;
1177 }
1178
1179 /**
1180  * Shutdown all peers started in the given group.
1181  * 
1182  * @param pg handle to the peer group
1183  */
1184 void
1185 GNUNET_TESTING_daemons_stop (struct GNUNET_TESTING_PeerGroup *pg)
1186 {
1187   unsigned int off;
1188   struct PeerConnection *pos;
1189   struct PeerConnection *next;
1190
1191   for (off = 0; off < pg->total; off++)
1192     {
1193       /* FIXME: should we wait for our
1194          continuations to be called here? This
1195          would require us to take a continuation
1196          as well... */
1197
1198       if (NULL != pg->peers[off].daemon)
1199         GNUNET_TESTING_daemon_stop (pg->peers[off].daemon, NULL, NULL);
1200       if (NULL != pg->peers[off].cfg)
1201         GNUNET_CONFIGURATION_destroy (pg->peers[off].cfg);
1202
1203       pos = pg->peers[off].connected_peers;
1204       while (pos != NULL)
1205         {
1206           next = pos->next;
1207           GNUNET_free(pos);
1208           pos = next;
1209         }
1210
1211     }
1212   GNUNET_free (pg->peers);
1213   if (NULL != pg->hosts)
1214     {
1215       GNUNET_free (pg->hosts[0].hostname);
1216       GNUNET_free (pg->hosts);
1217     }
1218   GNUNET_free (pg);
1219 }
1220
1221
1222 /* end of testing_group.c */