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