-fix
[oweals/gnunet.git] / src / testing / testing.c
1 /*
2       This file is part of GNUnet
3       (C) 2008, 2009 Christian Grothoff (and other contributing authors)
4
5       GNUnet is free software; you can redistribute it and/or modify
6       it under the terms of the GNU General Public License as published
7       by the Free Software Foundation; either version 3, or (at your
8       option) any later version.
9
10       GNUnet is distributed in the hope that it will be useful, but
11       WITHOUT ANY WARRANTY; without even the implied warranty of
12       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13       General Public License for more details.
14
15       You should have received a copy of the GNU General Public License
16       along with GNUnet; see the file COPYING.  If not, write to the
17       Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18       Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * @file testing/testing.c
23  * @brief convenience API for writing testcases for GNUnet
24  *        Many testcases need to start and stop gnunetd,
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!
29  * @author Christian Grothoff
30  *
31  */
32 #include "platform.h"
33 #include "gnunet_arm_service.h"
34 #include "gnunet_core_service.h"
35 #include "gnunet_constants.h"
36 #include "gnunet_testing_lib.h"
37 #include "gnunet_transport_service.h"
38 #include "gnunet_hello_lib.h"
39
40 #define DEBUG_TESTING GNUNET_EXTRA_LOGGING
41
42 #define DEBUG_TESTING_RECONNECT GNUNET_EXTRA_LOGGING
43
44 /**
45  * Hack to deal with initial HELLO's being often devoid of addresses.
46  * This hack causes 'process_hello' to ignore HELLOs without addresses.
47  * The correct implementation would continue with 'process_hello' until
48  * the connection could be established...
49  */
50 #define EMPTY_HACK GNUNET_YES
51
52 /**
53  * How long do we wait after starting gnunet-service-arm
54  * for the core service to be alive?
55  */
56 #define ARM_START_WAIT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120)
57
58 /**
59  * How many times are we willing to try to wait for "scp" or
60  * "gnunet-service-arm" to complete (waitpid) before giving up?
61  */
62 #define MAX_EXEC_WAIT_RUNS 250
63
64 static struct GNUNET_CORE_MessageHandler no_handlers[] = { {NULL, 0, 0} };
65
66 #if EMPTY_HACK
67 static int
68 test_address (void *cls, const struct GNUNET_HELLO_Address *address,
69               struct GNUNET_TIME_Absolute expiration)
70 {
71   int *empty = cls;
72
73   *empty = GNUNET_NO;
74   return GNUNET_OK;
75 }
76 #endif
77
78 /**
79  * Receive the HELLO from one peer, give it to the other
80  * and ask them to connect.
81  *
82  * @param cls Closure (daemon whose hello is this).
83  * @param message HELLO message of peer
84  */
85 static void
86 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
87 {
88   struct GNUNET_TESTING_Daemon *daemon = cls;
89   int msize;
90
91 #if EMPTY_HACK
92   int empty;
93
94   empty = GNUNET_YES;
95   GNUNET_assert (message != NULL);
96   GNUNET_HELLO_iterate_addresses ((const struct GNUNET_HELLO_Message *) message,
97                                   GNUNET_NO, &test_address, &empty);
98   if (GNUNET_YES == empty)
99   {
100     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
101                 "Skipping empty HELLO address of peer %s\n",
102                 GNUNET_i2s (&daemon->id));
103     return;
104   }
105 #endif
106   GNUNET_assert (daemon->phase == SP_GET_HELLO ||
107                  daemon->phase == SP_START_DONE);
108   daemon->cb = NULL;            // FIXME: why??? (see fsm:SP_START_CORE, notify_daemon_started)
109   if (daemon->task != GNUNET_SCHEDULER_NO_TASK) /* Assertion here instead? */
110     GNUNET_SCHEDULER_cancel (daemon->task);
111
112   if (daemon->server != NULL)
113   {
114     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
115                 "Received `%s' from transport service of `%4s', disconnecting core!\n",
116                 "HELLO", GNUNET_i2s (&daemon->id));
117     GNUNET_CORE_disconnect (daemon->server);
118     daemon->server = NULL;
119   }
120
121   msize = ntohs (message->size);
122   if (msize < 1)
123   {
124     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
125                 "HELLO message of peer %s is of size 0\n",
126                 GNUNET_i2s (&daemon->id));
127     return;
128   }
129   if (daemon->ghh != NULL)
130   {
131     GNUNET_TRANSPORT_get_hello_cancel (daemon->ghh);
132     daemon->ghh = NULL;
133   }
134   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
135               "Received `%s' from transport service of `%4s'\n", "HELLO",
136               GNUNET_i2s (&daemon->id));
137   GNUNET_free_non_null (daemon->hello);
138   daemon->hello = GNUNET_malloc (msize);
139   memcpy (daemon->hello, message, msize);
140
141   if (daemon->th != NULL)
142   {
143     GNUNET_TRANSPORT_disconnect (daemon->th);
144     daemon->th = NULL;
145   }
146   daemon->phase = SP_START_DONE;
147 }
148
149
150 /**
151  * Notify of a peer being up and running.  Scheduled as a task
152  * so that variables which may need to be set are set before
153  * the connect callback can set up new operations.
154  * FIXME: what variables?????? where from????
155  *
156  * @param cls the testing daemon
157  * @param tc task scheduler context
158  */
159 static void
160 notify_daemon_started (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
161 {
162   struct GNUNET_TESTING_Daemon *d = cls;
163   GNUNET_TESTING_NotifyDaemonRunning cb;
164
165   cb = d->cb;
166   d->cb = NULL;
167   if (NULL != cb)
168     cb (d->cb_cls, &d->id, d->cfg, d, NULL);
169 }
170
171
172 /**
173  * Finite-state machine for starting GNUnet.
174  *
175  * @param cls our "struct GNUNET_TESTING_Daemon"
176  * @param tc unused
177  */
178 static void
179 start_fsm (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
180 {
181   struct GNUNET_TESTING_Daemon *d = cls;
182   GNUNET_TESTING_NotifyDaemonRunning cb;
183   enum GNUNET_OS_ProcessStatusType type;
184   unsigned long code;
185   char *dst;
186   int bytes_read;
187
188   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer %s FSM is in phase %u.\n",
189               GNUNET_i2s (&d->id), d->phase);
190   d->task = GNUNET_SCHEDULER_NO_TASK;
191   switch (d->phase)
192   {
193   case SP_COPYING:
194     /* confirm copying complete */
195     if (GNUNET_OK != GNUNET_OS_process_status (d->proc, &type, &code))
196     {
197       if (GNUNET_TIME_absolute_get_remaining (d->max_timeout).rel_value == 0)
198       {
199         cb = d->cb;
200         d->cb = NULL;
201         if (NULL != cb)
202           cb (d->cb_cls, NULL, d->cfg, d,
203               _
204               ("`scp' does not seem to terminate (timeout copying config).\n"));
205         return;
206       }
207       /* wait some more */
208       d->task =
209           GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
210                                         d);
211       return;
212     }
213     if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
214     {
215       cb = d->cb;
216       d->cb = NULL;
217       if (NULL != cb)
218         cb (d->cb_cls, NULL, d->cfg, d, _("`scp' did not complete cleanly.\n"));
219       return;
220     }
221     GNUNET_OS_process_close (d->proc);
222     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
223                 "Successfully copied configuration file.\n");
224     d->phase = SP_COPIED;
225     /* fall-through */
226   case SP_COPIED:
227     /* Start create hostkey process if we don't already know the peer identity! */
228     if (GNUNET_NO == d->have_hostkey)
229     {
230       d->pipe_stdout = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_YES);
231       if (d->pipe_stdout == NULL)
232       {
233         cb = d->cb;
234         d->cb = NULL;
235         if (NULL != cb)
236           cb (d->cb_cls, NULL, d->cfg, d,
237               (NULL ==
238                d->hostname) ?
239               _("Failed to create pipe for `gnunet-peerinfo' process.\n") :
240               _("Failed to create pipe for `ssh' process.\n"));
241         return;
242       }
243       if (NULL == d->hostname)
244       {
245         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
246                     "Starting `%s', with command `%s %s %s %s'.\n",
247                     "gnunet-peerinfo", "gnunet-peerinfo", "-c", d->cfgfile,
248                     "-sq");
249         d->proc =
250             GNUNET_OS_start_process (GNUNET_YES, NULL, d->pipe_stdout, "gnunet-peerinfo",
251                                      "gnunet-peerinfo", "-c", d->cfgfile, "-sq",
252                                      NULL);
253         GNUNET_DISK_pipe_close_end (d->pipe_stdout, GNUNET_DISK_PIPE_END_WRITE);
254       }
255       else
256       {
257         if (d->username != NULL)
258           GNUNET_asprintf (&dst, "%s@%s", d->username, d->hostname);
259         else
260           dst = GNUNET_strdup (d->hostname);
261
262         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
263                     "Starting `%s', with command `%s %s %s %s %s %s'.\n",
264                     "gnunet-peerinfo", "ssh", dst, "gnunet-peerinfo", "-c",
265                     d->cfgfile, "-sq");
266         if (d->ssh_port_str == NULL)
267         {
268           d->proc = GNUNET_OS_start_process (GNUNET_NO, NULL, d->pipe_stdout, "ssh", "ssh",
269 #if !DEBUG_TESTING
270                                              "-q",
271 #endif
272                                              dst, "gnunet-peerinfo", "-c",
273                                              d->cfgfile, "-sq", NULL);
274         }
275         else
276         {
277           d->proc =
278               GNUNET_OS_start_process (GNUNET_NO, NULL, d->pipe_stdout, "ssh", "ssh", "-p",
279                                        d->ssh_port_str,
280 #if !DEBUG_TESTING
281                                        "-q",
282 #endif
283                                        dst, "gnunet-peerinfo", "-c", d->cfgfile,
284                                        "-sq", NULL);
285         }
286         GNUNET_DISK_pipe_close_end (d->pipe_stdout, GNUNET_DISK_PIPE_END_WRITE);
287         GNUNET_free (dst);
288       }
289       if (NULL == d->proc)
290       {
291         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
292                     _("Could not start `%s' process to create hostkey.\n"),
293                     (NULL == d->hostname) ? "gnunet-peerinfo" : "ssh");
294         cb = d->cb;
295         d->cb = NULL;
296         if (NULL != cb)
297           cb (d->cb_cls, NULL, d->cfg, d,
298               (NULL ==
299                d->hostname) ? _("Failed to start `gnunet-peerinfo' process.\n")
300               : _("Failed to start `ssh' process.\n"));
301         GNUNET_DISK_pipe_close (d->pipe_stdout);
302         return;
303       }
304       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
305                   "Started `%s', waiting for hostkey.\n", "gnunet-peerinfo");
306       d->phase = SP_HOSTKEY_CREATE;
307       d->task =
308           GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
309                                           (d->max_timeout),
310                                           GNUNET_DISK_pipe_handle
311                                           (d->pipe_stdout,
312                                            GNUNET_DISK_PIPE_END_READ),
313                                           &start_fsm, d);
314     }
315     else                        /* Already have a hostkey! */
316     {
317       if (d->hostkey_callback != NULL)
318       {
319         d->hostkey_callback (d->hostkey_cls, &d->id, d, NULL);
320         d->hostkey_callback = NULL;
321         d->phase = SP_HOSTKEY_CREATED;
322       }
323       else
324         d->phase = SP_TOPOLOGY_SETUP;
325
326       /* wait some more */
327       d->task = GNUNET_SCHEDULER_add_now (&start_fsm, d);
328     }
329     break;
330   case SP_HOSTKEY_CREATE:
331     bytes_read =
332         GNUNET_DISK_file_read (GNUNET_DISK_pipe_handle
333                                (d->pipe_stdout, GNUNET_DISK_PIPE_END_READ),
334                                &d->hostkeybuf[d->hostkeybufpos],
335                                sizeof (d->hostkeybuf) - d->hostkeybufpos);
336     if (bytes_read > 0)
337       d->hostkeybufpos += bytes_read;
338
339     if ((d->hostkeybufpos < 104) && (bytes_read > 0))
340     {
341       /* keep reading */
342       d->task =
343           GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
344                                           (d->max_timeout),
345                                           GNUNET_DISK_pipe_handle
346                                           (d->pipe_stdout,
347                                            GNUNET_DISK_PIPE_END_READ),
348                                           &start_fsm, d);
349       return;
350     }
351     d->hostkeybuf[103] = '\0';
352
353     if ((bytes_read < 0) ||
354         (GNUNET_OK !=
355          GNUNET_CRYPTO_hash_from_string (d->hostkeybuf, &d->id.hashPubKey)))
356     {
357       /* error */
358       if (bytes_read < 0)
359         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
360                     _("Error reading from gnunet-peerinfo: %s\n"),
361                     STRERROR (errno));
362       else
363         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
364                     _("Malformed output from gnunet-peerinfo!\n"));
365       cb = d->cb;
366       d->cb = NULL;
367       GNUNET_DISK_pipe_close (d->pipe_stdout);
368       d->pipe_stdout = NULL;
369       (void) GNUNET_OS_process_kill (d->proc, SIGKILL);
370       GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (d->proc));
371       GNUNET_OS_process_close (d->proc);
372       d->proc = NULL;
373       if (NULL != cb)
374         cb (d->cb_cls, NULL, d->cfg, d, _("Failed to get hostkey!\n"));
375       return;
376     }
377     d->shortname = GNUNET_strdup (GNUNET_i2s (&d->id));
378     GNUNET_DISK_pipe_close (d->pipe_stdout);
379     d->pipe_stdout = NULL;
380     (void) GNUNET_OS_process_kill (d->proc, SIGKILL);
381     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (d->proc));
382     GNUNET_OS_process_close (d->proc);
383     d->proc = NULL;
384     d->have_hostkey = GNUNET_YES;
385     if (d->hostkey_callback != NULL)
386     {
387       d->hostkey_callback (d->hostkey_cls, &d->id, d, NULL);
388       d->hostkey_callback = NULL;
389       d->phase = SP_HOSTKEY_CREATED;
390     }
391     else
392     {
393       d->phase = SP_TOPOLOGY_SETUP;
394     }
395     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Successfully got hostkey!\n");
396     /* Fall through */
397   case SP_HOSTKEY_CREATED:
398     /* wait for topology finished */
399     if ((GNUNET_YES == d->dead) ||
400         (GNUNET_TIME_absolute_get_remaining (d->max_timeout).rel_value == 0))
401     {
402       cb = d->cb;
403       d->cb = NULL;
404       if (NULL != cb)
405         cb (d->cb_cls, NULL, d->cfg, d,
406             _("`Failed while waiting for topology setup!\n"));
407       return;
408     }
409
410     d->task =
411         GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
412                                       d);
413     break;
414   case SP_TOPOLOGY_SETUP:      /* Indicates topology setup has completed! */
415     /* start GNUnet on remote host */
416     if (NULL == d->hostname)
417     {
418       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
419                   "Starting `%s', with command `%s %s %s %s %s %s'.\n",
420                   "gnunet-arm", "gnunet-arm", "-c", d->cfgfile, "-L", "DEBUG",
421                   "-s");
422       d->proc =
423           GNUNET_OS_start_process (GNUNET_YES, NULL, NULL, "gnunet-arm", "gnunet-arm", "-c",
424                                    d->cfgfile,
425                                    "-L", "DEBUG",
426                                    "-s", "-q", "-T",
427                                    GNUNET_TIME_relative_to_string
428                                    (GNUNET_TIME_absolute_get_remaining
429                                     (d->max_timeout)), NULL);
430     }
431     else
432     {
433       if (d->username != NULL)
434         GNUNET_asprintf (&dst, "%s@%s", d->username, d->hostname);
435       else
436         dst = GNUNET_strdup (d->hostname);
437
438       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
439                   "Starting `%s', with command `%s %s %s %s %s %s %s %s'.\n",
440                   "gnunet-arm", "ssh", dst, "gnunet-arm", "-c", d->cfgfile,
441                   "-L", "DEBUG", "-s", "-q");
442       if (d->ssh_port_str == NULL)
443       {
444         d->proc = GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "ssh", "ssh",
445 #if !DEBUG_TESTING
446                                            "-q",
447 #endif
448                                            dst, "gnunet-arm",
449 #if DEBUG_TESTING
450                                            "-L", "DEBUG",
451 #endif
452                                            "-c", d->cfgfile, "-s", "-q", "-T",
453                                            GNUNET_TIME_relative_to_string
454                                            (GNUNET_TIME_absolute_get_remaining
455                                             (d->max_timeout)), NULL);
456       }
457       else
458       {
459
460         d->proc =
461             GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "ssh", "ssh", "-p",
462                                      d->ssh_port_str,
463 #if !DEBUG_TESTING
464                                      "-q",
465 #endif
466                                      dst, "gnunet-arm",
467 #if DEBUG_TESTING
468                                      "-L", "DEBUG",
469 #endif
470                                      "-c", d->cfgfile, "-s", "-q", "-T",
471                                      GNUNET_TIME_relative_to_string
472                                      (GNUNET_TIME_absolute_get_remaining
473                                       (d->max_timeout)), NULL);
474       }
475       GNUNET_free (dst);
476     }
477     if (NULL == d->proc)
478     {
479       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
480                   _("Could not start `%s' process to start GNUnet.\n"),
481                   (NULL == d->hostname) ? "gnunet-arm" : "ssh");
482       cb = d->cb;
483       d->cb = NULL;
484       if (NULL != cb)
485         cb (d->cb_cls, NULL, d->cfg, d,
486             (NULL ==
487              d->hostname) ? _("Failed to start `gnunet-arm' process.\n") :
488             _("Failed to start `ssh' process.\n"));
489       return;
490     }
491     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
492                 "Started `%s', waiting for `%s' to be up.\n", "gnunet-arm",
493                 "gnunet-service-core");
494     d->phase = SP_START_ARMING;
495     d->task =
496         GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
497                                       d);
498     break;
499   case SP_START_ARMING:
500     if (GNUNET_OK != GNUNET_OS_process_status (d->proc, &type, &code))
501     {
502       if (GNUNET_TIME_absolute_get_remaining (d->max_timeout).rel_value == 0)
503       {
504         cb = d->cb;
505         d->cb = NULL;
506         if (NULL != cb)
507           cb (d->cb_cls, NULL, d->cfg, d,
508               (NULL ==
509                d->hostname) ? _("`gnunet-arm' does not seem to terminate.\n") :
510               _("`ssh' does not seem to terminate.\n"));
511         if (d->cfg != NULL)
512         {
513           GNUNET_CONFIGURATION_destroy (d->cfg);
514           d->cfg = NULL;
515         }
516         if (d->cfgfile != NULL)
517         {
518           GNUNET_free (d->cfgfile);
519           d->cfgfile = NULL;
520         }
521         GNUNET_free_non_null (d->hostname);
522         GNUNET_free_non_null (d->username);
523         GNUNET_free (d->proc);
524 //         GNUNET_free (d); // FIXME (could this leak)
525         d->hostname = NULL;     // Quick hack to avoid crashing (testing need to be
526         d->cfg = NULL;          // overhauled anyway, and the error managing is
527         // pretty broken anyway.
528         return;
529       }
530       /* wait some more */
531       d->task =
532           GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
533                                         d);
534       return;
535     }
536     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Successfully started `%s'.\n",
537                 "gnunet-arm");
538     GNUNET_free (d->proc);
539     d->phase = SP_START_CORE;
540     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Calling CORE_connect\n");
541     /* Fall through */
542   case SP_START_CORE:
543     if (d->server != NULL)
544       GNUNET_CORE_disconnect (d->server);
545
546     d->th = GNUNET_TRANSPORT_connect (d->cfg, &d->id, d, NULL, NULL, NULL);
547     if (d->th == NULL)
548     {
549       if (GNUNET_YES == d->dead)
550         GNUNET_TESTING_daemon_stop (d,
551                                     GNUNET_TIME_absolute_get_remaining
552                                     (d->max_timeout), d->dead_cb,
553                                     d->dead_cb_cls, GNUNET_YES, GNUNET_NO);
554       else if (NULL != d->cb)
555         d->cb (d->cb_cls, &d->id, d->cfg, d,
556                _("Failed to connect to transport service!\n"));
557       return;
558     }
559     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
560                 "Connected to transport service `%s', getting HELLO\n",
561                 GNUNET_i2s (&d->id));
562     d->ghh = GNUNET_TRANSPORT_get_hello (d->th, &process_hello, d);
563     /* FIXME: store task ID somewhere! */
564     GNUNET_SCHEDULER_add_now (&notify_daemon_started, d);
565     /*cb = d->cb;
566      * d->cb = NULL;
567      * if (NULL != cb)
568      * cb (d->cb_cls, &d->id, d->cfg, d, NULL); */
569     d->running = GNUNET_YES;
570     d->phase = SP_GET_HELLO;
571     break;
572   case SP_GET_HELLO:
573     if (GNUNET_TIME_absolute_get_remaining (d->max_timeout).rel_value == 0)
574     {
575       if (d->server != NULL)
576         GNUNET_CORE_disconnect (d->server);
577       if (d->th != NULL)
578         GNUNET_TRANSPORT_disconnect (d->th);
579       cb = d->cb;
580       d->cb = NULL;
581       if (NULL != cb)
582         cb (d->cb_cls, NULL, d->cfg, d, _("Unable to get HELLO for peer!\n"));
583       GNUNET_CONFIGURATION_destroy (d->cfg);
584       GNUNET_free (d->cfgfile);
585       GNUNET_free_non_null (d->hostname);
586       GNUNET_free_non_null (d->username);
587       GNUNET_free (d);
588       return;
589     }
590     if (d->hello != NULL)
591       return;
592     GNUNET_assert (d->task == GNUNET_SCHEDULER_NO_TASK);
593     d->task =
594         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
595                                       (GNUNET_CONSTANTS_SERVICE_RETRY, 2),
596                                       &start_fsm, d);
597     break;
598   case SP_START_DONE:
599     GNUNET_break (0);
600     break;
601   case SP_SERVICE_START:
602     /* confirm gnunet-arm exited */
603     if (GNUNET_OK != GNUNET_OS_process_status (d->proc, &type, &code))
604     {
605       if (GNUNET_TIME_absolute_get_remaining (d->max_timeout).rel_value == 0)
606       {
607         cb = d->cb;
608         d->cb = NULL;
609         if (NULL != cb)
610           cb (d->cb_cls, NULL, d->cfg, d,
611               (NULL ==
612                d->hostname) ? _("`gnunet-arm' does not seem to terminate.\n") :
613               _("`ssh' does not seem to terminate.\n"));
614         return;
615       }
616       /* wait some more */
617       d->task =
618           GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
619                                         d);
620       return;
621     }
622 #if EXTRA_CHECKS
623     if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
624     {
625       cb = d->cb;
626       d->cb = NULL;
627       if (NULL != cb)
628         cb (d->cb_cls, NULL, d->cfg, d,
629             (NULL ==
630              d->hostname) ?
631             _
632             ("`gnunet-arm' terminated with non-zero exit status (or timed out)!\n")
633             : _("`ssh' does not seem to terminate.\n"));
634       return;
635     }
636 #endif
637     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service startup complete!\n");
638     cb = d->cb;
639     d->cb = NULL;
640     d->phase = SP_START_DONE;
641     if (NULL != cb)
642       cb (d->cb_cls, &d->id, d->cfg, d, NULL);
643     break;
644   case SP_SERVICE_SHUTDOWN_START:
645     /* confirm copying complete */
646     if (GNUNET_OK != GNUNET_OS_process_status (d->proc, &type, &code))
647     {
648       if (GNUNET_TIME_absolute_get_remaining (d->max_timeout).rel_value == 0)
649       {
650         if (NULL != d->dead_cb)
651           d->dead_cb (d->dead_cb_cls,
652                       _
653                       ("either `gnunet-arm' or `ssh' does not seem to terminate.\n"));
654         return;
655       }
656       /* wait some more */
657       d->task =
658           GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
659                                         d);
660       return;
661     }
662 #if EXTRA_CHECKS
663     if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
664     {
665       if (NULL != d->dead_cb)
666         d->dead_cb (d->dead_cb_cls,
667                     _
668                     ("shutdown (either `gnunet-arm' or `ssh') did not complete cleanly.\n"));
669       return;
670     }
671 #endif
672     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service shutdown complete.\n");
673     if (NULL != d->dead_cb)
674       d->dead_cb (d->dead_cb_cls, NULL);
675     break;
676   case SP_SHUTDOWN_START:
677     /* confirm copying complete */
678     if (GNUNET_OK != GNUNET_OS_process_status (d->proc, &type, &code))
679     {
680       if (GNUNET_TIME_absolute_get_remaining (d->max_timeout).rel_value == 0)
681       {
682         if (NULL != d->dead_cb)
683           d->dead_cb (d->dead_cb_cls,
684                       _
685                       ("either `gnunet-arm' or `ssh' does not seem to terminate.\n"));
686         if (d->th != NULL)
687         {
688           GNUNET_TRANSPORT_get_hello_cancel (d->ghh);
689           d->ghh = NULL;
690           GNUNET_TRANSPORT_disconnect (d->th);
691           d->th = NULL;
692         }
693         if (d->cfg != NULL)
694         {
695           GNUNET_CONFIGURATION_destroy (d->cfg);
696           d->cfg = NULL;
697         }
698         if (d->cfgfile != NULL)
699         {
700           GNUNET_free (d->cfgfile);
701           d->cfgfile = NULL;
702         }
703         GNUNET_free_non_null (d->hello);
704         GNUNET_free_non_null (d->hostname);
705         GNUNET_free_non_null (d->username);
706         GNUNET_free_non_null (d->shortname);
707         GNUNET_free_non_null (d->proc);
708         d->proc = NULL;
709         GNUNET_free (d);
710         return;
711       }
712       /* wait some more */
713       d->task =
714           GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
715                                         d);
716       return;
717     }
718     if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
719     {
720       if (NULL != d->dead_cb)
721         d->dead_cb (d->dead_cb_cls,
722                     _
723                     ("shutdown (either `gnunet-arm' or `ssh') did not complete cleanly.\n"));
724       if (d->th != NULL)
725       {
726         GNUNET_TRANSPORT_get_hello_cancel (d->ghh);
727         d->ghh = NULL;
728         GNUNET_TRANSPORT_disconnect (d->th);
729         d->th = NULL;
730       }
731       if (d->server != NULL)
732       {
733         GNUNET_CORE_disconnect (d->server);
734         d->server = NULL;
735       }
736       GNUNET_CONFIGURATION_destroy (d->cfg);
737       d->cfg = NULL;
738       GNUNET_free (d->cfgfile);
739       GNUNET_free_non_null (d->hello);
740       GNUNET_free_non_null (d->hostname);
741       GNUNET_free_non_null (d->username);
742       GNUNET_free_non_null (d->shortname);
743       GNUNET_free_non_null (d->proc);
744       d->proc = NULL;
745       GNUNET_free (d);
746       return;
747     }
748     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer shutdown complete.\n");
749     if (d->server != NULL)
750     {
751       GNUNET_CORE_disconnect (d->server);
752       d->server = NULL;
753     }
754
755     if (d->th != NULL)
756     {
757       GNUNET_TRANSPORT_get_hello_cancel (d->ghh);
758       d->ghh = NULL;
759       GNUNET_TRANSPORT_disconnect (d->th);
760       d->th = NULL;
761     }
762
763     if (NULL != d->dead_cb)
764       d->dead_cb (d->dead_cb_cls, NULL);
765
766     /* state clean up and notifications */
767     if (d->churn == GNUNET_NO)
768     {
769       GNUNET_CONFIGURATION_destroy (d->cfg);
770       d->cfg = NULL;
771       GNUNET_free (d->cfgfile);
772       GNUNET_free_non_null (d->hostname);
773       GNUNET_free_non_null (d->username);
774     }
775
776     GNUNET_free_non_null (d->hello);
777     d->hello = NULL;
778     GNUNET_free_non_null (d->shortname);
779     GNUNET_free_non_null (d->proc);
780     d->proc = NULL;
781     d->shortname = NULL;
782     if (d->churn == GNUNET_NO)
783       GNUNET_free (d);
784
785     break;
786   case SP_CONFIG_UPDATE:
787     /* confirm copying complete */
788     if (GNUNET_OK != GNUNET_OS_process_status (d->proc, &type, &code))
789     {
790       if (GNUNET_TIME_absolute_get_remaining (d->max_timeout).rel_value == 0)   /* FIXME: config update should take timeout parameter! */
791       {
792         cb = d->cb;
793         d->cb = NULL;
794         if (NULL != cb)
795           cb (d->cb_cls, NULL, d->cfg, d,
796               _("`scp' does not seem to terminate.\n"));
797         return;
798       }
799       /* wait some more */
800       d->task =
801           GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
802                                         d);
803       return;
804     }
805     if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
806     {
807       if (NULL != d->update_cb)
808         d->update_cb (d->update_cb_cls, _("`scp' did not complete cleanly.\n"));
809       return;
810     }
811     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
812                 "Successfully copied configuration file.\n");
813     if (NULL != d->update_cb)
814       d->update_cb (d->update_cb_cls, NULL);
815     d->phase = SP_START_DONE;
816     break;
817   }
818 }
819
820 /**
821  * Continues GNUnet daemon startup when user wanted to be notified
822  * once a hostkey was generated (for creating friends files, blacklists,
823  * etc.).
824  *
825  * @param daemon the daemon to finish starting
826  */
827 void
828 GNUNET_TESTING_daemon_continue_startup (struct GNUNET_TESTING_Daemon *daemon)
829 {
830   GNUNET_assert (daemon->phase == SP_HOSTKEY_CREATED);
831   daemon->phase = SP_TOPOLOGY_SETUP;
832 }
833
834 /**
835  * Check whether the given daemon is running.
836  *
837  * @param daemon the daemon to check
838  *
839  * @return GNUNET_YES if the daemon is up, GNUNET_NO if the
840  *         daemon is down, GNUNET_SYSERR on error.
841  */
842 int
843 GNUNET_TESTING_test_daemon_running (struct GNUNET_TESTING_Daemon *daemon)
844 {
845   if (daemon == NULL)
846     return GNUNET_SYSERR;
847
848   if (daemon->running == GNUNET_YES)
849     return GNUNET_YES;
850   return GNUNET_NO;
851 }
852
853
854 /**
855  * Starts a GNUnet daemon service which has been previously stopped.
856  *
857  * @param d the daemon for which the service should be started
858  * @param service the name of the service to start
859  * @param timeout how long to wait for process for shutdown to complete
860  * @param cb function called once the service starts
861  * @param cb_cls closure for cb
862  */
863 void
864 GNUNET_TESTING_daemon_start_stopped_service (struct GNUNET_TESTING_Daemon *d,
865                                              char *service,
866                                              struct GNUNET_TIME_Relative
867                                              timeout,
868                                              GNUNET_TESTING_NotifyDaemonRunning
869                                              cb, void *cb_cls)
870 {
871   char *arg;
872
873   d->cb = cb;
874   d->cb_cls = cb_cls;
875
876   GNUNET_assert (d->running == GNUNET_YES);
877
878   if (d->phase == SP_CONFIG_UPDATE)
879   {
880     GNUNET_SCHEDULER_cancel (d->task);
881     d->phase = SP_START_DONE;
882   }
883
884   if (d->churned_services == NULL)
885   {
886     d->cb (d->cb_cls, &d->id, d->cfg, d,
887            "No service has been churned off yet!!");
888     return;
889   }
890   d->phase = SP_SERVICE_START;
891   GNUNET_free (d->churned_services);
892   d->churned_services = NULL;
893   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
894   /* Check if this is a local or remote process */
895   if (NULL != d->hostname)
896   {
897     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
898                 "Starting gnunet-arm with config `%s' on host `%s'.\n",
899                 d->cfgfile, d->hostname);
900     if (d->username != NULL)
901       GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
902     else
903       arg = GNUNET_strdup (d->hostname);
904
905     d->proc = GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "ssh", "ssh",
906 #if !DEBUG_TESTING
907                                        "-q",
908 #endif
909                                        arg, "gnunet-arm",
910 #if DEBUG_TESTING
911                                        "-L", "DEBUG",
912 #endif
913                                        "-c", d->cfgfile, "-i", service, "-q",
914                                        "-T",
915                                        GNUNET_TIME_relative_to_string (timeout),
916                                        NULL);
917     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
918                 "Starting gnunet-arm with command ssh %s gnunet-arm -c %s -i %s -q\n",
919                 arg, "gnunet-arm", d->cfgfile, service);
920     GNUNET_free (arg);
921   }
922   else
923   {
924     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
925                 "Starting gnunet-arm with config `%s' locally.\n", d->cfgfile);
926     d->proc = GNUNET_OS_start_process (GNUNET_YES, NULL, NULL, "gnunet-arm", "gnunet-arm",
927 #if DEBUG_TESTING
928                                        "-L", "DEBUG",
929 #endif
930                                        "-c", d->cfgfile, "-i", service, "-q",
931                                        "-T",
932                                        GNUNET_TIME_relative_to_string (timeout),
933                                        NULL);
934   }
935
936   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
937   d->task = GNUNET_SCHEDULER_add_now (&start_fsm, d);
938 }
939
940 /**
941  * Starts a GNUnet daemon's service.
942  *
943  * @param d the daemon for which the service should be started
944  * @param service the name of the service to start
945  * @param timeout how long to wait for process for startup
946  * @param cb function called once gnunet-arm returns
947  * @param cb_cls closure for cb
948  */
949 void
950 GNUNET_TESTING_daemon_start_service (struct GNUNET_TESTING_Daemon *d,
951                                      const char *service,
952                                      struct GNUNET_TIME_Relative timeout,
953                                      GNUNET_TESTING_NotifyDaemonRunning cb,
954                                      void *cb_cls)
955 {
956   char *arg;
957
958   d->cb = cb;
959   d->cb_cls = cb_cls;
960
961   GNUNET_assert (service != NULL);
962   GNUNET_assert (d->running == GNUNET_YES);
963   GNUNET_assert (d->phase == SP_START_DONE);
964
965   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
966               _("Starting service %s for peer `%4s'\n"), service,
967               GNUNET_i2s (&d->id));
968   d->phase = SP_SERVICE_START;
969   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
970   /* Check if this is a local or remote process */
971   if (NULL != d->hostname)
972   {
973     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
974                 "Starting gnunet-arm with config `%s' on host `%s'.\n",
975                 d->cfgfile, d->hostname);
976     if (d->username != NULL)
977       GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
978     else
979       arg = GNUNET_strdup (d->hostname);
980
981     d->proc = GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "ssh", "ssh",
982 #if !DEBUG_TESTING
983                                        "-q",
984 #endif
985                                        arg, "gnunet-arm",
986 #if DEBUG_TESTING
987                                        "-L", "DEBUG",
988 #endif
989                                        "-c", d->cfgfile, "-i", service, "-q",
990                                        "-T",
991                                        GNUNET_TIME_relative_to_string (timeout),
992                                        NULL);
993     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
994                 "Starting gnunet-arm with command ssh %s gnunet-arm -c %s -i %s -q -T %s\n",
995                 arg, "gnunet-arm", d->cfgfile, service,
996                 GNUNET_TIME_relative_to_string (timeout));
997     GNUNET_free (arg);
998   }
999   else
1000   {
1001     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1002                 "Starting gnunet-arm with config `%s' locally.\n", d->cfgfile);
1003     d->proc = GNUNET_OS_start_process (GNUNET_YES, NULL, NULL, "gnunet-arm", "gnunet-arm",
1004 #if DEBUG_TESTING
1005                                        "-L", "DEBUG",
1006 #endif
1007                                        "-c", d->cfgfile, "-i", service, "-q",
1008                                        "-T",
1009                                        GNUNET_TIME_relative_to_string (timeout),
1010                                        NULL);
1011     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1012                 "Starting gnunet-arm with command %s -c %s -i %s -q -T %s\n",
1013                 "gnunet-arm", d->cfgfile, service,
1014                 GNUNET_TIME_relative_to_string (timeout));
1015   }
1016
1017   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1018   d->task = GNUNET_SCHEDULER_add_now (&start_fsm, d);
1019 }
1020
1021 /**
1022  * Start a peer that has previously been stopped using the daemon_stop
1023  * call (and files weren't deleted and the allow restart flag)
1024  *
1025  * @param daemon the daemon to start (has been previously stopped)
1026  * @param timeout how long to wait for restart
1027  * @param cb the callback for notification when the peer is running
1028  * @param cb_cls closure for the callback
1029  */
1030 void
1031 GNUNET_TESTING_daemon_start_stopped (struct GNUNET_TESTING_Daemon *daemon,
1032                                      struct GNUNET_TIME_Relative timeout,
1033                                      GNUNET_TESTING_NotifyDaemonRunning cb,
1034                                      void *cb_cls)
1035 {
1036   if (daemon->running == GNUNET_YES)
1037   {
1038     cb (cb_cls, &daemon->id, daemon->cfg, daemon,
1039         "Daemon already running, can't restart!");
1040     return;
1041   }
1042
1043   daemon->cb = cb;
1044   daemon->cb_cls = cb_cls;
1045   daemon->phase = SP_TOPOLOGY_SETUP;
1046   daemon->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1047   /* FIXME: why add_continuation? */
1048   GNUNET_SCHEDULER_add_continuation (&start_fsm, daemon,
1049                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1050 }
1051
1052 /**
1053  * Starts a GNUnet daemon.  GNUnet must be installed on the target
1054  * system and available in the PATH.  The machine must furthermore be
1055  * reachable via "ssh" (unless the hostname is "NULL") without the
1056  * need to enter a password.
1057  *
1058  * @param cfg configuration to use
1059  * @param timeout how long to wait starting up peers
1060  * @param pretend GNUNET_YES to set up files but not start peer GNUNET_NO
1061  *                to really start the peer (default)
1062  * @param hostname name of the machine where to run GNUnet
1063  *        (use NULL for localhost).
1064  * @param ssh_username ssh username to use when connecting to hostname
1065  * @param sshport port to pass to ssh process when connecting to hostname
1066  * @param hostkey pointer to a hostkey to be written to disk (instead of being generated)
1067  * @param hostkey_callback function to call once the hostkey has been
1068  *        generated for this peer, but it hasn't yet been started
1069  *        (NULL to start immediately, otherwise waits on GNUNET_TESTING_daemon_continue_start)
1070  * @param hostkey_cls closure for hostkey callback
1071  * @param cb function to call once peer is up, or failed to start
1072  * @param cb_cls closure for cb
1073  * @return handle to the daemon (actual start will be completed asynchronously)
1074  */
1075 struct GNUNET_TESTING_Daemon *
1076 GNUNET_TESTING_daemon_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
1077                              struct GNUNET_TIME_Relative timeout, int pretend,
1078                              const char *hostname, const char *ssh_username,
1079                              uint16_t sshport, const char *hostkey,
1080                              GNUNET_TESTING_NotifyHostkeyCreated
1081                              hostkey_callback, void *hostkey_cls,
1082                              GNUNET_TESTING_NotifyDaemonRunning cb,
1083                              void *cb_cls)
1084 {
1085   struct GNUNET_TESTING_Daemon *ret;
1086   char *arg;
1087   char *username;
1088   char *servicehome;
1089   char *baseservicehome;
1090   char *slash;
1091   char *hostkeyfile;
1092   char *temp_file_name;
1093   struct GNUNET_DISK_FileHandle *fn;
1094   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
1095   struct GNUNET_CRYPTO_RsaPrivateKey *private_key;
1096
1097   ret = GNUNET_malloc (sizeof (struct GNUNET_TESTING_Daemon));
1098   ret->hostname = (hostname == NULL) ? NULL : GNUNET_strdup (hostname);
1099   if (sshport != 0)
1100   {
1101     GNUNET_asprintf (&ret->ssh_port_str, "%d", sshport);
1102   }
1103   else
1104     ret->ssh_port_str = NULL;
1105
1106   /* Find service home and base service home directories, create it if it doesn't exist */
1107   GNUNET_assert (GNUNET_OK ==
1108                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
1109                                                         "SERVICEHOME",
1110                                                         &servicehome));
1111
1112   GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_create (servicehome));
1113   GNUNET_asprintf (&temp_file_name, "%s/gnunet-testing-config", servicehome);
1114   ret->cfgfile = GNUNET_DISK_mktemp (temp_file_name);
1115   GNUNET_free (temp_file_name);
1116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1117               "Setting up peer with configuration file `%s'.\n", ret->cfgfile);
1118   if (NULL == ret->cfgfile)
1119   {
1120     GNUNET_free_non_null (ret->ssh_port_str);
1121     GNUNET_free_non_null (ret->hostname);
1122     GNUNET_free (ret);
1123     return NULL;
1124   }
1125   ret->hostkey_callback = hostkey_callback;
1126   ret->hostkey_cls = hostkey_cls;
1127   ret->cb = cb;
1128   ret->cb_cls = cb_cls;
1129   ret->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1130   ret->cfg = GNUNET_CONFIGURATION_dup (cfg);
1131   GNUNET_CONFIGURATION_set_value_string (ret->cfg, "PATHS", "DEFAULTCONFIG",
1132                                          ret->cfgfile);
1133
1134   if (hostkey != NULL)          /* Get the peer identity from the hostkey */
1135   {
1136     private_key = GNUNET_CRYPTO_rsa_decode_key (hostkey, HOSTKEYFILESIZE);
1137     GNUNET_assert (private_key != NULL);
1138     GNUNET_CRYPTO_rsa_key_get_public (private_key, &public_key);
1139     GNUNET_CRYPTO_hash (&public_key,
1140                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1141                         &ret->id.hashPubKey);
1142     ret->shortname = GNUNET_strdup (GNUNET_i2s (&ret->id));
1143     ret->have_hostkey = GNUNET_YES;
1144     GNUNET_CRYPTO_rsa_key_free (private_key);
1145   }
1146
1147   /* Write hostkey to file, if we were given one */
1148   hostkeyfile = NULL;
1149   if (hostkey != NULL)
1150   {
1151     GNUNET_asprintf (&hostkeyfile, "%s/.hostkey", servicehome);
1152     fn = GNUNET_DISK_file_open (hostkeyfile,
1153                                 GNUNET_DISK_OPEN_READWRITE |
1154                                 GNUNET_DISK_OPEN_CREATE,
1155                                 GNUNET_DISK_PERM_USER_READ |
1156                                 GNUNET_DISK_PERM_USER_WRITE);
1157     GNUNET_assert (fn != NULL);
1158     GNUNET_assert (HOSTKEYFILESIZE ==
1159                    GNUNET_DISK_file_write (fn, hostkey, HOSTKEYFILESIZE));
1160     GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fn));
1161   }
1162
1163   /* write configuration to temporary file */
1164   if (GNUNET_OK != GNUNET_CONFIGURATION_write (ret->cfg, ret->cfgfile))
1165   {
1166     if (0 != UNLINK (ret->cfgfile))
1167       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
1168                                 ret->cfgfile);
1169     GNUNET_CONFIGURATION_destroy (ret->cfg);
1170     GNUNET_free_non_null (ret->hostname);
1171     GNUNET_free (ret->cfgfile);
1172     GNUNET_free (ret);
1173     return NULL;
1174   }
1175   if (ssh_username != NULL)
1176     username = GNUNET_strdup (ssh_username);
1177   if ((ssh_username == NULL) &&
1178       (GNUNET_OK !=
1179        GNUNET_CONFIGURATION_get_value_string (cfg, "TESTING", "USERNAME",
1180                                               &username)))
1181   {
1182     if (NULL != getenv ("USER"))
1183       username = GNUNET_strdup (getenv ("USER"));
1184     else
1185       username = NULL;
1186   }
1187   ret->username = username;
1188
1189   if (GNUNET_NO == pretend)     /* Copy files, enter finite state machine */
1190   {
1191     /* copy directory to remote host */
1192     if (NULL != hostname)
1193     {
1194       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1195                   "Copying configuration directory to host `%s'.\n", hostname);
1196       baseservicehome = GNUNET_strdup (servicehome);
1197       /* Remove trailing /'s */
1198       while (baseservicehome[strlen (baseservicehome) - 1] == '/')
1199         baseservicehome[strlen (baseservicehome) - 1] = '\0';
1200       /* Find next directory /, jump one ahead */
1201       slash = strrchr (baseservicehome, '/');
1202       if (slash != NULL)
1203         *(++slash) = '\0';
1204
1205       ret->phase = SP_COPYING;
1206       if (NULL != username)
1207         GNUNET_asprintf (&arg, "%s@%s:%s", username, hostname, baseservicehome);
1208       else
1209         GNUNET_asprintf (&arg, "%s:%s", hostname, baseservicehome);
1210       GNUNET_free (baseservicehome);
1211       if (ret->ssh_port_str == NULL)
1212       {
1213         ret->proc = GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "scp", "scp", "-r",
1214 #if !DEBUG_TESTING
1215                                              "-q",
1216 #endif
1217                                              servicehome, arg, NULL);
1218         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1219                     "copying directory with command scp -r %s %s\n",
1220                     servicehome, arg);
1221       }
1222       else
1223       {
1224         ret->proc =
1225             GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "scp", "scp", "-r", "-P",
1226                                      ret->ssh_port_str,
1227 #if !DEBUG_TESTING
1228                                      "-q",
1229 #endif
1230                                      servicehome, arg, NULL);
1231       }
1232       GNUNET_free (arg);
1233       if (NULL == ret->proc)
1234       {
1235         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1236                     _
1237                     ("Could not start `%s' process to copy configuration directory.\n"),
1238                     "scp");
1239         if (0 != UNLINK (ret->cfgfile))
1240           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
1241                                     ret->cfgfile);
1242         GNUNET_CONFIGURATION_destroy (ret->cfg);
1243         GNUNET_free_non_null (ret->hostname);
1244         GNUNET_free_non_null (ret->username);
1245         GNUNET_free (ret->cfgfile);
1246         GNUNET_free (ret);
1247         if ((hostkey != NULL) && (0 != UNLINK (hostkeyfile)))
1248           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
1249                                     hostkeyfile);
1250         GNUNET_free_non_null (hostkeyfile);
1251         GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_remove (servicehome));
1252         GNUNET_free (servicehome);
1253         return NULL;
1254       }
1255
1256       ret->task =
1257           GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
1258                                         ret);
1259       GNUNET_free_non_null (hostkeyfile);
1260       GNUNET_free (servicehome);
1261       return ret;
1262     }
1263     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1264                 "No need to copy configuration file since we are running locally.\n");
1265     ret->phase = SP_COPIED;
1266     /* FIXME: why add_cont? */
1267     GNUNET_SCHEDULER_add_continuation (&start_fsm, ret,
1268                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1269   }
1270   GNUNET_free_non_null (hostkeyfile);
1271   GNUNET_free (servicehome);
1272   return ret;
1273 }
1274
1275
1276 /**
1277  * Restart (stop and start) a GNUnet daemon.
1278  *
1279  * @param d the daemon that should be restarted
1280  * @param cb function called once the daemon is (re)started
1281  * @param cb_cls closure for cb
1282  */
1283 void
1284 GNUNET_TESTING_daemon_restart (struct GNUNET_TESTING_Daemon *d,
1285                                GNUNET_TESTING_NotifyDaemonRunning cb,
1286                                void *cb_cls)
1287 {
1288   char *arg;
1289   char *del_arg;
1290
1291   del_arg = NULL;
1292   if (NULL != d->cb)
1293   {
1294     d->dead = GNUNET_YES;
1295     return;
1296   }
1297
1298   d->cb = cb;
1299   d->cb_cls = cb_cls;
1300
1301   if (d->phase == SP_CONFIG_UPDATE)
1302   {
1303     GNUNET_SCHEDULER_cancel (d->task);
1304     d->phase = SP_START_DONE;
1305   }
1306   if (d->server != NULL)
1307   {
1308     GNUNET_CORE_disconnect (d->server);
1309     d->server = NULL;
1310   }
1311
1312   if (d->th != NULL)
1313   {
1314     GNUNET_TRANSPORT_get_hello_cancel (d->ghh);
1315     d->ghh = NULL;
1316     GNUNET_TRANSPORT_disconnect (d->th);
1317     d->th = NULL;
1318   }
1319   /* state clean up and notifications */
1320   GNUNET_free_non_null (d->hello);
1321
1322   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Terminating peer `%4s'\n"),
1323               GNUNET_i2s (&d->id));
1324   d->phase = SP_START_ARMING;
1325
1326   /* Check if this is a local or remote process */
1327   if (NULL != d->hostname)
1328   {
1329     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1330                 "Stopping gnunet-arm with config `%s' on host `%s'.\n",
1331                 d->cfgfile, d->hostname);
1332     if (d->username != NULL)
1333       GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
1334     else
1335       arg = GNUNET_strdup (d->hostname);
1336
1337     d->proc = GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "ssh", "ssh",
1338 #if !DEBUG_TESTING
1339                                        "-q",
1340 #endif
1341                                        arg, "gnunet-arm",
1342 #if DEBUG_TESTING
1343                                        "-L", "DEBUG",
1344 #endif
1345                                        "-c", d->cfgfile, "-e", "-r", NULL);
1346     /* Use -r to restart arm and all services */
1347
1348     GNUNET_free (arg);
1349   }
1350   else
1351   {
1352     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1353                 "Stopping gnunet-arm with config `%s' locally.\n", d->cfgfile);
1354     d->proc = GNUNET_OS_start_process (GNUNET_YES, NULL, NULL, "gnunet-arm", "gnunet-arm",
1355 #if DEBUG_TESTING
1356                                        "-L", "DEBUG",
1357 #endif
1358                                        "-c", d->cfgfile, "-e", "-r", NULL);
1359   }
1360
1361   GNUNET_free_non_null (del_arg);
1362   d->task =
1363       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm, d);
1364
1365 }
1366
1367
1368 /**
1369  * Stops a GNUnet daemon.
1370  *
1371  * @param d the daemon that should be stopped
1372  * @param service the name of the service to stop
1373  * @param timeout how long to wait for process for shutdown to complete
1374  * @param cb function called once the daemon was stopped
1375  * @param cb_cls closure for cb
1376  */
1377 void
1378 GNUNET_TESTING_daemon_stop_service (struct GNUNET_TESTING_Daemon *d,
1379                                     const char *service,
1380                                     struct GNUNET_TIME_Relative timeout,
1381                                     GNUNET_TESTING_NotifyCompletion cb,
1382                                     void *cb_cls)
1383 {
1384   char *arg;
1385
1386   d->dead_cb = cb;
1387   d->dead_cb_cls = cb_cls;
1388
1389   GNUNET_assert (d->running == GNUNET_YES);
1390
1391   if (d->phase == SP_CONFIG_UPDATE)
1392   {
1393     GNUNET_SCHEDULER_cancel (d->task);
1394     d->phase = SP_START_DONE;
1395   }
1396
1397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Terminating peer `%4s'\n"),
1398               GNUNET_i2s (&d->id));
1399   if (d->churned_services != NULL)
1400   {
1401     d->dead_cb (d->dead_cb_cls, "A service has already been turned off!!");
1402     return;
1403   }
1404   d->phase = SP_SERVICE_SHUTDOWN_START;
1405   d->churned_services = GNUNET_strdup (service);
1406   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1407   /* Check if this is a local or remote process */
1408   if (NULL != d->hostname)
1409   {
1410     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1411                 "Stopping gnunet-arm with config `%s' on host `%s'.\n",
1412                 d->cfgfile, d->hostname);
1413     if (d->username != NULL)
1414       GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
1415     else
1416       arg = GNUNET_strdup (d->hostname);
1417
1418     d->proc = GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "ssh", "ssh",
1419 #if !DEBUG_TESTING
1420                                        "-q",
1421 #endif
1422                                        arg, "gnunet-arm",
1423 #if DEBUG_TESTING
1424                                        "-L", "DEBUG",
1425 #endif
1426                                        "-c", d->cfgfile, "-k", service, "-q",
1427                                        "-T",
1428                                        GNUNET_TIME_relative_to_string (timeout),
1429                                        NULL);
1430     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1431                 "Stopping gnunet-arm with command ssh %s gnunet-arm -c %s -k %s -q\n",
1432                 arg, "gnunet-arm", d->cfgfile, service);
1433     GNUNET_free (arg);
1434   }
1435   else
1436   {
1437     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1438                 "Stopping gnunet-arm with config `%s' locally.\n", d->cfgfile);
1439     d->proc = GNUNET_OS_start_process (GNUNET_YES, NULL, NULL, "gnunet-arm", "gnunet-arm",
1440 #if DEBUG_TESTING
1441                                        "-L", "DEBUG",
1442 #endif
1443                                        "-c", d->cfgfile, "-k", service, "-q",
1444                                        "-T",
1445                                        GNUNET_TIME_relative_to_string (timeout),
1446                                        NULL);
1447   }
1448
1449   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1450   d->task = GNUNET_SCHEDULER_add_now (&start_fsm, d);
1451 }
1452
1453
1454 /**
1455  * Stops a GNUnet daemon.
1456  *
1457  * @param d the daemon that should be stopped
1458  * @param timeout how long to wait for process for shutdown to complete
1459  * @param cb function called once the daemon was stopped
1460  * @param cb_cls closure for cb
1461  * @param delete_files GNUNET_YES to remove files, GNUNET_NO
1462  *        to leave them
1463  * @param allow_restart GNUNET_YES to restart peer later (using this API)
1464  *        GNUNET_NO to kill off and clean up for good
1465  */
1466 void
1467 GNUNET_TESTING_daemon_stop (struct GNUNET_TESTING_Daemon *d,
1468                             struct GNUNET_TIME_Relative timeout,
1469                             GNUNET_TESTING_NotifyCompletion cb, void *cb_cls,
1470                             int delete_files, int allow_restart)
1471 {
1472   char *arg;
1473   char *del_arg;
1474
1475   d->dead_cb = cb;
1476   d->dead_cb_cls = cb_cls;
1477
1478   if (NULL != d->cb)
1479   {
1480     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Setting d->dead on peer `%4s'\n"),
1481                 GNUNET_i2s (&d->id));
1482     d->dead = GNUNET_YES;
1483     return;
1484   }
1485
1486   if ((d->running == GNUNET_NO) && (d->churn == GNUNET_YES))    /* Peer has already been stopped in churn context! */
1487   {
1488     /* Free what was left from churning! */
1489     GNUNET_assert (d->cfg != NULL);
1490     GNUNET_CONFIGURATION_destroy (d->cfg);
1491     if (delete_files == GNUNET_YES)
1492     {
1493       if (0 != UNLINK (d->cfgfile))
1494       {
1495         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "unlink");
1496       }
1497     }
1498     GNUNET_free (d->cfgfile);
1499     GNUNET_free_non_null (d->hostname);
1500     GNUNET_free_non_null (d->username);
1501     if (NULL != d->dead_cb)
1502       d->dead_cb (d->dead_cb_cls, NULL);
1503     GNUNET_free (d);
1504     return;
1505   }
1506
1507   del_arg = NULL;
1508   if (delete_files == GNUNET_YES)
1509   {
1510     GNUNET_asprintf (&del_arg, "-d");
1511   }
1512
1513   if (d->phase == SP_CONFIG_UPDATE)
1514   {
1515     GNUNET_SCHEDULER_cancel (d->task);
1516     d->phase = SP_START_DONE;
1517   }
1518   /** Move this call to scheduled shutdown as fix for CORE_connect calling daemon_stop?
1519   if (d->server != NULL)
1520     {
1521       GNUNET_CORE_disconnect (d->server);
1522       d->server = NULL;
1523     }
1524     */
1525   /* shutdown ARM process (will terminate others) */
1526   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Terminating peer `%4s'\n" ,
1527               GNUNET_i2s (&d->id));
1528   d->phase = SP_SHUTDOWN_START;
1529   d->running = GNUNET_NO;
1530   if (allow_restart == GNUNET_YES)
1531     d->churn = GNUNET_YES;
1532   if (d->th != NULL)
1533   {
1534     GNUNET_TRANSPORT_get_hello_cancel (d->ghh);
1535     d->ghh = NULL;
1536     GNUNET_TRANSPORT_disconnect (d->th);
1537     d->th = NULL;
1538   }
1539   /* Check if this is a local or remote process */
1540   if (NULL != d->hostname)
1541   {
1542     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1543                 "Stopping gnunet-arm with config `%s' on host `%s'.\n",
1544                 d->cfgfile, d->hostname);
1545     if (d->username != NULL)
1546       GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
1547     else
1548       arg = GNUNET_strdup (d->hostname);
1549
1550     d->proc = GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "ssh", "ssh",
1551 #if !DEBUG_TESTING
1552                                        "-q",
1553 #endif
1554                                        arg, "gnunet-arm",
1555 #if DEBUG_TESTING
1556                                        "-L", "DEBUG",
1557 #endif
1558                                        "-c", d->cfgfile, "-e", "-q", "-T",
1559                                        GNUNET_TIME_relative_to_string (timeout),
1560                                        del_arg, NULL);
1561     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1562                 "Stopping gnunet-arm with command ssh %s gnunet-arm -c %s -e -q %s\n",
1563                 arg, "gnunet-arm", d->cfgfile, del_arg);
1564     /* Use -e to end arm, and -d to remove temp files */
1565     GNUNET_free (arg);
1566   }
1567   else
1568   {
1569     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1570                 "Stopping gnunet-arm with config `%s' locally.\n", d->cfgfile);
1571     d->proc = GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "gnunet-arm", "gnunet-arm",
1572 #if DEBUG_TESTING
1573                                        "-L", "DEBUG",
1574 #endif
1575                                        "-c", d->cfgfile, "-e", "-q", "-T",
1576                                        GNUNET_TIME_relative_to_string (timeout),
1577                                        del_arg, NULL);
1578     GNUNET_assert (NULL != d->proc);
1579   }
1580
1581   GNUNET_free_non_null (del_arg);
1582   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1583   if (GNUNET_SCHEDULER_NO_TASK != d->task)
1584     GNUNET_SCHEDULER_cancel(d->task);
1585   d->task = GNUNET_SCHEDULER_add_now (&start_fsm, d);
1586 }
1587
1588
1589 /**
1590  * Changes the configuration of a GNUnet daemon.
1591  *
1592  * @param d the daemon that should be modified
1593  * @param cfg the new configuration for the daemon
1594  * @param cb function called once the configuration was changed
1595  * @param cb_cls closure for cb
1596  */
1597 void
1598 GNUNET_TESTING_daemon_reconfigure (struct GNUNET_TESTING_Daemon *d,
1599                                    struct GNUNET_CONFIGURATION_Handle *cfg,
1600                                    GNUNET_TESTING_NotifyCompletion cb,
1601                                    void *cb_cls)
1602 {
1603   char *arg;
1604
1605   if (d->phase != SP_START_DONE)
1606   {
1607     if (NULL != cb)
1608       cb (cb_cls,
1609           _
1610           ("Peer not yet running, can not change configuration at this point."));
1611     return;
1612   }
1613
1614   /* 1) write configuration to temporary file */
1615   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, d->cfgfile))
1616   {
1617     if (NULL != cb)
1618       cb (cb_cls, _("Failed to write new configuration to disk."));
1619     return;
1620   }
1621
1622   /* 2) copy file to remote host (if necessary) */
1623   if (NULL == d->hostname)
1624   {
1625     /* signal success */
1626     if (NULL != cb)
1627       cb (cb_cls, NULL);
1628     return;
1629   }
1630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1631               "Copying updated configuration file to remote host `%s'.\n",
1632               d->hostname);
1633   d->phase = SP_CONFIG_UPDATE;
1634   if (NULL != d->username)
1635     GNUNET_asprintf (&arg, "%s@%s:%s", d->username, d->hostname, d->cfgfile);
1636   else
1637     GNUNET_asprintf (&arg, "%s:%s", d->hostname, d->cfgfile);
1638   d->proc = GNUNET_OS_start_process (GNUNET_NO, NULL, NULL, "scp", "scp",
1639 #if !DEBUG_TESTING
1640                                      "-q",
1641 #endif
1642                                      d->cfgfile, arg, NULL);
1643   GNUNET_free (arg);
1644   if (NULL == d->proc)
1645   {
1646     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1647                 _("Could not start `%s' process to copy configuration file.\n"),
1648                 "scp");
1649     if (NULL != cb)
1650       cb (cb_cls, _("Failed to copy new configuration to remote machine."));
1651     d->phase = SP_START_DONE;
1652     return;
1653   }
1654   d->update_cb = cb;
1655   d->update_cb_cls = cb_cls;
1656   d->task =
1657       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm, d);
1658 }
1659
1660
1661 /**
1662  * Data kept for each pair of peers that we try
1663  * to connect.
1664  */
1665 struct GNUNET_TESTING_ConnectContext
1666 {
1667   /**
1668    * Testing handle to the first daemon.
1669    */
1670   struct GNUNET_TESTING_Daemon *d1;
1671
1672   /**
1673    * Handle to core of first daemon (to check connect)
1674    */
1675   struct GNUNET_CORE_Handle *d1core;
1676
1677   /**
1678    * Have we actually connected to the core of the first daemon yet?
1679    */
1680   int d1core_ready;
1681
1682   /**
1683    * Testing handle to the second daemon.
1684    */
1685   struct GNUNET_TESTING_Daemon *d2;
1686
1687   /**
1688    * Transport handle to the first daemon (to offer the HELLO of the second daemon to).
1689    */
1690   struct GNUNET_TRANSPORT_Handle *d1th;
1691
1692   /**
1693    * Function to call once we are done (or have timed out).
1694    */
1695   GNUNET_TESTING_NotifyConnection cb;
1696
1697   /**
1698    * Closure for "nb".
1699    */
1700   void *cb_cls;
1701
1702   /**
1703    * The relative timeout from whence this connect attempt was
1704    * started.  Allows for reconnect attempts.
1705    */
1706   struct GNUNET_TIME_Relative relative_timeout;
1707
1708   /**
1709    * Maximum number of connect attempts, will retry connection
1710    * this number of times on failures.
1711    */
1712   unsigned int connect_attempts;
1713
1714   /**
1715    * Hello timeout task
1716    */
1717   GNUNET_SCHEDULER_TaskIdentifier hello_send_task;
1718
1719   /**
1720    * Connect timeout task
1721    */
1722   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1723
1724   /**
1725    * When should this operation be complete (or we must trigger
1726    * a timeout).
1727    */
1728   struct GNUNET_TIME_Relative timeout_hello;
1729
1730   /**
1731    * Was the connection attempt successful?
1732    */
1733   int connected;
1734
1735   /**
1736    * When connecting, do we need to send the HELLO?
1737    */
1738   int send_hello;
1739
1740   /**
1741    * The distance between the two connected peers
1742    */
1743   uint32_t distance;
1744 };
1745
1746
1747 /** Forward declaration **/
1748 static void
1749 reattempt_daemons_connect (void *cls,
1750                            const struct GNUNET_SCHEDULER_TaskContext *tc);
1751
1752
1753 /**
1754  * Notify callback about success or failure of the attempt
1755  * to connect the two peers
1756  *
1757  * @param cls our "struct GNUNET_TESTING_ConnectContext" (freed)
1758  * @param tc reason tells us if we succeeded or failed
1759  */
1760 static void
1761 notify_connect_result (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1762 {
1763   struct GNUNET_TESTING_ConnectContext *ctx = cls;
1764
1765   ctx->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1766   if (ctx->hello_send_task != GNUNET_SCHEDULER_NO_TASK)
1767   {
1768     GNUNET_SCHEDULER_cancel (ctx->hello_send_task);
1769     ctx->hello_send_task = GNUNET_SCHEDULER_NO_TASK;
1770   }
1771
1772   if (ctx->d1th != NULL)
1773     GNUNET_TRANSPORT_disconnect (ctx->d1th);
1774   ctx->d1th = NULL;
1775   if (ctx->d1core != NULL)
1776     GNUNET_CORE_disconnect (ctx->d1core);
1777   ctx->d1core = NULL;
1778
1779   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1780   {
1781     GNUNET_free (ctx);
1782     return;
1783   }
1784
1785   if (ctx->connected == GNUNET_YES)
1786   {
1787     if (ctx->cb != NULL)
1788     {
1789       ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, ctx->distance,
1790                ctx->d1->cfg, ctx->d2->cfg, ctx->d1, ctx->d2, NULL);
1791     }
1792   }
1793   else if (ctx->connect_attempts > 0)
1794   {
1795     ctx->d1core_ready = GNUNET_NO;
1796     ctx->timeout_task =
1797         GNUNET_SCHEDULER_add_now (&reattempt_daemons_connect, ctx);
1798     return;
1799   }
1800   else
1801   {
1802     if (ctx->cb != NULL)
1803     {
1804       ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, 0, ctx->d1->cfg,
1805                ctx->d2->cfg, ctx->d1, ctx->d2, _("Peers failed to connect"));
1806     }
1807   }
1808   GNUNET_free (ctx);
1809 }
1810
1811
1812 /**
1813  * Success, connection is up.  Signal client our success.
1814  *
1815  * @param cls our "struct GNUNET_TESTING_ConnectContext"
1816  * @param peer identity of the peer that has connected
1817  * @param atsi performance information
1818  * @param atsi_count number of records in 'atsi'
1819  *
1820  */
1821 static void
1822 connect_notify (void *cls, const struct GNUNET_PeerIdentity *peer,
1823                 const struct GNUNET_ATS_Information *atsi,
1824                 unsigned int atsi_count)
1825 {
1826   struct GNUNET_TESTING_ConnectContext *ctx = cls;
1827
1828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected peer %s to peer %s\n",
1829               ctx->d1->shortname, GNUNET_i2s (peer));
1830   if (0 != memcmp (&ctx->d2->id, peer, sizeof (struct GNUNET_PeerIdentity)))
1831     return;
1832   ctx->connected = GNUNET_YES;
1833   ctx->distance = 0;            /* FIXME: distance */
1834   if (ctx->hello_send_task != GNUNET_SCHEDULER_NO_TASK)
1835   {
1836     GNUNET_SCHEDULER_cancel (ctx->hello_send_task);
1837     ctx->hello_send_task = GNUNET_SCHEDULER_NO_TASK;
1838   }
1839   GNUNET_SCHEDULER_cancel (ctx->timeout_task);
1840   ctx->timeout_task = GNUNET_SCHEDULER_add_now (&notify_connect_result, ctx);
1841 }
1842
1843
1844 static void
1845 send_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1846 {
1847   struct GNUNET_TESTING_ConnectContext *ctx = cls;
1848   struct GNUNET_MessageHeader *hello;
1849
1850   ctx->hello_send_task = GNUNET_SCHEDULER_NO_TASK;
1851   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1852     return;
1853   if ((ctx->d1core_ready == GNUNET_YES) && (ctx->d2->hello != NULL) &&
1854       (NULL != GNUNET_HELLO_get_header (ctx->d2->hello)) &&
1855       (ctx->d1->phase == SP_START_DONE) && (ctx->d2->phase == SP_START_DONE))
1856   {
1857     hello = GNUNET_HELLO_get_header (ctx->d2->hello);
1858     GNUNET_assert (hello != NULL);
1859     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Offering hello of %s to %s\n",
1860                 ctx->d2->shortname, ctx->d1->shortname);
1861     GNUNET_TRANSPORT_offer_hello (ctx->d1th, hello, NULL, NULL);
1862     GNUNET_assert (ctx->d1core != NULL);
1863     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1864                 "Sending connect request to TRANSPORT of %s for peer %s\n",
1865                 GNUNET_i2s (&ctx->d1->id),
1866                 GNUNET_h2s (&ctx->d2->id.hashPubKey));
1867     GNUNET_TRANSPORT_try_connect (ctx->d1th, &ctx->d2->id);
1868     ctx->timeout_hello =
1869         GNUNET_TIME_relative_add (ctx->timeout_hello,
1870                                   GNUNET_TIME_relative_multiply
1871                                   (GNUNET_TIME_UNIT_MILLISECONDS, 500));
1872   }
1873   ctx->hello_send_task =
1874       GNUNET_SCHEDULER_add_delayed (ctx->timeout_hello, &send_hello, ctx);
1875 }
1876
1877 /**
1878  * Notify of a successful connection to the core service.
1879  *
1880  * @param cls a ConnectContext
1881  * @param server handle to the core service
1882  * @param my_identity the peer identity of this peer
1883  */
1884 void
1885 core_init_notify (void *cls, struct GNUNET_CORE_Handle *server,
1886                   const struct GNUNET_PeerIdentity *my_identity)
1887 {
1888   struct GNUNET_TESTING_ConnectContext *connect_ctx = cls;
1889
1890   connect_ctx->d1core_ready = GNUNET_YES;
1891
1892   if (connect_ctx->send_hello == GNUNET_NO)
1893   {
1894     GNUNET_TRANSPORT_try_connect (connect_ctx->d1th, &connect_ctx->d2->id);
1895     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1896                 "Sending connect request to TRANSPORT of %s for peer %s\n",
1897                 connect_ctx->d1->shortname, connect_ctx->d2->shortname);
1898   }
1899 }
1900
1901
1902 /**
1903  * Try to connect again some peers that failed in an earlier attempt. This will
1904  * be tried as many times as connection_attempts in the configuration file.
1905  *
1906  * @param cls Closure (connection context between the two peers).
1907  * @param tc TaskContext.
1908  */
1909 static void
1910 reattempt_daemons_connect (void *cls,
1911                            const struct GNUNET_SCHEDULER_TaskContext *tc)
1912 {
1913   struct GNUNET_TESTING_ConnectContext *ctx = cls;
1914
1915   ctx->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1916   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1917     return;
1918   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1919               "re-attempting connect of peer %s to peer %s\n",
1920               ctx->d1->shortname, ctx->d2->shortname);
1921   ctx->connect_attempts--;
1922   GNUNET_assert (ctx->d1core == NULL);
1923   ctx->d1core_ready = GNUNET_NO;
1924   ctx->d1core =
1925       GNUNET_CORE_connect (ctx->d1->cfg, 1, ctx, &core_init_notify,
1926                            &connect_notify, NULL, NULL, GNUNET_NO, NULL,
1927                            GNUNET_NO, no_handlers);
1928   if (ctx->d1core == NULL)
1929   {
1930     if (NULL != ctx->cb)
1931       ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, 0, ctx->d1->cfg,
1932                ctx->d2->cfg, ctx->d1, ctx->d2,
1933                _("Failed to connect to core service of first peer!\n"));
1934     GNUNET_free (ctx);
1935     return;
1936   }
1937
1938   /* Don't know reason for initial connect failure, update the HELLO for the second peer */
1939   if (NULL != ctx->d2->hello)
1940   {
1941     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "updating %s's HELLO\n",
1942                 ctx->d2->shortname);
1943     GNUNET_free (ctx->d2->hello);
1944     ctx->d2->hello = NULL;
1945     if (NULL != ctx->d2->th)
1946     {
1947       GNUNET_TRANSPORT_get_hello_cancel (ctx->d2->ghh);
1948       ctx->d2->ghh = NULL;
1949       GNUNET_TRANSPORT_disconnect (ctx->d2->th);
1950     }
1951     ctx->d2->th =
1952         GNUNET_TRANSPORT_connect (ctx->d2->cfg, &ctx->d2->id, NULL, NULL, NULL,
1953                                   NULL);
1954     GNUNET_assert (ctx->d2->th != NULL);
1955     ctx->d2->ghh =
1956         GNUNET_TRANSPORT_get_hello (ctx->d2->th, &process_hello, ctx->d2);
1957   }
1958   else
1959   {
1960     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "didn't have %s's HELLO\n",
1961                 ctx->d2->shortname);
1962   }
1963
1964   if ((NULL == ctx->d2->hello) && (ctx->d2->th == NULL))
1965   {
1966     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1967                 "didn't have %s's HELLO, trying to get it now\n",
1968                 ctx->d2->shortname);
1969     ctx->d2->th =
1970         GNUNET_TRANSPORT_connect (ctx->d2->cfg, &ctx->d2->id, NULL, NULL, NULL,
1971                                   NULL);
1972     if (NULL == ctx->d2->th)
1973     {
1974       GNUNET_CORE_disconnect (ctx->d1core);
1975       GNUNET_free (ctx);
1976       if (NULL != ctx->cb)
1977         ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, 0, ctx->d1->cfg,
1978                  ctx->d2->cfg, ctx->d1, ctx->d2,
1979                  _("Failed to connect to transport service!\n"));
1980       return;
1981     }
1982     ctx->d2->ghh =
1983         GNUNET_TRANSPORT_get_hello (ctx->d2->th, &process_hello, ctx->d2);
1984   }
1985   else
1986   {
1987     if (NULL == ctx->d2->hello)
1988     {
1989       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1990                   "didn't have %s's HELLO but th wasn't NULL, not trying!!\n",
1991                   ctx->d2->shortname);
1992     }
1993   }
1994
1995   if (ctx->send_hello == GNUNET_YES)
1996   {
1997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending %s's HELLO to %s\n",
1998                 ctx->d1->shortname, ctx->d2->shortname);
1999     ctx->d1th =
2000         GNUNET_TRANSPORT_connect (ctx->d1->cfg, &ctx->d1->id, ctx->d1, NULL,
2001                                   NULL, NULL);
2002     if (ctx->d1th == NULL)
2003     {
2004       GNUNET_CORE_disconnect (ctx->d1core);
2005       GNUNET_free (ctx);
2006       if (NULL != ctx->cb)
2007         ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, 0, ctx->d1->cfg,
2008                  ctx->d2->cfg, ctx->d1, ctx->d2,
2009                  _("Failed to connect to transport service!\n"));
2010       return;
2011     }
2012     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == ctx->hello_send_task);
2013     ctx->hello_send_task = GNUNET_SCHEDULER_add_now (&send_hello, ctx);
2014   }
2015   else
2016   {
2017     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Trying to reconnect %s to %s\n",
2018                 ctx->d1->shortname, ctx->d2->shortname);
2019     GNUNET_TRANSPORT_try_connect (ctx->d1th, &ctx->d2->id);
2020   }
2021   ctx->timeout_task =
2022       GNUNET_SCHEDULER_add_delayed (ctx->relative_timeout,
2023                                     &notify_connect_result, ctx);
2024 }
2025
2026 /**
2027  * Iterator for currently known peers, to ensure
2028  * that we don't try to send duplicate connect
2029  * requests to core.
2030  *
2031  * @param cls our "struct GNUNET_TESTING_ConnectContext"
2032  * @param peer identity of the peer that has connected,
2033  *        NULL when iteration has finished
2034  * @param atsi performance information
2035  * @param atsi_count number of records in 'atsi'
2036  *
2037  */
2038 static void
2039 core_initial_iteration (void *cls, const struct GNUNET_PeerIdentity *peer,
2040                         const struct GNUNET_ATS_Information *atsi,
2041                         unsigned int atsi_count)
2042 {
2043   struct GNUNET_TESTING_ConnectContext *ctx = cls;
2044
2045   if ((peer != NULL) &&
2046       (0 == memcmp (&ctx->d2->id, peer, sizeof (struct GNUNET_PeerIdentity))))
2047   {
2048     ctx->connected = GNUNET_YES;
2049     ctx->distance = 0;          /* FIXME: distance */
2050     return;
2051   }
2052   if (peer != NULL)
2053     return;                     /* ignore other peers */
2054   /* peer == NULL: End of iteration over peers */
2055
2056   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == ctx->timeout_task);
2057   if (ctx->connected == GNUNET_YES)
2058   {
2059     ctx->timeout_task = GNUNET_SCHEDULER_add_now (&notify_connect_result, ctx);
2060     return;
2061   }
2062
2063   /* Peer not already connected, need to schedule connect request! */
2064   if (ctx->d1core == NULL)
2065   {
2066     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2067                 "Peers are NOT connected, connecting to core!\n");
2068     ctx->d1core =
2069         GNUNET_CORE_connect (ctx->d1->cfg, 1, ctx, &core_init_notify,
2070                              &connect_notify, NULL, NULL, GNUNET_NO, NULL,
2071                              GNUNET_NO, no_handlers);
2072   }
2073
2074   if (ctx->d1core == NULL)
2075   {
2076     ctx->timeout_task = GNUNET_SCHEDULER_add_now (&notify_connect_result, ctx);
2077     return;
2078   }
2079
2080   if ((NULL == ctx->d2->hello) && (ctx->d2->th == NULL))        /* Do not yet have the second peer's hello, set up a task to get it */
2081   {
2082     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2083                 "Don't have d2's HELLO, trying to get it!\n");
2084     ctx->d2->th =
2085         GNUNET_TRANSPORT_connect (ctx->d2->cfg, &ctx->d2->id, NULL, NULL, NULL,
2086                                   NULL);
2087     if (ctx->d2->th == NULL)
2088     {
2089       GNUNET_CORE_disconnect (ctx->d1core);
2090       ctx->d1core = NULL;
2091       ctx->timeout_task =
2092           GNUNET_SCHEDULER_add_now (&notify_connect_result, ctx);
2093       return;
2094     }
2095     ctx->d2->ghh =
2096         GNUNET_TRANSPORT_get_hello (ctx->d2->th, &process_hello, ctx->d2);
2097   }
2098
2099   if (ctx->send_hello == GNUNET_YES)
2100   {
2101     ctx->d1th =
2102         GNUNET_TRANSPORT_connect (ctx->d1->cfg, &ctx->d1->id, ctx->d1, NULL,
2103                                   NULL, NULL);
2104     if (ctx->d1th == NULL)
2105     {
2106       GNUNET_CORE_disconnect (ctx->d1core);
2107       ctx->d1core = NULL;
2108       ctx->timeout_task =
2109           GNUNET_SCHEDULER_add_now (&notify_connect_result, ctx);
2110       return;
2111     }
2112     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == ctx->hello_send_task);
2113     ctx->hello_send_task = GNUNET_SCHEDULER_add_now (&send_hello, ctx);
2114   }
2115
2116   ctx->timeout_task =
2117       GNUNET_SCHEDULER_add_delayed (ctx->relative_timeout,
2118                                     &notify_connect_result, ctx);
2119
2120 }
2121
2122
2123 /**
2124  * Establish a connection between two GNUnet daemons.  The daemons
2125  * must both be running and not be stopped until either the
2126  * 'cb' callback is called OR the connection request has been
2127  * explicitly cancelled.
2128  *
2129  * @param d1 handle for the first daemon
2130  * @param d2 handle for the second daemon
2131  * @param timeout how long is the connection attempt
2132  *        allowed to take?
2133  * @param max_connect_attempts how many times should we try to reconnect
2134  *        (within timeout)
2135  * @param send_hello GNUNET_YES to send the HELLO, GNUNET_NO to assume
2136  *                   the HELLO has already been exchanged
2137  * @param cb function to call at the end
2138  * @param cb_cls closure for cb
2139  * @return handle to cancel the request
2140  */
2141 struct GNUNET_TESTING_ConnectContext *
2142 GNUNET_TESTING_daemons_connect (struct GNUNET_TESTING_Daemon *d1,
2143                                 struct GNUNET_TESTING_Daemon *d2,
2144                                 struct GNUNET_TIME_Relative timeout,
2145                                 unsigned int max_connect_attempts,
2146                                 int send_hello,
2147                                 GNUNET_TESTING_NotifyConnection cb,
2148                                 void *cb_cls)
2149 {
2150   struct GNUNET_TESTING_ConnectContext *ctx;
2151
2152   if ((d1->running == GNUNET_NO) || (d2->running == GNUNET_NO))
2153   {
2154     if (NULL != cb)
2155       cb (cb_cls, &d1->id, &d2->id, 0, d1->cfg, d2->cfg, d1, d2,
2156           _("Peers are not fully running yet, can not connect!\n"));
2157     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Peers are not up!\n");
2158     return NULL;
2159   }
2160
2161   ctx = GNUNET_malloc (sizeof (struct GNUNET_TESTING_ConnectContext));
2162   ctx->d1 = d1;
2163   ctx->d2 = d2;
2164   ctx->timeout_hello =
2165       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500);
2166   ctx->relative_timeout =
2167       GNUNET_TIME_relative_divide (timeout, max_connect_attempts);
2168   ctx->cb = cb;
2169   ctx->cb_cls = cb_cls;
2170   ctx->connect_attempts = max_connect_attempts;
2171   ctx->connected = GNUNET_NO;
2172   ctx->send_hello = send_hello;
2173   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asked to connect peer %s to peer %s\n",
2174               d1->shortname, d2->shortname);
2175   /* Core is up! Iterate over all _known_ peers first to check if we are already connected to the peer! */
2176   GNUNET_assert (GNUNET_OK ==
2177                  GNUNET_CORE_is_peer_connected (ctx->d1->cfg, &ctx->d2->id,
2178                                                 &core_initial_iteration, ctx));
2179   return ctx;
2180 }
2181
2182
2183 /**
2184  * Cancel an attempt to connect two daemons.
2185  *
2186  * @param cc connect context
2187  */
2188 void
2189 GNUNET_TESTING_daemons_connect_cancel (struct GNUNET_TESTING_ConnectContext *cc)
2190 {
2191   if (GNUNET_SCHEDULER_NO_TASK != cc->timeout_task)
2192   {
2193     GNUNET_SCHEDULER_cancel (cc->timeout_task);
2194     cc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2195   }
2196   if (GNUNET_SCHEDULER_NO_TASK != cc->hello_send_task)
2197   {
2198     GNUNET_SCHEDULER_cancel (cc->hello_send_task);
2199     cc->hello_send_task = GNUNET_SCHEDULER_NO_TASK;
2200   }
2201   if (NULL != cc->d1core)
2202   {
2203     GNUNET_CORE_disconnect (cc->d1core);
2204     cc->d1core = NULL;
2205   }
2206   if (NULL != cc->d1th)
2207   {
2208     GNUNET_TRANSPORT_disconnect (cc->d1th);
2209     cc->d1th = NULL;
2210   }
2211   GNUNET_free (cc);
2212 }
2213
2214
2215 /* end of testing.c */