- fix 2699
[oweals/gnunet.git] / src / testing / testing.c
1 /*
2       This file is part of GNUnet
3       (C) 2008, 2009, 2012 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.c
23  * @brief convenience API for writing testcases for GNUnet
24  *        Many testcases need to start and stop a peer/service
25  *        and this library is supposed to make that easier
26  *        for TESTCASES.  Normal programs should always
27  *        use functions from gnunet_{util,arm}_lib.h.  This API is
28  *        ONLY for writing testcases (or internal use of the testbed).
29  * @author Christian Grothoff
30  *
31  */
32 #include "platform.h"
33 #include "gnunet_util_lib.h"
34 #include "gnunet_testing_lib.h"
35
36 #define LOG(kind,...)                                           \
37   GNUNET_log_from (kind, "testing-api", __VA_ARGS__)
38
39
40 /**
41  * We need pipe control only on WINDOWS
42  */
43 #if WINDOWS
44 #define PIPE_CONTROL GNUNET_YES
45 #else
46 #define PIPE_CONTROL GNUNET_NO
47 #endif
48
49
50 /**
51  * Lowest port used for GNUnet testing.  Should be high enough to not
52  * conflict with other applications running on the hosts but be low
53  * enough to not conflict with client-ports (typically starting around
54  * 32k).
55  */
56 #define LOW_PORT 12000
57
58 /**
59  * Highest port used for GNUnet testing.  Should be low enough to not
60  * conflict with the port range for "local" ports (client apps; see
61  * /proc/sys/net/ipv4/ip_local_port_range on Linux for example).
62  */
63 #define HIGH_PORT 56000
64
65
66 /**
67  * Handle for a system on which GNUnet peers are executed;
68  * a system is used for reserving unique paths and ports.
69  */
70 struct GNUNET_TESTING_System
71 {
72   /**
73    * Prefix (i.e. "/tmp/gnunet-testing/") we prepend to each
74    * SERVICEHOME.    */
75   char *tmppath;
76
77   /**
78    * The trusted ip. Can either be a single ip address or a network address in
79    * CIDR notation.
80    */
81   char *trusted_ip;
82
83   /**
84    * our hostname
85    */
86   char *hostname;
87
88   /**
89    * Hostkeys data, contains "GNUNET_TESTING_HOSTKEYFILESIZE * total_hostkeys" bytes.
90    */
91   char *hostkeys_data;
92
93   /**
94    * memory map for 'hostkeys_data'.
95    */
96   struct GNUNET_DISK_MapHandle *map;
97
98   /**
99    * File descriptor for the map.
100    */
101   struct GNUNET_DISK_FileHandle *map_fd;
102
103   /**
104    * Bitmap where each TCP port that has already been reserved for
105    * some GNUnet peer is recorded.  Note that we additionally need to
106    * test if a port is already in use by non-GNUnet components before
107    * assigning it to a peer/service.  If we detect that a port is
108    * already in use, we also mark it in this bitmap.  So all the bits
109    * that are zero merely indicate ports that MIGHT be available for
110    * peers.
111    */
112   uint32_t reserved_tcp_ports[65536 / 32];
113
114   /**
115    * Bitmap where each UDP port that has already been reserved for
116    * some GNUnet peer is recorded.  Note that we additionally need to
117    * test if a port is already in use by non-GNUnet components before
118    * assigning it to a peer/service.  If we detect that a port is
119    * already in use, we also mark it in this bitmap.  So all the bits
120    * that are zero merely indicate ports that MIGHT be available for
121    * peers.
122    */
123   uint32_t reserved_udp_ports[65536 / 32];
124
125   /**
126    * Counter we use to make service home paths unique on this system;
127    * the full path consists of the tmppath and this number.  Each
128    * UNIXPATH for a peer is also modified to include the respective
129    * path counter to ensure uniqueness.  This field is incremented
130    * by one for each configured peer.  Even if peers are destroyed,
131    * we never re-use path counters.
132    */
133   uint32_t path_counter;  
134
135   /**
136    * The number of hostkeys
137    */
138   uint32_t total_hostkeys;
139
140   /**
141    * Lowest port we are allowed to use.
142    */
143   uint16_t lowport;
144
145   /**
146    * Highest port we are allowed to use.
147    */
148   uint16_t highport;
149 };
150
151
152 /**
153  * Handle for a GNUnet peer controlled by testing.
154  */
155 struct GNUNET_TESTING_Peer
156 {
157   /**
158    * The TESTING system associated with this peer
159    */
160   struct GNUNET_TESTING_System *system;
161
162   /**
163    * Path to the configuration file for this peer.
164    */
165   char *cfgfile;
166
167   /**
168    * Binary to be executed during 'GNUNET_TESTING_peer_start'.
169    * Typically 'gnunet-service-arm' (but can be set to a 
170    * specific service by 'GNUNET_TESTING_service_run' if
171    * necessary).
172    */ 
173   char *main_binary;
174   char *args;
175   
176   /**
177    * Handle to the running binary of the service, NULL if the
178    * peer/service is currently not running.
179    */
180   struct GNUNET_OS_Process *main_process;
181
182   /**
183    * The keynumber of this peer's hostkey
184    */
185   uint32_t key_number;
186 };
187
188
189 /**
190  * Testing includes a number of pre-created hostkeys for faster peer
191  * startup. This function loads such keys into memory from a file.
192  *
193  * @param system the testing system handle
194  * @return GNUNET_OK on success; GNUNET_SYSERR on error
195  */
196 static int
197 hostkeys_load (struct GNUNET_TESTING_System *system)
198 {
199   uint64_t fs; 
200   char *data_dir;
201   char *filename;
202   
203   GNUNET_assert (NULL == system->hostkeys_data);
204   data_dir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
205   GNUNET_asprintf (&filename, "%s/testing_hostkeys.ecc", data_dir);
206   GNUNET_free (data_dir);  
207
208   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
209   {
210     LOG (GNUNET_ERROR_TYPE_ERROR,
211          _("Hostkeys file not found: %s\n"), filename);
212     GNUNET_free (filename);
213     return GNUNET_SYSERR;
214   }
215   /* Check hostkey file size, read entire thing into memory */
216   if (GNUNET_OK != 
217       GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
218     fs = 0;
219   if (0 == fs)
220   {
221     GNUNET_free (filename);
222     return GNUNET_SYSERR;       /* File is empty */
223   }
224   if (0 != (fs % GNUNET_TESTING_HOSTKEYFILESIZE))
225   {
226     LOG (GNUNET_ERROR_TYPE_ERROR,
227          _("Incorrect hostkey file format: %s\n"), filename);
228     GNUNET_free (filename);
229     return GNUNET_SYSERR;
230   }
231   system->map_fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
232                                          GNUNET_DISK_PERM_NONE);
233   if (NULL == system->map_fd)
234   {
235     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", filename);
236     GNUNET_free (filename);
237     return GNUNET_SYSERR;
238   }
239   system->total_hostkeys = fs / GNUNET_TESTING_HOSTKEYFILESIZE;
240   system->hostkeys_data = GNUNET_DISK_file_map (system->map_fd,
241                                                 &system->map,
242                                                 GNUNET_DISK_MAP_TYPE_READ,
243                                                 fs);
244   GNUNET_free (filename);
245   return GNUNET_OK;
246 }
247
248
249 /**
250  * Function to remove the loaded hostkeys
251  *
252  * @param system the testing system handle
253  */
254 static void
255 hostkeys_unload (struct GNUNET_TESTING_System *system)
256 {
257   GNUNET_break (NULL != system->hostkeys_data);
258   system->hostkeys_data = NULL;
259   GNUNET_DISK_file_unmap (system->map);
260   system->map = NULL;
261   GNUNET_DISK_file_close (system->map_fd);
262   system->map_fd = NULL;
263   system->hostkeys_data = NULL;
264   system->total_hostkeys = 0;
265 }
266
267
268 /**
269  * Create a system handle.  There must only be one system
270  * handle per operating system.
271  *
272  * @param testdir only the directory name without any path. This is used for
273  *          all service homes; the directory will be created in a temporary
274  *          location depending on the underlying OS
275  * @param trusted_ip the ip address which will be set as TRUSTED HOST in all
276  *          service configurations generated to allow control connections from
277  *          this ip. This can either be a single ip address or a network address
278  *          in CIDR notation.
279  * @param hostname the hostname of the system we are using for testing; NULL for
280  *          localhost
281  * @param lowport lowest port number this system is allowed to allocate (inclusive)
282  * @param highport highest port number this system is allowed to allocate (exclusive)
283  * @return handle to this system, NULL on error
284  */
285 struct GNUNET_TESTING_System *
286 GNUNET_TESTING_system_create_with_portrange (const char *testdir,
287                                              const char *trusted_ip,
288                                              const char *hostname,
289                                              uint16_t lowport,
290                                              uint16_t highport)
291 {
292   struct GNUNET_TESTING_System *system;
293
294   GNUNET_assert (NULL != testdir);
295   system = GNUNET_malloc (sizeof (struct GNUNET_TESTING_System));
296   system->tmppath = GNUNET_DISK_mkdtemp (testdir);
297   system->lowport = lowport;
298   system->highport = highport;
299   if (NULL == system->tmppath)
300   {
301     GNUNET_free (system);
302     return NULL;
303   }
304   if (NULL != trusted_ip)
305     system->trusted_ip = GNUNET_strdup (trusted_ip);
306   if (NULL != hostname)
307     system->hostname = GNUNET_strdup (hostname);
308   if (GNUNET_OK != hostkeys_load (system))
309   {
310     GNUNET_TESTING_system_destroy (system, GNUNET_YES);
311     return NULL;
312   }
313   return system;
314 }
315
316
317 /**
318  * Create a system handle.  There must only be one system handle per operating
319  * system.  Uses a default range for allowed ports.  Ports are still tested for
320  * availability.
321  *
322  * @param testdir only the directory name without any path. This is used for all
323  *          service homes; the directory will be created in a temporary location
324  *          depending on the underlying OS
325  * @param trusted_ip the ip address which will be set as TRUSTED HOST in all
326  *          service configurations generated to allow control connections from
327  *          this ip. This can either be a single ip address or a network address
328  *          in CIDR notation.
329  * @param hostname the hostname of the system we are using for testing; NULL for
330  *          localhost
331  * @return handle to this system, NULL on error
332  */
333 struct GNUNET_TESTING_System *
334 GNUNET_TESTING_system_create (const char *testdir,
335                               const char *trusted_ip,
336                               const char *hostname)
337 {
338   return GNUNET_TESTING_system_create_with_portrange (testdir,
339                                                       trusted_ip,
340                                                       hostname,
341                                                       LOW_PORT,
342                                                       HIGH_PORT);
343 }
344
345
346 /**
347  * Free system resources.
348  *
349  * @param system system to be freed
350  * @param remove_paths should the 'testdir' and all subdirectories
351  *        be removed (clean up on shutdown)?
352  */
353 void
354 GNUNET_TESTING_system_destroy (struct GNUNET_TESTING_System *system,
355                                int remove_paths)
356 {
357   if (NULL != system->hostkeys_data)
358     hostkeys_unload (system);
359   if (GNUNET_YES == remove_paths)
360     GNUNET_DISK_directory_remove (system->tmppath);
361   GNUNET_free (system->tmppath);
362   GNUNET_free_non_null (system->trusted_ip);
363   GNUNET_free_non_null (system->hostname);
364   GNUNET_free (system);
365 }
366
367
368 /**
369  * Reserve a TCP or UDP port for a peer.
370  *
371  * @param system system to use for reservation tracking
372  * @param is_tcp GNUNET_YES for TCP ports, GNUNET_NO for UDP
373  * @return 0 if no free port was available
374  */
375 uint16_t 
376 GNUNET_TESTING_reserve_port (struct GNUNET_TESTING_System *system,
377                              int is_tcp)
378 {
379   struct GNUNET_NETWORK_Handle *socket;
380   struct addrinfo hint;
381   struct addrinfo *ret;
382   struct addrinfo *ai;
383   uint32_t *port_buckets;
384   char *open_port_str;
385   int bind_status;
386   uint32_t xor_image;
387   uint16_t index;
388   uint16_t open_port;
389   uint16_t pos;
390
391   /*
392   FIXME: Instead of using getaddrinfo we should try to determine the port
393          status by the following heurestics.
394   
395          On systems which support both IPv4 and IPv6, only ports open on both
396          address families are considered open.
397          On system with either IPv4 or IPv6. A port is considered open if it's
398          open in the respective address family
399   */
400   hint.ai_family = AF_UNSPEC;   /* IPv4 and IPv6 */
401   hint.ai_socktype = (GNUNET_YES == is_tcp)? SOCK_STREAM : SOCK_DGRAM;
402   hint.ai_protocol = 0;
403   hint.ai_addrlen = 0;
404   hint.ai_addr = NULL;
405   hint.ai_canonname = NULL;
406   hint.ai_next = NULL;
407   hint.ai_flags = AI_PASSIVE | AI_NUMERICSERV;  /* Wild card address */
408   port_buckets = (GNUNET_YES == is_tcp) ?
409     system->reserved_tcp_ports : system->reserved_udp_ports;
410   for (index = (system->lowport / 32) + 1; index < (system->highport / 32); index++)
411   {
412     xor_image = (UINT32_MAX ^ port_buckets[index]);
413     if (0 == xor_image)        /* Ports in the bucket are full */
414       continue;
415     pos = system->lowport % 32;
416     while (pos < 32)
417     {
418       if (0 == ((xor_image >> pos) & 1U))
419       {
420         pos++;
421         continue;
422       }
423       open_port = (index * 32) + pos;
424       if (open_port >= system->highport)
425         return 0;
426       GNUNET_asprintf (&open_port_str, "%u", (unsigned int) open_port);
427       ret = NULL;
428       GNUNET_assert (0 == getaddrinfo (NULL, open_port_str, &hint, &ret));
429       GNUNET_free (open_port_str);
430       bind_status = GNUNET_NO;
431       for (ai = ret; NULL != ai; ai = ai->ai_next)
432       {
433         socket = GNUNET_NETWORK_socket_create (ai->ai_family,
434                                                (GNUNET_YES == is_tcp) ?
435                                                SOCK_STREAM : SOCK_DGRAM,
436                                                0);
437         if (NULL == socket)
438           continue;
439         bind_status = GNUNET_NETWORK_socket_bind (socket,
440                                                   ai->ai_addr,
441                                                   ai->ai_addrlen);
442         GNUNET_NETWORK_socket_close (socket);
443         if (GNUNET_OK != bind_status)
444           break;
445       }
446       port_buckets[index] |= (1U << pos); /* Set the port bit */
447       freeaddrinfo (ret);
448       if (GNUNET_OK == bind_status)
449       {
450         LOG (GNUNET_ERROR_TYPE_DEBUG,
451              "Found a free port %u\n", (unsigned int) open_port);
452         return open_port;
453       }
454       pos++;
455     }
456   }
457   return 0;
458 }
459
460
461 /**
462  * Release reservation of a TCP or UDP port for a peer
463  * (used during GNUNET_TESTING_peer_destroy).
464  *
465  * @param system system to use for reservation tracking
466  * @param is_tcp GNUNET_YES for TCP ports, GNUNET_NO for UDP
467  * @param port reserved port to release
468  */
469 void
470 GNUNET_TESTING_release_port (struct GNUNET_TESTING_System *system,
471                              int is_tcp,
472                              uint16_t port)
473 {
474   uint32_t *port_buckets;
475   uint16_t bucket;
476   uint16_t pos;
477
478   port_buckets = (GNUNET_YES == is_tcp) ?
479     system->reserved_tcp_ports : system->reserved_udp_ports;
480   bucket = port / 32;
481   pos = port % 32;
482   LOG (GNUNET_ERROR_TYPE_DEBUG, "Releasing port %u\n", port);
483   if (0 == (port_buckets[bucket] & (1U << pos)))
484   {
485     GNUNET_break(0); /* Port was not reserved by us using reserve_port() */
486     return;
487   }
488   port_buckets[bucket] &= ~(1U << pos);
489 }
490
491
492 /**
493  * Reserve a SERVICEHOME path for a peer.
494  *
495  * @param system system to use for reservation tracking
496  * @return NULL on error, otherwise fresh unique path to use
497  *         as the servicehome for the peer; must be freed by the caller
498  */
499 // static 
500 char *
501 reserve_path (struct GNUNET_TESTING_System *system)
502 {
503   char *reserved_path;
504
505   GNUNET_asprintf (&reserved_path,
506                    "%s/%u", system->tmppath, system->path_counter++);
507   return reserved_path;
508 }             
509
510
511 /**
512  * Testing includes a number of pre-created hostkeys for
513  * faster peer startup.  This function can be used to
514  * access the n-th key of those pre-created hostkeys; note
515  * that these keys are ONLY useful for testing and not
516  * secure as the private keys are part of the public 
517  * GNUnet source code.
518  *
519  * This is primarily a helper function used internally
520  * by 'GNUNET_TESTING_peer_configure'.
521  *
522  * @param system the testing system handle
523  * @param key_number desired pre-created hostkey to obtain
524  * @param id set to the peer's identity (hash of the public
525  *        key; if NULL, GNUNET_SYSERR is returned immediately
526  * @return NULL on error (not enough keys)
527  */
528 struct GNUNET_CRYPTO_EccPrivateKey *
529 GNUNET_TESTING_hostkey_get (const struct GNUNET_TESTING_System *system,
530                             uint32_t key_number,
531                             struct GNUNET_PeerIdentity *id)
532 {  
533   struct GNUNET_CRYPTO_EccPrivateKey *private_key;
534   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded public_key;
535   
536   if ((NULL == id) || (NULL == system->hostkeys_data))
537     return NULL;
538   if (key_number >= system->total_hostkeys)
539   {
540     LOG (GNUNET_ERROR_TYPE_ERROR,
541          _("Key number %u does not exist\n"), key_number);
542     return NULL;
543   }   
544   private_key = GNUNET_CRYPTO_ecc_decode_key (system->hostkeys_data +
545                                               (key_number *
546                                                GNUNET_TESTING_HOSTKEYFILESIZE),
547                                               GNUNET_TESTING_HOSTKEYFILESIZE);
548   if (NULL == private_key)
549   {
550     LOG (GNUNET_ERROR_TYPE_ERROR,
551          _("Error while decoding key %u\n"), key_number);
552     return NULL;
553   }
554   GNUNET_CRYPTO_ecc_key_get_public (private_key, &public_key);
555   GNUNET_CRYPTO_hash (&public_key,
556                       sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded),
557                       &(id->hashPubKey));
558   return private_key;
559 }
560
561
562 /**
563  * Structure for holding data to build new configurations from a configuration
564  * template
565  */
566 struct UpdateContext
567 {
568   /**
569    * The system for which we are building configurations
570    */
571   struct GNUNET_TESTING_System *system;
572   
573   /**
574    * The configuration we are building
575    */
576   struct GNUNET_CONFIGURATION_Handle *cfg;
577
578   /**
579    * The customized service home path for this peer
580    */
581   char *service_home;
582
583   /**
584    * build status - to signal error while building a configuration
585    */
586   int status;
587 };
588
589
590 /**
591  * Function to iterate over options.  Copies
592  * the options to the target configuration,
593  * updating PORT values as needed.
594  *
595  * @param cls the UpdateContext
596  * @param section name of the section
597  * @param option name of the option
598  * @param value value of the option
599  */
600 static void
601 update_config (void *cls, const char *section, const char *option,
602                const char *value)
603 {
604   struct UpdateContext *uc = cls;
605   unsigned int ival;
606   char cval[12];
607   char uval[128];
608   char *single_variable;
609   char *per_host_variable;
610   unsigned long long num_per_host;
611   uint16_t new_port;
612
613   if (GNUNET_OK != uc->status)
614     return;
615   if (! ((0 == strcmp (option, "PORT"))
616          || (0 == strcmp (option, "UNIXPATH"))
617          || (0 == strcmp (option, "HOSTNAME"))))
618     return;
619   GNUNET_asprintf (&single_variable, "single_%s_per_host", section);
620   GNUNET_asprintf (&per_host_variable, "num_%s_per_host", section);
621   if ((0 == strcmp (option, "PORT")) && (1 == SSCANF (value, "%u", &ival)))
622   {
623     if ((ival != 0) &&
624         (GNUNET_YES !=
625          GNUNET_CONFIGURATION_get_value_yesno (uc->cfg, "testing",
626                                                single_variable)))
627     {
628       /* FIXME: What about UDP? */
629       new_port = GNUNET_TESTING_reserve_port (uc->system, GNUNET_YES);
630       if (0 == new_port)
631       {
632         uc->status = GNUNET_SYSERR;
633         GNUNET_free (single_variable);
634         GNUNET_free (per_host_variable);
635         return;
636       }
637       GNUNET_snprintf (cval, sizeof (cval), "%u", new_port);
638       value = cval;
639     }
640     else if ((ival != 0) &&
641              (GNUNET_YES ==
642               GNUNET_CONFIGURATION_get_value_yesno (uc->cfg, "testing",
643                                                     single_variable)) &&
644              GNUNET_CONFIGURATION_get_value_number (uc->cfg, "testing",
645                                                     per_host_variable,
646                                                     &num_per_host))
647     {
648       /* GNUNET_snprintf (cval, sizeof (cval), "%u", */
649       /*                  ival + ctx->fdnum % num_per_host); */
650       /* value = cval; */
651       GNUNET_break (0);         /* FIXME */
652     }
653   }
654   if (0 == strcmp (option, "UNIXPATH"))
655   {
656     if (GNUNET_YES !=
657         GNUNET_CONFIGURATION_get_value_yesno (uc->cfg, "testing",
658                                               single_variable))
659     {
660       GNUNET_snprintf (uval, sizeof (uval), "%s/%s.sock",
661                        uc->service_home, section);
662       value = uval;
663     }
664     else if ((GNUNET_YES ==
665               GNUNET_CONFIGURATION_get_value_number (uc->cfg, "testing",
666                                                      per_host_variable,
667                                                      &num_per_host)) &&
668              (num_per_host > 0))
669     {
670       GNUNET_break(0);          /* FIXME */
671     }
672   }
673   if (0 == strcmp (option, "HOSTNAME"))
674   {
675     value = (NULL == uc->system->hostname) ? "localhost" : uc->system->hostname;
676   }
677   GNUNET_free (single_variable);
678   GNUNET_free (per_host_variable);
679   GNUNET_CONFIGURATION_set_value_string (uc->cfg, section, option, value);
680 }
681
682
683 /**
684  * Section iterator to set ACCEPT_FROM/ACCEPT_FROM6 to include the address of
685  * 'trusted_hosts' in all sections
686  *
687  * @param cls the UpdateContext
688  * @param section name of the section
689  */
690 static void
691 update_config_sections (void *cls,
692                         const char *section)
693 {
694   struct UpdateContext *uc = cls;  
695   char **ikeys;
696   char *val;
697   char *ptr;
698   char *orig_allowed_hosts;
699   char *allowed_hosts;
700   char *ACCEPT_FROM_key;
701   uint16_t ikeys_cnt;
702   uint16_t key;
703   
704   ikeys_cnt = 0;
705   val = NULL;
706   if (GNUNET_YES == GNUNET_CONFIGURATION_have_value (uc->cfg, section,
707                                                      "TESTING_IGNORE_KEYS"))
708   {
709     GNUNET_assert 
710       (GNUNET_YES == 
711        GNUNET_CONFIGURATION_get_value_string (uc->cfg, section,
712                                               "TESTING_IGNORE_KEYS", &val));
713     ptr = val;
714     for (ikeys_cnt = 0; NULL != (ptr = strstr (ptr, ";")); ikeys_cnt++)
715       ptr++;
716     if (0 == ikeys_cnt)
717       GNUNET_break (0);
718     else
719     {
720       ikeys = GNUNET_malloc ((sizeof (char *)) * ikeys_cnt);
721       ptr = val;
722       for (key = 0; key < ikeys_cnt; key++)
723       {
724         ikeys[key] = ptr;
725         ptr = strstr (ptr, ";");
726         *ptr = '\0';
727         ptr++;
728       }
729     }
730   }
731   if (0 != ikeys_cnt)
732   {
733     for (key = 0; key < ikeys_cnt; key++)
734     {
735       if (NULL != strstr (ikeys[key], "ADVERTISED_PORT"))
736         break;
737     }
738     if ((key == ikeys_cnt) &&
739         (GNUNET_YES == GNUNET_CONFIGURATION_have_value (uc->cfg, section,
740                                                         "ADVERTISED_PORT")))
741     {
742       if (GNUNET_OK == 
743           GNUNET_CONFIGURATION_get_value_string (uc->cfg, section, "PORT", &ptr))
744       {
745         GNUNET_CONFIGURATION_set_value_string (uc->cfg, section, 
746                                                "ADVERTISED_PORT", ptr);
747         GNUNET_free (ptr);
748       }
749     }
750     for (key = 0; key < ikeys_cnt; key++)
751     {
752       if (NULL != strstr (ikeys[key], "ACCEPT_FROM"))
753       {
754         GNUNET_free (ikeys);
755         GNUNET_free (val);
756         return;
757       }
758     }
759     GNUNET_free (ikeys);
760   }
761   GNUNET_free_non_null (val);
762   ACCEPT_FROM_key = "ACCEPT_FROM";  
763   if ((NULL != uc->system->trusted_ip) && 
764       (NULL != strstr (uc->system->trusted_ip, ":"))) /* IPv6 in use */
765     ACCEPT_FROM_key = "ACCEPT_FROM6";
766   if (GNUNET_OK != 
767       GNUNET_CONFIGURATION_get_value_string (uc->cfg, section, ACCEPT_FROM_key,
768                                              &orig_allowed_hosts))
769   {
770     orig_allowed_hosts = GNUNET_strdup ("127.0.0.1;");
771   }
772   if (NULL == uc->system->trusted_ip)
773     allowed_hosts = GNUNET_strdup (orig_allowed_hosts);
774   else
775     GNUNET_asprintf (&allowed_hosts, "%s%s;", orig_allowed_hosts,
776                      uc->system->trusted_ip);
777   GNUNET_free (orig_allowed_hosts);
778   GNUNET_CONFIGURATION_set_value_string (uc->cfg, section, ACCEPT_FROM_key,
779                                          allowed_hosts);
780   GNUNET_free (allowed_hosts);  
781 }
782
783
784 /**
785  * Create a new configuration using the given configuration as a template;
786  * ports and paths will be modified to select available ports on the local
787  * system. The default configuration will be available in PATHS section under
788  * the option DEFAULTCONFIG after the call. SERVICE_HOME is also set in PATHS
789  * section to the temporary directory specific to this configuration. If we run
790  * out of "*port" numbers, return SYSERR.
791  *
792  * This is primarily a helper function used internally
793  * by 'GNUNET_TESTING_peer_configure'.
794  *
795  * @param system system to use to coordinate resource usage
796  * @param cfg template configuration to update
797  * @return GNUNET_OK on success, GNUNET_SYSERR on error - the configuration will
798  *           be incomplete and should not be used there upon
799  */
800 int
801 GNUNET_TESTING_configuration_create (struct GNUNET_TESTING_System *system,
802                                      struct GNUNET_CONFIGURATION_Handle *cfg)
803 {
804   struct UpdateContext uc;
805   char *default_config;
806   
807   uc.system = system;
808   uc.cfg = cfg;
809   uc.status = GNUNET_OK;
810   GNUNET_asprintf (&uc.service_home, "%s/%u", system->tmppath,
811                    system->path_counter++);
812   GNUNET_asprintf (&default_config, "%s/config", uc.service_home);
813   GNUNET_CONFIGURATION_set_value_string (cfg, "PATHS", "DEFAULTCONFIG",
814                                          default_config);
815   GNUNET_free (default_config);
816   GNUNET_CONFIGURATION_set_value_string (cfg, "PATHS", "SERVICEHOME",
817                                          uc.service_home);
818   /* make PORTs and UNIXPATHs unique */
819   GNUNET_CONFIGURATION_iterate (cfg, &update_config, &uc);
820   /* allow connections to services from system trusted_ip host */
821   GNUNET_CONFIGURATION_iterate_sections (cfg, &update_config_sections, &uc);
822   /* enable loopback-based connections between peers */
823   GNUNET_CONFIGURATION_set_value_string (cfg, 
824                                          "nat",
825                                          "USE_LOCALADDR", "YES");
826   GNUNET_free (uc.service_home);
827   return uc.status;
828 }
829
830
831 /**
832  * Configure a GNUnet peer.  GNUnet must be installed on the local
833  * system and available in the PATH. 
834  *
835  * @param system system to use to coordinate resource usage
836  * @param cfg configuration to use; will be UPDATED (to reflect needed
837  *            changes in port numbers and paths)
838  * @param key_number number of the hostkey to use for the peer
839  * @param id identifier for the daemon, will be set, can be NULL
840  * @param emsg set to freshly allocated error message (set to NULL on success), 
841  *          can be NULL
842  * @return handle to the peer, NULL on error
843  */
844 struct GNUNET_TESTING_Peer *
845 GNUNET_TESTING_peer_configure (struct GNUNET_TESTING_System *system,
846                                struct GNUNET_CONFIGURATION_Handle *cfg,
847                                uint32_t key_number,
848                                struct GNUNET_PeerIdentity *id,
849                                char **emsg)
850 {
851   struct GNUNET_TESTING_Peer *peer;
852   struct GNUNET_DISK_FileHandle *fd;
853   char *service_home;  
854   char hostkey_filename[128];
855   char *config_filename;
856   char *libexec_binary;
857   char *emsg_;
858   struct GNUNET_CRYPTO_EccPrivateKey *pk;
859
860   if (NULL != emsg)
861     *emsg = NULL;
862   if (GNUNET_OK != GNUNET_TESTING_configuration_create (system, cfg))
863   {
864     GNUNET_asprintf (&emsg_,
865                        _("Failed to create configuration for peer (not enough free ports?)\n"));
866     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s", emsg_);
867     if (NULL != emsg)
868       *emsg = emsg_;
869     else
870       GNUNET_free (emsg_);
871     return NULL;
872   }
873   if (key_number >= system->total_hostkeys)
874   {
875     GNUNET_asprintf (&emsg_,
876                      _("You attempted to create a testbed with more than %u hosts.  Please precompute more hostkeys first.\n"),
877                      (unsigned int) system->total_hostkeys);    
878     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s", emsg_);
879     if (NULL != emsg)
880       *emsg = emsg_;
881     else
882       GNUNET_free (emsg_);
883     return NULL;
884   }
885   pk = NULL;
886   if ((NULL != id) &&
887       (NULL == (pk = GNUNET_TESTING_hostkey_get (system, key_number, id))))
888   {
889     GNUNET_asprintf (&emsg_,
890                      _("Failed to initialize hostkey for peer %u\n"),
891                      (unsigned int) key_number);
892     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s", emsg_);
893     if (NULL != emsg)
894       *emsg = emsg_;
895     else
896       GNUNET_free (emsg_);
897     return NULL;
898   }
899   if (NULL != pk)
900     GNUNET_CRYPTO_ecc_key_free (pk);
901   GNUNET_assert (GNUNET_OK == 
902                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
903                                                         "SERVICEHOME",
904                                                         &service_home));
905   /* FIXME: might be better to evaluate actual configuration option here... */
906   GNUNET_snprintf (hostkey_filename, sizeof (hostkey_filename), "%s/private.ecc",
907                    service_home);
908   GNUNET_free (service_home);
909   fd = GNUNET_DISK_file_open (hostkey_filename,
910                               GNUNET_DISK_OPEN_CREATE | GNUNET_DISK_OPEN_WRITE,
911                               GNUNET_DISK_PERM_USER_READ 
912                               | GNUNET_DISK_PERM_USER_WRITE);
913   if (NULL == fd)
914   {
915     GNUNET_break (0); 
916     return NULL;
917   }
918   if (GNUNET_TESTING_HOSTKEYFILESIZE !=
919       GNUNET_DISK_file_write (fd, system->hostkeys_data 
920                               + (key_number * GNUNET_TESTING_HOSTKEYFILESIZE),
921                               GNUNET_TESTING_HOSTKEYFILESIZE))
922   {
923     GNUNET_asprintf (&emsg_,
924                      _("Failed to write hostkey file for peer %u: %s\n"),
925                      (unsigned int) key_number,
926                      STRERROR (errno));
927     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s", emsg_);
928     if (NULL != emsg)
929       *emsg = emsg_;
930     else
931       GNUNET_free (emsg_);
932     GNUNET_DISK_file_close (fd);
933     return NULL;
934   }
935   GNUNET_DISK_file_close (fd);
936   GNUNET_assert (GNUNET_OK ==
937                  GNUNET_CONFIGURATION_get_value_string 
938                  (cfg, "PATHS", "DEFAULTCONFIG", &config_filename));  
939   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config_filename))
940   {
941     GNUNET_asprintf (&emsg_,
942                      _("Failed to write configuration file `%s' for peer %u: %s\n"),
943                      config_filename,
944                      (unsigned int) key_number,
945                      STRERROR (errno));
946     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s", emsg_);
947     if (NULL != emsg)
948       *emsg = emsg_;
949     else
950       GNUNET_free (emsg_);
951     GNUNET_free (config_filename);
952     return NULL;
953   }
954   peer = GNUNET_malloc (sizeof (struct GNUNET_TESTING_Peer));
955   peer->cfgfile = config_filename; /* Free in peer_destroy */
956   libexec_binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-arm");
957   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "arm", "PREFIX", &peer->main_binary))
958   {
959     /* No prefix */
960     GNUNET_asprintf(&peer->main_binary, "%s", libexec_binary);
961     peer->args = strdup ("");
962   }
963   else
964     peer->args = strdup (libexec_binary);
965   peer->system = system;
966   peer->key_number = key_number;
967   GNUNET_free (libexec_binary);
968   return peer;
969 }
970
971
972 /**
973  * Obtain the peer identity from a peer handle.
974  *
975  * @param peer peer handle for which we want the peer's identity
976  * @param id identifier for the daemon, will be set
977  */
978 void
979 GNUNET_TESTING_peer_get_identity (const struct GNUNET_TESTING_Peer *peer,
980                                   struct GNUNET_PeerIdentity *id)
981 {
982   GNUNET_CRYPTO_ecc_key_free (GNUNET_TESTING_hostkey_get (peer->system,
983                                                           peer->key_number,
984                                                           id));
985 }
986
987
988 /**
989  * Start the peer. 
990  *
991  * @param peer peer to start
992  * @return GNUNET_OK on success, GNUNET_SYSERR on error (i.e. peer already running)
993  */
994 int
995 GNUNET_TESTING_peer_start (struct GNUNET_TESTING_Peer *peer)
996 {
997   if (NULL != peer->main_process)
998   {
999     GNUNET_break (0);
1000     return GNUNET_SYSERR;
1001   }
1002   GNUNET_assert (NULL != peer->cfgfile);
1003   peer->main_process = GNUNET_OS_start_process (PIPE_CONTROL, 
1004                                                 GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
1005                                                 NULL, NULL,
1006                                                 peer->main_binary,
1007                                                 peer->main_binary,
1008                                                 peer->args,
1009                                                 "-c",
1010                                                 peer->cfgfile,
1011                                                 NULL);
1012   if (NULL == peer->main_process)
1013   {
1014     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1015                 _("Failed to start `%s': %s\n"),
1016                 peer->main_binary,
1017                 STRERROR (errno));
1018     return GNUNET_SYSERR;
1019   }
1020   return GNUNET_OK;
1021 }
1022
1023
1024 /**
1025  * Sends SIGTERM to the peer's main process
1026  *
1027  * @param peer the handle to the peer
1028  * @return GNUNET_OK if successful; GNUNET_SYSERR if the main process is NULL
1029  *           or upon any error while sending SIGTERM
1030  */
1031 int
1032 GNUNET_TESTING_peer_kill (struct GNUNET_TESTING_Peer *peer)
1033 {
1034   if (NULL == peer->main_process)
1035   {
1036     GNUNET_break (0);
1037     return GNUNET_SYSERR;
1038   }
1039   return (0 == GNUNET_OS_process_kill (peer->main_process, SIGTERM)) ?
1040       GNUNET_OK : GNUNET_SYSERR;
1041 }
1042
1043
1044 /**
1045  * Waits for a peer to terminate. The peer's main process will also be destroyed.
1046  *
1047  * @param peer the handle to the peer
1048  * @return GNUNET_OK if successful; GNUNET_SYSERR if the main process is NULL
1049  *           or upon any error while waiting
1050  */
1051 int
1052 GNUNET_TESTING_peer_wait (struct GNUNET_TESTING_Peer *peer)
1053 {
1054   int ret;
1055
1056   if (NULL == peer->main_process)
1057   {
1058     GNUNET_break (0);
1059     return GNUNET_SYSERR;
1060   }
1061   ret = GNUNET_OS_process_wait (peer->main_process);
1062   GNUNET_OS_process_destroy (peer->main_process);
1063   peer->main_process = NULL;
1064   return ret;
1065 }
1066
1067
1068 /**
1069  * Stop the peer. 
1070  *
1071  * @param peer peer to stop
1072  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1073  */
1074 int
1075 GNUNET_TESTING_peer_stop (struct GNUNET_TESTING_Peer *peer)
1076 {
1077   if (GNUNET_SYSERR == GNUNET_TESTING_peer_kill (peer))
1078     return GNUNET_SYSERR;
1079   if (GNUNET_SYSERR == GNUNET_TESTING_peer_wait (peer))
1080     return GNUNET_SYSERR;
1081   return GNUNET_OK;
1082 }
1083
1084
1085 /**
1086  * Destroy the peer.  Releases resources locked during peer configuration.
1087  * If the peer is still running, it will be stopped AND a warning will be
1088  * printed (users of the API should stop the peer explicitly first).
1089  *
1090  * @param peer peer to destroy
1091  */
1092 void
1093 GNUNET_TESTING_peer_destroy (struct GNUNET_TESTING_Peer *peer)
1094 {
1095   if (NULL != peer->main_process)
1096   {
1097     GNUNET_break (0);
1098     GNUNET_TESTING_peer_stop (peer);
1099   }
1100   GNUNET_free (peer->cfgfile);
1101   GNUNET_free (peer->main_binary);
1102   GNUNET_free (peer->args);
1103   GNUNET_free (peer);
1104 }
1105
1106
1107 /**
1108  * Start a single peer and run a test using the testing library.
1109  * Starts a peer using the given configuration and then invokes the
1110  * given callback.  This function ALSO initializes the scheduler loop
1111  * and should thus be called directly from "main".  The testcase
1112  * should self-terminate by invoking 'GNUNET_SCHEDULER_shutdown'.
1113  *
1114  * @param testdir only the directory name without any path. This is used for
1115  *          all service homes; the directory will be created in a temporary
1116  *          location depending on the underlying OS
1117  * @param cfgfilename name of the configuration file to use;
1118  *         use NULL to only run with defaults
1119  * @param tm main function of the testcase
1120  * @param tm_cls closure for 'tm'
1121  * @return 0 on success, 1 on error
1122  */
1123 int
1124 GNUNET_TESTING_peer_run (const char *testdir,
1125                          const char *cfgfilename,
1126                          GNUNET_TESTING_TestMain tm,
1127                          void *tm_cls)
1128 {
1129   return GNUNET_TESTING_service_run (testdir, "arm",
1130                                      cfgfilename, tm, tm_cls);
1131 }
1132
1133
1134 /**
1135  * Structure for holding service data
1136  */
1137 struct ServiceContext
1138 {
1139   /**
1140    * The configuration of the peer in which the service is run
1141    */
1142   const struct GNUNET_CONFIGURATION_Handle *cfg;
1143
1144   /**
1145    * Callback to signal service startup
1146    */
1147   GNUNET_TESTING_TestMain tm;
1148   
1149   /**
1150    * The peer in which the service is run.
1151    */
1152   struct GNUNET_TESTING_Peer *peer;
1153
1154   /**
1155    * Closure for the above callback
1156    */
1157   void *tm_cls;
1158 };
1159
1160
1161 /**
1162  * Callback to be called when SCHEDULER has been started
1163  *
1164  * @param cls the ServiceContext
1165  * @param tc the TaskContext
1166  */
1167 static void
1168 service_run_main (void *cls,
1169                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1170 {
1171   struct ServiceContext *sc = cls;
1172
1173   sc->tm (sc->tm_cls, sc->cfg, sc->peer);
1174 }
1175
1176
1177 /**
1178  * Start a single service (no ARM, except of course if the given
1179  * service name is 'arm') and run a test using the testing library.
1180  * Starts a service using the given configuration and then invokes the
1181  * given callback.  This function ALSO initializes the scheduler loop
1182  * and should thus be called directly from "main".  The testcase
1183  * should self-terminate by invoking 'GNUNET_SCHEDULER_shutdown'.
1184  *
1185  * This function is useful if the testcase is for a single service
1186  * and if that service doesn't itself depend on other services.
1187  *
1188  * @param testdir only the directory name without any path. This is used for
1189  *          all service homes; the directory will be created in a temporary
1190  *          location depending on the underlying OS
1191  * @param service_name name of the service to run
1192  * @param cfgfilename name of the configuration file to use;
1193  *         use NULL to only run with defaults
1194  * @param tm main function of the testcase
1195  * @param tm_cls closure for 'tm'
1196  * @return 0 on success, 1 on error
1197  */
1198 int
1199 GNUNET_TESTING_service_run (const char *testdir,
1200                             const char *service_name,
1201                             const char *cfgfilename,
1202                             GNUNET_TESTING_TestMain tm,
1203                             void *tm_cls)
1204 {
1205   struct ServiceContext sc;
1206   struct GNUNET_TESTING_System *system;
1207   struct GNUNET_TESTING_Peer *peer;
1208   struct GNUNET_CONFIGURATION_Handle *cfg;
1209   char *binary;
1210   char *libexec_binary;
1211
1212   GNUNET_log_setup (testdir, "WARNING", NULL);
1213   system = GNUNET_TESTING_system_create (testdir, "127.0.0.1", NULL);
1214   if (NULL == system)
1215     return 1;
1216   cfg = GNUNET_CONFIGURATION_create ();
1217   if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfgfilename))
1218   {
1219     LOG (GNUNET_ERROR_TYPE_ERROR,
1220          _("Failed to load configuration from %s\n"), cfgfilename);
1221     GNUNET_CONFIGURATION_destroy (cfg);
1222     GNUNET_TESTING_system_destroy (system, GNUNET_YES);
1223     return 1;
1224   }
1225   peer = GNUNET_TESTING_peer_configure (system, cfg, 0, NULL, NULL);
1226   if (NULL == peer)
1227   {
1228     GNUNET_CONFIGURATION_destroy (cfg);
1229     hostkeys_unload (system);
1230     GNUNET_TESTING_system_destroy (system, GNUNET_YES);
1231     return 1;
1232   }
1233   GNUNET_free (peer->main_binary);
1234   GNUNET_free (peer->args);
1235   GNUNET_asprintf (&binary, "gnunet-service-%s", service_name);
1236   libexec_binary = GNUNET_OS_get_libexec_binary_path (binary);
1237   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, service_name, "PREFIX", &peer->main_binary))
1238   {
1239     /* No prefix */
1240     GNUNET_asprintf(&peer->main_binary, "%s", libexec_binary);
1241     peer->args = strdup ("");
1242   }
1243   else
1244     peer->args = strdup (libexec_binary);
1245
1246   GNUNET_free (libexec_binary);
1247   GNUNET_free (binary);
1248   if (GNUNET_OK != GNUNET_TESTING_peer_start (peer))
1249   {    
1250     GNUNET_TESTING_peer_destroy (peer);
1251     GNUNET_CONFIGURATION_destroy (cfg);
1252     GNUNET_TESTING_system_destroy (system, GNUNET_YES);
1253     return 1;
1254   }
1255   sc.cfg = cfg;
1256   sc.tm = tm;
1257   sc.tm_cls = tm_cls;
1258   sc.peer = peer;
1259   GNUNET_SCHEDULER_run (&service_run_main, &sc); /* Scheduler loop */
1260   if ((NULL != peer->main_process) &&
1261       (GNUNET_OK != GNUNET_TESTING_peer_stop (peer)))
1262   {
1263     GNUNET_TESTING_peer_destroy (peer);
1264     GNUNET_CONFIGURATION_destroy (cfg);
1265     GNUNET_TESTING_system_destroy (system, GNUNET_YES);
1266     return 1;
1267   }
1268   GNUNET_TESTING_peer_destroy (peer);
1269   GNUNET_CONFIGURATION_destroy (cfg);
1270   GNUNET_TESTING_system_destroy (system, GNUNET_YES);
1271   return 0;
1272 }
1273
1274
1275 /**
1276  * Sometimes we use the binary name to determine which specific
1277  * test to run.  In those cases, the string after the last "_"
1278  * in 'argv[0]' specifies a string that determines the configuration
1279  * file or plugin to use.  
1280  *
1281  * This function returns the respective substring, taking care
1282  * of issues such as binaries ending in '.exe' on W32.
1283  *
1284  * @param argv0 the name of the binary
1285  * @return string between the last '_' and the '.exe' (or the end of the string),
1286  *         NULL if argv0 has no '_' 
1287  */
1288 char *
1289 GNUNET_TESTING_get_testname_from_underscore (const char *argv0)
1290 {
1291   size_t slen = strlen (argv0) + 1;
1292   char sbuf[slen];
1293   char *ret;
1294   char *dot;
1295
1296   memcpy (sbuf, argv0, slen);
1297   ret = strrchr (sbuf, '_');
1298   if (NULL == ret)
1299     return NULL;
1300   ret++; /* skip underscore */
1301   dot = strchr (ret, '.');
1302   if (NULL != dot)
1303     *dot = '\0';
1304   return GNUNET_strdup (ret);
1305 }
1306
1307
1308 /* end of testing.c */