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