- doc
[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.dat", 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_RsaPrivateKey *
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_RsaPrivateKey *private_key;
534   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded 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_rsa_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_rsa_key_get_public (private_key, &public_key);
555   GNUNET_CRYPTO_hash (&public_key,
556                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
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_RsaPrivateKey *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_rsa_key_free (pk);
901   GNUNET_assert (GNUNET_OK == 
902                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
903                                                         "SERVICEHOME",
904                                                         &service_home));
905   GNUNET_snprintf (hostkey_filename, sizeof (hostkey_filename), "%s/.hostkey",
906                    service_home);
907   GNUNET_free (service_home);
908   fd = GNUNET_DISK_file_open (hostkey_filename,
909                               GNUNET_DISK_OPEN_CREATE | GNUNET_DISK_OPEN_WRITE,
910                               GNUNET_DISK_PERM_USER_READ 
911                               | GNUNET_DISK_PERM_USER_WRITE);
912   if (NULL == fd)
913   {
914     GNUNET_break (0); 
915     return NULL;
916   }
917   if (GNUNET_TESTING_HOSTKEYFILESIZE !=
918       GNUNET_DISK_file_write (fd, system->hostkeys_data 
919                               + (key_number * GNUNET_TESTING_HOSTKEYFILESIZE),
920                               GNUNET_TESTING_HOSTKEYFILESIZE))
921   {
922     GNUNET_asprintf (&emsg_,
923                      _("Failed to write hostkey file for peer %u: %s\n"),
924                      (unsigned int) key_number,
925                      STRERROR (errno));
926     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s", emsg_);
927     if (NULL != emsg)
928       *emsg = emsg_;
929     else
930       GNUNET_free (emsg_);
931     GNUNET_DISK_file_close (fd);
932     return NULL;
933   }
934   GNUNET_DISK_file_close (fd);
935   GNUNET_assert (GNUNET_OK ==
936                  GNUNET_CONFIGURATION_get_value_string 
937                  (cfg, "PATHS", "DEFAULTCONFIG", &config_filename));  
938   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, config_filename))
939   {
940     GNUNET_asprintf (&emsg_,
941                      _("Failed to write configuration file `%s' for peer %u: %s\n"),
942                      config_filename,
943                      (unsigned int) key_number,
944                      STRERROR (errno));
945     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s", emsg_);
946     if (NULL != emsg)
947       *emsg = emsg_;
948     else
949       GNUNET_free (emsg_);
950     GNUNET_free (config_filename);
951     return NULL;
952   }
953   peer = GNUNET_malloc (sizeof (struct GNUNET_TESTING_Peer));
954   peer->cfgfile = config_filename; /* Free in peer_destroy */
955   libexec_binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-arm");
956   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "arm", "PREFIX", &peer->main_binary))
957   {
958     /* No prefix */
959     GNUNET_asprintf(&peer->main_binary, "%s", libexec_binary);
960     peer->args = strdup ("");
961   }
962   else
963     peer->args = strdup (libexec_binary);
964   peer->system = system;
965   peer->key_number = key_number;
966   GNUNET_free (libexec_binary);
967   return peer;
968 }
969
970
971 /**
972  * Obtain the peer identity from a peer handle.
973  *
974  * @param peer peer handle for which we want the peer's identity
975  * @param id identifier for the daemon, will be set
976  */
977 void
978 GNUNET_TESTING_peer_get_identity (const struct GNUNET_TESTING_Peer *peer,
979                                   struct GNUNET_PeerIdentity *id)
980 {
981   GNUNET_CRYPTO_rsa_key_free (GNUNET_TESTING_hostkey_get (peer->system,
982                                                           peer->key_number,
983                                                           id));
984 }
985
986
987 /**
988  * Start the peer. 
989  *
990  * @param peer peer to start
991  * @return GNUNET_OK on success, GNUNET_SYSERR on error (i.e. peer already running)
992  */
993 int
994 GNUNET_TESTING_peer_start (struct GNUNET_TESTING_Peer *peer)
995 {
996   if (NULL != peer->main_process)
997   {
998     GNUNET_break (0);
999     return GNUNET_SYSERR;
1000   }
1001   GNUNET_assert (NULL != peer->cfgfile);
1002   peer->main_process = GNUNET_OS_start_process (PIPE_CONTROL, 
1003                                                 GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
1004                                                 NULL, NULL,
1005                                                 peer->main_binary,
1006                                                 peer->main_binary,
1007                                                 peer->args,
1008                                                 "-c",
1009                                                 peer->cfgfile,
1010                                                 NULL);
1011   if (NULL == peer->main_process)
1012   {
1013     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1014                 _("Failed to start `%s': %s\n"),
1015                 peer->main_binary,
1016                 STRERROR (errno));
1017     return GNUNET_SYSERR;
1018   }
1019   return GNUNET_OK;
1020 }
1021
1022
1023 /**
1024  * Sends SIGTERM to the peer's main process
1025  *
1026  * @param peer the handle to the peer
1027  * @return GNUNET_OK if successful; GNUNET_SYSERR if the main process is NULL
1028  *           or upon any error while sending SIGTERM
1029  */
1030 int
1031 GNUNET_TESTING_peer_kill (struct GNUNET_TESTING_Peer *peer)
1032 {
1033   if (NULL == peer->main_process)
1034   {
1035     GNUNET_break (0);
1036     return GNUNET_SYSERR;
1037   }
1038   return (0 == GNUNET_OS_process_kill (peer->main_process, SIGTERM)) ?
1039       GNUNET_OK : GNUNET_SYSERR;
1040 }
1041
1042
1043 /**
1044  * Waits for a peer to terminate. The peer's main process will also be destroyed.
1045  *
1046  * @param peer the handle to the peer
1047  * @return GNUNET_OK if successful; GNUNET_SYSERR if the main process is NULL
1048  *           or upon any error while waiting
1049  */
1050 int
1051 GNUNET_TESTING_peer_wait (struct GNUNET_TESTING_Peer *peer)
1052 {
1053   int ret;
1054
1055   if (NULL == peer->main_process)
1056   {
1057     GNUNET_break (0);
1058     return GNUNET_SYSERR;
1059   }
1060   ret = GNUNET_OS_process_wait (peer->main_process);
1061   GNUNET_OS_process_destroy (peer->main_process);
1062   peer->main_process = NULL;
1063   return ret;
1064 }
1065
1066
1067 /**
1068  * Stop the peer. 
1069  *
1070  * @param peer peer to stop
1071  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1072  */
1073 int
1074 GNUNET_TESTING_peer_stop (struct GNUNET_TESTING_Peer *peer)
1075 {
1076   if (GNUNET_SYSERR == GNUNET_TESTING_peer_kill (peer))
1077     return GNUNET_SYSERR;
1078   if (GNUNET_SYSERR == GNUNET_TESTING_peer_wait (peer))
1079     return GNUNET_SYSERR;
1080   return GNUNET_OK;
1081 }
1082
1083
1084 /**
1085  * Destroy the peer.  Releases resources locked during peer configuration.
1086  * If the peer is still running, it will be stopped AND a warning will be
1087  * printed (users of the API should stop the peer explicitly first).
1088  *
1089  * @param peer peer to destroy
1090  */
1091 void
1092 GNUNET_TESTING_peer_destroy (struct GNUNET_TESTING_Peer *peer)
1093 {
1094   if (NULL != peer->main_process)
1095   {
1096     GNUNET_break (0);
1097     GNUNET_TESTING_peer_stop (peer);
1098   }
1099   GNUNET_free (peer->cfgfile);
1100   GNUNET_free (peer->main_binary);
1101   GNUNET_free (peer->args);
1102   GNUNET_free (peer);
1103 }
1104
1105
1106 /**
1107  * Start a single peer and run a test using the testing library.
1108  * Starts a peer using the given configuration and then invokes the
1109  * given callback.  This function ALSO initializes the scheduler loop
1110  * and should thus be called directly from "main".  The testcase
1111  * should self-terminate by invoking 'GNUNET_SCHEDULER_shutdown'.
1112  *
1113  * @param testdir only the directory name without any path. This is used for
1114  *          all service homes; the directory will be created in a temporary
1115  *          location depending on the underlying OS
1116  * @param cfgfilename name of the configuration file to use;
1117  *         use NULL to only run with defaults
1118  * @param tm main function of the testcase
1119  * @param tm_cls closure for 'tm'
1120  * @return 0 on success, 1 on error
1121  */
1122 int
1123 GNUNET_TESTING_peer_run (const char *testdir,
1124                          const char *cfgfilename,
1125                          GNUNET_TESTING_TestMain tm,
1126                          void *tm_cls)
1127 {
1128   return GNUNET_TESTING_service_run (testdir, "arm",
1129                                      cfgfilename, tm, tm_cls);
1130 }
1131
1132
1133 /**
1134  * Structure for holding service data
1135  */
1136 struct ServiceContext
1137 {
1138   /**
1139    * The configuration of the peer in which the service is run
1140    */
1141   const struct GNUNET_CONFIGURATION_Handle *cfg;
1142
1143   /**
1144    * Callback to signal service startup
1145    */
1146   GNUNET_TESTING_TestMain tm;
1147   
1148   /**
1149    * The peer in which the service is run.
1150    */
1151   struct GNUNET_TESTING_Peer *peer;
1152
1153   /**
1154    * Closure for the above callback
1155    */
1156   void *tm_cls;
1157 };
1158
1159
1160 /**
1161  * Callback to be called when SCHEDULER has been started
1162  *
1163  * @param cls the ServiceContext
1164  * @param tc the TaskContext
1165  */
1166 static void
1167 service_run_main (void *cls,
1168                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1169 {
1170   struct ServiceContext *sc = cls;
1171
1172   sc->tm (sc->tm_cls, sc->cfg, sc->peer);
1173 }
1174
1175
1176 /**
1177  * Start a single service (no ARM, except of course if the given
1178  * service name is 'arm') and run a test using the testing library.
1179  * Starts a service using the given configuration and then invokes the
1180  * given callback.  This function ALSO initializes the scheduler loop
1181  * and should thus be called directly from "main".  The testcase
1182  * should self-terminate by invoking 'GNUNET_SCHEDULER_shutdown'.
1183  *
1184  * This function is useful if the testcase is for a single service
1185  * and if that service doesn't itself depend on other services.
1186  *
1187  * @param testdir only the directory name without any path. This is used for
1188  *          all service homes; the directory will be created in a temporary
1189  *          location depending on the underlying OS
1190  * @param service_name name of the service to run
1191  * @param cfgfilename name of the configuration file to use;
1192  *         use NULL to only run with defaults
1193  * @param tm main function of the testcase
1194  * @param tm_cls closure for 'tm'
1195  * @return 0 on success, 1 on error
1196  */
1197 int
1198 GNUNET_TESTING_service_run (const char *testdir,
1199                             const char *service_name,
1200                             const char *cfgfilename,
1201                             GNUNET_TESTING_TestMain tm,
1202                             void *tm_cls)
1203 {
1204   struct ServiceContext sc;
1205   struct GNUNET_TESTING_System *system;
1206   struct GNUNET_TESTING_Peer *peer;
1207   struct GNUNET_CONFIGURATION_Handle *cfg;
1208   char *binary;
1209   char *libexec_binary;
1210
1211   GNUNET_log_setup (testdir, "WARNING", NULL);
1212   system = GNUNET_TESTING_system_create (testdir, "127.0.0.1", NULL);
1213   if (NULL == system)
1214     return 1;
1215   cfg = GNUNET_CONFIGURATION_create ();
1216   if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfgfilename))
1217   {
1218     LOG (GNUNET_ERROR_TYPE_ERROR,
1219          _("Failed to load configuration from %s\n"), cfgfilename);
1220     GNUNET_CONFIGURATION_destroy (cfg);
1221     GNUNET_TESTING_system_destroy (system, GNUNET_YES);
1222     return 1;
1223   }
1224   peer = GNUNET_TESTING_peer_configure (system, cfg, 0, NULL, NULL);
1225   if (NULL == peer)
1226   {
1227     GNUNET_CONFIGURATION_destroy (cfg);
1228     hostkeys_unload (system);
1229     GNUNET_TESTING_system_destroy (system, GNUNET_YES);
1230     return 1;
1231   }
1232   GNUNET_free (peer->main_binary);
1233   GNUNET_free (peer->args);
1234   GNUNET_asprintf (&binary, "gnunet-service-%s", service_name);
1235   libexec_binary = GNUNET_OS_get_libexec_binary_path (binary);
1236   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, service_name, "PREFIX", &peer->main_binary))
1237   {
1238     /* No prefix */
1239     GNUNET_asprintf(&peer->main_binary, "%s", libexec_binary);
1240     peer->args = strdup ("");
1241   }
1242   else
1243     peer->args = strdup (libexec_binary);
1244
1245   GNUNET_free (libexec_binary);
1246   GNUNET_free (binary);
1247   if (GNUNET_OK != GNUNET_TESTING_peer_start (peer))
1248   {    
1249     GNUNET_TESTING_peer_destroy (peer);
1250     GNUNET_CONFIGURATION_destroy (cfg);
1251     GNUNET_TESTING_system_destroy (system, GNUNET_YES);
1252     return 1;
1253   }
1254   sc.cfg = cfg;
1255   sc.tm = tm;
1256   sc.tm_cls = tm_cls;
1257   sc.peer = peer;
1258   GNUNET_SCHEDULER_run (&service_run_main, &sc); /* Scheduler loop */
1259   if ((NULL != peer->main_process) &&
1260       (GNUNET_OK != GNUNET_TESTING_peer_stop (peer)))
1261   {
1262     GNUNET_TESTING_peer_destroy (peer);
1263     GNUNET_CONFIGURATION_destroy (cfg);
1264     GNUNET_TESTING_system_destroy (system, GNUNET_YES);
1265     return 1;
1266   }
1267   GNUNET_TESTING_peer_destroy (peer);
1268   GNUNET_CONFIGURATION_destroy (cfg);
1269   GNUNET_TESTING_system_destroy (system, GNUNET_YES);
1270   return 0;
1271 }
1272
1273
1274 /**
1275  * Sometimes we use the binary name to determine which specific
1276  * test to run.  In those cases, the string after the last "_"
1277  * in 'argv[0]' specifies a string that determines the configuration
1278  * file or plugin to use.  
1279  *
1280  * This function returns the respective substring, taking care
1281  * of issues such as binaries ending in '.exe' on W32.
1282  *
1283  * @param argv0 the name of the binary
1284  * @return string between the last '_' and the '.exe' (or the end of the string),
1285  *         NULL if argv0 has no '_' 
1286  */
1287 char *
1288 GNUNET_TESTING_get_testname_from_underscore (const char *argv0)
1289 {
1290   size_t slen = strlen (argv0) + 1;
1291   char sbuf[slen];
1292   char *ret;
1293   char *dot;
1294
1295   memcpy (sbuf, argv0, slen);
1296   ret = strrchr (sbuf, '_');
1297   if (NULL == ret)
1298     return NULL;
1299   ret++; /* skip underscore */
1300   dot = strchr (ret, '.');
1301   if (NULL != dot)
1302     *dot = '\0';
1303   return GNUNET_strdup (ret);
1304 }
1305
1306
1307 /* end of testing.c */