- disable unix
[oweals/gnunet.git] / src / dht / test_dht_twopeer_put_get.c
1 /*
2      This file is part of GNUnet.
3      (C) 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  * @file dht/test_dht_twopeer_put_get.c
22  * @brief base testcase for testing DHT service with
23  *        two running peers.
24  *
25  * This testcase starts peers using the GNUNET_TESTING_daemons_start
26  * function call.  On peer start, connects to the peers DHT service
27  * by calling GNUNET_DHT_connected.  Once notified about all peers
28  * being started (by the peers_started_callback function), calls
29  * GNUNET_TESTING_connect_topology, which connects the peers in a
30  * "straight line" topology.  On notification that all peers have
31  * been properly connected, runs the do_put function to insert data
32  * at the first peer.  Once the GNUNET_DHT_put function completes,
33  * calls the do_get function which initiates a GNUNET_DHT_get from
34  * the *second* peer.  If the GET is successful, schedules finish_testing
35  * to stop the test and shut down peers.  If GET is unsuccessful
36  * after GET_TIMEOUT seconds, prints an error message and shuts down
37  * the peers.
38  */
39 #include "platform.h"
40 #include "gnunet_testing_lib.h"
41 #include "gnunet_core_service.h"
42 #include "gnunet_dht_service.h"
43 #include "block_dns.h"
44 #include "gnunet_signatures.h"
45
46 /* DEFINES */
47 #define VERBOSE GNUNET_NO
48
49 /* Timeout for entire testcase */
50 #define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
51
52 /* Timeout for waiting for replies to get requests */
53 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
54
55 /* If number of peers not in config file, use this number */
56 #define DEFAULT_NUM_PEERS 2
57
58 /* Globals */
59
60 /**
61  * Directory to store temp data in, defined in config file
62  */
63 static char *test_directory;
64
65 /**
66  * Variable used to store the number of connections we should wait for.
67  */
68 static unsigned int expected_connections;
69
70 /**
71  * Variable used to keep track of how many peers aren't yet started.
72  */
73 static unsigned long long peers_left;
74
75 /**
76  * Handle to the set of all peers run for this test.
77  */
78 static struct GNUNET_TESTING_PeerGroup *pg;
79
80 /**
81  * Global handle we will use for GET requests.
82  */
83 struct GNUNET_DHT_GetHandle *global_get_handle;
84
85
86 /**
87  * Total number of peers to run, set based on config file.
88  */
89 static unsigned long long num_peers;
90
91 /**
92  * Global used to count how many connections we have currently
93  * been notified about (how many times has topology_callback been called
94  * with success?)
95  */
96 static unsigned int total_connections;
97
98 /**
99  * Global used to count how many failed connections we have
100  * been notified about (how many times has topology_callback
101  * been called with failure?)
102  */
103 static unsigned int failed_connections;
104
105 /* Task handle to use to schedule test failure */
106 static GNUNET_SCHEDULER_TaskIdentifier die_task;
107
108 /* Global return value (0 for success, anything else for failure) */
109 static int ok;
110
111 /**
112  * Peer identity of the first peer started.
113  */
114 static struct GNUNET_PeerIdentity peer1id;
115
116 /**
117  * Peer identity of the second peer started.
118  */
119 static struct GNUNET_PeerIdentity peer2id;
120
121 /**
122  * Handle to the first peers DHT service (via the API)
123  */
124 static struct GNUNET_DHT_Handle *peer1dht;
125
126 /**
127  * Handle to the second peers DHT service (via the API)
128  */
129 static struct GNUNET_DHT_Handle *peer2dht;
130
131 /**
132  * Handle for our PUT operation.
133  */
134 static struct GNUNET_DHT_PutHandle *put_op;
135
136
137 /**
138  * Check whether peers successfully shut down.
139  */
140 static void
141 shutdown_callback (void *cls, const char *emsg)
142 {
143   if (emsg != NULL)
144   {
145     if (ok == 0)
146       ok = 2;
147   }
148 }
149
150 /**
151  * Function scheduled to be run on the successful completion of this
152  * testcase.  Specifically, called when our get request completes.
153  */
154 static void
155 finish_testing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
156 {
157   GNUNET_assert (pg != NULL);
158   GNUNET_assert (peer1dht != NULL);
159   GNUNET_assert (peer2dht != NULL);
160   GNUNET_DHT_disconnect (peer1dht);
161   GNUNET_DHT_disconnect (peer2dht);
162   GNUNET_TESTING_daemons_stop (pg, TIMEOUT, &shutdown_callback, NULL);
163   ok = 0;
164 }
165
166 /**
167  * Continuation for the GNUNET_DHT_get_stop call, so that we don't shut
168  * down the peers without freeing memory associated with GET request.
169  */
170 static void
171 end_badly_cont (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
172 {
173   if (NULL != put_op)
174   {
175     GNUNET_DHT_put_cancel (put_op);
176     put_op = NULL;
177   }
178   if (peer1dht != NULL)
179     GNUNET_DHT_disconnect (peer1dht);
180
181   if (peer2dht != NULL)
182     GNUNET_DHT_disconnect (peer2dht);
183
184   if (pg != NULL)
185     GNUNET_TESTING_daemons_stop (pg, TIMEOUT, &shutdown_callback, NULL);
186 }
187
188
189 /**
190  * Check if the get_handle is being used, if so stop the request.  Either
191  * way, schedule the end_badly_cont function which actually shuts down the
192  * test.
193  */
194 static void
195 end_badly (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
196 {
197   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failing test with error: `%s'!\n",
198               (char *) cls);
199   if (global_get_handle != NULL)
200   {
201     GNUNET_DHT_get_stop (global_get_handle);
202     global_get_handle = NULL;
203   }
204   GNUNET_SCHEDULER_add_now (&end_badly_cont, NULL);
205   ok = 1;
206 }
207
208 /**
209  * Iterator called if the GET request initiated returns a response.
210  *
211  * @param cls closure
212  * @param exp when will this value expire
213  * @param key key of the result
214  * @param type type of the result
215  * @param size number of bytes in data
216  * @param data pointer to the result data
217  */
218 static void
219 get_result_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
220                      const GNUNET_HashCode * key,
221                      const struct GNUNET_PeerIdentity *get_path,
222                      unsigned int get_path_size,
223                      const struct GNUNET_PeerIdentity *put_path,
224                      unsigned int put_path_size, enum GNUNET_BLOCK_Type type,
225                      size_t size, const void *result_data)
226 {
227   GNUNET_HashCode original_key; /* Key data was stored data under */
228   char original_data[4];        /* Made up data that was stored */
229
230   memset (&original_key, 42, sizeof (GNUNET_HashCode)); /* Set the key to what it was set to previously */
231   memset (original_data, 43, sizeof (original_data));
232
233   if ((sizeof (original_data) != size) ||
234       (0 != memcmp (&original_key, key, sizeof (GNUNET_HashCode))) ||
235       (0 != memcmp (original_data, result_data, sizeof (original_data))))
236   {
237     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
238                 "Key or data is not the same as was inserted!\n");
239     GNUNET_SCHEDULER_cancel (die_task);
240     GNUNET_SCHEDULER_add_now (&end_badly,
241                               "key or data mismatch in get response!\n");
242     return;
243   }
244
245   GNUNET_SCHEDULER_cancel (die_task);
246   GNUNET_DHT_get_stop (global_get_handle);
247   global_get_handle = NULL;
248   GNUNET_SCHEDULER_add_now (&finish_testing, NULL);
249 }
250
251
252 /**
253  * Called when the PUT request has been transmitted to the DHT service.
254  * Schedule the GET request for some time in the future.
255  */
256 static void
257 put_finished (void *cls, int success)
258 {
259   GNUNET_HashCode key;          /* Key for data lookup */
260
261   put_op = NULL;
262   GNUNET_SCHEDULER_cancel (die_task);
263   die_task =
264       GNUNET_SCHEDULER_add_delayed (GET_TIMEOUT, &end_badly,
265                                     "waiting for get response (data not found)");
266
267   memset (&key, 42, sizeof (GNUNET_HashCode));  /* Set the key to the same thing as when data was inserted */
268   global_get_handle =
269       GNUNET_DHT_get_start (peer2dht, GNUNET_TIME_UNIT_FOREVER_REL,
270                             GNUNET_BLOCK_TYPE_TEST, &key, 1, GNUNET_DHT_RO_NONE,
271                             NULL, 0, &get_result_iterator, NULL);
272 }
273
274
275 /**
276  * Set up some data, and call API PUT function
277  */
278 static void
279 do_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
280 {
281   GNUNET_HashCode key;          /* Made up key to store data under */
282   char data[4];                 /* Made up data to store */
283
284   memset (&key, 42, sizeof (GNUNET_HashCode));  /* Set the key to something simple so we can issue GET request */
285   memset (data, 43, sizeof (data));
286
287   /* Insert the data at the first peer */
288   put_op = GNUNET_DHT_put (peer1dht, &key, 1, GNUNET_DHT_RO_NONE, GNUNET_BLOCK_TYPE_TEST,
289                            sizeof (data), data, GNUNET_TIME_UNIT_FOREVER_ABS,
290                            GNUNET_TIME_UNIT_FOREVER_REL, &put_finished, NULL);
291 }
292
293
294 /**
295  * This function is called whenever a connection attempt is finished between two of
296  * the started peers (started with GNUNET_TESTING_daemons_start).  The total
297  * number of times this function is called should equal the number returned
298  * from the GNUNET_TESTING_connect_topology call.
299  *
300  * The emsg variable is NULL on success (peers connected), and non-NULL on
301  * failure (peers failed to connect).
302  */
303 static void
304 topology_callback (void *cls, const struct GNUNET_PeerIdentity *first,
305                    const struct GNUNET_PeerIdentity *second, uint32_t distance,
306                    const struct GNUNET_CONFIGURATION_Handle *first_cfg,
307                    const struct GNUNET_CONFIGURATION_Handle *second_cfg,
308                    struct GNUNET_TESTING_Daemon *first_daemon,
309                    struct GNUNET_TESTING_Daemon *second_daemon,
310                    const char *emsg)
311 {
312   if (emsg == NULL)
313   {
314     total_connections++;
315 #if VERBOSE
316     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
317                 "connected peer %s to peer %s, distance %u\n",
318                 first_daemon->shortname, second_daemon->shortname, distance);
319 #endif
320   }
321 #if VERBOSE
322   else
323   {
324     failed_connections++;
325     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
326                 "Failed to connect peer %s to peer %s with error :\n%s\n",
327                 first_daemon->shortname, second_daemon->shortname, emsg);
328   }
329 #endif
330
331   if (total_connections == expected_connections)
332   {
333 #if VERBOSE
334     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
335                 "Created %d total connections, which is our target number!  Starting next phase of testing.\n",
336                 total_connections);
337 #endif
338     GNUNET_SCHEDULER_cancel (die_task);
339     die_task =
340         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly, "from test gets");
341
342     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &do_put, NULL);
343   }
344   else if (total_connections + failed_connections == expected_connections)
345   {
346     GNUNET_SCHEDULER_cancel (die_task);
347     die_task =
348         GNUNET_SCHEDULER_add_now (&end_badly,
349                                   "from topology_callback (too many failed connections)");
350   }
351 }
352
353
354 /**
355  * Callback which is called whenever a peer is started (as a result of the
356  * GNUNET_TESTING_daemons_start call.
357  *
358  * @param cls closure argument given to GNUNET_TESTING_daemons_start
359  * @param id the GNUNET_PeerIdentity of the started peer
360  * @param cfg the configuration for this specific peer (needed to connect
361  *            to the DHT)
362  * @param d the handle to the daemon started
363  * @param emsg NULL if peer started, non-NULL on error
364  */
365 static void
366 peers_started_callback (void *cls, const struct GNUNET_PeerIdentity *id,
367                         const struct GNUNET_CONFIGURATION_Handle *cfg,
368                         struct GNUNET_TESTING_Daemon *d, const char *emsg)
369 {
370   if (emsg != NULL)
371   {
372     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
373                 "Failed to start daemon with error: `%s'\n", emsg);
374     return;
375   }
376   GNUNET_assert (id != NULL);
377
378   /* This is the first peer started */
379   if (peers_left == num_peers)
380   {
381     memcpy (&peer1id, id, sizeof (struct GNUNET_PeerIdentity)); /* Save the peer id */
382     peer1dht = GNUNET_DHT_connect (cfg, 100);   /* Connect to the first peers DHT service */
383     if (peer1dht == NULL)       /* If DHT connect failed */
384     {
385       GNUNET_SCHEDULER_cancel (die_task);
386       GNUNET_SCHEDULER_add_now (&end_badly, "Failed to get dht handle!\n");
387     }
388   }
389   else                          /* This is the second peer started */
390   {
391     memcpy (&peer2id, id, sizeof (struct GNUNET_PeerIdentity)); /* Same as for first peer... */
392     peer2dht = GNUNET_DHT_connect (cfg, 100);
393     if (peer2dht == NULL)
394     {
395       GNUNET_SCHEDULER_cancel (die_task);
396       GNUNET_SCHEDULER_add_now (&end_badly, "Failed to get dht handle!\n");
397     }
398   }
399
400   /* Decrement number of peers left to start */
401   peers_left--;
402
403   if (peers_left == 0)          /* Indicates all peers started */
404   {
405 #if VERBOSE
406     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
407                 "All %d daemons started, now connecting peers!\n", num_peers);
408 #endif
409     expected_connections = -1;
410     if ((pg != NULL))           /* Sanity check */
411     {
412       /* Connect peers in a "straight line" topology, return the number of expected connections */
413       expected_connections =
414           GNUNET_TESTING_connect_topology (pg, GNUNET_TESTING_TOPOLOGY_LINE,
415                                            GNUNET_TESTING_TOPOLOGY_OPTION_ALL,
416                                            0.0, TIMEOUT, 12, NULL, NULL);
417     }
418
419     /* Cancel current timeout fail task */
420     GNUNET_SCHEDULER_cancel (die_task);
421     if (expected_connections == GNUNET_SYSERR)  /* Some error happened */
422       die_task =
423           GNUNET_SCHEDULER_add_now (&end_badly,
424                                     "from connect topology (bad return)");
425
426     /* Schedule timeout on failure task */
427     die_task =
428         GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly,
429                                       "from connect topology (timeout)");
430     ok = 0;
431   }
432 }
433
434 static void
435 run (void *cls, char *const *args, const char *cfgfile,
436      const struct GNUNET_CONFIGURATION_Handle *cfg)
437 {
438
439   /* Get path from configuration file */
440   if (GNUNET_YES !=
441       GNUNET_CONFIGURATION_get_value_string (cfg, "paths", "servicehome",
442                                              &test_directory))
443   {
444     ok = 404;
445     return;
446   }
447
448   /* Get number of peers to start from configuration (should be two) */
449   if (GNUNET_SYSERR ==
450       GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "num_peers",
451                                              &num_peers))
452     num_peers = DEFAULT_NUM_PEERS;
453
454   /* Set peers_left so we know when all peers started */
455   peers_left = num_peers;
456
457   /* Set up a task to end testing if peer start fails */
458   die_task =
459       GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly,
460                                     "didn't start all daemons in reasonable amount of time!!!");
461
462   /* Start num_peers peers, call peers_started_callback on peer start, topology_callback on peer connect */
463   /* Read the API documentation for other parameters! */
464   pg = GNUNET_TESTING_daemons_start (cfg, num_peers, 2, 2, TIMEOUT, NULL, NULL,
465                                      &peers_started_callback, NULL,
466                                      &topology_callback, NULL, NULL);
467
468 }
469
470 static int
471 check ()
472 {
473   int ret;
474
475   /* Arguments for GNUNET_PROGRAM_run */
476   char *const argv[] = { "test-dht-twopeer-put-get",    /* Name to give running binary */
477     "-c",
478     "test_dht_twopeer_data.conf",       /* Config file to use */
479 #if VERBOSE
480     "-L", "DEBUG",
481 #endif
482     NULL
483   };
484   struct GNUNET_GETOPT_CommandLineOption options[] = {
485     GNUNET_GETOPT_OPTION_END
486   };
487   /* Run the run function as a new program */
488   ret =
489       GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, argv,
490                           "test-dht-twopeer-put-get", "nohelp", options, &run,
491                           &ok);
492   if (ret != GNUNET_OK)
493   {
494     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
495                 "`test-dht-twopeer': Failed with error code %d\n", ret);
496   }
497   return ok;
498 }
499
500 int
501 main (int argc, char *argv[])
502 {
503   int ret;
504
505   GNUNET_log_setup ("test-dht-twopeer",
506 #if VERBOSE
507                     "DEBUG",
508 #else
509                     "WARNING",
510 #endif
511                     NULL);
512   ret = check ();
513   /**
514    * Need to remove base directory, subdirectories taken care
515    * of by the testing framework.
516    */
517   if (GNUNET_DISK_directory_remove (test_directory) != GNUNET_OK)
518   {
519     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
520                 "Failed to remove testing directory %s\n", test_directory);
521   }
522   return ret;
523 }
524
525 /* end of test_dht_twopeer_put_get.c */