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