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