-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       d->cfg = NULL;
777       GNUNET_free (d->cfgfile);
778       GNUNET_free_non_null (d->hello);
779       GNUNET_free_non_null (d->hostname);
780       GNUNET_free_non_null (d->username);
781       GNUNET_free_non_null (d->shortname);
782       GNUNET_free_non_null (d->proc);
783       d->proc = NULL;
784       GNUNET_free (d);
785       return;
786     }
787 #if DEBUG_TESTING
788     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer shutdown complete.\n");
789 #endif
790     if (d->server != NULL)
791     {
792       GNUNET_CORE_disconnect (d->server);
793       d->server = NULL;
794     }
795
796     if (d->th != NULL)
797     {
798       GNUNET_TRANSPORT_get_hello_cancel (d->ghh);
799       d->ghh = NULL;
800       GNUNET_TRANSPORT_disconnect (d->th);
801       d->th = NULL;
802     }
803
804     if (NULL != d->dead_cb)
805       d->dead_cb (d->dead_cb_cls, NULL);
806
807     /* state clean up and notifications */
808     if (d->churn == GNUNET_NO)
809     {
810       GNUNET_CONFIGURATION_destroy (d->cfg);
811       d->cfg = NULL;
812       GNUNET_free (d->cfgfile);
813       GNUNET_free_non_null (d->hostname);
814       GNUNET_free_non_null (d->username);
815     }
816
817     GNUNET_free_non_null (d->hello);
818     d->hello = NULL;
819     GNUNET_free_non_null (d->shortname);
820     GNUNET_free_non_null (d->proc);
821     d->proc = NULL;
822     d->shortname = NULL;
823     if (d->churn == GNUNET_NO)
824       GNUNET_free (d);
825
826     break;
827   case SP_CONFIG_UPDATE:
828     /* confirm copying complete */
829     if (GNUNET_OK != GNUNET_OS_process_status (d->proc, &type, &code))
830     {
831       if (GNUNET_TIME_absolute_get_remaining (d->max_timeout).rel_value == 0)   /* FIXME: config update should take timeout parameter! */
832       {
833         cb = d->cb;
834         d->cb = NULL;
835         if (NULL != cb)
836           cb (d->cb_cls, NULL, d->cfg, d,
837               _("`scp' does not seem to terminate.\n"));
838         return;
839       }
840       /* wait some more */
841       d->task =
842           GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
843                                         d);
844       return;
845     }
846     if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
847     {
848       if (NULL != d->update_cb)
849         d->update_cb (d->update_cb_cls, _("`scp' did not complete cleanly.\n"));
850       return;
851     }
852 #if DEBUG_TESTING
853     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
854                 "Successfully copied configuration file.\n");
855 #endif
856     if (NULL != d->update_cb)
857       d->update_cb (d->update_cb_cls, NULL);
858     d->phase = SP_START_DONE;
859     break;
860   }
861 }
862
863 /**
864  * Continues GNUnet daemon startup when user wanted to be notified
865  * once a hostkey was generated (for creating friends files, blacklists,
866  * etc.).
867  *
868  * @param daemon the daemon to finish starting
869  */
870 void
871 GNUNET_TESTING_daemon_continue_startup (struct GNUNET_TESTING_Daemon *daemon)
872 {
873   GNUNET_assert (daemon->phase == SP_HOSTKEY_CREATED);
874   daemon->phase = SP_TOPOLOGY_SETUP;
875 }
876
877 /**
878  * Check whether the given daemon is running.
879  *
880  * @param daemon the daemon to check
881  *
882  * @return GNUNET_YES if the daemon is up, GNUNET_NO if the
883  *         daemon is down, GNUNET_SYSERR on error.
884  */
885 int
886 GNUNET_TESTING_test_daemon_running (struct GNUNET_TESTING_Daemon *daemon)
887 {
888   if (daemon == NULL)
889     return GNUNET_SYSERR;
890
891   if (daemon->running == GNUNET_YES)
892     return GNUNET_YES;
893   return GNUNET_NO;
894 }
895
896
897 /**
898  * Starts a GNUnet daemon service which has been previously stopped.
899  *
900  * @param d the daemon for which the service should be started
901  * @param service the name of the service to start
902  * @param timeout how long to wait for process for shutdown to complete
903  * @param cb function called once the service starts
904  * @param cb_cls closure for cb
905  */
906 void
907 GNUNET_TESTING_daemon_start_stopped_service (struct GNUNET_TESTING_Daemon *d,
908                                              char *service,
909                                              struct GNUNET_TIME_Relative
910                                              timeout,
911                                              GNUNET_TESTING_NotifyDaemonRunning
912                                              cb, void *cb_cls)
913 {
914   char *arg;
915
916   d->cb = cb;
917   d->cb_cls = cb_cls;
918
919   GNUNET_assert (d->running == GNUNET_YES);
920
921   if (d->phase == SP_CONFIG_UPDATE)
922   {
923     GNUNET_SCHEDULER_cancel (d->task);
924     d->phase = SP_START_DONE;
925   }
926
927   if (d->churned_services == NULL)
928   {
929     d->cb (d->cb_cls, &d->id, d->cfg, d,
930            "No service has been churned off yet!!");
931     return;
932   }
933   d->phase = SP_SERVICE_START;
934   GNUNET_free (d->churned_services);
935   d->churned_services = NULL;
936   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
937   /* Check if this is a local or remote process */
938   if (NULL != d->hostname)
939   {
940 #if DEBUG_TESTING
941     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
942                 "Starting gnunet-arm with config `%s' on host `%s'.\n",
943                 d->cfgfile, d->hostname);
944 #endif
945
946     if (d->username != NULL)
947       GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
948     else
949       arg = GNUNET_strdup (d->hostname);
950
951     d->proc = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh",
952 #if !DEBUG_TESTING
953                                        "-q",
954 #endif
955                                        arg, "gnunet-arm",
956 #if DEBUG_TESTING
957                                        "-L", "DEBUG",
958 #endif
959                                        "-c", d->cfgfile, "-i", service, "-q",
960                                        "-T",
961                                        GNUNET_TIME_relative_to_string (timeout),
962                                        NULL);
963     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964                 "Starting gnunet-arm with command ssh %s gnunet-arm -c %s -i %s -q\n",
965                 arg, "gnunet-arm", d->cfgfile, service);
966     GNUNET_free (arg);
967   }
968   else
969   {
970 #if DEBUG_TESTING
971     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
972                 "Starting gnunet-arm with config `%s' locally.\n", d->cfgfile);
973 #endif
974     d->proc = GNUNET_OS_start_process (NULL, NULL, "gnunet-arm", "gnunet-arm",
975 #if DEBUG_TESTING
976                                        "-L", "DEBUG",
977 #endif
978                                        "-c", d->cfgfile, "-i", service, "-q",
979                                        "-T",
980                                        GNUNET_TIME_relative_to_string (timeout),
981                                        NULL);
982   }
983
984   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
985   d->task = GNUNET_SCHEDULER_add_now (&start_fsm, d);
986 }
987
988 /**
989  * Starts a GNUnet daemon's service.
990  *
991  * @param d the daemon for which the service should be started
992  * @param service the name of the service to start
993  * @param timeout how long to wait for process for startup
994  * @param cb function called once gnunet-arm returns
995  * @param cb_cls closure for cb
996  */
997 void
998 GNUNET_TESTING_daemon_start_service (struct GNUNET_TESTING_Daemon *d,
999                                      const char *service,
1000                                      struct GNUNET_TIME_Relative timeout,
1001                                      GNUNET_TESTING_NotifyDaemonRunning cb,
1002                                      void *cb_cls)
1003 {
1004   char *arg;
1005
1006   d->cb = cb;
1007   d->cb_cls = cb_cls;
1008
1009   GNUNET_assert (service != NULL);
1010   GNUNET_assert (d->running == GNUNET_YES);
1011   GNUNET_assert (d->phase == SP_START_DONE);
1012
1013 #if DEBUG_TESTING
1014   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1015               _("Starting service %s for peer `%4s'\n"), service,
1016               GNUNET_i2s (&d->id));
1017 #endif
1018
1019   d->phase = SP_SERVICE_START;
1020   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1021   /* Check if this is a local or remote process */
1022   if (NULL != d->hostname)
1023   {
1024 #if DEBUG_TESTING
1025     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1026                 "Starting gnunet-arm with config `%s' on host `%s'.\n",
1027                 d->cfgfile, d->hostname);
1028 #endif
1029
1030     if (d->username != NULL)
1031       GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
1032     else
1033       arg = GNUNET_strdup (d->hostname);
1034
1035     d->proc = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh",
1036 #if !DEBUG_TESTING
1037                                        "-q",
1038 #endif
1039                                        arg, "gnunet-arm",
1040 #if DEBUG_TESTING
1041                                        "-L", "DEBUG",
1042 #endif
1043                                        "-c", d->cfgfile, "-i", service, "-q",
1044                                        "-T",
1045                                        GNUNET_TIME_relative_to_string (timeout),
1046                                        NULL);
1047     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1048                 "Starting gnunet-arm with command ssh %s gnunet-arm -c %s -i %s -q -T %s\n",
1049                 arg, "gnunet-arm", d->cfgfile, service,
1050                 GNUNET_TIME_relative_to_string (timeout));
1051     GNUNET_free (arg);
1052   }
1053   else
1054   {
1055 #if DEBUG_TESTING
1056     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1057                 "Starting gnunet-arm with config `%s' locally.\n", d->cfgfile);
1058 #endif
1059     d->proc = GNUNET_OS_start_process (NULL, NULL, "gnunet-arm", "gnunet-arm",
1060 #if DEBUG_TESTING
1061                                        "-L", "DEBUG",
1062 #endif
1063                                        "-c", d->cfgfile, "-i", service, "-q",
1064                                        "-T",
1065                                        GNUNET_TIME_relative_to_string (timeout),
1066                                        NULL);
1067     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1068                 "Starting gnunet-arm with command %s -c %s -i %s -q -T %s\n",
1069                 "gnunet-arm", d->cfgfile, service,
1070                 GNUNET_TIME_relative_to_string (timeout));
1071   }
1072
1073   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1074   d->task = GNUNET_SCHEDULER_add_now (&start_fsm, d);
1075 }
1076
1077 /**
1078  * Start a peer that has previously been stopped using the daemon_stop
1079  * call (and files weren't deleted and the allow restart flag)
1080  *
1081  * @param daemon the daemon to start (has been previously stopped)
1082  * @param timeout how long to wait for restart
1083  * @param cb the callback for notification when the peer is running
1084  * @param cb_cls closure for the callback
1085  */
1086 void
1087 GNUNET_TESTING_daemon_start_stopped (struct GNUNET_TESTING_Daemon *daemon,
1088                                      struct GNUNET_TIME_Relative timeout,
1089                                      GNUNET_TESTING_NotifyDaemonRunning cb,
1090                                      void *cb_cls)
1091 {
1092   if (daemon->running == GNUNET_YES)
1093   {
1094     cb (cb_cls, &daemon->id, daemon->cfg, daemon,
1095         "Daemon already running, can't restart!");
1096     return;
1097   }
1098
1099   daemon->cb = cb;
1100   daemon->cb_cls = cb_cls;
1101   daemon->phase = SP_TOPOLOGY_SETUP;
1102   daemon->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1103   /* FIXME: why add_continuation? */
1104   GNUNET_SCHEDULER_add_continuation (&start_fsm, daemon,
1105                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1106 }
1107
1108 /**
1109  * Starts a GNUnet daemon.  GNUnet must be installed on the target
1110  * system and available in the PATH.  The machine must furthermore be
1111  * reachable via "ssh" (unless the hostname is "NULL") without the
1112  * need to enter a password.
1113  *
1114  * @param cfg configuration to use
1115  * @param timeout how long to wait starting up peers
1116  * @param pretend GNUNET_YES to set up files but not start peer GNUNET_NO
1117  *                to really start the peer (default)
1118  * @param hostname name of the machine where to run GNUnet
1119  *        (use NULL for localhost).
1120  * @param ssh_username ssh username to use when connecting to hostname
1121  * @param sshport port to pass to ssh process when connecting to hostname
1122  * @param hostkey pointer to a hostkey to be written to disk (instead of being generated)
1123  * @param hostkey_callback function to call once the hostkey has been
1124  *        generated for this peer, but it hasn't yet been started
1125  *        (NULL to start immediately, otherwise waits on GNUNET_TESTING_daemon_continue_start)
1126  * @param hostkey_cls closure for hostkey callback
1127  * @param cb function to call once peer is up, or failed to start
1128  * @param cb_cls closure for cb
1129  * @return handle to the daemon (actual start will be completed asynchronously)
1130  */
1131 struct GNUNET_TESTING_Daemon *
1132 GNUNET_TESTING_daemon_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
1133                              struct GNUNET_TIME_Relative timeout, int pretend,
1134                              const char *hostname, const char *ssh_username,
1135                              uint16_t sshport, const char *hostkey,
1136                              GNUNET_TESTING_NotifyHostkeyCreated
1137                              hostkey_callback, void *hostkey_cls,
1138                              GNUNET_TESTING_NotifyDaemonRunning cb,
1139                              void *cb_cls)
1140 {
1141   struct GNUNET_TESTING_Daemon *ret;
1142   char *arg;
1143   char *username;
1144   char *servicehome;
1145   char *baseservicehome;
1146   char *slash;
1147   char *hostkeyfile;
1148   char *temp_file_name;
1149   struct GNUNET_DISK_FileHandle *fn;
1150   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
1151   struct GNUNET_CRYPTO_RsaPrivateKey *private_key;
1152
1153   ret = GNUNET_malloc (sizeof (struct GNUNET_TESTING_Daemon));
1154   ret->hostname = (hostname == NULL) ? NULL : GNUNET_strdup (hostname);
1155   if (sshport != 0)
1156   {
1157     GNUNET_asprintf (&ret->ssh_port_str, "%d", sshport);
1158   }
1159   else
1160     ret->ssh_port_str = NULL;
1161
1162   /* Find service home and base service home directories, create it if it doesn't exist */
1163   GNUNET_assert (GNUNET_OK ==
1164                  GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
1165                                                         "SERVICEHOME",
1166                                                         &servicehome));
1167
1168   GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_create (servicehome));
1169   GNUNET_asprintf (&temp_file_name, "%s/gnunet-testing-config", servicehome);
1170   ret->cfgfile = GNUNET_DISK_mktemp (temp_file_name);
1171   GNUNET_free (temp_file_name);
1172 #if DEBUG_TESTING
1173   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1174               "Setting up peer with configuration file `%s'.\n", ret->cfgfile);
1175 #endif
1176   if (NULL == ret->cfgfile)
1177   {
1178     GNUNET_free_non_null (ret->ssh_port_str);
1179     GNUNET_free_non_null (ret->hostname);
1180     GNUNET_free (ret);
1181     return NULL;
1182   }
1183   ret->hostkey_callback = hostkey_callback;
1184   ret->hostkey_cls = hostkey_cls;
1185   ret->cb = cb;
1186   ret->cb_cls = cb_cls;
1187   ret->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1188   ret->cfg = GNUNET_CONFIGURATION_dup (cfg);
1189   GNUNET_CONFIGURATION_set_value_string (ret->cfg, "PATHS", "DEFAULTCONFIG",
1190                                          ret->cfgfile);
1191
1192   if (hostkey != NULL)          /* Get the peer identity from the hostkey */
1193   {
1194     private_key = GNUNET_CRYPTO_rsa_decode_key (hostkey, HOSTKEYFILESIZE);
1195     GNUNET_assert (private_key != NULL);
1196     GNUNET_CRYPTO_rsa_key_get_public (private_key, &public_key);
1197     GNUNET_CRYPTO_hash (&public_key,
1198                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1199                         &ret->id.hashPubKey);
1200     ret->shortname = GNUNET_strdup (GNUNET_i2s (&ret->id));
1201     ret->have_hostkey = GNUNET_YES;
1202     GNUNET_CRYPTO_rsa_key_free (private_key);
1203   }
1204
1205   /* Write hostkey to file, if we were given one */
1206   hostkeyfile = NULL;
1207   if (hostkey != NULL)
1208   {
1209     GNUNET_asprintf (&hostkeyfile, "%s/.hostkey", servicehome);
1210     fn = GNUNET_DISK_file_open (hostkeyfile,
1211                                 GNUNET_DISK_OPEN_READWRITE |
1212                                 GNUNET_DISK_OPEN_CREATE,
1213                                 GNUNET_DISK_PERM_USER_READ |
1214                                 GNUNET_DISK_PERM_USER_WRITE);
1215     GNUNET_assert (fn != NULL);
1216     GNUNET_assert (HOSTKEYFILESIZE ==
1217                    GNUNET_DISK_file_write (fn, hostkey, HOSTKEYFILESIZE));
1218     GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fn));
1219   }
1220
1221   /* write configuration to temporary file */
1222   if (GNUNET_OK != GNUNET_CONFIGURATION_write (ret->cfg, ret->cfgfile))
1223   {
1224     if (0 != UNLINK (ret->cfgfile))
1225       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
1226                                 ret->cfgfile);
1227     GNUNET_CONFIGURATION_destroy (ret->cfg);
1228     GNUNET_free_non_null (ret->hostname);
1229     GNUNET_free (ret->cfgfile);
1230     GNUNET_free (ret);
1231     return NULL;
1232   }
1233   if (ssh_username != NULL)
1234     username = GNUNET_strdup (ssh_username);
1235   if ((ssh_username == NULL) &&
1236       (GNUNET_OK !=
1237        GNUNET_CONFIGURATION_get_value_string (cfg, "TESTING", "USERNAME",
1238                                               &username)))
1239   {
1240     if (NULL != getenv ("USER"))
1241       username = GNUNET_strdup (getenv ("USER"));
1242     else
1243       username = NULL;
1244   }
1245   ret->username = username;
1246
1247   if (GNUNET_NO == pretend)     /* Copy files, enter finite state machine */
1248   {
1249     /* copy directory to remote host */
1250     if (NULL != hostname)
1251     {
1252 #if DEBUG_TESTING
1253       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1254                   "Copying configuration directory to host `%s'.\n", hostname);
1255 #endif
1256       baseservicehome = GNUNET_strdup (servicehome);
1257       /* Remove trailing /'s */
1258       while (baseservicehome[strlen (baseservicehome) - 1] == '/')
1259         baseservicehome[strlen (baseservicehome) - 1] = '\0';
1260       /* Find next directory /, jump one ahead */
1261       slash = strrchr (baseservicehome, '/');
1262       if (slash != NULL)
1263         *(++slash) = '\0';
1264
1265       ret->phase = SP_COPYING;
1266       if (NULL != username)
1267         GNUNET_asprintf (&arg, "%s@%s:%s", username, hostname, baseservicehome);
1268       else
1269         GNUNET_asprintf (&arg, "%s:%s", hostname, baseservicehome);
1270       GNUNET_free (baseservicehome);
1271       if (ret->ssh_port_str == NULL)
1272       {
1273         ret->proc = GNUNET_OS_start_process (NULL, NULL, "scp", "scp", "-r",
1274 #if !DEBUG_TESTING
1275                                              "-q",
1276 #endif
1277                                              servicehome, arg, NULL);
1278 #if DEBUG_TESTING
1279         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1280                     "copying directory with command scp -r %s %s\n",
1281                     servicehome, arg);
1282 #endif
1283       }
1284       else
1285       {
1286         ret->proc =
1287             GNUNET_OS_start_process (NULL, NULL, "scp", "scp", "-r", "-P",
1288                                      ret->ssh_port_str,
1289 #if !DEBUG_TESTING
1290                                      "-q",
1291 #endif
1292                                      servicehome, arg, NULL);
1293       }
1294       GNUNET_free (arg);
1295       if (NULL == ret->proc)
1296       {
1297         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1298                     _
1299                     ("Could not start `%s' process to copy configuration directory.\n"),
1300                     "scp");
1301         if (0 != UNLINK (ret->cfgfile))
1302           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
1303                                     ret->cfgfile);
1304         GNUNET_CONFIGURATION_destroy (ret->cfg);
1305         GNUNET_free_non_null (ret->hostname);
1306         GNUNET_free_non_null (ret->username);
1307         GNUNET_free (ret->cfgfile);
1308         GNUNET_free (ret);
1309         if ((hostkey != NULL) && (0 != UNLINK (hostkeyfile)))
1310           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
1311                                     hostkeyfile);
1312         GNUNET_free_non_null (hostkeyfile);
1313         GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_remove (servicehome));
1314         GNUNET_free (servicehome);
1315         return NULL;
1316       }
1317
1318       ret->task =
1319           GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm,
1320                                         ret);
1321       GNUNET_free_non_null (hostkeyfile);
1322       GNUNET_free (servicehome);
1323       return ret;
1324     }
1325 #if DEBUG_TESTING
1326     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1327                 "No need to copy configuration file since we are running locally.\n");
1328 #endif
1329     ret->phase = SP_COPIED;
1330     /* FIXME: why add_cont? */
1331     GNUNET_SCHEDULER_add_continuation (&start_fsm, ret,
1332                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1333   }
1334   GNUNET_free_non_null (hostkeyfile);
1335   GNUNET_free (servicehome);
1336   return ret;
1337 }
1338
1339
1340 /**
1341  * Restart (stop and start) a GNUnet daemon.
1342  *
1343  * @param d the daemon that should be restarted
1344  * @param cb function called once the daemon is (re)started
1345  * @param cb_cls closure for cb
1346  */
1347 void
1348 GNUNET_TESTING_daemon_restart (struct GNUNET_TESTING_Daemon *d,
1349                                GNUNET_TESTING_NotifyDaemonRunning cb,
1350                                void *cb_cls)
1351 {
1352   char *arg;
1353   char *del_arg;
1354
1355   del_arg = NULL;
1356   if (NULL != d->cb)
1357   {
1358     d->dead = GNUNET_YES;
1359     return;
1360   }
1361
1362   d->cb = cb;
1363   d->cb_cls = cb_cls;
1364
1365   if (d->phase == SP_CONFIG_UPDATE)
1366   {
1367     GNUNET_SCHEDULER_cancel (d->task);
1368     d->phase = SP_START_DONE;
1369   }
1370   if (d->server != NULL)
1371   {
1372     GNUNET_CORE_disconnect (d->server);
1373     d->server = NULL;
1374   }
1375
1376   if (d->th != NULL)
1377   {
1378     GNUNET_TRANSPORT_get_hello_cancel (d->ghh);
1379     d->ghh = NULL;
1380     GNUNET_TRANSPORT_disconnect (d->th);
1381     d->th = NULL;
1382   }
1383   /* state clean up and notifications */
1384   GNUNET_free_non_null (d->hello);
1385
1386 #if DEBUG_TESTING
1387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Terminating peer `%4s'\n"),
1388               GNUNET_i2s (&d->id));
1389 #endif
1390
1391   d->phase = SP_START_ARMING;
1392
1393   /* Check if this is a local or remote process */
1394   if (NULL != d->hostname)
1395   {
1396 #if DEBUG_TESTING
1397     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1398                 "Stopping gnunet-arm with config `%s' on host `%s'.\n",
1399                 d->cfgfile, d->hostname);
1400 #endif
1401
1402     if (d->username != NULL)
1403       GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
1404     else
1405       arg = GNUNET_strdup (d->hostname);
1406
1407     d->proc = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh",
1408 #if !DEBUG_TESTING
1409                                        "-q",
1410 #endif
1411                                        arg, "gnunet-arm",
1412 #if DEBUG_TESTING
1413                                        "-L", "DEBUG",
1414 #endif
1415                                        "-c", d->cfgfile, "-e", "-r", NULL);
1416     /* Use -r to restart arm and all services */
1417
1418     GNUNET_free (arg);
1419   }
1420   else
1421   {
1422 #if DEBUG_TESTING
1423     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1424                 "Stopping gnunet-arm with config `%s' locally.\n", d->cfgfile);
1425 #endif
1426     d->proc = GNUNET_OS_start_process (NULL, NULL, "gnunet-arm", "gnunet-arm",
1427 #if DEBUG_TESTING
1428                                        "-L", "DEBUG",
1429 #endif
1430                                        "-c", d->cfgfile, "-e", "-r", NULL);
1431   }
1432
1433   GNUNET_free_non_null (del_arg);
1434   d->task =
1435       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm, d);
1436
1437 }
1438
1439
1440 /**
1441  * Stops a GNUnet daemon.
1442  *
1443  * @param d the daemon that should be stopped
1444  * @param service the name of the service to stop
1445  * @param timeout how long to wait for process for shutdown to complete
1446  * @param cb function called once the daemon was stopped
1447  * @param cb_cls closure for cb
1448  */
1449 void
1450 GNUNET_TESTING_daemon_stop_service (struct GNUNET_TESTING_Daemon *d,
1451                                     const char *service,
1452                                     struct GNUNET_TIME_Relative timeout,
1453                                     GNUNET_TESTING_NotifyCompletion cb,
1454                                     void *cb_cls)
1455 {
1456   char *arg;
1457
1458   d->dead_cb = cb;
1459   d->dead_cb_cls = cb_cls;
1460
1461   GNUNET_assert (d->running == GNUNET_YES);
1462
1463   if (d->phase == SP_CONFIG_UPDATE)
1464   {
1465     GNUNET_SCHEDULER_cancel (d->task);
1466     d->phase = SP_START_DONE;
1467   }
1468
1469 #if DEBUG_TESTING
1470   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Terminating peer `%4s'\n"),
1471               GNUNET_i2s (&d->id));
1472 #endif
1473   if (d->churned_services != NULL)
1474   {
1475     d->dead_cb (d->dead_cb_cls, "A service has already been turned off!!");
1476     return;
1477   }
1478   d->phase = SP_SERVICE_SHUTDOWN_START;
1479   d->churned_services = GNUNET_strdup (service);
1480   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1481   /* Check if this is a local or remote process */
1482   if (NULL != d->hostname)
1483   {
1484 #if DEBUG_TESTING
1485     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1486                 "Stopping gnunet-arm with config `%s' on host `%s'.\n",
1487                 d->cfgfile, d->hostname);
1488 #endif
1489
1490     if (d->username != NULL)
1491       GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
1492     else
1493       arg = GNUNET_strdup (d->hostname);
1494
1495     d->proc = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh",
1496 #if !DEBUG_TESTING
1497                                        "-q",
1498 #endif
1499                                        arg, "gnunet-arm",
1500 #if DEBUG_TESTING
1501                                        "-L", "DEBUG",
1502 #endif
1503                                        "-c", d->cfgfile, "-k", service, "-q",
1504                                        "-T",
1505                                        GNUNET_TIME_relative_to_string (timeout),
1506                                        NULL);
1507     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1508                 "Stopping gnunet-arm with command ssh %s gnunet-arm -c %s -k %s -q\n",
1509                 arg, "gnunet-arm", d->cfgfile, service);
1510     GNUNET_free (arg);
1511   }
1512   else
1513   {
1514 #if DEBUG_TESTING
1515     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1516                 "Stopping gnunet-arm with config `%s' locally.\n", d->cfgfile);
1517 #endif
1518     d->proc = GNUNET_OS_start_process (NULL, NULL, "gnunet-arm", "gnunet-arm",
1519 #if DEBUG_TESTING
1520                                        "-L", "DEBUG",
1521 #endif
1522                                        "-c", d->cfgfile, "-k", service, "-q",
1523                                        "-T",
1524                                        GNUNET_TIME_relative_to_string (timeout),
1525                                        NULL);
1526   }
1527
1528   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1529   d->task = GNUNET_SCHEDULER_add_now (&start_fsm, d);
1530 }
1531
1532
1533 /**
1534  * Stops a GNUnet daemon.
1535  *
1536  * @param d the daemon that should be stopped
1537  * @param timeout how long to wait for process for shutdown to complete
1538  * @param cb function called once the daemon was stopped
1539  * @param cb_cls closure for cb
1540  * @param delete_files GNUNET_YES to remove files, GNUNET_NO
1541  *        to leave them
1542  * @param allow_restart GNUNET_YES to restart peer later (using this API)
1543  *        GNUNET_NO to kill off and clean up for good
1544  */
1545 void
1546 GNUNET_TESTING_daemon_stop (struct GNUNET_TESTING_Daemon *d,
1547                             struct GNUNET_TIME_Relative timeout,
1548                             GNUNET_TESTING_NotifyCompletion cb, void *cb_cls,
1549                             int delete_files, int allow_restart)
1550 {
1551   char *arg;
1552   char *del_arg;
1553
1554   d->dead_cb = cb;
1555   d->dead_cb_cls = cb_cls;
1556
1557   if (NULL != d->cb)
1558   {
1559 #if DEBUG_TESTING
1560     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Setting d->dead on peer `%4s'\n"),
1561                 GNUNET_i2s (&d->id));
1562 #endif
1563     d->dead = GNUNET_YES;
1564     return;
1565   }
1566
1567   if ((d->running == GNUNET_NO) && (d->churn == GNUNET_YES))    /* Peer has already been stopped in churn context! */
1568   {
1569     /* Free what was left from churning! */
1570     GNUNET_assert (d->cfg != NULL);
1571     GNUNET_CONFIGURATION_destroy (d->cfg);
1572     if (delete_files == GNUNET_YES)
1573     {
1574       if (0 != UNLINK (d->cfgfile))
1575       {
1576         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "unlink");
1577       }
1578     }
1579     GNUNET_free (d->cfgfile);
1580     GNUNET_free_non_null (d->hostname);
1581     GNUNET_free_non_null (d->username);
1582     if (NULL != d->dead_cb)
1583       d->dead_cb (d->dead_cb_cls, NULL);
1584     GNUNET_free (d);
1585     return;
1586   }
1587
1588   del_arg = NULL;
1589   if (delete_files == GNUNET_YES)
1590   {
1591     GNUNET_asprintf (&del_arg, "-d");
1592   }
1593
1594   if (d->phase == SP_CONFIG_UPDATE)
1595   {
1596     GNUNET_SCHEDULER_cancel (d->task);
1597     d->phase = SP_START_DONE;
1598   }
1599   /** Move this call to scheduled shutdown as fix for CORE_connect calling daemon_stop?
1600   if (d->server != NULL)
1601     {
1602       GNUNET_CORE_disconnect (d->server);
1603       d->server = NULL;
1604     }
1605     */
1606   /* shutdown ARM process (will terminate others) */
1607 #if DEBUG_TESTING
1608   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Terminating peer `%4s'\n"),
1609               GNUNET_i2s (&d->id));
1610 #endif
1611   d->phase = SP_SHUTDOWN_START;
1612   d->running = GNUNET_NO;
1613   if (allow_restart == GNUNET_YES)
1614     d->churn = GNUNET_YES;
1615   if (d->th != NULL)
1616   {
1617     GNUNET_TRANSPORT_get_hello_cancel (d->ghh);
1618     d->ghh = NULL;
1619     GNUNET_TRANSPORT_disconnect (d->th);
1620     d->th = NULL;
1621   }
1622   /* Check if this is a local or remote process */
1623   if (NULL != d->hostname)
1624   {
1625 #if DEBUG_TESTING
1626     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1627                 "Stopping gnunet-arm with config `%s' on host `%s'.\n",
1628                 d->cfgfile, d->hostname);
1629 #endif
1630
1631     if (d->username != NULL)
1632       GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
1633     else
1634       arg = GNUNET_strdup (d->hostname);
1635
1636     d->proc = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh",
1637 #if !DEBUG_TESTING
1638                                        "-q",
1639 #endif
1640                                        arg, "gnunet-arm",
1641 #if DEBUG_TESTING
1642                                        "-L", "DEBUG",
1643 #endif
1644                                        "-c", d->cfgfile, "-e", "-q", "-T",
1645                                        GNUNET_TIME_relative_to_string (timeout),
1646                                        del_arg, NULL);
1647     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1648                 "Stopping gnunet-arm with command ssh %s gnunet-arm -c %s -e -q %s\n",
1649                 arg, "gnunet-arm", d->cfgfile, del_arg);
1650     /* Use -e to end arm, and -d to remove temp files */
1651     GNUNET_free (arg);
1652   }
1653   else
1654   {
1655 #if DEBUG_TESTING
1656     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1657                 "Stopping gnunet-arm with config `%s' locally.\n", d->cfgfile);
1658 #endif
1659     d->proc = GNUNET_OS_start_process (NULL, NULL, "gnunet-arm", "gnunet-arm",
1660 #if DEBUG_TESTING
1661                                        "-L", "DEBUG",
1662 #endif
1663                                        "-c", d->cfgfile, "-e", "-q", "-T",
1664                                        GNUNET_TIME_relative_to_string (timeout),
1665                                        del_arg, NULL);
1666     GNUNET_assert (NULL != d->proc);
1667   }
1668
1669   GNUNET_free_non_null (del_arg);
1670   d->max_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1671   if (GNUNET_SCHEDULER_NO_TASK != d->task)
1672     GNUNET_SCHEDULER_cancel(d->task);
1673   d->task = GNUNET_SCHEDULER_add_now (&start_fsm, d);
1674 }
1675
1676
1677 /**
1678  * Changes the configuration of a GNUnet daemon.
1679  *
1680  * @param d the daemon that should be modified
1681  * @param cfg the new configuration for the daemon
1682  * @param cb function called once the configuration was changed
1683  * @param cb_cls closure for cb
1684  */
1685 void
1686 GNUNET_TESTING_daemon_reconfigure (struct GNUNET_TESTING_Daemon *d,
1687                                    struct GNUNET_CONFIGURATION_Handle *cfg,
1688                                    GNUNET_TESTING_NotifyCompletion cb,
1689                                    void *cb_cls)
1690 {
1691   char *arg;
1692
1693   if (d->phase != SP_START_DONE)
1694   {
1695     if (NULL != cb)
1696       cb (cb_cls,
1697           _
1698           ("Peer not yet running, can not change configuration at this point."));
1699     return;
1700   }
1701
1702   /* 1) write configuration to temporary file */
1703   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, d->cfgfile))
1704   {
1705     if (NULL != cb)
1706       cb (cb_cls, _("Failed to write new configuration to disk."));
1707     return;
1708   }
1709
1710   /* 2) copy file to remote host (if necessary) */
1711   if (NULL == d->hostname)
1712   {
1713     /* signal success */
1714     if (NULL != cb)
1715       cb (cb_cls, NULL);
1716     return;
1717   }
1718 #if DEBUG_TESTING
1719   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1720               "Copying updated configuration file to remote host `%s'.\n",
1721               d->hostname);
1722 #endif
1723   d->phase = SP_CONFIG_UPDATE;
1724   if (NULL != d->username)
1725     GNUNET_asprintf (&arg, "%s@%s:%s", d->username, d->hostname, d->cfgfile);
1726   else
1727     GNUNET_asprintf (&arg, "%s:%s", d->hostname, d->cfgfile);
1728   d->proc = GNUNET_OS_start_process (NULL, NULL, "scp", "scp",
1729 #if !DEBUG_TESTING
1730                                      "-q",
1731 #endif
1732                                      d->cfgfile, arg, NULL);
1733   GNUNET_free (arg);
1734   if (NULL == d->proc)
1735   {
1736     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1737                 _("Could not start `%s' process to copy configuration file.\n"),
1738                 "scp");
1739     if (NULL != cb)
1740       cb (cb_cls, _("Failed to copy new configuration to remote machine."));
1741     d->phase = SP_START_DONE;
1742     return;
1743   }
1744   d->update_cb = cb;
1745   d->update_cb_cls = cb_cls;
1746   d->task =
1747       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_EXEC_WAIT, &start_fsm, d);
1748 }
1749
1750
1751 /**
1752  * Data kept for each pair of peers that we try
1753  * to connect.
1754  */
1755 struct GNUNET_TESTING_ConnectContext
1756 {
1757   /**
1758    * Testing handle to the first daemon.
1759    */
1760   struct GNUNET_TESTING_Daemon *d1;
1761
1762   /**
1763    * Handle to core of first daemon (to check connect)
1764    */
1765   struct GNUNET_CORE_Handle *d1core;
1766
1767   /**
1768    * Have we actually connected to the core of the first daemon yet?
1769    */
1770   int d1core_ready;
1771
1772   /**
1773    * Testing handle to the second daemon.
1774    */
1775   struct GNUNET_TESTING_Daemon *d2;
1776
1777   /**
1778    * Transport handle to the first daemon (to offer the HELLO of the second daemon to).
1779    */
1780   struct GNUNET_TRANSPORT_Handle *d1th;
1781
1782   /**
1783    * Function to call once we are done (or have timed out).
1784    */
1785   GNUNET_TESTING_NotifyConnection cb;
1786
1787   /**
1788    * Closure for "nb".
1789    */
1790   void *cb_cls;
1791
1792   /**
1793    * The relative timeout from whence this connect attempt was
1794    * started.  Allows for reconnect attempts.
1795    */
1796   struct GNUNET_TIME_Relative relative_timeout;
1797
1798   /**
1799    * Maximum number of connect attempts, will retry connection
1800    * this number of times on failures.
1801    */
1802   unsigned int connect_attempts;
1803
1804   /**
1805    * Hello timeout task
1806    */
1807   GNUNET_SCHEDULER_TaskIdentifier hello_send_task;
1808
1809   /**
1810    * Connect timeout task
1811    */
1812   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1813
1814   /**
1815    * When should this operation be complete (or we must trigger
1816    * a timeout).
1817    */
1818   struct GNUNET_TIME_Relative timeout_hello;
1819
1820   /**
1821    * Was the connection attempt successful?
1822    */
1823   int connected;
1824
1825   /**
1826    * When connecting, do we need to send the HELLO?
1827    */
1828   int send_hello;
1829
1830   /**
1831    * The distance between the two connected peers
1832    */
1833   uint32_t distance;
1834 };
1835
1836
1837 /** Forward declaration **/
1838 static void
1839 reattempt_daemons_connect (void *cls,
1840                            const struct GNUNET_SCHEDULER_TaskContext *tc);
1841
1842
1843 /**
1844  * Notify callback about success or failure of the attempt
1845  * to connect the two peers
1846  *
1847  * @param cls our "struct GNUNET_TESTING_ConnectContext" (freed)
1848  * @param tc reason tells us if we succeeded or failed
1849  */
1850 static void
1851 notify_connect_result (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1852 {
1853   struct GNUNET_TESTING_ConnectContext *ctx = cls;
1854
1855   ctx->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1856   if (ctx->hello_send_task != GNUNET_SCHEDULER_NO_TASK)
1857   {
1858     GNUNET_SCHEDULER_cancel (ctx->hello_send_task);
1859     ctx->hello_send_task = GNUNET_SCHEDULER_NO_TASK;
1860   }
1861
1862   if (ctx->d1th != NULL)
1863     GNUNET_TRANSPORT_disconnect (ctx->d1th);
1864   ctx->d1th = NULL;
1865   if (ctx->d1core != NULL)
1866     GNUNET_CORE_disconnect (ctx->d1core);
1867   ctx->d1core = NULL;
1868
1869   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1870   {
1871     GNUNET_free (ctx);
1872     return;
1873   }
1874
1875   if (ctx->connected == GNUNET_YES)
1876   {
1877     if (ctx->cb != NULL)
1878     {
1879       ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, ctx->distance,
1880                ctx->d1->cfg, ctx->d2->cfg, ctx->d1, ctx->d2, NULL);
1881     }
1882   }
1883   else if (ctx->connect_attempts > 0)
1884   {
1885     ctx->d1core_ready = GNUNET_NO;
1886     ctx->timeout_task =
1887         GNUNET_SCHEDULER_add_now (&reattempt_daemons_connect, ctx);
1888     return;
1889   }
1890   else
1891   {
1892     if (ctx->cb != NULL)
1893     {
1894       ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, 0, ctx->d1->cfg,
1895                ctx->d2->cfg, ctx->d1, ctx->d2, _("Peers failed to connect"));
1896     }
1897   }
1898   GNUNET_free (ctx);
1899 }
1900
1901
1902 /**
1903  * Success, connection is up.  Signal client our success.
1904  *
1905  * @param cls our "struct GNUNET_TESTING_ConnectContext"
1906  * @param peer identity of the peer that has connected
1907  * @param atsi performance information
1908  * @param atsi_count number of records in 'atsi'
1909  *
1910  */
1911 static void
1912 connect_notify (void *cls, const struct GNUNET_PeerIdentity *peer,
1913                 const struct GNUNET_ATS_Information *atsi,
1914                 unsigned int atsi_count)
1915 {
1916   struct GNUNET_TESTING_ConnectContext *ctx = cls;
1917
1918 #if DEBUG_TESTING
1919   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected peer %s to peer %s\n",
1920               ctx->d1->shortname, GNUNET_i2s (peer));
1921 #endif
1922
1923   if (0 != memcmp (&ctx->d2->id, peer, sizeof (struct GNUNET_PeerIdentity)))
1924     return;
1925   ctx->connected = GNUNET_YES;
1926   ctx->distance = 0;            /* FIXME: distance */
1927   if (ctx->hello_send_task != GNUNET_SCHEDULER_NO_TASK)
1928   {
1929     GNUNET_SCHEDULER_cancel (ctx->hello_send_task);
1930     ctx->hello_send_task = GNUNET_SCHEDULER_NO_TASK;
1931   }
1932   GNUNET_SCHEDULER_cancel (ctx->timeout_task);
1933   ctx->timeout_task = GNUNET_SCHEDULER_add_now (&notify_connect_result, ctx);
1934 }
1935
1936
1937 static void
1938 send_hello (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1939 {
1940   struct GNUNET_TESTING_ConnectContext *ctx = cls;
1941   struct GNUNET_MessageHeader *hello;
1942
1943   ctx->hello_send_task = GNUNET_SCHEDULER_NO_TASK;
1944   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1945     return;
1946   if ((ctx->d1core_ready == GNUNET_YES) && (ctx->d2->hello != NULL) &&
1947       (NULL != GNUNET_HELLO_get_header (ctx->d2->hello)) &&
1948       (ctx->d1->phase == SP_START_DONE) && (ctx->d2->phase == SP_START_DONE))
1949   {
1950     hello = GNUNET_HELLO_get_header (ctx->d2->hello);
1951     GNUNET_assert (hello != NULL);
1952 #if DEBUG_TESTING
1953     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Offering hello of %s to %s\n",
1954                 ctx->d2->shortname, ctx->d1->shortname);
1955 #endif
1956     GNUNET_TRANSPORT_offer_hello (ctx->d1th, hello, NULL, NULL);
1957     GNUNET_assert (ctx->d1core != NULL);
1958 #if DEBUG_TESTING
1959     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1960                 "Sending connect request to TRANSPORT of %s for peer %s\n",
1961                 GNUNET_i2s (&ctx->d1->id),
1962                 GNUNET_h2s (&ctx->d2->id.hashPubKey));
1963 #endif
1964     GNUNET_TRANSPORT_try_connect (ctx->d1th, &ctx->d2->id);
1965     ctx->timeout_hello =
1966         GNUNET_TIME_relative_add (ctx->timeout_hello,
1967                                   GNUNET_TIME_relative_multiply
1968                                   (GNUNET_TIME_UNIT_MILLISECONDS, 500));
1969   }
1970   ctx->hello_send_task =
1971       GNUNET_SCHEDULER_add_delayed (ctx->timeout_hello, &send_hello, ctx);
1972 }
1973
1974 /**
1975  * Notify of a successful connection to the core service.
1976  *
1977  * @param cls a ConnectContext
1978  * @param server handle to the core service
1979  * @param my_identity the peer identity of this peer
1980  */
1981 void
1982 core_init_notify (void *cls, struct GNUNET_CORE_Handle *server,
1983                   const struct GNUNET_PeerIdentity *my_identity)
1984 {
1985   struct GNUNET_TESTING_ConnectContext *connect_ctx = cls;
1986
1987   connect_ctx->d1core_ready = GNUNET_YES;
1988
1989   if (connect_ctx->send_hello == GNUNET_NO)
1990   {
1991     GNUNET_TRANSPORT_try_connect (connect_ctx->d1th, &connect_ctx->d2->id);
1992 #if DEBUG_TESTING
1993     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1994                 "Sending connect request to TRANSPORT of %s for peer %s\n",
1995                 connect_ctx->d1->shortname, connect_ctx->d2->shortname);
1996 #endif
1997   }
1998
1999 }
2000
2001
2002 /**
2003  * Try to connect again some peers that failed in an earlier attempt. This will
2004  * be tried as many times as connection_attempts in the configuration file.
2005  *
2006  * @param cls Closure (connection context between the two peers).
2007  * @param tc TaskContext.
2008  */
2009 static void
2010 reattempt_daemons_connect (void *cls,
2011                            const struct GNUNET_SCHEDULER_TaskContext *tc)
2012 {
2013   struct GNUNET_TESTING_ConnectContext *ctx = cls;
2014
2015   ctx->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2016   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
2017     return;
2018 #if DEBUG_TESTING_RECONNECT
2019   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2020               "re-attempting connect of peer %s to peer %s\n",
2021               ctx->d1->shortname, ctx->d2->shortname);
2022 #endif
2023   ctx->connect_attempts--;
2024   GNUNET_assert (ctx->d1core == NULL);
2025   ctx->d1core_ready = GNUNET_NO;
2026   ctx->d1core =
2027       GNUNET_CORE_connect (ctx->d1->cfg, 1, ctx, &core_init_notify,
2028                            &connect_notify, NULL, NULL, GNUNET_NO, NULL,
2029                            GNUNET_NO, no_handlers);
2030   if (ctx->d1core == NULL)
2031   {
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 core service of first peer!\n"));
2036     GNUNET_free (ctx);
2037     return;
2038   }
2039
2040   /* Don't know reason for initial connect failure, update the HELLO for the second peer */
2041   if (NULL != ctx->d2->hello)
2042   {
2043 #if DEBUG_TESTING_RECONNECT
2044     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "updating %s's HELLO\n",
2045                 ctx->d2->shortname);
2046 #endif
2047     GNUNET_free (ctx->d2->hello);
2048     ctx->d2->hello = NULL;
2049     if (NULL != ctx->d2->th)
2050     {
2051       GNUNET_TRANSPORT_get_hello_cancel (ctx->d2->ghh);
2052       ctx->d2->ghh = NULL;
2053       GNUNET_TRANSPORT_disconnect (ctx->d2->th);
2054     }
2055     ctx->d2->th =
2056         GNUNET_TRANSPORT_connect (ctx->d2->cfg, &ctx->d2->id, NULL, NULL, NULL,
2057                                   NULL);
2058     GNUNET_assert (ctx->d2->th != NULL);
2059     ctx->d2->ghh =
2060         GNUNET_TRANSPORT_get_hello (ctx->d2->th, &process_hello, ctx->d2);
2061   }
2062 #if DEBUG_TESTING_RECONNECT
2063   else
2064   {
2065     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "didn't have %s's HELLO\n",
2066                 ctx->d2->shortname);
2067   }
2068 #endif
2069
2070   if ((NULL == ctx->d2->hello) && (ctx->d2->th == NULL))
2071   {
2072 #if DEBUG_TESTING_RECONNECT
2073     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2074                 "didn't have %s's HELLO, trying to get it now\n",
2075                 ctx->d2->shortname);
2076 #endif
2077     ctx->d2->th =
2078         GNUNET_TRANSPORT_connect (ctx->d2->cfg, &ctx->d2->id, NULL, NULL, NULL,
2079                                   NULL);
2080     if (NULL == ctx->d2->th)
2081     {
2082       GNUNET_CORE_disconnect (ctx->d1core);
2083       GNUNET_free (ctx);
2084       if (NULL != ctx->cb)
2085         ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, 0, ctx->d1->cfg,
2086                  ctx->d2->cfg, ctx->d1, ctx->d2,
2087                  _("Failed to connect to transport service!\n"));
2088       return;
2089     }
2090     ctx->d2->ghh =
2091         GNUNET_TRANSPORT_get_hello (ctx->d2->th, &process_hello, ctx->d2);
2092   }
2093 #if DEBUG_TESTING_RECONNECT
2094   else
2095   {
2096     if (NULL == ctx->d2->hello)
2097     {
2098       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2099                   "didn't have %s's HELLO but th wasn't NULL, not trying!!\n",
2100                   ctx->d2->shortname);
2101     }
2102   }
2103 #endif
2104
2105   if (ctx->send_hello == GNUNET_YES)
2106   {
2107 #if DEBUG_TESTING_RECONNECT
2108     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending %s's HELLO to %s\n",
2109                 ctx->d1->shortname, ctx->d2->shortname);
2110 #endif
2111     ctx->d1th =
2112         GNUNET_TRANSPORT_connect (ctx->d1->cfg, &ctx->d1->id, ctx->d1, NULL,
2113                                   NULL, NULL);
2114     if (ctx->d1th == NULL)
2115     {
2116       GNUNET_CORE_disconnect (ctx->d1core);
2117       GNUNET_free (ctx);
2118       if (NULL != ctx->cb)
2119         ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, 0, ctx->d1->cfg,
2120                  ctx->d2->cfg, ctx->d1, ctx->d2,
2121                  _("Failed to connect to transport service!\n"));
2122       return;
2123     }
2124     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == ctx->hello_send_task);
2125     ctx->hello_send_task = GNUNET_SCHEDULER_add_now (&send_hello, ctx);
2126   }
2127   else
2128   {
2129 #if DEBUG_TESTING_RECONNECT
2130     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Trying to reconnect %s to %s\n",
2131                 ctx->d1->shortname, ctx->d2->shortname);
2132 #endif
2133     GNUNET_TRANSPORT_try_connect (ctx->d1th, &ctx->d2->id);
2134   }
2135   ctx->timeout_task =
2136       GNUNET_SCHEDULER_add_delayed (ctx->relative_timeout,
2137                                     &notify_connect_result, ctx);
2138 }
2139
2140 /**
2141  * Iterator for currently known peers, to ensure
2142  * that we don't try to send duplicate connect
2143  * requests to core.
2144  *
2145  * @param cls our "struct GNUNET_TESTING_ConnectContext"
2146  * @param peer identity of the peer that has connected,
2147  *        NULL when iteration has finished
2148  * @param atsi performance information
2149  * @param atsi_count number of records in 'atsi'
2150  *
2151  */
2152 static void
2153 core_initial_iteration (void *cls, const struct GNUNET_PeerIdentity *peer,
2154                         const struct GNUNET_ATS_Information *atsi,
2155                         unsigned int atsi_count)
2156 {
2157   struct GNUNET_TESTING_ConnectContext *ctx = cls;
2158
2159   if ((peer != NULL) &&
2160       (0 == memcmp (&ctx->d2->id, peer, sizeof (struct GNUNET_PeerIdentity))))
2161   {
2162     ctx->connected = GNUNET_YES;
2163     ctx->distance = 0;          /* FIXME: distance */
2164     return;
2165   }
2166   if (peer != NULL)
2167     return;                     /* ignore other peers */
2168   /* peer == NULL: End of iteration over peers */
2169
2170   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == ctx->timeout_task);
2171   if (ctx->connected == GNUNET_YES)
2172   {
2173     ctx->timeout_task = GNUNET_SCHEDULER_add_now (&notify_connect_result, ctx);
2174     return;
2175   }
2176
2177   /* Peer not already connected, need to schedule connect request! */
2178   if (ctx->d1core == NULL)
2179   {
2180 #if DEBUG_TESTING
2181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2182                 "Peers are NOT connected, connecting to core!\n");
2183 #endif
2184     ctx->d1core =
2185         GNUNET_CORE_connect (ctx->d1->cfg, 1, ctx, &core_init_notify,
2186                              &connect_notify, NULL, NULL, GNUNET_NO, NULL,
2187                              GNUNET_NO, no_handlers);
2188   }
2189
2190   if (ctx->d1core == NULL)
2191   {
2192     ctx->timeout_task = GNUNET_SCHEDULER_add_now (&notify_connect_result, ctx);
2193     return;
2194   }
2195
2196   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 */
2197   {
2198 #if DEBUG_TESTING
2199     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2200                 "Don't have d2's HELLO, trying to get it!\n");
2201 #endif
2202     ctx->d2->th =
2203         GNUNET_TRANSPORT_connect (ctx->d2->cfg, &ctx->d2->id, NULL, NULL, NULL,
2204                                   NULL);
2205     if (ctx->d2->th == NULL)
2206     {
2207       GNUNET_CORE_disconnect (ctx->d1core);
2208       ctx->d1core = NULL;
2209       ctx->timeout_task =
2210           GNUNET_SCHEDULER_add_now (&notify_connect_result, ctx);
2211       return;
2212     }
2213     ctx->d2->ghh =
2214         GNUNET_TRANSPORT_get_hello (ctx->d2->th, &process_hello, ctx->d2);
2215   }
2216
2217   if (ctx->send_hello == GNUNET_YES)
2218   {
2219     ctx->d1th =
2220         GNUNET_TRANSPORT_connect (ctx->d1->cfg, &ctx->d1->id, ctx->d1, NULL,
2221                                   NULL, NULL);
2222     if (ctx->d1th == NULL)
2223     {
2224       GNUNET_CORE_disconnect (ctx->d1core);
2225       ctx->d1core = NULL;
2226       ctx->timeout_task =
2227           GNUNET_SCHEDULER_add_now (&notify_connect_result, ctx);
2228       return;
2229     }
2230     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == ctx->hello_send_task);
2231     ctx->hello_send_task = GNUNET_SCHEDULER_add_now (&send_hello, ctx);
2232   }
2233
2234   ctx->timeout_task =
2235       GNUNET_SCHEDULER_add_delayed (ctx->relative_timeout,
2236                                     &notify_connect_result, ctx);
2237
2238 }
2239
2240
2241 /**
2242  * Establish a connection between two GNUnet daemons.  The daemons
2243  * must both be running and not be stopped until either the
2244  * 'cb' callback is called OR the connection request has been
2245  * explicitly cancelled.
2246  *
2247  * @param d1 handle for the first daemon
2248  * @param d2 handle for the second daemon
2249  * @param timeout how long is the connection attempt
2250  *        allowed to take?
2251  * @param max_connect_attempts how many times should we try to reconnect
2252  *        (within timeout)
2253  * @param send_hello GNUNET_YES to send the HELLO, GNUNET_NO to assume
2254  *                   the HELLO has already been exchanged
2255  * @param cb function to call at the end
2256  * @param cb_cls closure for cb
2257  * @return handle to cancel the request
2258  */
2259 struct GNUNET_TESTING_ConnectContext *
2260 GNUNET_TESTING_daemons_connect (struct GNUNET_TESTING_Daemon *d1,
2261                                 struct GNUNET_TESTING_Daemon *d2,
2262                                 struct GNUNET_TIME_Relative timeout,
2263                                 unsigned int max_connect_attempts,
2264                                 int send_hello,
2265                                 GNUNET_TESTING_NotifyConnection cb,
2266                                 void *cb_cls)
2267 {
2268   struct GNUNET_TESTING_ConnectContext *ctx;
2269
2270   if ((d1->running == GNUNET_NO) || (d2->running == GNUNET_NO))
2271   {
2272     if (NULL != cb)
2273       cb (cb_cls, &d1->id, &d2->id, 0, d1->cfg, d2->cfg, d1, d2,
2274           _("Peers are not fully running yet, can not connect!\n"));
2275     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Peers are not up!\n");
2276     return NULL;
2277   }
2278
2279   ctx = GNUNET_malloc (sizeof (struct GNUNET_TESTING_ConnectContext));
2280   ctx->d1 = d1;
2281   ctx->d2 = d2;
2282   ctx->timeout_hello =
2283       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500);
2284   ctx->relative_timeout =
2285       GNUNET_TIME_relative_divide (timeout, max_connect_attempts);
2286   ctx->cb = cb;
2287   ctx->cb_cls = cb_cls;
2288   ctx->connect_attempts = max_connect_attempts;
2289   ctx->connected = GNUNET_NO;
2290   ctx->send_hello = send_hello;
2291 #if DEBUG_TESTING
2292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asked to connect peer %s to peer %s\n",
2293               d1->shortname, d2->shortname);
2294 #endif
2295
2296   /* Core is up! Iterate over all _known_ peers first to check if we are already connected to the peer! */
2297   GNUNET_assert (GNUNET_OK ==
2298                  GNUNET_CORE_is_peer_connected (ctx->d1->cfg, &ctx->d2->id,
2299                                                 &core_initial_iteration, ctx));
2300   return ctx;
2301 }
2302
2303
2304 /**
2305  * Cancel an attempt to connect two daemons.
2306  *
2307  * @param cc connect context
2308  */
2309 void
2310 GNUNET_TESTING_daemons_connect_cancel (struct GNUNET_TESTING_ConnectContext *cc)
2311 {
2312   if (GNUNET_SCHEDULER_NO_TASK != cc->timeout_task)
2313   {
2314     GNUNET_SCHEDULER_cancel (cc->timeout_task);
2315     cc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2316   }
2317   if (GNUNET_SCHEDULER_NO_TASK != cc->hello_send_task)
2318   {
2319     GNUNET_SCHEDULER_cancel (cc->hello_send_task);
2320     cc->hello_send_task = GNUNET_SCHEDULER_NO_TASK;
2321   }
2322   if (NULL != cc->d1core)
2323   {
2324     GNUNET_CORE_disconnect (cc->d1core);
2325     cc->d1core = NULL;
2326   }
2327   if (NULL != cc->d1th)
2328   {
2329     GNUNET_TRANSPORT_disconnect (cc->d1th);
2330     cc->d1th = NULL;
2331   }
2332   GNUNET_free (cc);
2333 }
2334
2335
2336 /* end of testing.c */