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