core request connect in addition to hello, minor driver stuff
[oweals/gnunet.git] / src / dht / gnunet-dht-driver.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/gnunet-dht-driver.c
22  * @brief Driver for setting up a group of gnunet peers and
23  *        then issuing GETS and PUTS on the DHT.  Coarse results
24  *        are reported, fine grained results (if requested) are
25  *        logged to a (mysql) database, or to file.
26  *
27  * FIXME: Do churn!
28  */
29 #include "platform.h"
30 #include "gnunet_testing_lib.h"
31 #include "gnunet_core_service.h"
32 #include "gnunet_dht_service.h"
33 #include "dhtlog.h"
34 #include "dht.h"
35
36 /* DEFINES */
37 #define VERBOSE GNUNET_NO
38
39 /* Timeout for entire driver to run */
40 #define DEFAULT_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
41
42 /* Timeout for waiting for (individual) replies to get requests */
43 #define DEFAULT_GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
44
45 #define DEFAULT_TOPOLOGY_CAPTURE_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
46
47 /* Timeout for waiting for gets to be sent to the service */
48 #define DEFAULT_GET_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10)
49
50 /* Timeout for waiting for puts to be sent to the service */
51 #define DEFAULT_PUT_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10)
52
53 /* Time to allow a find peer request to take */
54 #define DEFAULT_FIND_PEER_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 40)
55
56 #define DEFAULT_SECONDS_PER_PEER_START GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 45)
57
58 #define DEFAULT_TEST_DATA_SIZE 8
59
60 #define DEFAULT_BUCKET_SIZE 4
61
62 #define FIND_PEER_THRESHOLD DEFAULT_BUCKET_SIZE * 2
63
64 /* If more than this many peers are added, slow down sending */
65 #define MAX_FIND_PEER_CUTOFF 2500
66
67 /* If less than this many peers are added, speed up sending */
68 #define MIN_FIND_PEER_CUTOFF 500
69
70 #define DEFAULT_MAX_OUTSTANDING_PUTS 10
71
72 #define DEFAULT_MAX_OUTSTANDING_FIND_PEERS 64
73
74 #define DEFAULT_FIND_PEER_OFFSET GNUNET_TIME_relative_divide (DEFAULT_FIND_PEER_DELAY, DEFAULT_MAX_OUTSTANDING_FIND_PEERS)
75
76 #define DEFAULT_MAX_OUTSTANDING_GETS 10
77
78 #define DEFAULT_CONNECT_TIMEOUT 60
79
80 #define DEFAULT_TOPOLOGY_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
81
82 /*
83  * Default frequency for sending malicious get messages
84  */
85 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
86
87 /*
88  * Default frequency for sending malicious put messages
89  */
90 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
91
92 /* Structs */
93
94 struct MaliciousContext
95 {
96   /**
97    * Handle to DHT service (via the API)
98    */
99   struct GNUNET_DHT_Handle *dht_handle;
100
101   /**
102    *  Handle to the peer daemon
103    */
104   struct GNUNET_TESTING_Daemon *daemon;
105
106   /**
107    * Task for disconnecting DHT handles
108    */
109   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
110
111   /**
112    * What type of malicious to set this peer to.
113    */
114   int malicious_type;
115 };
116
117 struct TestFindPeer
118 {
119   /* This is a linked list */
120   struct TestFindPeer *next;
121
122   /* Handle to the bigger context */
123   struct FindPeerContext *find_peer_context;
124
125   /**
126    * Handle to the peer's DHT service (via the API)
127    */
128   struct GNUNET_DHT_Handle *dht_handle;
129
130   /**
131    *  Handle to the peer daemon
132    */
133   struct GNUNET_TESTING_Daemon *daemon;
134
135   /**
136    * Task for disconnecting DHT handles
137    */
138   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
139 };
140
141 struct TestPutContext
142 {
143   /* This is a linked list */
144   struct TestPutContext *next;
145
146   /**
147    * Handle to the first peers DHT service (via the API)
148    */
149   struct GNUNET_DHT_Handle *dht_handle;
150
151   /**
152    *  Handle to the PUT peer daemon
153    */
154   struct GNUNET_TESTING_Daemon *daemon;
155
156   /**
157    *  Identifier for this PUT
158    */
159   uint32_t uid;
160
161   /**
162    * Task for disconnecting DHT handles
163    */
164   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
165 };
166
167 struct TestGetContext
168 {
169   /* This is a linked list */
170   struct TestGetContext *next;
171
172   /**
173    * Handle to the first peers DHT service (via the API)
174    */
175   struct GNUNET_DHT_Handle *dht_handle;
176
177   /**
178    * Handle for the DHT get request
179    */
180   struct GNUNET_DHT_GetHandle *get_handle;
181
182   /**
183    *  Handle to the GET peer daemon
184    */
185   struct GNUNET_TESTING_Daemon *daemon;
186
187   /**
188    *  Identifier for this GET
189    */
190   uint32_t uid;
191
192   /**
193    * Task for disconnecting DHT handles (and stopping GET)
194    */
195   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
196
197   /**
198    * Whether or not this request has been fulfilled already.
199    */
200   int succeeded;
201 };
202
203 /**
204  * Simple struct to keep track of progress, and print a
205  * nice little percentage meter for long running tasks.
206  */
207 struct ProgressMeter
208 {
209   unsigned int total;
210
211   unsigned int modnum;
212
213   unsigned int dotnum;
214
215   unsigned int completed;
216
217   int print;
218
219   char *startup_string;
220 };
221
222 /**
223  * Linked list of information for populating statistics
224  * before ending trial.
225  */
226 struct StatisticsIteratorContext
227 {
228   const struct GNUNET_PeerIdentity *peer;
229   unsigned int stat_routes;
230   unsigned int stat_route_forwards;
231   unsigned int stat_results;
232   unsigned int stat_results_to_client;
233   unsigned int stat_result_forwards;
234   unsigned int stat_gets;
235   unsigned int stat_puts;
236   unsigned int stat_puts_inserted;
237   unsigned int stat_find_peer;
238   unsigned int stat_find_peer_start;
239   unsigned int stat_get_start;
240   unsigned int stat_put_start;
241   unsigned int stat_find_peer_reply;
242   unsigned int stat_get_reply;
243   unsigned int stat_find_peer_answer;
244   unsigned int stat_get_response_start;
245 };
246
247 /**
248  * Context for getting a topology, logging it, and continuing
249  * on with some next operation.
250  */
251 struct TopologyIteratorContext
252 {
253   unsigned int total_iterations;
254   unsigned int current_iteration;
255   unsigned int total_connections;
256   struct GNUNET_PeerIdentity *peer;
257   GNUNET_SCHEDULER_Task cont;
258   void *cls;
259   struct GNUNET_TIME_Relative timeout;
260 };
261
262 /* Globals */
263
264 /**
265  * Timeout to let all get requests happen.
266  */
267 static struct GNUNET_TIME_Relative all_get_timeout;
268
269 /**
270  * Per get timeout
271  */
272 static struct GNUNET_TIME_Relative get_timeout;
273
274 static struct GNUNET_TIME_Relative get_delay;
275
276 static struct GNUNET_TIME_Relative put_delay;
277
278 static struct GNUNET_TIME_Relative find_peer_delay;
279
280 static struct GNUNET_TIME_Relative find_peer_offset;
281
282 static struct GNUNET_TIME_Relative seconds_per_peer_start;
283
284 static int do_find_peer;
285
286 static unsigned long long test_data_size = DEFAULT_TEST_DATA_SIZE;
287
288 static unsigned long long max_outstanding_puts = DEFAULT_MAX_OUTSTANDING_PUTS;
289
290 static unsigned long long max_outstanding_gets = DEFAULT_MAX_OUTSTANDING_GETS;
291
292 static unsigned long long malicious_getters;
293
294 static unsigned long long max_outstanding_find_peers;
295
296 static unsigned long long malicious_putters;
297
298 static unsigned long long malicious_droppers;
299
300 static unsigned long long malicious_get_frequency;
301
302 static unsigned long long malicious_put_frequency;
303
304 static unsigned long long settle_time;
305
306 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
307
308 static unsigned long long trialuid;
309
310 /**
311  * Hash map of stats contexts.
312  */
313 struct GNUNET_CONTAINER_MultiHashMap *stats_map;
314
315 /**
316  * LL of malicious settings.
317  */
318 struct MaliciousContext *all_malicious;
319
320 /**
321  * List of GETS to perform
322  */
323 struct TestGetContext *all_gets;
324
325 /**
326  * List of PUTS to perform
327  */
328 struct TestPutContext *all_puts;
329
330 /**
331  * Directory to store temporary data in, defined in config file
332  */
333 static char *test_directory;
334
335 /**
336  * Variable used to store the number of connections we should wait for.
337  */
338 static unsigned int expected_connections;
339
340 /**
341  * Variable used to keep track of how many peers aren't yet started.
342  */
343 static unsigned long long peers_left;
344
345 /**
346  * Handle to the set of all peers run for this test.
347  */
348 static struct GNUNET_TESTING_PeerGroup *pg;
349
350 /**
351  * Global scheduler, used for all GNUNET_SCHEDULER_* functions.
352  */
353 static struct GNUNET_SCHEDULER_Handle *sched;
354
355 /**
356  * Global config handle.
357  */
358 const struct GNUNET_CONFIGURATION_Handle *config;
359
360 /**
361  * Total number of peers to run, set based on config file.
362  */
363 static unsigned long long num_peers;
364
365 /**
366  * Total number of items to insert.
367  */
368 static unsigned long long num_puts;
369
370 /**
371  * How many puts do we currently have in flight?
372  */
373 static unsigned long long outstanding_puts;
374
375 /**
376  * How many puts are done?
377  */
378 static unsigned long long puts_completed;
379
380 /**
381  * Total number of items to attempt to get.
382  */
383 static unsigned long long num_gets;
384
385 /**
386  * How many puts do we currently have in flight?
387  */
388 static unsigned long long outstanding_gets;
389
390 /**
391  * How many gets are done?
392  */
393 static unsigned long long gets_completed;
394
395 /**
396  * How many gets failed?
397  */
398 static unsigned long long gets_failed;
399
400 /**
401  * How many malicious control messages do
402  * we currently have in flight?
403  */
404 static unsigned long long outstanding_malicious;
405
406 /**
407  * How many set malicious peers are done?
408  */
409 static unsigned long long malicious_completed;
410
411 /**
412  * Global used to count how many connections we have currently
413  * been notified about (how many times has topology_callback been called
414  * with success?)
415  */
416 static unsigned int total_connections;
417
418 /**
419  * Global used to count how many failed connections we have
420  * been notified about (how many times has topology_callback
421  * been called with failure?)
422  */
423 static unsigned int failed_connections;
424
425 /* Task handle to use to schedule shutdown if something goes wrong */
426 GNUNET_SCHEDULER_TaskIdentifier die_task;
427
428 static char *blacklist_transports;
429
430 static enum GNUNET_TESTING_Topology topology;
431
432 static enum GNUNET_TESTING_Topology blacklist_topology = GNUNET_TESTING_TOPOLOGY_NONE; /* Don't do any blacklisting */
433
434 static enum GNUNET_TESTING_Topology connect_topology = GNUNET_TESTING_TOPOLOGY_NONE; /* NONE actually means connect all allowed peers */
435
436 static enum GNUNET_TESTING_TopologyOption connect_topology_option = GNUNET_TESTING_TOPOLOGY_OPTION_ALL;
437
438 static double connect_topology_option_modifier = 0.0;
439
440 static struct ProgressMeter *hostkey_meter;
441
442 static struct ProgressMeter *peer_start_meter;
443
444 static struct ProgressMeter *peer_connect_meter;
445
446 static struct ProgressMeter *put_meter;
447
448 static struct ProgressMeter *get_meter;
449
450 /* Global return value (0 for success, anything else for failure) */
451 static int ok;
452
453 /**
454  * Create a meter to keep track of the progress of some task.
455  *
456  * @param total the total number of items to complete
457  * @param start_string a string to prefix the meter with (if printing)
458  * @param print GNUNET_YES to print the meter, GNUNET_NO to count
459  *              internally only
460  *
461  * @return the progress meter
462  */
463 static struct ProgressMeter *
464 create_meter(unsigned int total, char * start_string, int print)
465 {
466   struct ProgressMeter *ret;
467   ret = GNUNET_malloc(sizeof(struct ProgressMeter));
468   ret->print = print;
469   ret->total = total;
470   ret->modnum = total / 4;
471   ret->dotnum = (total / 50) + 1;
472   if (start_string != NULL)
473     ret->startup_string = GNUNET_strdup(start_string);
474   else
475     ret->startup_string = GNUNET_strdup("");
476
477   return ret;
478 }
479
480 /**
481  * Update progress meter (increment by one).
482  *
483  * @param meter the meter to update and print info for
484  *
485  * @return GNUNET_YES if called the total requested,
486  *         GNUNET_NO if more items expected
487  */
488 static int
489 update_meter(struct ProgressMeter *meter)
490 {
491   if (meter->print == GNUNET_YES)
492     {
493       if (meter->completed % meter->modnum == 0)
494         {
495           if (meter->completed == 0)
496             {
497               fprintf(stdout, "%sProgress: [0%%", meter->startup_string);
498             }
499           else
500             fprintf(stdout, "%d%%", (int)(((float)meter->completed / meter->total) * 100));
501         }
502       else if (meter->completed % meter->dotnum == 0)
503         fprintf(stdout, ".");
504
505       if (meter->completed + 1 == meter->total)
506         fprintf(stdout, "%d%%]\n", 100);
507       fflush(stdout);
508     }
509   meter->completed++;
510
511   if (meter->completed == meter->total)
512     return GNUNET_YES;
513   return GNUNET_NO;
514 }
515
516 /**
517  * Release resources for meter
518  *
519  * @param meter the meter to free
520  */
521 static void
522 free_meter(struct ProgressMeter *meter)
523 {
524   GNUNET_free_non_null(meter->startup_string);
525   GNUNET_free_non_null(meter);
526 }
527
528 /**
529  * Check whether peers successfully shut down.
530  */
531 void shutdown_callback (void *cls,
532                         const char *emsg)
533 {
534   if (emsg != NULL)
535     {
536       if (ok == 0)
537         ok = 2;
538     }
539 }
540
541 /**
542  * Task to release DHT handles for PUT
543  */
544 static void
545 put_disconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
546 {
547   struct TestPutContext *test_put = cls;
548   test_put->disconnect_task = GNUNET_SCHEDULER_NO_TASK;
549   GNUNET_DHT_disconnect(test_put->dht_handle);
550   test_put->dht_handle = NULL;
551 }
552
553 /**
554  * Function scheduled to be run on the successful completion of this
555  * testcase.
556  */
557 static void
558 finish_testing (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
559 {
560   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Ending test normally!\n", (char *)cls);
561   GNUNET_assert (pg != NULL);
562   struct TestPutContext *test_put = all_puts;
563   struct TestGetContext *test_get = all_gets;
564
565   while (test_put != NULL)
566     {
567       if (test_put->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
568         GNUNET_SCHEDULER_cancel(sched, test_put->disconnect_task);
569       if (test_put->dht_handle != NULL)
570         GNUNET_DHT_disconnect(test_put->dht_handle);
571       test_put = test_put->next;
572     }
573
574   while (test_get != NULL)
575     {
576       if (test_get->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
577         GNUNET_SCHEDULER_cancel(sched, test_get->disconnect_task);
578       if (test_get->get_handle != NULL)
579         GNUNET_DHT_get_stop(test_get->get_handle, NULL, NULL);
580       if (test_get->dht_handle != NULL)
581         GNUNET_DHT_disconnect(test_get->dht_handle);
582       test_get = test_get->next;
583     }
584
585   GNUNET_TESTING_daemons_stop (pg, DEFAULT_TIMEOUT, &shutdown_callback, NULL);
586
587   if (dhtlog_handle != NULL)
588     {
589       fprintf(stderr, "Update trial endtime\n");
590       dhtlog_handle->update_trial (trialuid, gets_completed);
591       GNUNET_DHTLOG_disconnect(dhtlog_handle);
592       dhtlog_handle = NULL;
593     }
594
595   if (hostkey_meter != NULL)
596     free_meter(hostkey_meter);
597   if (peer_start_meter != NULL)
598     free_meter(peer_start_meter);
599   if (peer_connect_meter != NULL)
600     free_meter(peer_connect_meter);
601   if (put_meter != NULL)
602     free_meter(put_meter);
603   if (get_meter != NULL)
604     free_meter(get_meter);
605
606   ok = 0;
607 }
608
609 /**
610  * Callback for iterating over all the peer connections of a peer group.
611  */
612 void log_topology_cb (void *cls,
613                       const struct GNUNET_PeerIdentity *first,
614                       const struct GNUNET_PeerIdentity *second,
615                       struct GNUNET_TIME_Relative latency,
616                       uint32_t distance,
617                       const char *emsg)
618 {
619   struct TopologyIteratorContext *topo_ctx = cls;
620   if ((first != NULL) && (second != NULL))
621     {
622       topo_ctx->total_connections++;
623       if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(config, "dht_testing", "mysql_logging_extended"))
624         dhtlog_handle->insert_extended_topology(first, second);
625     }
626   else
627     {
628       GNUNET_assert(dhtlog_handle != NULL);
629       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Topology iteration (%u/%u) finished (%u connections)\n", topo_ctx->current_iteration, topo_ctx->total_iterations, topo_ctx->total_connections);
630       dhtlog_handle->update_topology(topo_ctx->total_connections);
631       if (topo_ctx->cont != NULL)
632         GNUNET_SCHEDULER_add_now (sched, topo_ctx->cont, topo_ctx->cls);
633       GNUNET_free(topo_ctx);
634     }
635 }
636
637 /**
638  * Iterator over hash map entries.
639  *
640  * @param cls closure - always NULL
641  * @param key current key code
642  * @param value value in the hash map, a stats context
643  * @return GNUNET_YES if we should continue to
644  *         iterate,
645  *         GNUNET_NO if not.
646  */
647 static int stats_iterate (void *cls,
648                           const GNUNET_HashCode * key,
649                           void *value)
650 {
651   struct StatisticsIteratorContext *stats_ctx;
652   if (value == NULL)
653     return GNUNET_NO;
654   stats_ctx = value;
655   dhtlog_handle->insert_stat(stats_ctx->peer, stats_ctx->stat_routes, stats_ctx->stat_route_forwards, stats_ctx->stat_results,
656                              stats_ctx->stat_results_to_client, stats_ctx->stat_result_forwards, stats_ctx->stat_gets,
657                              stats_ctx->stat_puts, stats_ctx->stat_puts_inserted, stats_ctx->stat_find_peer,
658                              stats_ctx->stat_find_peer_start, stats_ctx->stat_get_start, stats_ctx->stat_put_start,
659                              stats_ctx->stat_find_peer_reply, stats_ctx->stat_get_reply, stats_ctx->stat_find_peer_answer,
660                              stats_ctx->stat_get_response_start);
661   GNUNET_free(stats_ctx);
662   return GNUNET_YES;
663 }
664
665 static void stats_finished (void *cls, int result)
666 {
667   fprintf(stderr, "Finished getting all peers statistics, iterating!\n");
668   GNUNET_CONTAINER_multihashmap_iterate(stats_map, &stats_iterate, NULL);
669   GNUNET_CONTAINER_multihashmap_destroy(stats_map);
670   GNUNET_SCHEDULER_add_now (sched, &finish_testing, NULL);
671 }
672
673 /**
674  * Callback function to process statistic values.
675  *
676  * @param cls closure
677  * @param peer the peer the statistics belong to
678  * @param subsystem name of subsystem that created the statistic
679  * @param name the name of the datum
680  * @param value the current value
681  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
682  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
683  */
684 static int stats_handle  (void *cls,
685                           const struct GNUNET_PeerIdentity *peer,
686                           const char *subsystem,
687                           const char *name,
688                           uint64_t value,
689                           int is_persistent)
690 {
691   struct StatisticsIteratorContext *stats_ctx;
692
693   if (dhtlog_handle != NULL)
694     dhtlog_handle->add_generic_stat(peer, name, subsystem, value);
695   if (GNUNET_CONTAINER_multihashmap_contains(stats_map, &peer->hashPubKey))
696     {
697       stats_ctx = GNUNET_CONTAINER_multihashmap_get(stats_map, &peer->hashPubKey);
698     }
699   else
700     {
701       stats_ctx = GNUNET_malloc(sizeof(struct StatisticsIteratorContext));
702       stats_ctx->peer = peer;
703       GNUNET_CONTAINER_multihashmap_put(stats_map, &peer->hashPubKey, stats_ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
704     }
705   GNUNET_assert(stats_ctx != NULL);
706
707   if (strcmp(name, STAT_ROUTES) == 0)
708     stats_ctx->stat_routes = value;
709   else if (strcmp(name, STAT_ROUTE_FORWARDS) == 0)
710     stats_ctx->stat_route_forwards = value;
711   else if (strcmp(name, STAT_RESULTS) == 0)
712     stats_ctx->stat_results = value;
713   else if (strcmp(name, STAT_RESULTS_TO_CLIENT) == 0)
714     stats_ctx->stat_results_to_client = value;
715   else if (strcmp(name, STAT_RESULT_FORWARDS) == 0)
716     stats_ctx->stat_result_forwards = value;
717   else if (strcmp(name, STAT_GETS) == 0)
718     stats_ctx->stat_gets = value;
719   else if (strcmp(name, STAT_PUTS) == 0)
720     stats_ctx->stat_puts = value;
721   else if (strcmp(name, STAT_PUTS_INSERTED) == 0)
722     stats_ctx->stat_puts_inserted = value;
723   else if (strcmp(name, STAT_FIND_PEER) == 0)
724     stats_ctx->stat_find_peer = value;
725   else if (strcmp(name, STAT_FIND_PEER_START) == 0)
726     stats_ctx->stat_find_peer_start = value;
727   else if (strcmp(name, STAT_GET_START) == 0)
728     stats_ctx->stat_get_start = value;
729   else if (strcmp(name, STAT_PUT_START) == 0)
730     stats_ctx->stat_put_start = value;
731   else if (strcmp(name, STAT_FIND_PEER_REPLY) == 0)
732     stats_ctx->stat_find_peer_reply = value;
733   else if (strcmp(name, STAT_GET_REPLY) == 0)
734     stats_ctx->stat_get_reply = value;
735   else if (strcmp(name, STAT_FIND_PEER_ANSWER) == 0)
736     stats_ctx->stat_find_peer_answer = value;
737   else if (strcmp(name, STAT_GET_RESPONSE_START) == 0)
738     stats_ctx->stat_get_response_start = value;
739
740   return GNUNET_OK;
741 }
742
743 /**
744  * Connect to statistics service for each peer and get the appropriate
745  * dht statistics for safe keeping.
746  */
747 static void
748 log_dht_statistics (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
749 {
750   stats_map = GNUNET_CONTAINER_multihashmap_create(num_peers);
751   fprintf(stderr, "Starting statistics logging\n");
752   GNUNET_TESTING_get_statistics(pg, &stats_finished, &stats_handle, NULL);
753 }
754
755
756 /**
757  * Connect to all peers in the peer group and iterate over their
758  * connections.
759  */
760 static void
761 capture_current_topology (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
762 {
763   struct TopologyIteratorContext *topo_ctx = cls;
764   dhtlog_handle->insert_topology(0);
765   GNUNET_TESTING_get_topology (pg, &log_topology_cb, topo_ctx);
766 }
767
768
769 /**
770  * Check if the get_handle is being used, if so stop the request.  Either
771  * way, schedule the end_badly_cont function which actually shuts down the
772  * test.
773  */
774 static void
775 end_badly (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
776 {
777   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Failing test with error: `%s'!\n", (char *)cls);
778
779   struct TestPutContext *test_put = all_puts;
780   struct TestGetContext *test_get = all_gets;
781
782   while (test_put != NULL)
783     {
784       if (test_put->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
785         GNUNET_SCHEDULER_cancel(sched, test_put->disconnect_task);
786       if (test_put->dht_handle != NULL)
787         GNUNET_DHT_disconnect(test_put->dht_handle);
788       test_put = test_put->next;
789     }
790
791   while (test_get != NULL)
792     {
793       if (test_get->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
794         GNUNET_SCHEDULER_cancel(sched, test_get->disconnect_task);
795       if (test_get->get_handle != NULL)
796         GNUNET_DHT_get_stop(test_get->get_handle, NULL, NULL);
797       if (test_get->dht_handle != NULL)
798         GNUNET_DHT_disconnect(test_get->dht_handle);
799       test_get = test_get->next;
800     }
801
802   GNUNET_TESTING_daemons_stop (pg, DEFAULT_TIMEOUT, &shutdown_callback, NULL);
803
804   if (dhtlog_handle != NULL)
805     {
806       fprintf(stderr, "Update trial endtime\n");
807       dhtlog_handle->update_trial (trialuid, gets_completed);
808       GNUNET_DHTLOG_disconnect(dhtlog_handle);
809       dhtlog_handle = NULL;
810     }
811
812   if (hostkey_meter != NULL)
813     free_meter(hostkey_meter);
814   if (peer_start_meter != NULL)
815     free_meter(peer_start_meter);
816   if (peer_connect_meter != NULL)
817     free_meter(peer_connect_meter);
818   if (put_meter != NULL)
819     free_meter(put_meter);
820   if (get_meter != NULL)
821     free_meter(get_meter);
822
823   ok = 1;
824 }
825
826 /**
827  * Task to release DHT handle associated with GET request.
828  */
829 static void
830 get_stop_finished (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
831 {
832   struct TestGetContext *test_get = cls;
833   struct TopologyIteratorContext *topo_ctx;
834   outstanding_gets--; /* GET is really finished */
835   GNUNET_DHT_disconnect(test_get->dht_handle);
836   test_get->dht_handle = NULL;
837
838 #if VERBOSE > 1
839   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%d gets succeeded, %d gets failed!\n", gets_completed, gets_failed);
840 #endif
841   update_meter(get_meter);
842   if ((gets_completed + gets_failed == num_gets) && (outstanding_gets == 0))
843     {
844       GNUNET_SCHEDULER_cancel(sched, die_task);
845       //GNUNET_SCHEDULER_add_now(sched, &finish_testing, NULL);
846       if (dhtlog_handle != NULL)
847         {
848           topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
849           topo_ctx->cont = &log_dht_statistics;
850           GNUNET_SCHEDULER_add_now(sched, &capture_current_topology, topo_ctx);
851         }
852       else
853         GNUNET_SCHEDULER_add_now (sched, &finish_testing, NULL);
854     }
855 }
856
857 /**
858  * Task to release get handle.
859  */
860 static void
861 get_stop_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
862 {
863   struct TestGetContext *test_get = cls;
864
865   if (tc->reason == GNUNET_SCHEDULER_REASON_TIMEOUT)
866     gets_failed++;
867   GNUNET_assert(test_get->get_handle != NULL);
868   GNUNET_DHT_get_stop(test_get->get_handle, &get_stop_finished, test_get);
869   test_get->get_handle = NULL;
870   test_get->disconnect_task = GNUNET_SCHEDULER_NO_TASK;
871 }
872
873 /**
874  * Iterator called if the GET request initiated returns a response.
875  *
876  * @param cls closure
877  * @param exp when will this value expire
878  * @param key key of the result
879  * @param type type of the result
880  * @param size number of bytes in data
881  * @param data pointer to the result data
882  */
883 void get_result_iterator (void *cls,
884                           struct GNUNET_TIME_Absolute exp,
885                           const GNUNET_HashCode * key,
886                           uint32_t type,
887                           uint32_t size,
888                           const void *data)
889 {
890   struct TestGetContext *test_get = cls;
891   GNUNET_HashCode search_key; /* Key stored under */
892   char original_data[test_data_size]; /* Made up data to store */
893
894   memset(original_data, test_get->uid, sizeof(original_data));
895   GNUNET_CRYPTO_hash(original_data, test_data_size, &search_key);
896
897   if (test_get->succeeded == GNUNET_YES)
898     return; /* Get has already been successful, probably ending now */
899
900   if ((0 != memcmp(&search_key, key, sizeof (GNUNET_HashCode))) || (0 != memcmp(original_data, data, sizeof(original_data))))
901     {
902       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Key or data is not the same as was inserted!\n");
903     }
904   else
905     {
906       gets_completed++;
907       test_get->succeeded = GNUNET_YES;
908     }
909 #if VERBOSE > 1
910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received correct GET response!\n");
911 #endif
912   GNUNET_SCHEDULER_cancel(sched, test_get->disconnect_task);
913   GNUNET_SCHEDULER_add_continuation(sched, &get_stop_task, test_get, GNUNET_SCHEDULER_REASON_PREREQ_DONE);
914 }
915
916 /**
917  * Continuation telling us GET request was sent.
918  */
919 static void
920 get_continuation (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
921 {
922   // Is there something to be done here?
923   if (tc->reason != GNUNET_SCHEDULER_REASON_PREREQ_DONE)
924     return;
925 }
926
927 /**
928  * Set up some data, and call API PUT function
929  */
930 static void
931 do_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
932 {
933   struct TestGetContext *test_get = cls;
934   GNUNET_HashCode key; /* Made up key to store data under */
935   char data[test_data_size]; /* Made up data to store */
936
937   if (num_gets == 0)
938     {
939       GNUNET_SCHEDULER_cancel(sched, die_task);
940       GNUNET_SCHEDULER_add_now(sched, &finish_testing, NULL);
941     }
942   if (test_get == NULL)
943     return; /* End of the list */
944
945   memset(data, test_get->uid, sizeof(data));
946   GNUNET_CRYPTO_hash(data, test_data_size, &key);
947
948   if (outstanding_gets > max_outstanding_gets)
949     {
950       GNUNET_SCHEDULER_add_delayed (sched, get_delay, &do_get, test_get);
951       return;
952     }
953
954   test_get->dht_handle = GNUNET_DHT_connect(sched, test_get->daemon->cfg, 10);
955   /* Insert the data at the first peer */
956   GNUNET_assert(test_get->dht_handle != NULL);
957   outstanding_gets++;
958   test_get->get_handle = GNUNET_DHT_get_start(test_get->dht_handle,
959                                               GNUNET_TIME_relative_get_forever(),
960                                               1,
961                                               &key,
962                                               &get_result_iterator,
963                                               test_get,
964                                               &get_continuation,
965                                               test_get);
966 #if VERBOSE > 1
967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting get for uid %u from peer %s\n",
968              test_get->uid,
969              test_get->daemon->shortname);
970 #endif
971   test_get->disconnect_task = GNUNET_SCHEDULER_add_delayed(sched, get_timeout, &get_stop_task, test_get);
972   GNUNET_SCHEDULER_add_now (sched, &do_get, test_get->next);
973 }
974
975 /**
976  * Called when the PUT request has been transmitted to the DHT service.
977  * Schedule the GET request for some time in the future.
978  */
979 static void
980 put_finished (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
981 {
982   struct TestPutContext *test_put = cls;
983   struct TopologyIteratorContext *topo_ctx;
984   outstanding_puts--;
985   puts_completed++;
986
987   if (tc->reason == GNUNET_SCHEDULER_REASON_TIMEOUT)
988     fprintf(stderr, "PUT Request failed!\n");
989
990   GNUNET_SCHEDULER_cancel(sched, test_put->disconnect_task);
991   test_put->disconnect_task = GNUNET_SCHEDULER_add_now(sched, &put_disconnect_task, test_put);
992   if (GNUNET_YES == update_meter(put_meter))
993     {
994       GNUNET_assert(outstanding_puts == 0);
995       GNUNET_SCHEDULER_cancel (sched, die_task);
996       if (dhtlog_handle != NULL)
997         {
998           topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
999           topo_ctx->cont = &do_get;
1000           topo_ctx->cls = all_gets;
1001           topo_ctx->timeout = DEFAULT_GET_TIMEOUT;
1002           die_task = GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_add(GNUNET_TIME_relative_add(DEFAULT_GET_TIMEOUT, all_get_timeout), DEFAULT_TOPOLOGY_CAPTURE_TIMEOUT),
1003                                                    &end_badly, "from do gets");
1004           GNUNET_SCHEDULER_add_now(sched, &capture_current_topology, topo_ctx);
1005         }
1006       else
1007         {
1008           die_task = GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_add(DEFAULT_GET_TIMEOUT, all_get_timeout),
1009                                                        &end_badly, "from do gets");
1010           GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_GET_TIMEOUT, &do_get, all_gets);
1011           GNUNET_SCHEDULER_add_now (sched, &finish_testing, NULL);
1012         }
1013       return;
1014     }
1015 }
1016
1017 /**
1018  * Set up some data, and call API PUT function
1019  */
1020 static void
1021 do_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1022 {
1023   struct TestPutContext *test_put = cls;
1024   GNUNET_HashCode key; /* Made up key to store data under */
1025   char data[test_data_size]; /* Made up data to store */
1026   uint32_t rand;
1027
1028   if (test_put == NULL)
1029     return; /* End of list */
1030
1031   memset(data, test_put->uid, sizeof(data));
1032   GNUNET_CRYPTO_hash(data, test_data_size, &key);
1033
1034   if (outstanding_puts > max_outstanding_puts)
1035     {
1036       GNUNET_SCHEDULER_add_delayed (sched, put_delay, &do_put, test_put);
1037       return;
1038     }
1039
1040 #if VERBOSE > 1
1041     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting put for uid %u from peer %s\n",
1042                test_put->uid,
1043                test_put->daemon->shortname);
1044 #endif
1045   test_put->dht_handle = GNUNET_DHT_connect(sched, test_put->daemon->cfg, 10);
1046
1047   GNUNET_assert(test_put->dht_handle != NULL);
1048   outstanding_puts++;
1049   GNUNET_DHT_put(test_put->dht_handle,
1050                  &key,
1051                  1,
1052                  sizeof(data), data,
1053                  GNUNET_TIME_absolute_get_forever(),
1054                  GNUNET_TIME_relative_get_forever(),
1055                  &put_finished, test_put);
1056   test_put->disconnect_task = GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_get_forever(), &put_disconnect_task, test_put);
1057   rand = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 2);
1058   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, rand), &do_put, test_put->next);
1059 }
1060
1061 /**
1062  * Context for sending out find peer requests.
1063  */
1064 struct FindPeerContext
1065 {
1066   /**
1067    * How long to send find peer requests, once the settle time
1068    * is over don't send any more out!
1069    *
1070    * TODO: Add option for settle time and find peer sending time?
1071    */
1072   struct GNUNET_TIME_Absolute endtime;
1073
1074   /**
1075    * Number of connections in the current topology
1076    * (after this round of find peer requests has ended).
1077    */
1078   unsigned int current_peers;
1079
1080   /**
1081    * Number of connections in the current topology
1082    * (before this round of find peer requests started).
1083    */
1084   unsigned int previous_peers;
1085
1086   /**
1087    * Number of find peer requests we have currently
1088    * outstanding.
1089    */
1090   unsigned int outstanding;
1091
1092   /**
1093    * Number of find peer requests to send in this round.
1094    */
1095   unsigned int total;
1096
1097   /**
1098    * Number of find peer requests sent last time around.
1099    */
1100   unsigned int last_sent;
1101
1102   /**
1103    * Hashmap of peers in the current topology, value
1104    * is a PeerCount, with the number of connections
1105    * this peer has.
1106    */
1107   struct GNUNET_CONTAINER_MultiHashMap *peer_hash;
1108
1109   /**
1110    * Min heap which orders values in the peer_hash for
1111    * easy lookup.
1112    */
1113   struct GNUNET_CONTAINER_Heap *peer_min_heap;
1114 };
1115
1116 static void
1117 schedule_find_peer_requests (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc);
1118
1119 /**
1120  * Given a number of total peers and a bucket size, estimate the number of
1121  * connections in a perfect kademlia topology.
1122  */
1123 static unsigned int connection_estimate(unsigned int peer_count, unsigned int bucket_size)
1124 {
1125   unsigned int i;
1126   unsigned int filled;
1127   i = num_peers;
1128
1129   filled = 0;
1130   while (i >= bucket_size)
1131     {
1132       filled++;
1133       i = i/2;
1134     }
1135   filled++; /* Add one filled bucket to account for one "half full" and some miscellaneous */
1136   return filled * bucket_size * peer_count;
1137
1138 }
1139
1140 struct PeerCount
1141 {
1142   /** Node in the heap */
1143   struct GNUNET_CONTAINER_HeapNode *heap_node;
1144
1145   /** Peer the count refers to */
1146   struct GNUNET_PeerIdentity peer_id;
1147
1148   /** Count of connections this peer has */
1149   unsigned int count;
1150 };
1151
1152
1153 /**
1154  * Add a connection to the find_peer_context given.  This may
1155  * be complete overkill, but allows us to choose the peers with
1156  * the least connections to initiate find peer requests from.
1157  */
1158 static void add_new_connection(struct FindPeerContext *find_peer_context,
1159                                const struct GNUNET_PeerIdentity *first,
1160                                const struct GNUNET_PeerIdentity *second)
1161 {
1162   struct PeerCount *first_count;
1163   struct PeerCount *second_count;
1164
1165   if (GNUNET_CONTAINER_multihashmap_contains(find_peer_context->peer_hash, &first->hashPubKey))
1166   {
1167     first_count = GNUNET_CONTAINER_multihashmap_get(find_peer_context->peer_hash, &first->hashPubKey);
1168     first_count->count++;
1169     GNUNET_CONTAINER_heap_update_cost(find_peer_context->peer_min_heap, first_count->heap_node, first_count->count);
1170   }
1171   else
1172   {
1173     first_count = GNUNET_malloc(sizeof(struct PeerCount));
1174     first_count->count = 1;
1175     memcpy(&first_count->peer_id, first, sizeof(struct GNUNET_PeerIdentity));
1176     first_count->heap_node = GNUNET_CONTAINER_heap_insert(find_peer_context->peer_min_heap, first_count, first_count->count);
1177     GNUNET_CONTAINER_multihashmap_put(find_peer_context->peer_hash, &first->hashPubKey, first_count, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1178   }
1179
1180   if (GNUNET_CONTAINER_multihashmap_contains(find_peer_context->peer_hash, &second->hashPubKey))
1181   {
1182     second_count = GNUNET_CONTAINER_multihashmap_get(find_peer_context->peer_hash, &second->hashPubKey);
1183     second_count->count++;
1184     GNUNET_CONTAINER_heap_update_cost(find_peer_context->peer_min_heap, second_count->heap_node, second_count->count);
1185   }
1186   else
1187   {
1188     second_count = GNUNET_malloc(sizeof(struct PeerCount));
1189     second_count->count = 1;
1190     memcpy(&second_count->peer_id, second, sizeof(struct GNUNET_PeerIdentity));
1191     second_count->heap_node = GNUNET_CONTAINER_heap_insert(find_peer_context->peer_min_heap, second_count, second_count->count);
1192     GNUNET_CONTAINER_multihashmap_put(find_peer_context->peer_hash, &second->hashPubKey, second_count, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1193   }
1194 }
1195
1196 /**
1197  * Callback for iterating over all the peer connections of a peer group.
1198  */
1199 void count_peers_cb (void *cls,
1200                       const struct GNUNET_PeerIdentity *first,
1201                       const struct GNUNET_PeerIdentity *second,
1202                       struct GNUNET_TIME_Relative latency,
1203                       uint32_t distance,
1204                       const char *emsg)
1205 {
1206   struct FindPeerContext *find_peer_context = cls;
1207   if ((first != NULL) && (second != NULL))
1208     {
1209       add_new_connection(find_peer_context, first, second);
1210       find_peer_context->current_peers++;
1211     }
1212   else
1213     {
1214       GNUNET_assert(dhtlog_handle != NULL);
1215       /*GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer count finished (%u connections), %u new peers, connection estimate %u\n", find_peer_context->current_peers, find_peer_context->current_peers - find_peer_context->previous_peers, connection_estimate(num_peers, DEFAULT_BUCKET_SIZE));*/
1216       if ((find_peer_context->current_peers - find_peer_context->previous_peers > FIND_PEER_THRESHOLD) &&
1217           (find_peer_context->current_peers < connection_estimate(num_peers, DEFAULT_BUCKET_SIZE)) &&
1218           (GNUNET_TIME_absolute_get_remaining(find_peer_context->endtime).value > 0))
1219         {
1220           GNUNET_SCHEDULER_add_now(sched, &schedule_find_peer_requests, find_peer_context);
1221         }
1222       else
1223         {
1224           fprintf(stderr, "Not sending any more find peer requests.\n");
1225         }
1226     }
1227 }
1228
1229 /**
1230  * Connect to all peers in the peer group and iterate over their
1231  * connections.
1232  */
1233 static void
1234 count_new_peers (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1235 {
1236   struct FindPeerContext *find_peer_context = cls;
1237   find_peer_context->previous_peers = find_peer_context->current_peers;
1238   find_peer_context->current_peers = 0;
1239   GNUNET_TESTING_get_topology (pg, &count_peers_cb, find_peer_context);
1240 }
1241
1242
1243 static void
1244 decrement_find_peers (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1245 {
1246   struct TestFindPeer *test_find_peer = cls;
1247   GNUNET_assert(test_find_peer->find_peer_context->outstanding > 0);
1248   test_find_peer->find_peer_context->outstanding--;
1249   test_find_peer->find_peer_context->total--;
1250   if ((0 == test_find_peer->find_peer_context->total) &&
1251       (GNUNET_TIME_absolute_get_remaining(test_find_peer->find_peer_context->endtime).value > 0))
1252   {
1253     GNUNET_SCHEDULER_add_now(sched, &count_new_peers, test_find_peer->find_peer_context);
1254   }
1255   GNUNET_free(test_find_peer);
1256 }
1257
1258 /**
1259  * A find peer request has been sent to the server, now we will schedule a task
1260  * to wait the appropriate time to allow the request to go out and back.
1261  *
1262  * @param cls closure - a TestFindPeer struct
1263  * @param tc context the task is being called with
1264  */
1265 static void
1266 handle_find_peer_sent (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1267 {
1268   struct TestFindPeer *test_find_peer = cls;
1269
1270   GNUNET_DHT_disconnect(test_find_peer->dht_handle);
1271   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_divide(find_peer_delay, 2), &decrement_find_peers, test_find_peer);
1272 }
1273
1274 static void
1275 send_find_peer_request (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1276 {
1277   struct TestFindPeer *test_find_peer = cls;
1278
1279   if (test_find_peer->find_peer_context->outstanding > max_outstanding_find_peers)
1280   {
1281     GNUNET_SCHEDULER_add_delayed(sched, find_peer_offset, &send_find_peer_request, test_find_peer);
1282     return;
1283   }
1284
1285   test_find_peer->find_peer_context->outstanding++;
1286   if (GNUNET_TIME_absolute_get_remaining(test_find_peer->find_peer_context->endtime).value == 0)
1287   {
1288     GNUNET_SCHEDULER_add_now(sched, &decrement_find_peers, test_find_peer);
1289     return;
1290   }
1291
1292   test_find_peer->dht_handle = GNUNET_DHT_connect(sched, test_find_peer->daemon->cfg, 1);
1293   GNUNET_assert(test_find_peer->dht_handle != NULL);
1294   GNUNET_DHT_find_peers (test_find_peer->dht_handle,
1295                          &handle_find_peer_sent, test_find_peer);
1296 }
1297
1298 /**
1299  * Iterator over hash map entries.
1300  *
1301  * @param cls closure
1302  * @param key current key code
1303  * @param value value in the hash map
1304  * @return GNUNET_YES if we should continue to
1305  *         iterate,
1306  *         GNUNET_NO if not.
1307  */
1308 static int remove_peer_count (void *cls,
1309                               const GNUNET_HashCode * key,
1310                               void *value)
1311 {
1312   struct FindPeerContext *find_peer_ctx = cls;
1313   struct PeerCount *peer_count = value;
1314   GNUNET_CONTAINER_heap_remove_node(find_peer_ctx->peer_min_heap, peer_count->heap_node);
1315   GNUNET_free(peer_count);
1316
1317   return GNUNET_YES;
1318 }
1319
1320
1321 /**
1322  * Set up a single find peer request for each peer in the topology.  Do this
1323  * until the settle time is over, limited by the number of outstanding requests
1324  * and the time allowed for each one!
1325  */
1326 static void
1327 schedule_find_peer_requests (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1328 {
1329   struct FindPeerContext *find_peer_ctx = cls;
1330   struct TestFindPeer *test_find_peer;
1331   struct PeerCount *peer_count;
1332   uint32_t i;
1333   uint32_t random;
1334
1335   if (find_peer_ctx->previous_peers == 0) /* First time, go slowly */
1336     find_peer_ctx->total = 1;
1337   else if (find_peer_ctx->current_peers - find_peer_ctx->previous_peers > MAX_FIND_PEER_CUTOFF) /* Found LOTS of peers, still go slowly */
1338     find_peer_ctx->total = find_peer_ctx->last_sent - (find_peer_ctx->last_sent / 8);
1339 #if USE_MIN
1340   else if (find_peer_ctx->current_peers - find_peer_ctx->previous_peers < MIN_FIND_PEER_CUTOFF)
1341     find_peer_ctx->total = find_peer_ctx->last_sent * 2; /* FIXME: always multiply by two (unless above max?) */
1342   else
1343     find_peer_ctx->total = find_peer_ctx->last_sent;
1344 #else
1345   else
1346     find_peer_ctx->total = find_peer_ctx->last_sent * 2;
1347 #endif
1348
1349   if (find_peer_ctx->total > max_outstanding_find_peers)
1350     find_peer_ctx->total = max_outstanding_find_peers;
1351
1352   find_peer_ctx->last_sent = find_peer_ctx->total;
1353   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending %u find peer messages (goal %u connections)\n", find_peer_ctx->total, connection_estimate(num_peers, DEFAULT_BUCKET_SIZE));
1354
1355   find_peer_offset = GNUNET_TIME_relative_divide(find_peer_delay, find_peer_ctx->total);
1356   for (i = 0; i < find_peer_ctx->total; i++)
1357     {
1358       test_find_peer = GNUNET_malloc(sizeof(struct TestFindPeer));
1359       if (find_peer_ctx->previous_peers == 0) /* If we haven't sent any requests, yet choose random peers */
1360         {
1361           /**
1362            * Attempt to spread find peer requests across even sections of the peer address
1363            * space.  Choose basically 1 peer in every num_peers / max_outstanding_requests
1364            * each time, then offset it by a randomish value.
1365            *
1366            * For instance, if num_peers is 100 and max_outstanding is 10, first chosen peer
1367            * will be between 0 - 10, second between 10 - 20, etc.
1368            */
1369           random = (num_peers / find_peer_ctx->total) * i;
1370           random = random + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (num_peers / find_peer_ctx->total));
1371           if (random >= num_peers)
1372             {
1373               random = random - num_peers;
1374             }
1375     #if REAL_RANDOM
1376           random = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
1377     #endif
1378           test_find_peer->daemon = GNUNET_TESTING_daemon_get(pg, random);
1379         }
1380       else /* If we have sent requests, choose peers with a low number of connections to send requests from */
1381         {
1382           peer_count = GNUNET_CONTAINER_heap_remove_root(find_peer_ctx->peer_min_heap);
1383           GNUNET_CONTAINER_multihashmap_remove(find_peer_ctx->peer_hash, &peer_count->peer_id.hashPubKey, peer_count);
1384           test_find_peer->daemon = GNUNET_TESTING_daemon_get_by_id(pg, &peer_count->peer_id);
1385           GNUNET_assert(test_find_peer->daemon != NULL);
1386         }
1387
1388       test_find_peer->find_peer_context = find_peer_ctx;
1389       GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(find_peer_offset, i), &send_find_peer_request, test_find_peer);
1390     }
1391
1392   if ((find_peer_ctx->peer_hash == NULL) && (find_peer_ctx->peer_min_heap == NULL))
1393     {
1394       find_peer_ctx->peer_hash = GNUNET_CONTAINER_multihashmap_create(num_peers);
1395       find_peer_ctx->peer_min_heap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
1396     }
1397   else
1398     {
1399       GNUNET_CONTAINER_multihashmap_iterate(find_peer_ctx->peer_hash, &remove_peer_count, find_peer_ctx);
1400       GNUNET_CONTAINER_multihashmap_destroy(find_peer_ctx->peer_hash);
1401       find_peer_ctx->peer_hash = GNUNET_CONTAINER_multihashmap_create(num_peers);
1402     }
1403
1404   GNUNET_assert(0 == GNUNET_CONTAINER_multihashmap_size(find_peer_ctx->peer_hash));
1405   GNUNET_assert(0 == GNUNET_CONTAINER_heap_get_size(find_peer_ctx->peer_min_heap));
1406
1407 }
1408
1409 /**
1410  * Set up some all of the put and get operations we want
1411  * to do.  Allocate data structure for each, add to list,
1412  * then call actual insert functions.
1413  */
1414 static void
1415 setup_puts_and_gets (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1416 {
1417   int i;
1418   uint32_t temp_daemon;
1419   struct TestPutContext *test_put;
1420   struct TestGetContext *test_get;
1421   int remember[num_puts][num_peers];
1422
1423   memset(&remember, 0, sizeof(int) * num_puts * num_peers);
1424   for (i = 0; i < num_puts; i++)
1425     {
1426       test_put = GNUNET_malloc(sizeof(struct TestPutContext));
1427       test_put->uid = i;
1428       temp_daemon = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
1429       test_put->daemon = GNUNET_TESTING_daemon_get(pg, temp_daemon);
1430       test_put->next = all_puts;
1431       all_puts = test_put;
1432     }
1433
1434   for (i = 0; i < num_gets; i++)
1435     {
1436       test_get = GNUNET_malloc(sizeof(struct TestGetContext));
1437       test_get->uid = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_puts);
1438       temp_daemon = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
1439       while (remember[test_get->uid][temp_daemon] == 1)
1440         temp_daemon = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
1441       test_get->daemon = GNUNET_TESTING_daemon_get(pg, temp_daemon);
1442       remember[test_get->uid][temp_daemon] = 1;
1443       test_get->next = all_gets;
1444       all_gets = test_get;
1445     }
1446
1447   /*GNUNET_SCHEDULER_cancel (sched, die_task);*/
1448   die_task = GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, num_puts * 2),
1449                                            &end_badly, "from do puts");
1450   GNUNET_SCHEDULER_add_now (sched, &do_put, all_puts);
1451 }
1452
1453 /**
1454  * Set up some all of the put and get operations we want
1455  * to do.  Allocate data structure for each, add to list,
1456  * then call actual insert functions.
1457  */
1458 static void
1459 continue_puts_and_gets (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1460 {
1461   int i;
1462   int max;
1463   struct TopologyIteratorContext *topo_ctx;
1464   struct FindPeerContext *find_peer_context;
1465   if (dhtlog_handle != NULL)
1466     {
1467       if (settle_time >= 180 * 2)
1468         max = (settle_time / 180) - 2;
1469       else
1470         max = 1;
1471       for (i = 1; i < max; i++)
1472         {
1473           topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
1474           topo_ctx->current_iteration = i;
1475           topo_ctx->total_iterations = max;
1476           //fprintf(stderr, "scheduled topology iteration in %d minutes\n", i);
1477           GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, i * 3), &capture_current_topology, topo_ctx);
1478         }
1479       topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
1480       topo_ctx->cont = &setup_puts_and_gets;
1481       GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, settle_time), &capture_current_topology, topo_ctx);
1482     }
1483   else
1484     GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, settle_time), &setup_puts_and_gets, NULL);
1485
1486   if (GNUNET_YES == do_find_peer)
1487   {
1488     find_peer_context = GNUNET_malloc(sizeof(struct FindPeerContext));
1489     find_peer_context->endtime = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, settle_time));
1490     GNUNET_SCHEDULER_add_now(sched, &schedule_find_peer_requests, find_peer_context);
1491   }
1492 }
1493
1494 /**
1495  * Task to release DHT handles
1496  */
1497 static void
1498 malicious_disconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1499 {
1500   struct MaliciousContext *ctx = cls;
1501   outstanding_malicious--;
1502   malicious_completed++;
1503   ctx->disconnect_task = GNUNET_SCHEDULER_NO_TASK;
1504   GNUNET_DHT_disconnect(ctx->dht_handle);
1505   ctx->dht_handle = NULL;
1506   GNUNET_free(ctx);
1507
1508   if (malicious_completed == malicious_getters + malicious_putters + malicious_droppers)
1509     {
1510       GNUNET_SCHEDULER_cancel(sched, die_task);
1511       fprintf(stderr, "Finished setting all malicious peers up, calling continuation!\n");
1512       if (dhtlog_handle != NULL)
1513         GNUNET_SCHEDULER_add_now (sched,
1514                                   &continue_puts_and_gets, NULL);
1515       else
1516         GNUNET_SCHEDULER_add_delayed (sched,
1517                                     GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, settle_time),
1518                                     &continue_puts_and_gets, NULL);
1519     }
1520
1521 }
1522
1523 /**
1524  * Task to release DHT handles
1525  */
1526 static void
1527 malicious_done_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1528 {
1529   struct MaliciousContext *ctx = cls;
1530   GNUNET_SCHEDULER_cancel(sched, ctx->disconnect_task);
1531   GNUNET_SCHEDULER_add_now(sched, &malicious_disconnect_task, ctx);
1532 }
1533
1534 /**
1535  * Set up some data, and call API PUT function
1536  */
1537 static void
1538 set_malicious (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1539 {
1540   struct MaliciousContext *ctx = cls;
1541   int ret;
1542
1543   if (outstanding_malicious > DEFAULT_MAX_OUTSTANDING_GETS)
1544     {
1545       GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &set_malicious, ctx);
1546       return;
1547     }
1548
1549   if (ctx->dht_handle == NULL)
1550     {
1551       ctx->dht_handle = GNUNET_DHT_connect(sched, ctx->daemon->cfg, 1);
1552       outstanding_malicious++;
1553     }
1554
1555   GNUNET_assert(ctx->dht_handle != NULL);
1556
1557
1558 #if VERBOSE > 1
1559     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Setting peer %s malicious type %d\n",
1560                 ctx->daemon->shortname, ctx->malicious_type);
1561 #endif
1562
1563   ret = GNUNET_YES;
1564   switch (ctx->malicious_type)
1565   {
1566   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
1567     ret = GNUNET_DHT_set_malicious_getter(ctx->dht_handle, malicious_get_frequency, &malicious_done_task, ctx);
1568     break;
1569   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
1570     ret = GNUNET_DHT_set_malicious_putter(ctx->dht_handle, malicious_put_frequency, &malicious_done_task, ctx);
1571     break;
1572   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
1573     ret = GNUNET_DHT_set_malicious_dropper(ctx->dht_handle, &malicious_done_task, ctx);
1574     break;
1575   default:
1576     break;
1577   }
1578
1579   if (ret == GNUNET_NO)
1580     {
1581       GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &set_malicious, ctx);
1582     }
1583   else
1584     ctx->disconnect_task = GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_get_forever(), &malicious_disconnect_task, ctx);
1585 }
1586
1587 /**
1588  * Select randomly from set of known peers,
1589  * set the desired number of peers to the
1590  * proper malicious types.
1591  */
1592 static void
1593 setup_malicious_peers (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1594 {
1595   struct MaliciousContext *ctx;
1596   int i;
1597   uint32_t temp_daemon;
1598
1599   for (i = 0; i < malicious_getters; i++)
1600     {
1601       ctx = GNUNET_malloc(sizeof(struct MaliciousContext));
1602       temp_daemon = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
1603       ctx->daemon = GNUNET_TESTING_daemon_get(pg, temp_daemon);
1604       ctx->malicious_type = GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET;
1605       GNUNET_SCHEDULER_add_now (sched, &set_malicious, ctx);
1606
1607     }
1608
1609   for (i = 0; i < malicious_putters; i++)
1610     {
1611       ctx = GNUNET_malloc(sizeof(struct MaliciousContext));
1612       temp_daemon = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
1613       ctx->daemon = GNUNET_TESTING_daemon_get(pg, temp_daemon);
1614       ctx->malicious_type = GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT;
1615       GNUNET_SCHEDULER_add_now (sched, &set_malicious, ctx);
1616
1617     }
1618
1619   for (i = 0; i < malicious_droppers; i++)
1620     {
1621       ctx = GNUNET_malloc(sizeof(struct MaliciousContext));
1622       temp_daemon = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
1623       ctx->daemon = GNUNET_TESTING_daemon_get(pg, temp_daemon);
1624       ctx->malicious_type = GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP;
1625       GNUNET_SCHEDULER_add_now (sched, &set_malicious, ctx);
1626     }
1627
1628   if (malicious_getters + malicious_putters + malicious_droppers > 0)
1629     die_task = GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, (malicious_getters + malicious_putters + malicious_droppers) * 2),
1630                                              &end_badly, "from set malicious");
1631   else
1632     {
1633       if (dhtlog_handle != NULL)
1634         GNUNET_SCHEDULER_add_now (sched,
1635                                   &continue_puts_and_gets, NULL);
1636       else
1637         GNUNET_SCHEDULER_add_delayed (sched,
1638                                     GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, settle_time),
1639                                     &continue_puts_and_gets, NULL);
1640     }
1641
1642 }
1643
1644 /**
1645  * This function is called whenever a connection attempt is finished between two of
1646  * the started peers (started with GNUNET_TESTING_daemons_start).  The total
1647  * number of times this function is called should equal the number returned
1648  * from the GNUNET_TESTING_connect_topology call.
1649  *
1650  * The emsg variable is NULL on success (peers connected), and non-NULL on
1651  * failure (peers failed to connect).
1652  */
1653 void
1654 topology_callback (void *cls,
1655                    const struct GNUNET_PeerIdentity *first,
1656                    const struct GNUNET_PeerIdentity *second,
1657                    uint32_t distance,
1658                    const struct GNUNET_CONFIGURATION_Handle *first_cfg,
1659                    const struct GNUNET_CONFIGURATION_Handle *second_cfg,
1660                    struct GNUNET_TESTING_Daemon *first_daemon,
1661                    struct GNUNET_TESTING_Daemon *second_daemon,
1662                    const char *emsg)
1663 {
1664   struct TopologyIteratorContext *topo_ctx;
1665   if (emsg == NULL)
1666     {
1667       total_connections++;
1668 #if VERBOSE > 1
1669       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connected peer %s to peer %s, distance %u\n",
1670                  first_daemon->shortname,
1671                  second_daemon->shortname,
1672                  distance);
1673 #endif
1674     }
1675 #if VERBOSE
1676   else
1677     {
1678       failed_connections++;
1679       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failed to connect peer %s to peer %s with error :\n%s\n",
1680                   first_daemon->shortname,
1681                   second_daemon->shortname, emsg);
1682     }
1683 #endif
1684   GNUNET_assert(peer_connect_meter != NULL);
1685   if (GNUNET_YES == update_meter(peer_connect_meter))
1686     {
1687 #if VERBOSE
1688       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1689                   "Created %d total connections, which is our target number!  Starting next phase of testing.\n",
1690                   total_connections);
1691 #endif
1692       if (dhtlog_handle != NULL)
1693         {
1694           dhtlog_handle->update_connections (trialuid, total_connections);
1695           dhtlog_handle->insert_topology(expected_connections);
1696         }
1697
1698       GNUNET_SCHEDULER_cancel (sched, die_task);
1699       /*die_task = GNUNET_SCHEDULER_add_delayed (sched, DEFAULT_TIMEOUT,
1700                                                &end_badly, "from setup puts/gets");*/
1701       if ((dhtlog_handle != NULL) && (settle_time > 0))
1702         {
1703           topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
1704           topo_ctx->cont = &setup_malicious_peers;
1705           //topo_ctx->cont = &continue_puts_and_gets;
1706           GNUNET_SCHEDULER_add_now(sched, &capture_current_topology, topo_ctx);
1707         }
1708       else
1709         {
1710           GNUNET_SCHEDULER_add_now(sched, &setup_malicious_peers, NULL);
1711           /*GNUNET_SCHEDULER_add_delayed (sched,
1712                                         GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, settle_time),
1713                                         &continue_puts_and_gets, NULL);*/
1714         }
1715     }
1716   else if (total_connections + failed_connections == expected_connections)
1717     {
1718       GNUNET_SCHEDULER_cancel (sched, die_task);
1719       die_task = GNUNET_SCHEDULER_add_now (sched,
1720                                            &end_badly, "from topology_callback (too many failed connections)");
1721     }
1722 }
1723
1724 static void
1725 peers_started_callback (void *cls,
1726        const struct GNUNET_PeerIdentity *id,
1727        const struct GNUNET_CONFIGURATION_Handle *cfg,
1728        struct GNUNET_TESTING_Daemon *d, const char *emsg)
1729 {
1730   if (emsg != NULL)
1731     {
1732       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failed to start daemon with error: `%s'\n",
1733                   emsg);
1734       return;
1735     }
1736   GNUNET_assert (id != NULL);
1737
1738 #if VERBOSE > 1
1739   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Started daemon %llu out of %llu\n",
1740               (num_peers - peers_left) + 1, num_peers);
1741 #endif
1742
1743   peers_left--;
1744
1745   if (GNUNET_YES == update_meter(peer_start_meter))
1746     {
1747 #if VERBOSE
1748       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1749                   "All %d daemons started, now connecting peers!\n",
1750                   num_peers);
1751 #endif
1752       GNUNET_SCHEDULER_cancel (sched, die_task);
1753
1754       expected_connections = -1;
1755       if ((pg != NULL) && (peers_left == 0))
1756         {
1757           expected_connections = GNUNET_TESTING_connect_topology (pg, connect_topology, connect_topology_option, connect_topology_option_modifier);
1758
1759           peer_connect_meter = create_meter(expected_connections, "Peer connection ", GNUNET_YES);
1760           fprintf(stderr, "Have %d expected connections\n", expected_connections);
1761         }
1762
1763       if (expected_connections == GNUNET_SYSERR)
1764         {
1765           die_task = GNUNET_SCHEDULER_add_now (sched,
1766                                                &end_badly, "from connect topology (bad return)");
1767         }
1768
1769       die_task = GNUNET_SCHEDULER_add_delayed (sched,
1770                                                GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, DEFAULT_CONNECT_TIMEOUT * expected_connections),
1771                                                &end_badly, "from connect topology (timeout)");
1772
1773       ok = 0;
1774     }
1775 }
1776
1777 static void
1778 create_topology ()
1779 {
1780   peers_left = num_peers; /* Reset counter */
1781   if (GNUNET_TESTING_create_topology (pg, topology, blacklist_topology, blacklist_transports) != GNUNET_SYSERR)
1782     {
1783 #if VERBOSE
1784       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1785                   "Topology set up, now starting peers!\n");
1786 #endif
1787       GNUNET_TESTING_daemons_continue_startup(pg);
1788     }
1789   else
1790     {
1791       GNUNET_SCHEDULER_cancel (sched, die_task);
1792       die_task = GNUNET_SCHEDULER_add_now (sched,
1793                                            &end_badly, "from create topology (bad return)");
1794     }
1795   GNUNET_free_non_null(blacklist_transports);
1796   GNUNET_SCHEDULER_cancel (sched, die_task);
1797   die_task = GNUNET_SCHEDULER_add_delayed (sched,
1798                                            GNUNET_TIME_relative_multiply(seconds_per_peer_start, num_peers),
1799                                            &end_badly, "from continue startup (timeout)");
1800 }
1801
1802 /**
1803  * Callback indicating that the hostkey was created for a peer.
1804  *
1805  * @param cls NULL
1806  * @param id the peer identity
1807  * @param d the daemon handle (pretty useless at this point, remove?)
1808  * @param emsg non-null on failure
1809  */
1810 void hostkey_callback (void *cls,
1811                        const struct GNUNET_PeerIdentity *id,
1812                        struct GNUNET_TESTING_Daemon *d,
1813                        const char *emsg)
1814 {
1815   if (emsg != NULL)
1816     {
1817       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Hostkey callback received error: %s\n", emsg);
1818     }
1819
1820 #if VERBOSE > 1
1821     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1822                 "Hostkey (%d/%d) created for peer `%s'\n",
1823                 num_peers - peers_left, num_peers, GNUNET_i2s(id));
1824 #endif
1825
1826     peers_left--;
1827     if (GNUNET_YES == update_meter(hostkey_meter))
1828       {
1829 #if VERBOSE
1830         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1831                     "All %d hostkeys created, now creating topology!\n",
1832                     num_peers);
1833 #endif
1834         GNUNET_SCHEDULER_cancel (sched, die_task);
1835         /* Set up task in case topology creation doesn't finish
1836          * within a reasonable amount of time */
1837         die_task = GNUNET_SCHEDULER_add_delayed (sched,
1838                                                  DEFAULT_TOPOLOGY_TIMEOUT,
1839                                                  &end_badly, "from create_topology");
1840         GNUNET_SCHEDULER_add_now(sched, &create_topology, NULL);
1841         ok = 0;
1842       }
1843 }
1844
1845
1846 static void
1847 run (void *cls,
1848      struct GNUNET_SCHEDULER_Handle *s,
1849      char *const *args,
1850      const char *cfgfile, const struct GNUNET_CONFIGURATION_Handle *cfg)
1851 {
1852   struct stat frstat;
1853   struct GNUNET_TESTING_Host *hosts;
1854   struct GNUNET_TESTING_Host *temphost;
1855   char *topology_str;
1856   char *connect_topology_str;
1857   char *blacklist_topology_str;
1858   char *connect_topology_option_str;
1859   char *connect_topology_option_modifier_string;
1860   char *trialmessage;
1861   char *topology_percentage_str;
1862   float topology_percentage;
1863   char *topology_probability_str;
1864   char *hostfile;
1865   float topology_probability;
1866   unsigned long long temp_config_number;
1867   int stop_closest;
1868   int stop_found;
1869   int strict_kademlia;
1870   char *buf;
1871   char *data;
1872   int count;
1873
1874   sched = s;
1875   config = cfg;
1876   /* Get path from configuration file */
1877   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_string(cfg, "paths", "servicehome", &test_directory))
1878     {
1879       ok = 404;
1880       return;
1881     }
1882
1883   /**
1884    * Get DHT specific testing options.
1885    */
1886   if ((GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging")) ||
1887       (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging_extended")))
1888     {
1889       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
1890       if (dhtlog_handle == NULL)
1891         {
1892           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1893                       "Could not connect to mysql server for logging, will NOT log dht operations!");
1894           ok = 3306;
1895           return;
1896         }
1897     }
1898
1899   stop_closest = GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht", "stop_on_closest");
1900   if (stop_closest == GNUNET_SYSERR)
1901     stop_closest = GNUNET_NO;
1902
1903   stop_found = GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht", "stop_found");
1904   if (stop_found == GNUNET_SYSERR)
1905     stop_found = GNUNET_NO;
1906
1907   strict_kademlia = GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht", "strict_kademlia");
1908   if (strict_kademlia == GNUNET_SYSERR)
1909     strict_kademlia = GNUNET_NO;
1910
1911   if (GNUNET_OK !=
1912       GNUNET_CONFIGURATION_get_value_string (cfg, "dht_testing", "comment",
1913                                              &trialmessage))
1914     trialmessage = NULL;
1915
1916   if (GNUNET_OK !=
1917       GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "hostfile",
1918                                              &hostfile))
1919     hostfile = NULL;
1920
1921   hosts = NULL;
1922   temphost = NULL;
1923   if (hostfile != NULL)
1924     {
1925       if (GNUNET_OK != GNUNET_DISK_file_test (hostfile))
1926           GNUNET_DISK_fn_write (hostfile, NULL, 0, GNUNET_DISK_PERM_USER_READ
1927             | GNUNET_DISK_PERM_USER_WRITE);
1928       if ((0 != STAT (hostfile, &frstat)) || (frstat.st_size == 0))
1929         {
1930           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1931                       "Could not open file specified for host list, ending test!");
1932           ok = 1119;
1933           GNUNET_free_non_null(trialmessage);
1934           GNUNET_free(hostfile);
1935           return;
1936         }
1937
1938     data = GNUNET_malloc_large (frstat.st_size);
1939     GNUNET_assert(data != NULL);
1940     if (frstat.st_size !=
1941         GNUNET_DISK_fn_read (hostfile, data, frstat.st_size))
1942       {
1943         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1944                   "Could not read file %s specified for host list, ending test!", hostfile);
1945         GNUNET_free (hostfile);
1946         GNUNET_free (data);
1947         GNUNET_free_non_null(trialmessage);
1948         return;
1949       }
1950
1951     GNUNET_free_non_null(hostfile);
1952
1953     buf = data;
1954     count = 0;
1955     while (count < frstat.st_size)
1956       {
1957         count++;
1958         if (((data[count] == '\n') || (data[count] == '\0')) && (buf != &data[count]))
1959           {
1960             data[count] = '\0';
1961             temphost = GNUNET_malloc(sizeof(struct GNUNET_TESTING_Host));
1962             temphost->hostname = buf;
1963             temphost->next = hosts;
1964             hosts = temphost;
1965             buf = &data[count + 1];
1966           }
1967         else if ((data[count] == '\n') || (data[count] == '\0'))
1968           buf = &data[count + 1];
1969       }
1970     }
1971
1972   if (GNUNET_OK !=
1973           GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "malicious_getters",
1974                                                  &malicious_getters))
1975     malicious_getters = 0;
1976
1977   if (GNUNET_OK !=
1978           GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "malicious_putters",
1979                                                  &malicious_putters))
1980     malicious_putters = 0;
1981
1982   if (GNUNET_OK !=
1983             GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "malicious_droppers",
1984                                                    &malicious_droppers))
1985     malicious_droppers = 0;
1986
1987   if (GNUNET_OK !=
1988       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "settle_time",
1989                                                  &settle_time))
1990     settle_time = 0;
1991
1992   if (GNUNET_SYSERR ==
1993       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "num_puts",
1994                                              &num_puts))
1995     num_puts = num_peers;
1996
1997   if (GNUNET_SYSERR ==
1998       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "num_gets",
1999                                              &num_gets))
2000     num_gets = num_peers;
2001
2002   if (GNUNET_OK ==
2003         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "find_peer_delay",
2004                                                &temp_config_number))
2005     find_peer_delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
2006   else
2007     find_peer_delay = DEFAULT_FIND_PEER_DELAY;
2008
2009   if (GNUNET_OK ==
2010         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "concurrent_find_peers",
2011                                                &temp_config_number))
2012     max_outstanding_find_peers = temp_config_number;
2013   else
2014     max_outstanding_find_peers = DEFAULT_MAX_OUTSTANDING_FIND_PEERS;
2015
2016   if (GNUNET_OK ==
2017         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "get_timeout",
2018                                                &temp_config_number))
2019     get_timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
2020   else
2021     get_timeout = DEFAULT_GET_TIMEOUT;
2022
2023   if (GNUNET_OK ==
2024         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "concurrent_puts",
2025                                                &temp_config_number))
2026     max_outstanding_puts = temp_config_number;
2027   else
2028     max_outstanding_puts = DEFAULT_MAX_OUTSTANDING_PUTS;
2029
2030   if (GNUNET_OK ==
2031         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "concurrent_gets",
2032                                                &temp_config_number))
2033     max_outstanding_gets = temp_config_number;
2034   else
2035     max_outstanding_gets = DEFAULT_MAX_OUTSTANDING_GETS;
2036
2037   if (GNUNET_OK ==
2038         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "timeout",
2039                                                &temp_config_number))
2040     all_get_timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
2041   else
2042     all_get_timeout.value = get_timeout.value * ((num_gets / max_outstanding_gets) + 1);
2043
2044   if (GNUNET_OK ==
2045         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "get_delay",
2046                                                &temp_config_number))
2047     get_delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
2048   else
2049     get_delay = DEFAULT_GET_DELAY;
2050
2051   if (GNUNET_OK ==
2052         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "put_delay",
2053                                                &temp_config_number))
2054     put_delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
2055   else
2056     put_delay = DEFAULT_PUT_DELAY;
2057
2058   if (GNUNET_OK ==
2059       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "peer_start_timeout",
2060                                              &temp_config_number))
2061     seconds_per_peer_start = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
2062   else
2063     seconds_per_peer_start = DEFAULT_SECONDS_PER_PEER_START;
2064
2065   if (GNUNET_OK ==
2066         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "data_size",
2067                                                &temp_config_number))
2068     test_data_size = temp_config_number;
2069   else
2070     test_data_size = DEFAULT_TEST_DATA_SIZE;
2071
2072   /**
2073    * Get testing related options.
2074    */
2075
2076   if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT_TESTING",
2077                                                           "MALICIOUS_GET_FREQUENCY",
2078                                                           &malicious_get_frequency))
2079     malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
2080
2081
2082   if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT_TESTING",
2083                                                           "MALICIOUS_PUT_FREQUENCY",
2084                                                           &malicious_put_frequency))
2085     malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
2086
2087   if (GNUNET_NO ==
2088         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
2089                                              "find_peers"))
2090     {
2091       do_find_peer = GNUNET_NO;
2092     }
2093   else
2094     do_find_peer = GNUNET_YES;
2095
2096   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT_TESTING",
2097                                                           "FIND_PEER_DELAY",
2098                                                           &temp_config_number))
2099     {
2100       find_peer_delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
2101     }
2102   else
2103     find_peer_delay = DEFAULT_FIND_PEER_DELAY;
2104
2105   if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT_TESTING",
2106                                                             "OUTSTANDING_FIND_PEERS",
2107                                                             &max_outstanding_find_peers))
2108       max_outstanding_find_peers = DEFAULT_MAX_OUTSTANDING_FIND_PEERS;
2109
2110   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht", "strict_kademlia"))
2111     max_outstanding_find_peers = max_outstanding_find_peers * 1;
2112
2113   find_peer_offset = GNUNET_TIME_relative_divide (find_peer_delay, max_outstanding_find_peers);
2114
2115   topology_str = NULL;
2116   if ((GNUNET_YES ==
2117       GNUNET_CONFIGURATION_get_value_string(cfg, "testing", "topology",
2118                                             &topology_str)) && (GNUNET_NO == GNUNET_TESTING_topology_get(&topology, topology_str)))
2119     {
2120       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2121                   "Invalid topology `%s' given for section %s option %s\n", topology_str, "TESTING", "TOPOLOGY");
2122       topology = GNUNET_TESTING_TOPOLOGY_CLIQUE; /* Defaults to NONE, so set better default here */
2123     }
2124
2125   if (GNUNET_OK !=
2126       GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "percentage",
2127                                                  &topology_percentage_str))
2128     topology_percentage = 0.5;
2129   else
2130     {
2131       topology_percentage = atof (topology_percentage_str);
2132       GNUNET_free(topology_percentage_str);
2133     }
2134
2135   if (GNUNET_OK !=
2136       GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "probability",
2137                                                  &topology_probability_str))
2138     topology_probability = 0.5;
2139   else
2140     {
2141      topology_probability = atof (topology_probability_str);
2142      GNUNET_free(topology_probability_str);
2143     }
2144
2145   if ((GNUNET_YES ==
2146       GNUNET_CONFIGURATION_get_value_string(cfg, "testing", "connect_topology",
2147                                             &connect_topology_str)) && (GNUNET_NO == GNUNET_TESTING_topology_get(&connect_topology, connect_topology_str)))
2148     {
2149       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2150                   "Invalid connect topology `%s' given for section %s option %s\n", connect_topology_str, "TESTING", "CONNECT_TOPOLOGY");
2151     }
2152   GNUNET_free_non_null(connect_topology_str);
2153
2154   if ((GNUNET_YES ==
2155       GNUNET_CONFIGURATION_get_value_string(cfg, "testing", "connect_topology_option",
2156                                             &connect_topology_option_str)) && (GNUNET_NO == GNUNET_TESTING_topology_option_get(&connect_topology_option, connect_topology_option_str)))
2157     {
2158       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2159                   "Invalid connect topology option `%s' given for section %s option %s\n", connect_topology_option_str, "TESTING", "CONNECT_TOPOLOGY_OPTION");
2160       connect_topology_option = GNUNET_TESTING_TOPOLOGY_OPTION_ALL; /* Defaults to NONE, set to ALL */
2161     }
2162   GNUNET_free_non_null(connect_topology_option_str);
2163
2164   if (GNUNET_YES ==
2165         GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "connect_topology_option_modifier",
2166                                                &connect_topology_option_modifier_string))
2167     {
2168       if (sscanf(connect_topology_option_modifier_string, "%lf", &connect_topology_option_modifier) != 1)
2169       {
2170         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2171         _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
2172         connect_topology_option_modifier_string,
2173         "connect_topology_option_modifier",
2174         "TESTING");
2175       }
2176       GNUNET_free (connect_topology_option_modifier_string);
2177     }
2178
2179   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "blacklist_transports",
2180                                          &blacklist_transports))
2181     blacklist_transports = NULL;
2182
2183   if ((GNUNET_YES ==
2184       GNUNET_CONFIGURATION_get_value_string(cfg, "testing", "blacklist_topology",
2185                                             &blacklist_topology_str)) &&
2186       (GNUNET_NO == GNUNET_TESTING_topology_get(&blacklist_topology, blacklist_topology_str)))
2187     {
2188       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2189                   "Invalid topology `%s' given for section %s option %s\n", topology_str, "TESTING", "BLACKLIST_TOPOLOGY");
2190     }
2191   GNUNET_free_non_null(topology_str);
2192   GNUNET_free_non_null(blacklist_topology_str);
2193
2194   /* Get number of peers to start from configuration */
2195   if (GNUNET_SYSERR ==
2196       GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "num_peers",
2197                                              &num_peers))
2198     {
2199       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2200                   "Number of peers must be specified in section %s option %s\n", topology_str, "TESTING", "NUM_PEERS");
2201     }
2202   GNUNET_assert(num_peers > 0 && num_peers < (unsigned long long)-1);
2203   /* Set peers_left so we know when all peers started */
2204   peers_left = num_peers;
2205
2206   /* Set up a task to end testing if peer start fails */
2207   die_task = GNUNET_SCHEDULER_add_delayed (sched,
2208                                            GNUNET_TIME_relative_multiply(seconds_per_peer_start, num_peers),
2209                                            &end_badly, "didn't generate all hostkeys within allowed startup time!");
2210
2211   if (dhtlog_handle == NULL)
2212     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2213                 "dhtlog_handle is NULL!");
2214
2215   if ((trialmessage != NULL) && (dhtlog_handle != NULL))
2216     {
2217       dhtlog_handle->insert_trial (&trialuid, peers_left, topology,
2218                                     blacklist_topology, connect_topology,
2219                                     connect_topology_option,
2220                                     connect_topology_option_modifier, topology_percentage,
2221                                     topology_probability, num_puts, num_gets,
2222                                     max_outstanding_gets, settle_time, 1,
2223                                     malicious_getters, malicious_putters,
2224                                     malicious_droppers, malicious_get_frequency,
2225                                     malicious_put_frequency, stop_closest, stop_found,
2226                                     strict_kademlia, 0, trialmessage);
2227     }
2228   else if (dhtlog_handle != NULL)
2229     {
2230       dhtlog_handle->insert_trial (&trialuid, peers_left, topology,
2231                                     blacklist_topology, connect_topology,
2232                                     connect_topology_option,
2233                                     connect_topology_option_modifier, topology_percentage,
2234                                     topology_probability, num_puts, num_gets,
2235                                     max_outstanding_gets, settle_time, 1,
2236                                     malicious_getters, malicious_putters,
2237                                     malicious_droppers, malicious_get_frequency,
2238                                     malicious_put_frequency, stop_closest, stop_found,
2239                                     strict_kademlia, 0, "");
2240     }
2241
2242   GNUNET_free_non_null(trialmessage);
2243
2244   hostkey_meter = create_meter(peers_left, "Hostkeys created ", GNUNET_YES);
2245   peer_start_meter = create_meter(peers_left, "Peers started ", GNUNET_YES);
2246
2247   put_meter = create_meter(num_puts, "Puts completed ", GNUNET_YES);
2248   get_meter = create_meter(num_gets, "Gets completed ", GNUNET_YES);
2249   pg = GNUNET_TESTING_daemons_start (sched, cfg,
2250                                      peers_left,
2251                                      GNUNET_TIME_relative_multiply(seconds_per_peer_start, num_peers),
2252                                      &hostkey_callback, NULL,
2253                                      &peers_started_callback, NULL,
2254                                      &topology_callback, NULL,
2255                                      hosts);
2256
2257   GNUNET_free_non_null(temphost);
2258 }
2259
2260
2261 int
2262 main (int argc, char *argv[])
2263 {
2264   int ret;
2265   struct GNUNET_GETOPT_CommandLineOption options[] = {
2266       GNUNET_GETOPT_OPTION_END
2267     };
2268
2269   ret = GNUNET_PROGRAM_run (argc,
2270                             argv, "gnunet-dht-driver", "nohelp",
2271                             options, &run, &ok);
2272
2273   if (ret != GNUNET_OK)
2274     {
2275       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "`gnunet-dht-driver': Failed with error code %d\n", ret);
2276     }
2277
2278   /**
2279    * Need to remove base directory, subdirectories taken care
2280    * of by the testing framework.
2281    */
2282   if (GNUNET_DISK_directory_remove (test_directory) != GNUNET_OK)
2283     {
2284       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to remove testing directory %s\n", test_directory);
2285     }
2286   return ret;
2287 }
2288
2289 /* end of test_dht_twopeer_put_get.c */