documentation for new parameters
[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_NO
41 #define DEBUG_TESTING_RECONNECT GNUNET_NO
42
43 /**
44  * How long do we wait after starting gnunet-service-arm
45  * for the core service to be alive?
46  */
47 #define ARM_START_WAIT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120)
48
49 /**
50  * How many times are we willing to try to wait for "scp" or
51  * "gnunet-service-arm" to complete (waitpid) before giving up?
52  */
53 #define MAX_EXEC_WAIT_RUNS 250
54
55 static struct GNUNET_CORE_MessageHandler no_handlers[] = { {NULL, 0, 0} };
56
57 /**
58  * Receive the HELLO from one peer, give it to the other
59  * and ask them to connect.
60  *
61  * @param cls "struct ConnectContext"
62  * @param message HELLO message of peer
63  */
64 static void
65 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
66 {
67   struct GNUNET_TESTING_Daemon *daemon = cls;
68   int msize;
69   if (daemon == NULL)
70     return;
71
72   if (daemon->server != NULL)
73     {
74       GNUNET_CORE_disconnect(daemon->server);
75       daemon->server = NULL;
76     }
77
78   GNUNET_assert (message != NULL);
79   msize = ntohs(message->size);
80   if (msize < 1)
81     {
82       return;
83     }
84   if (daemon->th != NULL)
85     {
86       GNUNET_TRANSPORT_get_hello_cancel(daemon->th, &process_hello, daemon);
87     }
88 #if DEBUG_TESTING
89   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
90               "Received `%s' from transport service of `%4s'\n",
91               "HELLO", GNUNET_i2s (&daemon->id));
92 #endif
93
94
95
96     {
97       GNUNET_free_non_null(daemon->hello);
98       daemon->hello = GNUNET_malloc(msize);
99       memcpy(daemon->hello, message, msize);
100
101       if (daemon->th != NULL)
102         {
103           GNUNET_TRANSPORT_disconnect(daemon->th);
104           daemon->th = NULL;
105         }
106     }
107
108 }
109
110 /**
111  * Function called after GNUNET_CORE_connect has succeeded
112  * (or failed for good).  Note that the private key of the
113  * peer is intentionally not exposed here; if you need it,
114  * your process should try to read the private key file
115  * directly (which should work if you are authorized...).
116  *
117  * @param cls closure
118  * @param server handle to the server, NULL if we failed
119  * @param my_identity ID of this peer, NULL if we failed
120  * @param publicKey public key of this peer, NULL if we failed
121  */
122 static void
123 testing_init (void *cls,
124               struct GNUNET_CORE_Handle *server,
125               const struct GNUNET_PeerIdentity *my_identity,
126               const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
127 {
128   struct GNUNET_TESTING_Daemon *d = cls;
129   GNUNET_TESTING_NotifyDaemonRunning cb;
130
131   GNUNET_assert (d->phase == SP_START_CORE);
132   d->phase = SP_START_DONE;
133   cb = d->cb;
134   d->cb = NULL;
135   if (server == NULL)
136     {
137       d->server = NULL;
138       if (GNUNET_YES == d->dead)
139         GNUNET_TESTING_daemon_stop (d, GNUNET_TIME_absolute_get_remaining(d->max_timeout), d->dead_cb, d->dead_cb_cls, GNUNET_YES, GNUNET_NO);
140       else if (NULL != cb)
141         cb (d->cb_cls, NULL, d->cfg, d,
142             _("Failed to connect to core service\n"));
143       return;
144     }
145 #if DEBUG_TESTING
146   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
147               "Successfully started peer `%4s'.\n", GNUNET_i2s (my_identity));
148 #endif
149   d->id = *my_identity;
150   d->shortname = strdup (GNUNET_i2s (my_identity));
151   d->server = server;
152   d->running = GNUNET_YES;
153   if (GNUNET_YES == d->dead)
154     GNUNET_TESTING_daemon_stop (d, GNUNET_TIME_absolute_get_remaining(d->max_timeout), d->dead_cb, d->dead_cb_cls, GNUNET_YES, GNUNET_NO);
155   else if (NULL != cb)
156     cb (d->cb_cls, my_identity, d->cfg, d, NULL);
157 #if DEBUG_TESTING
158   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
159               "Successfully started peer `%4s'.\n", GNUNET_i2s (my_identity));
160 #endif
161
162
163   d->th = GNUNET_TRANSPORT_connect (d->sched,
164                                     d->cfg, 
165                                     &d->id,
166                                     d, NULL, NULL, NULL);
167   if (d->th == NULL)
168     {
169       if (GNUNET_YES == d->dead)
170         GNUNET_TESTING_daemon_stop (d, GNUNET_TIME_absolute_get_remaining(d->max_timeout), d->dead_cb, d->dead_cb_cls, GNUNET_YES, GNUNET_NO);
171       else if (NULL != d->cb)
172         d->cb (d->cb_cls, &d->id, d->cfg, d,
173             _("Failed to connect to transport service!\n"));
174       return;
175     }
176
177   GNUNET_TRANSPORT_get_hello (d->th, &process_hello, d);
178 }
179
180
181 /**
182  * Finite-state machine for starting GNUnet.
183  *
184  * @param cls our "struct GNUNET_TESTING_Daemon"
185  * @param tc unused
186  */
187 static void
188 start_fsm (void *cls, 
189            const struct GNUNET_SCHEDULER_TaskContext *tc)
190 {
191   struct GNUNET_TESTING_Daemon *d = cls;
192   GNUNET_TESTING_NotifyDaemonRunning cb;
193   enum GNUNET_OS_ProcessStatusType type;
194   unsigned long code;
195   char *dst;
196   int bytes_read;
197
198 #if DEBUG_TESTING
199   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
200               "Peer FSM is in phase %u.\n", d->phase);
201 #endif
202
203   d->task = GNUNET_SCHEDULER_NO_TASK;
204   switch (d->phase)
205     {
206     case SP_COPYING:
207       /* confirm copying complete */
208       if (GNUNET_OK != GNUNET_OS_process_status (d->pid, &type, &code))
209         {
210           if (GNUNET_TIME_absolute_get_remaining(d->max_timeout).value == 0)
211             {
212               cb = d->cb;
213               d->cb = NULL;
214               if (NULL != cb)
215                 cb (d->cb_cls,
216                     NULL,
217                     d->cfg, d, _("`scp' does not seem to terminate (timeout copying config).\n"));
218               return;
219             }
220           /* wait some more */
221           d->task
222             = GNUNET_SCHEDULER_add_delayed (d->sched,
223                                             GNUNET_CONSTANTS_EXEC_WAIT,
224                                             &start_fsm, d);
225           return;
226         }
227       if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
228         {
229           cb = d->cb;
230           d->cb = NULL;
231           if (NULL != cb)
232             cb (d->cb_cls,
233                 NULL, d->cfg, d, _("`scp' did not complete cleanly.\n"));
234           return;
235         }
236 #if DEBUG_TESTING
237       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
238                   "Successfully copied configuration file.\n");
239 #endif
240       d->phase = SP_COPIED;
241       /* fall-through */
242     case SP_COPIED:
243       /* Start create hostkey process */
244       d->pipe_stdout = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_YES);
245       if (d->pipe_stdout == NULL)
246         {
247           cb = d->cb;
248           d->cb = NULL;
249           if (NULL != cb)
250             cb (d->cb_cls,
251                 NULL,
252                 d->cfg,
253                 d,
254                 (NULL == d->hostname)
255                 ? _("Failed to create pipe for `gnunet-peerinfo' process.\n")
256                 : _("Failed to create pipe for `ssh' process.\n"));
257           return;
258         }
259       if (NULL == d->hostname)
260         {
261 #if DEBUG_TESTING
262           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
263                       "Starting `%s', with command `%s %s %s %s'.\n",
264                       "gnunet-peerinfo", "gnunet-peerinfo", "-c", d->cfgfile,
265                       "-sq");
266 #endif
267           d->pid = GNUNET_OS_start_process (NULL, d->pipe_stdout, "gnunet-peerinfo",
268                                             "gnunet-peerinfo",
269                                             "-c", d->cfgfile,
270                                             "-sq", NULL);
271           GNUNET_DISK_pipe_close_end(d->pipe_stdout, GNUNET_DISK_PIPE_END_WRITE);
272         }
273       else
274         {
275           if (d->username != NULL)
276             GNUNET_asprintf (&dst, "%s@%s", d->username, d->hostname);
277           else
278             dst = GNUNET_strdup (d->hostname);
279
280 #if DEBUG_TESTING
281           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
282                       "Starting `%s', with command `%s %s %s %s %s %s'.\n",
283                       "gnunet-peerinfo", "ssh", dst, "gnunet-peerinfo", "-c", d->cfgfile,
284                       "-sq");
285 #endif
286           if (d->ssh_port_str == NULL)
287             {
288               d->pid = GNUNET_OS_start_process (NULL, d->pipe_stdout, "ssh",
289                                                 "ssh",
290 #if !DEBUG_TESTING
291                                                 "-q",
292 #endif
293                                                 dst,
294                                                 "gnunet-peerinfo",
295                                                 "-c", d->cfgfile, "-sq", NULL);
296             }
297           else
298             {
299               d->pid = GNUNET_OS_start_process (NULL, d->pipe_stdout, "ssh",
300                                                 "ssh", "-p", d->ssh_port_str,
301 #if !DEBUG_TESTING
302                                                 "-q",
303 #endif
304                                                 dst,
305                                                 "gnunet-peerinfo",
306                                                 "-c", d->cfgfile, "-sq", NULL);
307             }
308           GNUNET_DISK_pipe_close_end(d->pipe_stdout, GNUNET_DISK_PIPE_END_WRITE);
309           GNUNET_free (dst);
310         }
311       if (-1 == d->pid)
312         {
313           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
314                       _("Could not start `%s' process to create hostkey.\n"),
315                       (NULL == d->hostname) ? "gnunet-peerinfo" : "ssh");
316           cb = d->cb;
317           d->cb = NULL;
318           if (NULL != cb)
319             cb (d->cb_cls,
320                 NULL,
321                 d->cfg,
322                 d,
323                 (NULL == d->hostname)
324                 ? _("Failed to start `gnunet-peerinfo' process.\n")
325                 : _("Failed to start `ssh' process.\n"));
326           GNUNET_DISK_pipe_close(d->pipe_stdout);
327           return;
328         }
329 #if DEBUG_TESTING
330       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
331                   "Started `%s', waiting for hostkey.\n",
332                   "gnunet-peerinfo");
333 #endif
334       d->phase = SP_HOSTKEY_CREATE;
335       d->task
336         = GNUNET_SCHEDULER_add_read_file (d->sched,
337                                           GNUNET_TIME_absolute_get_remaining(d->max_timeout),
338                                           GNUNET_DISK_pipe_handle(d->pipe_stdout, 
339                                                                   GNUNET_DISK_PIPE_END_READ),
340                                           &start_fsm, 
341                                           d);
342       break;
343     case SP_HOSTKEY_CREATE:
344       bytes_read = GNUNET_DISK_file_read(GNUNET_DISK_pipe_handle(d->pipe_stdout, 
345                                                                  GNUNET_DISK_PIPE_END_READ),
346                                          &d->hostkeybuf[d->hostkeybufpos], 
347                                          sizeof(d->hostkeybuf) - d->hostkeybufpos);
348       if (bytes_read > 0)
349         d->hostkeybufpos += bytes_read;      
350
351       if ( (d->hostkeybufpos < 104) &&
352            (bytes_read > 0) )
353         {
354           /* keep reading */
355           d->task
356             = GNUNET_SCHEDULER_add_read_file (d->sched,
357                                               GNUNET_TIME_absolute_get_remaining(d->max_timeout),
358                                               GNUNET_DISK_pipe_handle(d->pipe_stdout, 
359                                                                       GNUNET_DISK_PIPE_END_READ),
360                                               &start_fsm, 
361                                               d);
362           return;
363         }
364       d->hostkeybuf[103] = '\0';
365       if ( (bytes_read < 0) ||
366            (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (d->hostkeybuf,
367                                                          &d->id.hashPubKey)) )
368         {
369           /* error */
370           if (bytes_read < 0)
371             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
372                        _("Error reading from gnunet-peerinfo: %s\n"),
373                        STRERROR (errno));
374           else
375             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
376                        _("Malformed output from gnunet-peerinfo!\n"));
377           cb = d->cb;
378           d->cb = NULL;
379           GNUNET_DISK_pipe_close(d->pipe_stdout);
380           d->pipe_stdout = NULL;
381           (void) PLIBC_KILL (d->pid, SIGKILL);
382           GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (d->pid));
383           d->pid = 0;
384           if (NULL != cb)
385             cb (d->cb_cls,
386                 NULL,
387                 d->cfg,
388                 d,
389                 _("`Failed to get hostkey!\n"));
390           return;
391         } 
392       GNUNET_DISK_pipe_close(d->pipe_stdout);
393       d->pipe_stdout = NULL;
394       (void) PLIBC_KILL (d->pid, SIGKILL);
395       GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (d->pid));
396       d->pid = 0;
397 #if DEBUG_TESTING
398       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
399                   "Successfully got hostkey!\n");
400 #endif
401       if (d->hostkey_callback != NULL)
402         {
403           d->hostkey_callback(d->hostkey_cls, &d->id, d, NULL);
404           d->phase = SP_HOSTKEY_CREATED;
405         }
406       else
407         {
408           d->phase = SP_TOPOLOGY_SETUP;
409         }
410       /* Fall through */
411     case SP_HOSTKEY_CREATED:
412       /* wait for topology finished */
413       if ((GNUNET_YES == d->dead) || (GNUNET_TIME_absolute_get_remaining(d->max_timeout).value == 0))
414         {
415           cb = d->cb;
416           d->cb = NULL;
417           if (NULL != cb)
418             cb (d->cb_cls,
419                 NULL,
420                 d->cfg,
421                 d,
422                 _("`Failed while waiting for topology setup!\n"));
423           return;
424         }
425
426       d->task
427         = GNUNET_SCHEDULER_add_delayed (d->sched,
428                                         GNUNET_CONSTANTS_EXEC_WAIT,
429                                         &start_fsm, d);
430       break;
431     case SP_TOPOLOGY_SETUP:
432       /* start GNUnet on remote host */
433       if (NULL == d->hostname)
434         {
435 #if DEBUG_TESTING
436           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
437                       "Starting `%s', with command `%s %s %s %s %s %s'.\n",
438                       "gnunet-arm", "gnunet-arm", "-c", d->cfgfile,
439                       "-L", "DEBUG",
440                       "-s");
441 #endif
442           d->pid = GNUNET_OS_start_process (NULL, NULL, "gnunet-arm",
443                                             "gnunet-arm",
444                                             "-c", d->cfgfile,
445 #if DEBUG_TESTING
446                                             "-L", "DEBUG",
447 #endif
448                                             "-s", "-q", NULL);
449         }
450       else
451         {
452           if (d->username != NULL)
453             GNUNET_asprintf (&dst, "%s@%s", d->username, d->hostname);
454           else
455             dst = GNUNET_strdup (d->hostname);
456
457 #if DEBUG_TESTING
458           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
459                       "Starting `%s', with command `%s %s %s %s %s %s %s %s'.\n",
460                       "gnunet-arm", "ssh", dst, "gnunet-arm", "-c", d->cfgfile,
461                       "-L", "DEBUG", "-s", "-q");
462 #endif
463           if (d->ssh_port_str == NULL)
464             {
465               d->pid = GNUNET_OS_start_process (NULL, NULL, "ssh",
466                                                 "ssh",
467 #if !DEBUG_TESTING
468                                                 "-q",
469 #endif
470                                                 dst,
471                                                 "gnunet-arm",
472 #if DEBUG_TESTING
473                                                 "-L", "DEBUG",
474 #endif
475                                                 "-c", d->cfgfile, "-s", "-q", NULL);
476             }
477           else
478             {
479
480               d->pid = GNUNET_OS_start_process (NULL, NULL, "ssh",
481                                                 "ssh", "-p", d->ssh_port_str,
482 #if !DEBUG_TESTING
483                                                 "-q",
484 #endif
485                                                 dst,
486                                                 "gnunet-arm",
487 #if DEBUG_TESTING
488                                                 "-L", "DEBUG",
489 #endif
490                                                 "-c", d->cfgfile, "-s", "-q", NULL);
491             }
492           GNUNET_free (dst);
493         }
494       if (-1 == d->pid)
495         {
496           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
497                       _("Could not start `%s' process to start GNUnet.\n"),
498                       (NULL == d->hostname) ? "gnunet-arm" : "ssh");
499           cb = d->cb;
500           d->cb = NULL;
501           if (NULL != cb)
502             cb (d->cb_cls,
503                 NULL,
504                 d->cfg,
505                 d,
506                 (NULL == d->hostname)
507                 ? _("Failed to start `gnunet-arm' process.\n")
508                 : _("Failed to start `ssh' process.\n"));
509           return;
510         }
511 #if DEBUG_TESTING
512       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
513                   "Started `%s', waiting for `%s' to be up.\n",
514                   "gnunet-arm", "gnunet-service-core");
515 #endif
516       d->phase = SP_START_ARMING;
517       d->task
518         = GNUNET_SCHEDULER_add_delayed (d->sched,
519                                         GNUNET_CONSTANTS_EXEC_WAIT,
520                                         &start_fsm, d);
521       break;
522     case SP_START_ARMING:
523       if (GNUNET_OK != GNUNET_OS_process_status (d->pid, &type, &code))
524         {
525           if (GNUNET_TIME_absolute_get_remaining(d->max_timeout).value == 0)
526             {
527               cb = d->cb;
528               d->cb = NULL;
529               if (NULL != cb)
530                 cb (d->cb_cls,
531                     NULL,
532                     d->cfg,
533                     d,
534                     (NULL == d->hostname)
535                     ? _("`gnunet-arm' does not seem to terminate.\n")
536                     : _("`ssh' does not seem to terminate.\n"));
537               return;
538             }
539           /* wait some more */
540           d->task
541             = GNUNET_SCHEDULER_add_delayed (d->sched,
542                                             GNUNET_CONSTANTS_EXEC_WAIT,
543                                             &start_fsm, d);
544           return;
545         }
546 #if DEBUG_TESTING
547       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
548                   "Successfully started `%s'.\n", "gnunet-arm");
549 #endif
550       d->phase = SP_START_CORE;
551       d->server = GNUNET_CORE_connect (d->sched,
552                                        d->cfg,
553                                        ARM_START_WAIT,
554                                        d,
555                                        &testing_init,
556                                        NULL, NULL, NULL,
557                                        NULL, GNUNET_NO,
558                                        NULL, GNUNET_NO, no_handlers);
559       break;
560     case SP_START_CORE:
561       GNUNET_break (0);
562       break;
563     case SP_START_DONE:
564       GNUNET_break (0);
565       break;
566     case SP_SHUTDOWN_START:
567       /* confirm copying complete */
568       if (GNUNET_OK != GNUNET_OS_process_status (d->pid, &type, &code))
569         {
570           if (GNUNET_TIME_absolute_get_remaining(d->max_timeout).value == 0)
571             {
572               if (NULL != d->dead_cb)
573                 d->dead_cb (d->dead_cb_cls,
574                             _("either `gnunet-arm' or `ssh' does not seem to terminate.\n"));
575               if (d->th != NULL)
576                 {
577                   GNUNET_TRANSPORT_get_hello_cancel(d->th, &process_hello, d);
578                   GNUNET_TRANSPORT_disconnect(d->th);
579                   d->th = NULL;
580                 }
581               GNUNET_CONFIGURATION_destroy (d->cfg);
582               GNUNET_free (d->cfgfile);
583               GNUNET_free_non_null(d->hello);
584               GNUNET_free_non_null (d->hostname);
585               GNUNET_free_non_null (d->username);
586               GNUNET_free_non_null (d->shortname);
587               GNUNET_free (d);
588               return;
589             }
590           /* wait some more */
591           d->task
592             = GNUNET_SCHEDULER_add_delayed (d->sched,
593                                             GNUNET_CONSTANTS_EXEC_WAIT,
594                                             &start_fsm, d);
595           return;
596         }
597       if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
598         {
599           if (NULL != d->dead_cb)
600             d->dead_cb (d->dead_cb_cls,
601                         _("shutdown (either `gnunet-arm' or `ssh') did not complete cleanly.\n"));
602           if (d->th != NULL)
603             {
604               GNUNET_TRANSPORT_get_hello_cancel(d->th, &process_hello, d);
605               GNUNET_TRANSPORT_disconnect(d->th);
606               d->th = NULL;
607             }
608           GNUNET_CONFIGURATION_destroy (d->cfg);
609           GNUNET_free (d->cfgfile);
610           GNUNET_free_non_null(d->hello);
611           GNUNET_free_non_null (d->hostname);
612           GNUNET_free_non_null (d->username);
613           GNUNET_free_non_null (d->shortname);
614           GNUNET_free (d);
615           return;
616         }
617 #if DEBUG_TESTING
618       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer shutdown complete.\n");
619 #endif
620       if (d->th != NULL)
621         {
622           GNUNET_TRANSPORT_get_hello_cancel(d->th, &process_hello, d);
623           GNUNET_TRANSPORT_disconnect(d->th);
624           d->th = NULL;
625         }
626       /* state clean up and notifications */
627       if (d->churn == GNUNET_NO)
628         {
629           GNUNET_CONFIGURATION_destroy (d->cfg);
630           GNUNET_free (d->cfgfile);
631           GNUNET_free_non_null (d->hostname);
632           GNUNET_free_non_null (d->username);
633         }
634
635       GNUNET_free_non_null(d->hello);
636       d->hello = NULL;
637       GNUNET_free_non_null (d->shortname);
638       d->shortname = NULL;
639       if (NULL != d->dead_cb)
640         d->dead_cb (d->dead_cb_cls, NULL);
641
642       if (d->churn == GNUNET_NO)
643         GNUNET_free (d);
644
645       break;
646     case SP_CONFIG_UPDATE:
647       /* confirm copying complete */
648       if (GNUNET_OK != GNUNET_OS_process_status (d->pid, &type, &code))
649         {
650           if (GNUNET_TIME_absolute_get_remaining(d->max_timeout).value == 0) /* FIXME: config update should take timeout parameter! */
651             {
652               cb = d->cb;
653               d->cb = NULL;
654               if (NULL != cb)
655                 cb (d->cb_cls,
656                     NULL,
657                     d->cfg, d, _("`scp' does not seem to terminate.\n"));
658               return;
659             }
660           /* wait some more */
661           d->task
662             = GNUNET_SCHEDULER_add_delayed (d->sched,
663                                             GNUNET_CONSTANTS_EXEC_WAIT,
664                                             &start_fsm, d);
665           return;
666         }
667       if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
668         {
669           if (NULL != d->update_cb)
670             d->update_cb (d->update_cb_cls,
671                           _("`scp' did not complete cleanly.\n"));
672           return;
673         }
674 #if DEBUG_TESTING
675       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
676                   "Successfully copied configuration file.\n");
677 #endif
678       if (NULL != d->update_cb)
679         d->update_cb (d->update_cb_cls, NULL);
680       d->phase = SP_START_DONE;
681       break;
682     }
683 }
684
685 /**
686  * Continues GNUnet daemon startup when user wanted to be notified
687  * once a hostkey was generated (for creating friends files, blacklists,
688  * etc.).
689  *
690  * @param daemon the daemon to finish starting
691  */
692 void
693 GNUNET_TESTING_daemon_continue_startup(struct GNUNET_TESTING_Daemon *daemon)
694 {
695   GNUNET_assert(daemon->phase == SP_HOSTKEY_CREATED);
696   daemon->phase = SP_TOPOLOGY_SETUP;
697 }
698
699
700 /**
701  * Start a peer that has previously been stopped using the daemon_stop
702  * call (and files weren't deleted and the allow restart flag)
703  *
704  * @param daemon the daemon to start (has been previously stopped)
705  * @param timeout how long to wait for restart
706  * @param cb the callback for notification when the peer is running
707  * @param cb_cls closure for the callback
708  */
709 void
710 GNUNET_TESTING_daemon_start_stopped (struct GNUNET_TESTING_Daemon *daemon,
711                                      struct GNUNET_TIME_Relative timeout,
712                                      GNUNET_TESTING_NotifyDaemonRunning cb,
713                                      void *cb_cls)
714 {
715   if (daemon->running == GNUNET_YES)
716   {
717     cb(cb_cls, &daemon->id, daemon->cfg, daemon, "Daemon already running, can't restart!");
718     return;
719   }
720
721   daemon->cb = cb;
722   daemon->cb_cls = cb_cls;
723   daemon->phase = SP_TOPOLOGY_SETUP;
724   daemon->max_timeout = GNUNET_TIME_relative_to_absolute(timeout);
725
726   GNUNET_SCHEDULER_add_continuation (daemon->sched,
727                                      &start_fsm,
728                                      daemon,
729                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
730 }
731
732 /**
733  * Starts a GNUnet daemon.  GNUnet must be installed on the target
734  * system and available in the PATH.  The machine must furthermore be
735  * reachable via "ssh" (unless the hostname is "NULL") without the
736  * need to enter a password.
737  *
738  * @param sched scheduler to use
739  * @param cfg configuration to use
740  * @param timeout how long to wait starting up peers
741  * @param hostname name of the machine where to run GNUnet
742  *        (use NULL for localhost).
743  * @param ssh_username ssh username to use when connecting to hostname
744  * @param sshport port to pass to ssh process when connecting to hostname
745  * @param hostkey_callback function to call once the hostkey has been
746  *        generated for this peer, but it hasn't yet been started
747  *        (NULL to start immediately, otherwise waits on GNUNET_TESTING_daemon_continue_start)
748  * @param hostkey_cls closure for hostkey callback
749  * @param cb function to call once peer is up, or failed to start
750  * @param cb_cls closure for cb
751  * @return handle to the daemon (actual start will be completed asynchronously)
752  */
753 struct GNUNET_TESTING_Daemon *
754 GNUNET_TESTING_daemon_start (struct GNUNET_SCHEDULER_Handle *sched,
755                              const struct GNUNET_CONFIGURATION_Handle *cfg,
756                              struct GNUNET_TIME_Relative timeout,
757                              const char *hostname,
758                              const char *ssh_username,
759                              uint16_t sshport,
760                              GNUNET_TESTING_NotifyHostkeyCreated hostkey_callback,
761                              void *hostkey_cls,
762                              GNUNET_TESTING_NotifyDaemonRunning cb,
763                              void *cb_cls)
764 {
765   struct GNUNET_TESTING_Daemon *ret;
766   char *arg;
767   char *username;
768
769   ret = GNUNET_malloc (sizeof (struct GNUNET_TESTING_Daemon));
770   ret->sched = sched;
771   ret->hostname = (hostname == NULL) ? NULL : GNUNET_strdup (hostname);
772   if (sshport != 0)
773     {
774       GNUNET_asprintf(&ret->ssh_port_str, "%d", sshport);
775     }
776   else
777     ret->ssh_port_str = NULL;
778   ret->cfgfile = GNUNET_DISK_mktemp ("gnunet-testing-config");
779 #if DEBUG_TESTING
780   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
781               "Setting up peer with configuration file `%s'.\n",
782               ret->cfgfile);
783 #endif
784   if (NULL == ret->cfgfile)
785     {
786       GNUNET_free_non_null (ret->hostname);
787       GNUNET_free (ret);
788       return NULL;
789     }
790   ret->hostkey_callback = hostkey_callback;
791   ret->hostkey_cls = hostkey_cls;
792   ret->cb = cb;
793   ret->cb_cls = cb_cls;
794   ret->max_timeout = GNUNET_TIME_relative_to_absolute(timeout);
795   ret->cfg = GNUNET_CONFIGURATION_dup (cfg);
796   GNUNET_CONFIGURATION_set_value_string (ret->cfg,
797                                          "PATHS",
798                                          "DEFAULTCONFIG", ret->cfgfile);
799   /* 1) write configuration to temporary file */
800   if (GNUNET_OK != GNUNET_CONFIGURATION_write (ret->cfg, ret->cfgfile))
801     {
802       if (0 != UNLINK (ret->cfgfile))
803         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
804                                   "unlink", ret->cfgfile);
805       GNUNET_CONFIGURATION_destroy (ret->cfg);
806       GNUNET_free_non_null (ret->hostname);
807       GNUNET_free (ret->cfgfile);
808       GNUNET_free (ret);
809       return NULL;
810     }
811   if (ssh_username != NULL)
812     username = GNUNET_strdup(ssh_username);
813   if ((ssh_username == NULL) && (GNUNET_OK !=
814       GNUNET_CONFIGURATION_get_value_string (cfg,
815                                              "TESTING",
816                                              "USERNAME", &username)))
817     {
818       if (NULL != getenv ("USER"))
819         username = GNUNET_strdup (getenv ("USER"));
820       else
821         username = NULL;
822     }
823   ret->username = username;
824
825   /* 2) copy file to remote host */
826   if (NULL != hostname)
827     {
828 #if DEBUG_TESTING
829       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
830                   "Copying configuration file to host `%s'.\n", hostname);
831 #endif
832       ret->phase = SP_COPYING;
833       if (NULL != username)
834         GNUNET_asprintf (&arg, "%s@%s:%s", username, hostname, ret->cfgfile);
835       else
836         GNUNET_asprintf (&arg, "%s:%s", hostname, ret->cfgfile);
837
838       if (ret->ssh_port_str == NULL)
839         {
840           ret->pid = GNUNET_OS_start_process (NULL, NULL, "scp",
841                                               "scp",
842 #if !DEBUG_TESTING
843                                               "-q",
844 #endif
845                                               ret->cfgfile, arg, NULL);
846         }
847       else
848         {
849           ret->pid = GNUNET_OS_start_process (NULL, NULL, "scp",
850                                               "scp", "-P", ret->ssh_port_str,
851 #if !DEBUG_TESTING
852                                               "-q",
853 #endif
854                                               ret->cfgfile, arg, NULL);
855         }
856       GNUNET_free (arg);
857       if (-1 == ret->pid)
858         {
859           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
860                       _
861                       ("Could not start `%s' process to copy configuration file.\n"),
862                       "scp");
863           if (0 != UNLINK (ret->cfgfile))
864             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
865                                       "unlink", ret->cfgfile);
866           GNUNET_CONFIGURATION_destroy (ret->cfg);
867           GNUNET_free_non_null (ret->hostname);
868           GNUNET_free_non_null (ret->username);
869           GNUNET_free (ret->cfgfile);
870           GNUNET_free (ret);
871           return NULL;
872         }
873       ret->task
874         = GNUNET_SCHEDULER_add_delayed (sched,
875                                         GNUNET_CONSTANTS_EXEC_WAIT,
876                                         &start_fsm, ret);
877       return ret;
878     }
879 #if DEBUG_TESTING
880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
881               "No need to copy configuration file since we are running locally.\n");
882 #endif
883   ret->phase = SP_COPIED;
884   GNUNET_SCHEDULER_add_continuation (sched,
885                                      &start_fsm,
886                                      ret,
887                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
888   return ret;
889 }
890
891
892 /**
893  * Restart (stop and start) a GNUnet daemon.
894  *
895  * @param d the daemon that should be restarted
896  * @param cb function called once the daemon is (re)started
897  * @param cb_cls closure for cb
898  */
899 void
900 GNUNET_TESTING_daemon_restart (struct GNUNET_TESTING_Daemon *d,
901                                GNUNET_TESTING_NotifyDaemonRunning cb, void *cb_cls)
902 {
903   char *arg;
904   char *del_arg;
905
906   del_arg = NULL;
907   if (NULL != d->cb)
908     {
909       d->dead = GNUNET_YES;
910       return;
911     }
912
913   d->cb = cb;
914   d->cb_cls = cb_cls;
915
916   if (d->phase == SP_CONFIG_UPDATE)
917     {
918       GNUNET_SCHEDULER_cancel (d->sched, d->task);
919       d->phase = SP_START_DONE;
920     }
921   if (d->server != NULL)
922     {
923       GNUNET_CORE_disconnect (d->server);
924       d->server = NULL;
925     }
926
927   if (d->th != NULL)
928     {
929       GNUNET_TRANSPORT_get_hello_cancel(d->th, &process_hello, d);
930       GNUNET_TRANSPORT_disconnect(d->th);
931       d->th = NULL;
932     }
933   /* state clean up and notifications */
934   GNUNET_free_non_null(d->hello);
935
936 #if DEBUG_TESTING
937     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938                 _("Terminating peer `%4s'\n"), GNUNET_i2s (&d->id));
939 #endif
940
941    d->phase = SP_START_ARMING;
942
943     /* Check if this is a local or remote process */
944   if (NULL != d->hostname)
945     {
946 #if DEBUG_TESTING
947       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
948                   "Stopping gnunet-arm with config `%s' on host `%s'.\n", d->cfgfile, d->hostname);
949 #endif
950
951       if (d->username != NULL)
952         GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
953       else
954         arg = GNUNET_strdup (d->hostname);
955
956       d->pid = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh",
957 #if !DEBUG_TESTING
958                                         "-q",
959 #endif
960                                         arg, "gnunet-arm",
961 #if DEBUG_TESTING
962                                         "-L", "DEBUG",
963 #endif
964                                         "-c", d->cfgfile, "-e", "-r", NULL);
965       /* Use -r to restart arm and all services */
966
967       GNUNET_free (arg);
968     }
969   else
970     {
971 #if DEBUG_TESTING
972       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
973                   "Stopping gnunet-arm with config `%s' locally.\n", d->cfgfile);
974 #endif
975       d->pid = GNUNET_OS_start_process (NULL, NULL, "gnunet-arm",
976                                         "gnunet-arm",
977 #if DEBUG_TESTING
978                                         "-L", "DEBUG",
979 #endif
980                                         "-c", d->cfgfile, "-e", "-r", NULL);
981     }
982
983     GNUNET_free_non_null(del_arg);
984     d->task
985       = GNUNET_SCHEDULER_add_delayed (d->sched,
986                                       GNUNET_CONSTANTS_EXEC_WAIT,
987                                       &start_fsm, d);
988
989 }
990
991
992 /**
993  * Stops a GNUnet daemon.
994  *
995  * @param d the daemon that should be stopped
996  * @param timeout how long to wait for process for shutdown to complete
997  * @param cb function called once the daemon was stopped
998  * @param cb_cls closure for cb
999  * @param delete_files GNUNET_YES to remove files, GNUNET_NO
1000  *        to leave them
1001  * @param allow_restart GNUNET_YES to restart peer later (using this API)
1002  *        GNUNET_NO to kill off and clean up for good
1003  */
1004 void
1005 GNUNET_TESTING_daemon_stop (struct GNUNET_TESTING_Daemon *d,
1006                             struct GNUNET_TIME_Relative timeout,
1007                             GNUNET_TESTING_NotifyCompletion cb, void *cb_cls,
1008                             int delete_files,
1009                             int allow_restart)
1010 {
1011   char *arg;
1012   char *del_arg;
1013   d->dead_cb = cb;
1014   d->dead_cb_cls = cb_cls;
1015
1016   if (NULL != d->cb)
1017     {
1018 #if DEBUG_TESTING
1019       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1020                  _("Setting d->dead on peer `%4s'\n"), GNUNET_i2s (&d->id));
1021 #endif
1022       d->dead = GNUNET_YES;
1023       return;
1024     }
1025
1026   if ((d->running == GNUNET_NO) && (d->churn == GNUNET_YES)) /* Peer has already been stopped in churn context! */
1027     {
1028       /* Free what was left from churning! */
1029       GNUNET_assert(d->cfg != NULL);
1030       GNUNET_CONFIGURATION_destroy (d->cfg);
1031       if (delete_files == GNUNET_YES)
1032         {
1033           if (0 != UNLINK(d->cfgfile))
1034             {
1035               GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "unlink");
1036             }
1037         }
1038       GNUNET_free (d->cfgfile);
1039       GNUNET_free_non_null (d->hostname);
1040       GNUNET_free_non_null (d->username);
1041       if (NULL != d->dead_cb)
1042         d->dead_cb (d->dead_cb_cls, NULL);
1043       GNUNET_free(d);
1044       return;
1045     }
1046
1047   del_arg = NULL;
1048   if (delete_files == GNUNET_YES)
1049     {
1050       GNUNET_asprintf(&del_arg, "-d");
1051     }
1052
1053   if (d->phase == SP_CONFIG_UPDATE)
1054     {
1055       GNUNET_SCHEDULER_cancel (d->sched, d->task);
1056       d->phase = SP_START_DONE;
1057     }
1058   if (d->server != NULL)
1059     {
1060       GNUNET_CORE_disconnect (d->server);
1061       d->server = NULL;
1062     }
1063   /* shutdown ARM process (will terminate others) */
1064 #if DEBUG_TESTING
1065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1066               _("Terminating peer `%4s'\n"), GNUNET_i2s (&d->id));
1067 #endif
1068   d->phase = SP_SHUTDOWN_START;
1069   d->running = GNUNET_NO;
1070   if (allow_restart == GNUNET_YES)
1071     d->churn = GNUNET_YES;
1072   if (d->th != NULL)
1073     {
1074       GNUNET_TRANSPORT_get_hello_cancel(d->th, &process_hello, d);
1075       GNUNET_TRANSPORT_disconnect(d->th);
1076       d->th = NULL;
1077     }
1078   /* Check if this is a local or remote process */
1079   if (NULL != d->hostname)
1080     {
1081 #if DEBUG_TESTING
1082       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1083                   "Stopping gnunet-arm with config `%s' on host `%s'.\n", d->cfgfile, d->hostname);
1084 #endif
1085
1086       if (d->username != NULL)
1087         GNUNET_asprintf (&arg, "%s@%s", d->username, d->hostname);
1088       else
1089         arg = GNUNET_strdup (d->hostname);
1090
1091       d->pid = GNUNET_OS_start_process (NULL, NULL, "ssh", "ssh",
1092 #if !DEBUG_TESTING
1093                                         "-q",
1094 #endif
1095                                         arg, "gnunet-arm",
1096 #if DEBUG_TESTING
1097                                         "-L", "DEBUG",
1098 #endif
1099                                         "-c", d->cfgfile, "-e", "-q", del_arg, NULL);
1100       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1101                   "Stopping gnunet-arm with command ssh %s gnunet-arm -c %s -e -q %s\n", arg, "gnunet-arm", d->cfgfile, del_arg);
1102       /* Use -e to end arm, and -d to remove temp files */
1103       GNUNET_free (arg);
1104     }
1105   else
1106     {
1107 #if DEBUG_TESTING
1108       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1109                   "Stopping gnunet-arm with config `%s' locally.\n", d->cfgfile);
1110 #endif
1111       d->pid = GNUNET_OS_start_process (NULL, NULL, "gnunet-arm",
1112                                         "gnunet-arm",
1113 #if DEBUG_TESTING
1114                                         "-L", "DEBUG",
1115 #endif
1116                                         "-c", d->cfgfile, "-e", "-q", del_arg, NULL);
1117     }
1118
1119   GNUNET_free_non_null(del_arg);
1120   d->max_timeout = GNUNET_TIME_relative_to_absolute(timeout);
1121   d->task
1122     = GNUNET_SCHEDULER_add_now (d->sched,
1123                                 &start_fsm, d);
1124 }
1125
1126
1127 /**
1128  * Changes the configuration of a GNUnet daemon.
1129  *
1130  * @param d the daemon that should be modified
1131  * @param cfg the new configuration for the daemon
1132  * @param cb function called once the configuration was changed
1133  * @param cb_cls closure for cb
1134  */
1135 void
1136 GNUNET_TESTING_daemon_reconfigure (struct GNUNET_TESTING_Daemon *d,
1137                                    struct GNUNET_CONFIGURATION_Handle *cfg,
1138                                    GNUNET_TESTING_NotifyCompletion cb,
1139                                    void *cb_cls)
1140 {
1141   char *arg;
1142
1143   if (d->phase != SP_START_DONE)
1144     {
1145       if (NULL != cb)
1146         cb (cb_cls,
1147             _
1148             ("Peer not yet running, can not change configuration at this point."));
1149       return;
1150     }
1151
1152   /* 1) write configuration to temporary file */
1153   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, d->cfgfile))
1154     {
1155       if (NULL != cb)
1156         cb (cb_cls, _("Failed to write new configuration to disk."));
1157       return;
1158     }
1159
1160   /* 2) copy file to remote host (if necessary) */
1161   if (NULL == d->hostname)
1162     {
1163       /* signal success */
1164       if (NULL != cb)
1165         cb (cb_cls, NULL);
1166       return;
1167     }
1168 #if DEBUG_TESTING
1169   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1170               "Copying updated configuration file to remote host `%s'.\n",
1171               d->hostname);
1172 #endif
1173   d->phase = SP_CONFIG_UPDATE;
1174   if (NULL != d->username)
1175     GNUNET_asprintf (&arg, "%s@%s:%s", d->username, d->hostname, d->cfgfile);
1176   else
1177     GNUNET_asprintf (&arg, "%s:%s", d->hostname, d->cfgfile);
1178   d->pid = GNUNET_OS_start_process (NULL, NULL, "scp", "scp",
1179 #if !DEBUG_TESTING
1180                                     "-q",
1181 #endif
1182                                     d->cfgfile, arg, NULL);
1183   GNUNET_free (arg);
1184   if (-1 == d->pid)
1185     {
1186       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1187                   _
1188                   ("Could not start `%s' process to copy configuration file.\n"),
1189                   "scp");
1190       if (NULL != cb)
1191         cb (cb_cls, _("Failed to copy new configuration to remote machine."));
1192       d->phase = SP_START_DONE;
1193       return;
1194     }
1195   d->update_cb = cb;
1196   d->update_cb_cls = cb_cls;
1197   d->task
1198     = GNUNET_SCHEDULER_add_delayed (d->sched,
1199                                     GNUNET_CONSTANTS_EXEC_WAIT,
1200                                     &start_fsm, d);
1201 }
1202
1203
1204 /**
1205  * Data kept for each pair of peers that we try
1206  * to connect.
1207  */
1208 struct ConnectContext
1209 {
1210   /**
1211    * Testing handle to the first daemon.
1212    */
1213   struct GNUNET_TESTING_Daemon *d1;
1214
1215   /**
1216    * Handle to core of first daemon (to check connect)
1217    */
1218   struct GNUNET_CORE_Handle * d1core;
1219
1220   /**
1221    * Testing handle to the second daemon.
1222    */
1223   struct GNUNET_TESTING_Daemon *d2;
1224
1225   /**
1226    * Handler for the request to core to connect to this peer.
1227    */
1228   struct GNUNET_CORE_PeerRequestHandle *connect_request_handle;
1229
1230   /**
1231    * Transport handle to the second daemon.
1232    */
1233   struct GNUNET_TRANSPORT_Handle *d2th;
1234
1235   /**
1236    * Function to call once we are done (or have timed out).
1237    */
1238   GNUNET_TESTING_NotifyConnection cb;
1239
1240   /**
1241    * Closure for "nb".
1242    */
1243   void *cb_cls;
1244
1245   /**
1246    * When should this operation be complete (or we must trigger
1247    * a timeout).
1248    */
1249   struct GNUNET_TIME_Absolute timeout;
1250
1251   /**
1252    * The relative timeout from whence this connect attempt was
1253    * started.  Allows for reconnect attempts.
1254    */
1255   struct GNUNET_TIME_Relative relative_timeout;
1256
1257   /**
1258    * Maximum number of connect attempts, will retry connection
1259    * this number of times on failures.
1260    */
1261   unsigned int max_connect_attempts;
1262
1263   /**
1264    * Hello timeout task
1265    */
1266   GNUNET_SCHEDULER_TaskIdentifier hello_send_task;
1267
1268   /**
1269    * Connect timeout task
1270    */
1271   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1272
1273   /**
1274    * When should this operation be complete (or we must trigger
1275    * a timeout).
1276    */
1277   struct GNUNET_TIME_Relative timeout_hello;
1278
1279   /**
1280    * Was the connection attempt successful?
1281    */
1282   int connected;
1283
1284   /**
1285    * The distance between the two connected peers
1286    */
1287   uint32_t distance;
1288 };
1289
1290
1291 /** Forward declaration **/
1292 static void
1293 reattempt_daemons_connect(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1294
1295
1296 /**
1297  * Notify callback about success or failure of the attempt
1298  * to connect the two peers
1299  *
1300  * @param cls our "struct ConnectContext" (freed)
1301  * @param tc reason tells us if we succeeded or failed
1302  */
1303 static void
1304 notify_connect_result (void *cls,
1305                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1306 {
1307   struct ConnectContext *ctx = cls;
1308   struct GNUNET_TIME_Relative remaining;
1309
1310   ctx->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1311   if (ctx->hello_send_task != GNUNET_SCHEDULER_NO_TASK)
1312     {
1313       GNUNET_SCHEDULER_cancel(ctx->d1->sched, ctx->hello_send_task);
1314       ctx->hello_send_task = GNUNET_SCHEDULER_NO_TASK;
1315     }
1316
1317   if (ctx->connect_request_handle != NULL)
1318     {
1319       GNUNET_CORE_peer_request_connect_cancel (ctx->connect_request_handle);
1320       ctx->connect_request_handle = NULL;
1321     }
1322   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1323     {
1324       if (ctx->d2th != NULL)
1325         GNUNET_TRANSPORT_disconnect (ctx->d2th);
1326       ctx->d2th = NULL;
1327       if (ctx->d1core != NULL)
1328         GNUNET_CORE_disconnect (ctx->d1core);
1329 #if CONNECT_CORE2
1330       if (ctx->d2core != NULL)
1331         GNUNET_CORE_disconnect (ctx->d2core);
1332       ctx->d2core = NULL;
1333 #endif
1334       ctx->d1core = NULL;
1335
1336       GNUNET_free (ctx);
1337       return;
1338     }
1339
1340   remaining = GNUNET_TIME_absolute_get_remaining(ctx->timeout);
1341
1342   if (ctx->connected == GNUNET_YES)
1343     {
1344       if (ctx->cb != NULL)
1345         {
1346           ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, ctx->distance, ctx->d1->cfg,
1347                    ctx->d2->cfg, ctx->d1, ctx->d2, NULL);
1348         }
1349     }
1350   else if (remaining.value > 0)
1351     {
1352       if (ctx->d1core != NULL)
1353         {
1354           GNUNET_CORE_disconnect(ctx->d1core);
1355           ctx->d1core = NULL;
1356         }
1357 #if CONNECT_CORE2
1358       if (ctx->d2core != NULL)
1359         {
1360           GNUNET_CORE_disconnect(ctx->d2core);
1361           ctx->d2core = NULL;
1362         }
1363 #endif
1364
1365       if (ctx->d2th != NULL)
1366         {
1367           GNUNET_TRANSPORT_disconnect(ctx->d2th);
1368           ctx->d2th = NULL;
1369         }
1370       GNUNET_SCHEDULER_add_now(ctx->d1->sched, &reattempt_daemons_connect, ctx);
1371       return;
1372     }
1373   else
1374     {
1375       if (ctx->cb != NULL)
1376         {
1377           ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, 0, ctx->d1->cfg,
1378                    ctx->d2->cfg, ctx->d1, ctx->d2,
1379                    _("Peers failed to connect"));
1380         }
1381     }
1382
1383   GNUNET_TRANSPORT_disconnect (ctx->d2th);
1384   ctx->d2th = NULL;
1385   GNUNET_CORE_disconnect (ctx->d1core);
1386   ctx->d1core = NULL;
1387   GNUNET_free (ctx);
1388 }
1389
1390
1391 /**
1392  * Success, connection is up.  Signal client our success.
1393  *
1394  * @param cls our "struct ConnectContext"
1395  * @param peer identity of the peer that has connected
1396  * @param latency the round trip latency of the connection to this peer
1397  * @param distance distance the transport level distance to this peer
1398  *
1399  */
1400 static void
1401 connect_notify (void *cls, const struct GNUNET_PeerIdentity * peer, struct GNUNET_TIME_Relative latency,
1402                 uint32_t distance)
1403 {
1404   struct ConnectContext *ctx = cls;
1405
1406   if (memcmp(&ctx->d2->id, peer, sizeof(struct GNUNET_PeerIdentity)) == 0)
1407     {
1408       ctx->connected = GNUNET_YES;
1409       ctx->distance = distance;
1410       GNUNET_SCHEDULER_cancel(ctx->d1->sched, ctx->timeout_task);
1411       ctx->timeout_task = GNUNET_SCHEDULER_add_now (ctx->d1->sched,
1412                                                     &notify_connect_result,
1413                                                     ctx);
1414     }
1415
1416 }
1417
1418 #if CONNECT_CORE2
1419 /**
1420  * Success, connection is up.  Signal client our success.
1421  *
1422  * @param cls our "struct ConnectContext"
1423  * @param peer identity of the peer that has connected
1424  * @param latency the round trip latency of the connection to this peer
1425  * @param distance distance the transport level distance to this peer
1426  *
1427  */
1428 static void
1429 connect_notify_core2 (void *cls, const struct GNUNET_PeerIdentity * peer, struct GNUNET_TIME_Relative latency,
1430                 uint32_t distance)
1431 {
1432   struct ConnectContext *ctx = cls;
1433
1434   if (memcmp(&ctx->d2->id, peer, sizeof(struct GNUNET_PeerIdentity)) == 0)
1435     {
1436       ctx->connected = GNUNET_YES;
1437       ctx->distance = distance;
1438       GNUNET_SCHEDULER_cancel(ctx->d1->sched, ctx->timeout_task);
1439       ctx->timeout_task = GNUNET_SCHEDULER_add_now (ctx->d1->sched,
1440                                                     &notify_connect_result,
1441                                                     ctx);
1442     }
1443
1444 }
1445 #endif
1446
1447 /**
1448  * Task called once a core connect request has been transmitted.
1449  *
1450  * @param cls struct ConnectContext
1451  * @param tc context information (why was this task triggered now)
1452  */
1453 void core_connect_request_cont (void *cls,
1454                                 const struct
1455                                 GNUNET_SCHEDULER_TaskContext * tc)
1456 {
1457   struct ConnectContext *ctx = cls;
1458
1459   if (tc->reason == GNUNET_SCHEDULER_REASON_PREREQ_DONE)
1460     ctx->connect_request_handle = NULL;
1461   return;
1462 }
1463
1464 static void
1465 send_hello(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1466 {
1467   struct ConnectContext *ctx = cls;
1468   struct GNUNET_MessageHeader *hello;
1469   ctx->hello_send_task = GNUNET_SCHEDULER_NO_TASK;
1470   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1471     return;
1472   if ((ctx->d1->hello != NULL) && (NULL != GNUNET_HELLO_get_header(ctx->d1->hello)))
1473     {
1474       hello = GNUNET_HELLO_get_header(ctx->d1->hello);
1475       GNUNET_assert(hello != NULL);
1476       GNUNET_TRANSPORT_offer_hello (ctx->d2th, hello);
1477
1478       ctx->connect_request_handle = GNUNET_CORE_peer_request_connect (ctx->d1->sched,
1479                                                                       ctx->d2->cfg,
1480                                                                       GNUNET_TIME_relative_divide(ctx->relative_timeout,
1481                                                                                                   ctx->max_connect_attempts + 1),
1482                                                                       &ctx->d1->id,
1483                                                                       &core_connect_request_cont,
1484                                                                       ctx);
1485       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending connect request to core for peer %s\n", GNUNET_i2s(&ctx->d1->id));
1486       ctx->timeout_hello = GNUNET_TIME_relative_add(ctx->timeout_hello,
1487                                                     GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS,
1488                                                                                   500));
1489     }
1490   ctx->hello_send_task = GNUNET_SCHEDULER_add_delayed(ctx->d1->sched,
1491                                                       ctx->timeout_hello,
1492                                                       &send_hello, ctx);
1493 }
1494
1495 /**
1496  * Establish a connection between two GNUnet daemons.
1497  *
1498  * @param d1 handle for the first daemon
1499  * @param d2 handle for the second daemon
1500  * @param timeout how long is the connection attempt
1501  *        allowed to take?
1502  * @param max_connect_attempts how many times should we try to reconnect
1503  *        (within timeout)
1504  * @param cb function to call at the end
1505  * @param cb_cls closure for cb
1506  */
1507 void
1508 GNUNET_TESTING_daemons_connect (struct GNUNET_TESTING_Daemon *d1,
1509                                 struct GNUNET_TESTING_Daemon *d2,
1510                                 struct GNUNET_TIME_Relative timeout,
1511                                 unsigned int max_connect_attempts,
1512                                 GNUNET_TESTING_NotifyConnection cb,
1513                                 void *cb_cls)
1514 {
1515   struct ConnectContext *ctx;
1516
1517   if ((d1->running == GNUNET_NO) || (d2->running == GNUNET_NO))
1518     {
1519       if (NULL != cb)
1520         cb (cb_cls, &d1->id, &d2->id, 0, d1->cfg, d2->cfg, d1, d2,
1521             _("Peers are not fully running yet, can not connect!\n"));
1522       return;
1523     }
1524   ctx = GNUNET_malloc (sizeof (struct ConnectContext));
1525   ctx->d1 = d1;
1526   ctx->d2 = d2;
1527   ctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1528   ctx->timeout_hello = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 500);
1529   ctx->relative_timeout = timeout;
1530   ctx->cb = cb;
1531   ctx->cb_cls = cb_cls;
1532   ctx->max_connect_attempts = max_connect_attempts;
1533   ctx->connected = GNUNET_NO;
1534 #if DEBUG_TESTING
1535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1536               "Asked to connect peer %s to peer %s\n",
1537               d1->shortname, d2->shortname);
1538 #endif
1539
1540   ctx->d1core = GNUNET_CORE_connect (d1->sched,
1541                                      d1->cfg,
1542                                      timeout,
1543                                      ctx,
1544                                      NULL,
1545                                      &connect_notify, NULL, NULL,
1546                                      NULL, GNUNET_NO,
1547                                      NULL, GNUNET_NO, no_handlers);
1548   if (ctx->d1core == NULL)
1549     {
1550       GNUNET_free (ctx);
1551       if (NULL != cb)
1552         cb (cb_cls, &d1->id, &d2->id, 0, d1->cfg, d2->cfg, d1, d2,
1553             _("Failed to connect to core service of first peer!\n"));
1554       return;
1555     }
1556
1557 #if CONNECT_CORE2
1558   ctx->d2core = GNUNET_CORE_connect (d2->sched,
1559                                      d2->cfg,
1560                                      timeout,
1561                                      ctx,
1562                                      NULL,
1563                                      NULL, NULL, NULL,
1564                                      NULL, GNUNET_NO,
1565                                      NULL, GNUNET_NO, no_handlers);
1566   if (ctx->d2core == NULL)
1567     {
1568       GNUNET_free (ctx);
1569       if (NULL != cb)
1570         cb (cb_cls, &d1->id, &d2->id, 0, d1->cfg, d2->cfg, d1, d2,
1571             _("Failed to connect to core service of second peer!\n"));
1572       return;
1573     }
1574 #endif
1575
1576 #if DEBUG_TESTING > 2
1577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1578               "Asked to connect peer %s to peer %s\n",
1579               d1->shortname, d2->shortname);
1580   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1581               "Connecting to transport service of peer %s\n", d2->shortname);
1582
1583 #endif
1584
1585   ctx->d2th = GNUNET_TRANSPORT_connect (d2->sched,
1586                                         d2->cfg, 
1587                                         &d2->id,
1588                                         d2, NULL, NULL, NULL);
1589   if (ctx->d2th == NULL)
1590     {
1591       GNUNET_CORE_disconnect(ctx->d1core);
1592       GNUNET_free (ctx);
1593       if (NULL != cb)
1594         cb (cb_cls, &d1->id, &d2->id, 0, d1->cfg, d2->cfg, d1, d2,
1595             _("Failed to connect to transport service!\n"));
1596       return;
1597     }
1598
1599   ctx->timeout_task = GNUNET_SCHEDULER_add_delayed (d1->sched,
1600                                                     GNUNET_TIME_relative_divide(ctx->relative_timeout, 
1601                                                     ctx->max_connect_attempts),
1602                                                     &notify_connect_result, ctx);
1603
1604   ctx->hello_send_task = GNUNET_SCHEDULER_add_now(ctx->d1->sched, &send_hello, ctx);
1605 }
1606
1607 static void
1608 reattempt_daemons_connect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1609 {
1610
1611   struct ConnectContext *ctx = cls;
1612   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1613     {
1614       return;
1615     }
1616 #if DEBUG_TESTING_RECONNECT
1617   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "re-attempting connect of peer %s to peer %s\n",
1618               ctx->d1->shortname, ctx->d2->shortname);
1619 #endif
1620
1621   GNUNET_assert(ctx->d1core == NULL);
1622
1623   ctx->d1core = GNUNET_CORE_connect (ctx->d1->sched,
1624                                      ctx->d1->cfg,
1625                                      GNUNET_TIME_absolute_get_remaining(ctx->timeout),
1626                                      ctx,
1627                                      NULL,
1628                                      &connect_notify, NULL, NULL,
1629                                      NULL, GNUNET_NO,
1630                                      NULL, GNUNET_NO, no_handlers);
1631   if (ctx->d1core == NULL)
1632     {
1633       if (NULL != ctx->cb)
1634         ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, 0, ctx->d1->cfg, ctx->d2->cfg, ctx->d1, ctx->d2,
1635                  _("Failed to connect to core service of first peer!\n"));
1636       GNUNET_free (ctx);
1637       return;
1638     }
1639
1640   ctx->d2th = GNUNET_TRANSPORT_connect (ctx->d2->sched,
1641                                         ctx->d2->cfg, 
1642                                         &ctx->d2->id,
1643                                         ctx->d2, NULL, NULL, NULL);
1644   if (ctx->d2th == NULL)
1645     {
1646       GNUNET_CORE_disconnect(ctx->d1core);
1647       GNUNET_free (ctx);
1648       if (NULL != ctx->cb)
1649         ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, 0, ctx->d1->cfg, ctx->d2->cfg, ctx->d1, ctx->d2,
1650             _("Failed to connect to transport service!\n"));
1651       return;
1652     }
1653
1654   ctx->timeout_task = GNUNET_SCHEDULER_add_delayed (ctx->d1->sched,
1655                                                     GNUNET_TIME_relative_divide(ctx->relative_timeout, ctx->max_connect_attempts),
1656                                                     &notify_connect_result, ctx);
1657
1658   ctx->hello_send_task = GNUNET_SCHEDULER_add_now(ctx->d1->sched, &send_hello, ctx);
1659 }
1660
1661 /* end of testing.c */