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