fix leaks, code cleanup
[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 2, 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  * TODO:
32  * - modify configuration to allow 2087-connections from
33  *   controlling host (otherwise shutdown won't work)
34  * 
35  */
36 #include "platform.h"
37 #include "gnunet_arm_service.h"
38 #include "gnunet_core_service.h"
39 #include "gnunet_constants.h"
40 #include "gnunet_testing_lib.h"
41 #include "gnunet_transport_service.h"
42
43 #define DEBUG_TESTING GNUNET_NO
44
45 /**
46  * How long do we wait after starting gnunet-service-arm
47  * for the core service to be alive?
48  */
49 #define ARM_START_WAIT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
50
51 /**
52  * How many times are we willing to try to wait for "scp" or
53  * "gnunet-service-arm" to complete (waitpid) before giving up?
54  */
55 #define MAX_EXEC_WAIT_RUNS 50
56
57
58 /**
59  * Function called after GNUNET_CORE_connect has succeeded
60  * (or failed for good).  Note that the private key of the
61  * peer is intentionally not exposed here; if you need it,
62  * your process should try to read the private key file
63  * directly (which should work if you are authorized...).
64  *
65  * @param cls closure
66  * @param server handle to the server, NULL if we failed
67  * @param my_identity ID of this peer, NULL if we failed
68  * @param publicKey public key of this peer, NULL if we failed
69  */
70 static void
71 testing_init (void *cls,
72               struct GNUNET_CORE_Handle *server,
73               const struct GNUNET_PeerIdentity *my_identity,
74               const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
75 {
76   struct GNUNET_TESTING_Daemon *d = cls;
77   GNUNET_TESTING_NotifyDaemonRunning cb;
78
79   GNUNET_assert (d->phase == SP_START_CORE);
80   d->phase = SP_START_DONE;
81   cb = d->cb;
82   d->cb = NULL;
83   if (server == NULL)
84     {
85       d->server = NULL;
86       if (GNUNET_YES == d->dead)
87         GNUNET_TESTING_daemon_stop (d, d->dead_cb, d->dead_cb_cls);
88       else if (NULL != cb)
89         cb (d->cb_cls, NULL, d->cfg, d,
90             _("Failed to connect to core service\n"));
91       return;
92     }
93 #if DEBUG_TESTING
94   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
95               "Successfully started peer `%4s'.\n", GNUNET_i2s (my_identity));
96 #endif
97   d->id = *my_identity;
98   d->shortname = strdup (GNUNET_i2s (my_identity));
99   d->server = server;
100   if (GNUNET_YES == d->dead)
101     GNUNET_TESTING_daemon_stop (d, d->dead_cb, d->dead_cb_cls);
102   else if (NULL != cb)
103     cb (d->cb_cls, my_identity, d->cfg, d, NULL);
104 }
105
106
107 /**
108  * Finite-state machine for starting GNUnet.
109  *
110  * @param cls our "struct GNUNET_TESTING_Daemon"
111  * @param tc unused
112  */
113 static void
114 start_fsm (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
115 {
116   static struct GNUNET_CORE_MessageHandler no_handlers[] = { {NULL, 0, 0} };
117   struct GNUNET_TESTING_Daemon *d = cls;
118   GNUNET_TESTING_NotifyDaemonRunning cb;
119   enum GNUNET_OS_ProcessStatusType type;
120   unsigned long code;
121   char *dst;
122
123 #if DEBUG_TESTING
124   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
125               "Peer FSM is in phase %u.\n", d->phase);
126 #endif
127   d->task = GNUNET_SCHEDULER_NO_TASK;
128   switch (d->phase)
129     {
130     case SP_COPYING:
131       /* confirm copying complete */
132       if (GNUNET_OK != GNUNET_OS_process_status (d->pid, &type, &code))
133         {
134           d->wait_runs++;
135           if (d->wait_runs > MAX_EXEC_WAIT_RUNS)
136             {
137               cb = d->cb;
138               d->cb = NULL;
139               if (NULL != cb)
140                 cb (d->cb_cls,
141                     NULL,
142                     d->cfg, d, _("`scp' does not seem to terminate.\n"));
143               return;
144             }
145           /* wait some more */
146           d->task
147             = GNUNET_SCHEDULER_add_delayed (d->sched,
148                                             GNUNET_CONSTANTS_EXEC_WAIT,
149                                             &start_fsm, d);
150           return;
151         }
152       if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
153         {
154           cb = d->cb;
155           d->cb = NULL;
156           if (NULL != cb)
157             cb (d->cb_cls,
158                 NULL, d->cfg, d, _("`scp' did not complete cleanly.\n"));
159           return;
160         }
161 #if DEBUG_TESTING
162       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
163                   "Successfully copied configuration file.\n");
164 #endif
165       d->phase = SP_COPIED;
166       /* fall-through */
167     case SP_COPIED:
168       /* start GNUnet on remote host */
169       if (NULL == d->hostname)
170         {
171           d->pid = GNUNET_OS_start_process (NULL, NULL, "gnunet-service-arm",
172                                             "gnunet-service-arm",
173                                             "-c", d->cfgfile,
174 #if DEBUG_TESTING
175                                             "-L", "DEBUG",
176 #endif
177                                             "-d", NULL);
178         }
179       else
180         {
181           if (d->username != NULL)
182             GNUNET_asprintf (&dst, "%s@%s", d->username, d->hostname);
183           else
184             dst = GNUNET_strdup (d->hostname);
185           d->pid = GNUNET_OS_start_process (NULL, NULL, "ssh",
186                                             "ssh",
187                                             dst,
188                                             "gnunet-service-arm",
189                                             "-c", d->cfgfile, "-d", NULL);
190           GNUNET_free (dst);
191         }
192       if (-1 == d->pid)
193         {
194           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
195                       _("Could not start `%s' process to start GNUnet.\n"),
196                       (NULL == d->hostname) ? "gnunet-service-arm" : "ssh");
197           cb = d->cb;
198           d->cb = NULL;
199           if (NULL != cb)
200             cb (d->cb_cls,
201                 NULL,
202                 d->cfg,
203                 d,
204                 (NULL == d->hostname)
205                 ? _("Failed to start `gnunet-service-arm' process.\n")
206                 : _("Failed to start `ssh' process.\n"));
207         }
208 #if DEBUG_TESTING
209       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
210                   "Started `%s', waiting for `%s' to be up.\n",
211                   "gnunet-service-arm", "gnunet-service-core");
212 #endif
213       d->phase = SP_START_ARMING;
214       d->wait_runs = 0;
215       d->task
216         = GNUNET_SCHEDULER_add_delayed (d->sched,
217                                         GNUNET_CONSTANTS_EXEC_WAIT,
218                                         &start_fsm, d);
219       break;
220     case SP_START_ARMING:
221       if (GNUNET_OK != GNUNET_OS_process_status (d->pid, &type, &code))
222         {
223           d->wait_runs++;
224           if (d->wait_runs > MAX_EXEC_WAIT_RUNS)
225             {
226               cb = d->cb;
227               d->cb = NULL;
228               if (NULL != cb)
229                 cb (d->cb_cls,
230                     NULL,
231                     d->cfg,
232                     d,
233                     (NULL == d->hostname)
234                     ? _("`gnunet-service-arm' does not seem to terminate.\n")
235                     : _("`ssh' does not seem to terminate.\n"));
236               return;
237             }
238           /* wait some more */
239           d->task
240             = GNUNET_SCHEDULER_add_delayed (d->sched,
241                                             GNUNET_CONSTANTS_EXEC_WAIT,
242                                             &start_fsm, d);
243           return;
244         }
245 #if DEBUG_TESTING
246       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
247                   "Successfully started `%s'.\n", "gnunet-service-arm");
248 #endif
249       d->phase = SP_START_CORE;
250       d->server = GNUNET_CORE_connect (d->sched,
251                                        d->cfg,
252                                        ARM_START_WAIT,
253                                        d,
254                                        &testing_init,
255                                        NULL, NULL, NULL,
256                                        NULL, GNUNET_NO,
257                                        NULL, GNUNET_NO, no_handlers);
258       break;
259     case SP_START_CORE:
260       GNUNET_break (0);
261       break;
262     case SP_START_DONE:
263       GNUNET_break (0);
264       break;
265     case SP_CLEANUP:
266       /* confirm copying complete */
267       if (GNUNET_OK != GNUNET_OS_process_status (d->pid, &type, &code))
268         {
269           d->wait_runs++;
270           if (d->wait_runs > MAX_EXEC_WAIT_RUNS)
271             {
272               d->dead_cb (d->dead_cb_cls,
273                           _("`ssh' does not seem to terminate.\n"));
274               GNUNET_free (d->cfgfile);
275               GNUNET_free_non_null (d->hostname);
276               GNUNET_free_non_null (d->username);
277               GNUNET_free (d);
278               return;
279             }
280           /* wait some more */
281           d->task
282             = GNUNET_SCHEDULER_add_delayed (d->sched,
283                                             GNUNET_CONSTANTS_EXEC_WAIT,
284                                             &start_fsm, d);
285           return;
286         }
287       if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
288         {
289           if (NULL != d->dead_cb)
290             d->dead_cb (d->dead_cb_cls,
291                         _("`ssh' did not complete cleanly.\n"));
292           GNUNET_free (d->cfgfile);
293           GNUNET_free_non_null (d->hostname);
294           GNUNET_free_non_null (d->username);
295           GNUNET_free (d);
296           return;
297         }
298 #if DEBUG_TESTING
299       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer shutdown complete.\n");
300 #endif
301       GNUNET_free (d->cfgfile);
302       GNUNET_free_non_null (d->hostname);
303       GNUNET_free_non_null (d->username);
304       if (NULL != d->dead_cb)
305         d->dead_cb (d->dead_cb_cls, NULL);
306       GNUNET_free (d);
307       break;
308     case SP_CONFIG_UPDATE:
309       /* confirm copying complete */
310       if (GNUNET_OK != GNUNET_OS_process_status (d->pid, &type, &code))
311         {
312           d->wait_runs++;
313           if (d->wait_runs > MAX_EXEC_WAIT_RUNS)
314             {
315               cb = d->cb;
316               d->cb = NULL;
317               if (NULL != cb)
318                 cb (d->cb_cls,
319                     NULL,
320                     d->cfg, d, _("`scp' does not seem to terminate.\n"));
321               return;
322             }
323           /* wait some more */
324           d->task
325             = GNUNET_SCHEDULER_add_delayed (d->sched,
326                                             GNUNET_CONSTANTS_EXEC_WAIT,
327                                             &start_fsm, d);
328           return;
329         }
330       if ((type != GNUNET_OS_PROCESS_EXITED) || (code != 0))
331         {
332           if (NULL != d->update_cb)
333             d->update_cb (d->update_cb_cls,
334                           _("`scp' did not complete cleanly.\n"));
335           return;
336         }
337 #if DEBUG_TESTING
338       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
339                   "Successfully copied configuration file.\n");
340 #endif
341       if (NULL != d->update_cb)
342         d->update_cb (d->update_cb_cls, NULL);
343       d->phase = SP_START_DONE;
344       break;
345     }
346 }
347
348
349 /**
350  * Starts a GNUnet daemon.  GNUnet must be installed on the target
351  * system and available in the PATH.  The machine must furthermore be
352  * reachable via "ssh" (unless the hostname is "NULL") without the
353  * need to enter a password.
354  *
355  * @param sched scheduler to use 
356  * @param cfg configuration to use
357  * @param hostname name of the machine where to run GNUnet
358  *        (use NULL for localhost).
359  * @param cb function to call with the result
360  * @param cb_cls closure for cb
361  * @return handle to the daemon (actual start will be completed asynchronously)
362  */
363 struct GNUNET_TESTING_Daemon *
364 GNUNET_TESTING_daemon_start (struct GNUNET_SCHEDULER_Handle *sched,
365                              const struct GNUNET_CONFIGURATION_Handle *cfg,
366                              const char *hostname,
367                              GNUNET_TESTING_NotifyDaemonRunning cb,
368                              void *cb_cls)
369 {
370   struct GNUNET_TESTING_Daemon *ret;
371   char *arg;
372   char *username;
373
374   ret = GNUNET_malloc (sizeof (struct GNUNET_TESTING_Daemon));
375   ret->sched = sched;
376   ret->hostname = (hostname == NULL) ? NULL : GNUNET_strdup (hostname);
377   ret->cfgfile = GNUNET_DISK_mktemp ("gnunet-testing-config");
378 #if DEBUG_TESTING
379   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
380               "Setting up peer with configuration file `%s'.\n",
381               ret->cfgfile);
382 #endif
383   if (NULL == ret->cfgfile)
384     {
385       GNUNET_free_non_null (ret->hostname);
386       GNUNET_free (ret);
387       return NULL;
388     }
389   ret->cb = cb;
390   ret->cb_cls = cb_cls;
391   ret->cfg = GNUNET_CONFIGURATION_dup (cfg);
392   GNUNET_CONFIGURATION_set_value_string (ret->cfg,
393                                          "PATHS",
394                                          "DEFAULTCONFIG", ret->cfgfile);
395   /* 1) write configuration to temporary file */
396   if (GNUNET_OK != GNUNET_CONFIGURATION_write (ret->cfg, ret->cfgfile))
397     {
398       if (0 != UNLINK (ret->cfgfile))
399         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
400                                   "unlink", ret->cfgfile);
401       GNUNET_CONFIGURATION_destroy (ret->cfg);
402       GNUNET_free_non_null (ret->hostname);
403       GNUNET_free (ret->cfgfile);
404       GNUNET_free (ret);
405       return NULL;
406     }
407   if (GNUNET_OK !=
408       GNUNET_CONFIGURATION_get_value_string (cfg,
409                                              "TESTING",
410                                              "USERNAME", &username))
411     {
412       if (NULL != getenv ("USER"))
413         username = GNUNET_strdup (getenv ("USER"));
414       else
415         username = NULL;
416     }
417   ret->username = username;
418
419   /* 2) copy file to remote host */
420   if (NULL != hostname)
421     {
422 #if DEBUG_TESTING
423       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
424                   "Copying configuration file to host `%s'.\n", hostname);
425 #endif
426       ret->phase = SP_COPYING;
427       if (NULL != username)
428         GNUNET_asprintf (&arg, "%s@%s:%s", username, hostname, ret->cfgfile);
429       else
430         GNUNET_asprintf (&arg, "%s:%s", hostname, ret->cfgfile);
431       ret->pid = GNUNET_OS_start_process (NULL, NULL, "scp",
432                                           "scp", ret->cfgfile, arg, NULL);
433       GNUNET_free (arg);
434       if (-1 == ret->pid)
435         {
436           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
437                       _
438                       ("Could not start `%s' process to copy configuration file.\n"),
439                       "scp");
440           if (0 != UNLINK (ret->cfgfile))
441             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
442                                       "unlink", ret->cfgfile);
443           GNUNET_CONFIGURATION_destroy (ret->cfg);
444           GNUNET_free_non_null (ret->hostname);
445           GNUNET_free_non_null (ret->username);
446           GNUNET_free (ret->cfgfile);
447           GNUNET_free (ret);
448           return NULL;
449         }
450       ret->task
451         = GNUNET_SCHEDULER_add_delayed (sched,
452                                         GNUNET_CONSTANTS_EXEC_WAIT,
453                                         &start_fsm, ret);
454       return ret;
455     }
456 #if DEBUG_TESTING
457   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
458               "No need to copy configuration file since we are running locally.\n");
459 #endif
460   ret->phase = SP_COPIED;
461   GNUNET_SCHEDULER_add_continuation (sched,
462                                      &start_fsm,
463                                      ret,
464                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
465   return ret;
466 }
467
468
469 /**
470  * Stops a GNUnet daemon.
471  *
472  * @param d the daemon that should be stopped
473  * @param cb function called once the daemon was stopped
474  * @param cb_cls closure for cb
475  */
476 void
477 GNUNET_TESTING_daemon_stop (struct GNUNET_TESTING_Daemon *d,
478                             GNUNET_TESTING_NotifyCompletion cb, void *cb_cls)
479 {
480   struct GNUNET_CLIENT_Connection *cc;
481   char *dst;
482
483   if (NULL != d->cb)
484     {
485       d->dead = GNUNET_YES;
486       d->dead_cb = cb;
487       d->dead_cb_cls = cb_cls;
488       return;
489     }
490   if (d->phase == SP_CONFIG_UPDATE)
491     {
492       GNUNET_SCHEDULER_cancel (d->sched, d->task);
493       d->phase = SP_START_DONE;
494     }
495   if (d->server != NULL)
496     {
497       GNUNET_CORE_disconnect (d->server);
498       d->server = NULL;
499     }
500   /* shutdown ARM process (will also terminate others) */
501 #if DEBUG_TESTING
502   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
503               _("Terminating peer `%4s'\n"), GNUNET_i2s (&d->id));
504 #endif
505   cc = GNUNET_CLIENT_connect (d->sched, "arm", d->cfg);
506   GNUNET_CLIENT_service_shutdown (cc);
507
508   /* state clean up and notifications */
509   if (0 != UNLINK (d->cfgfile))
510     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
511                               "unlink", d->cfgfile);
512   if (d->hostname != NULL)
513     {
514 #if DEBUG_TESTING
515       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
516                   "Removing configuration file on remote host `%s'.\n",
517                   d->hostname);
518 #endif
519       if (NULL != d->username)
520         GNUNET_asprintf (&dst, "%s@%s", d->username, d->hostname);
521       else
522         dst = GNUNET_strdup (d->hostname);
523       d->pid = GNUNET_OS_start_process (NULL, NULL, "ssh",
524                                         "ssh", dst, "rm", d->cfgfile, NULL);
525       GNUNET_free (dst);
526       if (-1 == d->pid)
527         {
528           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
529                       _
530                       ("Could not start `%s' process to delete configuration file.\n"),
531                       "ssh");
532           GNUNET_free (d->cfgfile);
533           GNUNET_free_non_null (d->hostname);
534           GNUNET_free_non_null (d->username);
535           GNUNET_free (d);
536           cb (cb_cls, _("Error cleaning up configuration file.\n"));
537           return;
538         }
539       d->phase = SP_CLEANUP;
540       d->dead_cb = cb;
541       d->dead_cb_cls = cb_cls;
542       d->task
543         = GNUNET_SCHEDULER_add_delayed (d->sched,
544                                         GNUNET_CONSTANTS_EXEC_WAIT,
545                                         &start_fsm, d);
546       return;
547     }
548   GNUNET_CONFIGURATION_destroy (d->cfg);
549   GNUNET_free (d->cfgfile);
550   GNUNET_free_non_null (d->hostname);
551   GNUNET_free_non_null (d->username);
552   GNUNET_free_non_null (d->shortname);
553   GNUNET_free (d);
554   if (NULL != cb)
555     cb (cb_cls, NULL);
556 }
557
558
559 /**
560  * Changes the configuration of a GNUnet daemon.
561  *
562  * @param d the daemon that should be modified
563  * @param cfg the new configuration for the daemon
564  * @param cb function called once the configuration was changed
565  * @param cb_cls closure for cb
566  */
567 void
568 GNUNET_TESTING_daemon_reconfigure (struct GNUNET_TESTING_Daemon *d,
569                                    struct GNUNET_CONFIGURATION_Handle *cfg,
570                                    GNUNET_TESTING_NotifyCompletion cb,
571                                    void *cb_cls)
572 {
573   char *arg;
574
575   if (d->phase != SP_START_DONE)
576     {
577       if (NULL != cb)
578         cb (cb_cls,
579             _
580             ("Peer not yet running, can not change configuration at this point."));
581       return;
582     }
583
584   /* 1) write configuration to temporary file */
585   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, d->cfgfile))
586     {
587       if (NULL != cb)
588         cb (cb_cls, _("Failed to write new configuration to disk."));
589       return;
590     }
591
592   /* 2) copy file to remote host (if necessary) */
593   if (NULL == d->hostname)
594     {
595       /* signal success */
596       if (NULL != cb)
597         cb (cb_cls, NULL);
598       return;
599     }
600 #if DEBUG_TESTING
601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
602               "Copying updated configuration file to remote host `%s'.\n",
603               d->hostname);
604 #endif
605   d->phase = SP_CONFIG_UPDATE;
606   if (NULL != d->username)
607     GNUNET_asprintf (&arg, "%s@%s:%s", d->username, d->hostname, d->cfgfile);
608   else
609     GNUNET_asprintf (&arg, "%s:%s", d->hostname, d->cfgfile);
610   d->pid = GNUNET_OS_start_process (NULL, NULL, "scp", "scp", d->cfgfile, arg, NULL);
611   GNUNET_free (arg);
612   if (-1 == d->pid)
613     {
614       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
615                   _
616                   ("Could not start `%s' process to copy configuration file.\n"),
617                   "scp");
618       if (NULL != cb)
619         cb (cb_cls, _("Failed to copy new configuration to remote machine."));
620       d->phase = SP_START_DONE;
621       return;
622     }
623   d->update_cb = cb;
624   d->update_cb_cls = cb_cls;
625   d->task
626     = GNUNET_SCHEDULER_add_delayed (d->sched,
627                                     GNUNET_CONSTANTS_EXEC_WAIT,
628                                     &start_fsm, d);
629 }
630
631
632 /**
633  * Data kept for each pair of peers that we try
634  * to connect.
635  */
636 struct ConnectContext
637 {
638   /**
639    * Testing handle to the first daemon.
640    */
641   struct GNUNET_TESTING_Daemon *d1;
642
643   /**
644    * Handle to core of first daemon (to check connect)
645    */
646   struct GNUNET_CORE_Handle * d1core;
647
648   /**
649    * Testing handle to the second daemon.
650    */
651   struct GNUNET_TESTING_Daemon *d2;
652
653   /**
654    * Handle to core of second daemon (to check connect)
655    */
656   struct GNUNET_CORE_Handle * d2core;
657
658   /**
659    * Transport handle to the first daemon.
660    */
661   struct GNUNET_TRANSPORT_Handle *d1th;
662
663   /**
664    * Transport handle to the second daemon.
665    */
666   struct GNUNET_TRANSPORT_Handle *d2th;
667
668   /**
669    * Function to call once we are done (or have timed out).
670    */
671   GNUNET_TESTING_NotifyConnection cb;
672
673   /**
674    * Closure for "nb".
675    */
676   void *cb_cls;
677
678   /**
679    * Transmit handle for our request for transmission
680    * (as given to d2 asking to talk to d1).
681    */
682   struct GNUNET_CORE_TransmitHandle *ntr;
683
684   /**
685    * When should this operation be complete (or we must trigger
686    * a timeout).
687    */
688   struct GNUNET_TIME_Absolute timeout;
689
690   /**
691    * Hello timeout task
692    */
693   GNUNET_SCHEDULER_TaskIdentifier hello_send_task;
694
695   /**
696    * Connect timeout task
697    */
698   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
699
700   /**
701    * When should this operation be complete (or we must trigger
702    * a timeout).
703    */
704   struct GNUNET_TIME_Relative timeout_hello;
705
706   /**
707    * The current hello message we have (for d1)
708    */
709   struct GNUNET_MessageHeader *hello;
710
711   /**
712    * Was the connection successful?
713    */
714   int connected;
715 };
716
717
718 /**
719  * Receive the HELLO from one peer, give it to the other
720  * and ask them to connect.
721  *
722  * @param cls "struct ConnectContext"
723  * @param message HELLO message of peer
724  */
725 static void
726 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
727 {
728   struct ConnectContext *ctx = cls;
729
730 #if DEBUG_TESTING
731   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
732               "Received `%s' from transport service of `%4s'\n",
733               "HELLO", GNUNET_i2s (&ctx->d1->id));
734 #endif
735
736   GNUNET_assert (message != NULL);
737   GNUNET_free_non_null(ctx->hello);
738   ctx->hello = GNUNET_malloc(ntohs(message->size));
739   memcpy(ctx->hello, message, ntohs(message->size));
740
741 }
742
743
744 /**
745  * Notify callback about success or failure of the attempt
746  * to connect the two peers
747  * 
748  * @param cls our "struct ConnectContext" (freed)
749  * @param tc reason tells us if we succeeded or failed
750  */
751 static void
752 notify_connect_result (void *cls,
753                        const struct GNUNET_SCHEDULER_TaskContext *tc)
754 {
755   struct ConnectContext *ctx = cls;
756
757   GNUNET_TRANSPORT_get_hello_cancel (ctx->d1th, &process_hello, ctx);
758   GNUNET_SCHEDULER_cancel(ctx->d1->sched, ctx->hello_send_task);
759
760   if (ctx->cb != NULL)
761     {
762       if (ctx->connected == GNUNET_NO)
763         {
764           ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, ctx->d1->cfg,
765                   ctx->d2->cfg, ctx->d1, ctx->d2,
766                   _("Peers failed to connect"));
767         }
768       else
769         {
770           ctx->cb (ctx->cb_cls, &ctx->d1->id, &ctx->d2->id, ctx->d1->cfg,
771                    ctx->d2->cfg, ctx->d1, ctx->d2, NULL);
772           GNUNET_SCHEDULER_cancel(ctx->d1->sched, ctx->timeout_task);
773         }
774     }
775
776   ctx->ntr = NULL;
777   GNUNET_TRANSPORT_disconnect (ctx->d1th);
778   ctx->d1th = NULL;
779   GNUNET_TRANSPORT_disconnect (ctx->d2th);
780   ctx->d2th = NULL;
781   GNUNET_CORE_disconnect (ctx->d1core);
782   ctx->d1core = NULL;
783   GNUNET_free_non_null (ctx->hello);
784   GNUNET_free (ctx);
785 }
786
787
788 /**
789  * Success, connection is up.  Signal client our success.
790  *
791  * @param cls our "struct ConnectContext"
792  * @param size number of bytes available in buf
793  * @param buf where to copy the message, NULL on error
794  * @return number of bytes copied to buf
795  */
796 static void
797 connect_notify (void *cls, const struct GNUNET_PeerIdentity * peer, struct GNUNET_TIME_Relative latency,
798                 uint32_t distance)
799 {
800   struct ConnectContext *ctx = cls;
801
802 #if DEBUG_TESTING
803   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
804               "Core notified us about connection to a peer\n");
805 #endif
806   if (memcmp(&ctx->d2->id, peer, sizeof(struct GNUNET_PeerIdentity)) == 0)
807     {
808 #if DEBUG_TESTING
809   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
810               "Core notified us about connection to peer %s\n", GNUNET_i2s(peer));
811 #endif
812       /*
813        * If we disconnect here, then the hello may never get sent (if it was delayed!)
814        * However I'm sure there was a reason it was here... so I'm just commenting.
815        */
816       ctx->connected = GNUNET_YES;
817       GNUNET_SCHEDULER_add_now (ctx->d1->sched,
818                                 &notify_connect_result,
819                                 ctx);
820     }
821
822 }
823
824 static void
825 send_hello(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
826 {
827   struct ConnectContext *ctx = cls;
828
829   if (ctx->hello != NULL)
830     {
831       GNUNET_TRANSPORT_offer_hello (ctx->d2th, ctx->hello);
832       ctx->timeout_hello = GNUNET_TIME_relative_add(ctx->timeout_hello,
833                                                     GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 
834                                                                                   200));
835     }
836   ctx->hello_send_task = GNUNET_SCHEDULER_add_delayed(ctx->d1->sched, 
837                                                       ctx->timeout_hello, 
838                                                       &send_hello, ctx);
839 }
840
841
842 #if HIDDEN
843 /*
844  * Accessor function since we have hidden what GNUNET_TESTING_Daemon is
845  *
846  * FIXME: Either expose members or figure out a better way!
847  */
848 char *
849 GNUNET_TESTING_daemon_get_shortname (struct GNUNET_TESTING_Daemon *d)
850 {
851   return d->shortname;
852 }
853
854 char *
855 GNUNET_TESTING_daemon_get_hostname (struct GNUNET_TESTING_Daemon *d)
856 {
857   return d->hostname;
858 }
859
860 char *
861 GNUNET_TESTING_daemon_get_username (struct GNUNET_TESTING_Daemon *d)
862 {
863   return d->username;
864 }
865
866 struct GNUNET_PeerIdentity *
867 GNUNET_TESTING_daemon_get_peer (struct GNUNET_TESTING_Daemon *d)
868 {
869   return &d->id;
870 }
871
872 struct GNUNET_CONFIGURATION_Handle *
873 GNUNET_TESTING_daemon_get_config (struct GNUNET_TESTING_Daemon *d)
874 {
875   return d->cfg;
876 }
877 #endif
878
879
880 /**
881  * Establish a connection between two GNUnet daemons.
882  *
883  * @param d1 handle for the first daemon
884  * @param d2 handle for the second daemon
885  * @param timeout how long is the connection attempt
886  *        allowed to take?
887  * @param cb function to call at the end
888  * @param cb_cls closure for cb
889  */
890 void
891 GNUNET_TESTING_daemons_connect (struct GNUNET_TESTING_Daemon *d1,
892                                 struct GNUNET_TESTING_Daemon *d2,
893                                 struct GNUNET_TIME_Relative timeout,
894                                 GNUNET_TESTING_NotifyConnection cb,
895                                 void *cb_cls)
896 {
897   struct ConnectContext *ctx;
898   static struct GNUNET_CORE_MessageHandler no_handlers[] = { {NULL, 0, 0} };
899
900   if ((d1->server == NULL) || (d2->server == NULL))
901     {
902       if (NULL != cb)
903         cb (cb_cls, &d1->id, &d2->id, d1->cfg, d2->cfg, d1, d2,
904             _("Peers are not fully running yet, can not connect!\n"));
905       return;
906     }
907   ctx = GNUNET_malloc (sizeof (struct ConnectContext));
908   ctx->d1 = d1;
909   ctx->d2 = d2;
910   ctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
911   ctx->cb = cb;
912   ctx->cb_cls = cb_cls;
913   ctx->timeout_hello = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 400);
914   ctx->connected = GNUNET_NO;
915 #if DEBUG_TESTING
916   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
917               "Asked to connect peer %s to peer %s\n",
918               d1->shortname, d2->shortname);
919   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
920               "Connecting to transport service of peer %s\n", d1->shortname);
921 #endif
922
923   ctx->d1core = GNUNET_CORE_connect (d1->sched,
924                                      d1->cfg,
925                                      timeout,
926                                      ctx,
927                                      NULL,
928                                      NULL, &connect_notify, NULL,
929                                      NULL, GNUNET_NO,
930                                      NULL, GNUNET_NO, no_handlers);
931   if (ctx->d1core == NULL)
932     {
933       GNUNET_free (ctx);
934       if (NULL != cb)
935         cb (cb_cls, &d1->id, &d2->id, d1->cfg, d2->cfg, d1, d2,
936             _("Failed to connect to core service of first peer!\n"));
937       return;
938     }
939
940   ctx->d1th = GNUNET_TRANSPORT_connect (d1->sched,
941                                         d1->cfg, d1, NULL, NULL, NULL);
942   if (ctx->d1th == NULL)
943     {
944       GNUNET_free (ctx);
945       if (NULL != cb)
946         cb (cb_cls, &d1->id, &d2->id, d1->cfg, d2->cfg, d1, d2,
947             _("Failed to connect to transport service!\n"));
948       return;
949     }
950 #if DEBUG_TESTING
951   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
952               "Asked to connect peer %s to peer %s\n",
953               d1->shortname, d2->shortname);
954   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
955               "Connecting to transport service of peer %s\n", d2->shortname);
956
957 #endif
958
959   ctx->d2th = GNUNET_TRANSPORT_connect (d2->sched,
960                                         d2->cfg, d2, NULL, NULL, NULL);
961   if (ctx->d2th == NULL)
962     {
963       GNUNET_TRANSPORT_disconnect (ctx->d1th);
964       GNUNET_free (ctx);
965       if (NULL != cb)
966         cb (cb_cls, &d1->id, &d2->id, d1->cfg, d2->cfg, d1, d2,
967             _("Failed to connect to transport service!\n"));
968       return;
969     }
970
971 #if DEBUG_TESTING
972   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
973               "Asking for HELLO from peer %s\n", GNUNET_i2s (&d1->id));
974 #endif
975
976   ctx->timeout_task = GNUNET_SCHEDULER_add_delayed (d1->sched,
977                                                     timeout,
978                                                     &notify_connect_result, ctx);
979
980   GNUNET_TRANSPORT_get_hello (ctx->d1th, &process_hello, ctx);
981   ctx->hello_send_task = GNUNET_SCHEDULER_add_delayed(ctx->d1->sched, ctx->timeout_hello,
982                                                       &send_hello, ctx);
983 }
984
985
986 /* end of testing.c */