all peers match bloom filter. inexplicable.
[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  * @author Nathan Evans (who to blame)
27  */
28 #include "platform.h"
29 #ifndef HAVE_MALICIOUS
30 #error foo
31 #endif
32 #include "gnunet_testing_lib.h"
33 #include "gnunet_core_service.h"
34 #include "gnunet_dht_service.h"
35 #include "dhtlog.h"
36 #include "dht.h"
37
38 /* DEFINES */
39 #define VERBOSE GNUNET_NO
40
41 /* Timeout for entire driver to run */
42 #define DEFAULT_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
43
44 /* Timeout for waiting for (individual) replies to get requests */
45 #define DEFAULT_GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
46
47 #define DEFAULT_TOPOLOGY_CAPTURE_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
48
49 /* Timeout for waiting for gets to be sent to the service */
50 #define DEFAULT_GET_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10)
51
52 /* Timeout for waiting for puts to be sent to the service */
53 #define DEFAULT_PUT_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10)
54
55 /* Time to allow a find peer request to take */
56 #define DEFAULT_FIND_PEER_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 40)
57
58 /* Time to wait for all peers disconnected due to to churn to actually be removed from system */
59 #define DEFAULT_PEER_DISCONNECT_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
60
61 #define DEFAULT_SECONDS_PER_PEER_START GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 45)
62
63 #define DEFAULT_TEST_DATA_SIZE 8
64
65 #define DEFAULT_BUCKET_SIZE 4
66
67 #define FIND_PEER_THRESHOLD 1
68
69 /* If more than this many peers are added, slow down sending */
70 #define MAX_FIND_PEER_CUTOFF 4000
71
72 /* If less than this many peers are added, speed up sending */
73 #define MIN_FIND_PEER_CUTOFF 500
74
75 #define DEFAULT_MAX_OUTSTANDING_PUTS 10
76
77 #define DEFAULT_MAX_OUTSTANDING_FIND_PEERS 196
78
79 #define DEFAULT_FIND_PEER_OFFSET GNUNET_TIME_relative_divide (DEFAULT_FIND_PEER_DELAY, DEFAULT_MAX_OUTSTANDING_FIND_PEERS)
80
81 #define DEFAULT_MAX_OUTSTANDING_GETS 10
82
83 #define DEFAULT_CONNECT_TIMEOUT 60
84
85 #define DEFAULT_TOPOLOGY_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
86
87 #define DEFAULT_RECONNECT_ATTEMPTS 8
88
89 /*
90  * Default frequency for sending malicious get messages
91  */
92 #define DEFAULT_MALICIOUS_GET_FREQUENCY GNUNET_TIME_UNIT_SECONDS
93
94 /*
95  * Default frequency for sending malicious put messages
96  */
97 #define DEFAULT_MALICIOUS_PUT_FREQUENCY GNUNET_TIME_UNIT_SECONDS
98
99 /* Structs */
100
101 struct MaliciousContext
102 {
103   /**
104    * Handle to DHT service (via the API)
105    */
106   struct GNUNET_DHT_Handle *dht_handle;
107
108   /**
109    *  Handle to the peer daemon
110    */
111   struct GNUNET_TESTING_Daemon *daemon;
112
113   /**
114    * Task for disconnecting DHT handles
115    */
116   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
117
118   /**
119    * What type of malicious to set this peer to.
120    */
121   int malicious_type;
122 };
123
124 struct TestFindPeer
125 {
126   /* This is a linked list */
127   struct TestFindPeer *next;
128
129   /* Handle to the bigger context */
130   struct FindPeerContext *find_peer_context;
131
132   /**
133    * Handle to the peer's DHT service (via the API)
134    */
135   struct GNUNET_DHT_Handle *dht_handle;
136
137   /**
138    *  Handle to the peer daemon
139    */
140   struct GNUNET_TESTING_Daemon *daemon;
141
142   /**
143    * Task for disconnecting DHT handles
144    */
145   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
146 };
147
148 struct TestPutContext
149 {
150   /* This is a linked list */
151   struct TestPutContext *next;
152
153   /**
154    * Handle to the first peers DHT service (via the API)
155    */
156   struct GNUNET_DHT_Handle *dht_handle;
157
158   /**
159    *  Handle to the PUT peer daemon
160    */
161   struct GNUNET_TESTING_Daemon *daemon;
162
163   /**
164    *  Identifier for this PUT
165    */
166   uint32_t uid;
167
168   /**
169    * Task for disconnecting DHT handles
170    */
171   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
172 };
173
174 struct TestGetContext
175 {
176   /* This is a linked list */
177   struct TestGetContext *next;
178
179   /**
180    * Handle to the first peers DHT service (via the API)
181    */
182   struct GNUNET_DHT_Handle *dht_handle;
183
184   /**
185    * Handle for the DHT get request
186    */
187   struct GNUNET_DHT_GetHandle *get_handle;
188
189   /**
190    *  Handle to the GET peer daemon
191    */
192   struct GNUNET_TESTING_Daemon *daemon;
193
194   /**
195    *  Identifier for this GET
196    */
197   uint32_t uid;
198
199   /**
200    * Task for disconnecting DHT handles (and stopping GET)
201    */
202   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
203
204   /**
205    * Whether or not this request has been fulfilled already.
206    */
207   int succeeded;
208 };
209
210 /**
211  * Simple struct to keep track of progress, and print a
212  * nice little percentage meter for long running tasks.
213  */
214 struct ProgressMeter
215 {
216   unsigned int total;
217
218   unsigned int modnum;
219
220   unsigned int dotnum;
221
222   unsigned int completed;
223
224   int print;
225
226   char *startup_string;
227 };
228
229 /**
230  * Linked list of information for populating statistics
231  * before ending trial.
232  */
233 struct StatisticsIteratorContext
234 {
235   const struct GNUNET_PeerIdentity *peer;
236   unsigned int stat_routes;
237   unsigned int stat_route_forwards;
238   unsigned int stat_results;
239   unsigned int stat_results_to_client;
240   unsigned int stat_result_forwards;
241   unsigned int stat_gets;
242   unsigned int stat_puts;
243   unsigned int stat_puts_inserted;
244   unsigned int stat_find_peer;
245   unsigned int stat_find_peer_start;
246   unsigned int stat_get_start;
247   unsigned int stat_put_start;
248   unsigned int stat_find_peer_reply;
249   unsigned int stat_get_reply;
250   unsigned int stat_find_peer_answer;
251   unsigned int stat_get_response_start;
252 };
253
254 /**
255  * Context for getting a topology, logging it, and continuing
256  * on with some next operation.
257  */
258 struct TopologyIteratorContext
259 {
260   unsigned int total_iterations;
261   unsigned int current_iteration;
262   unsigned int total_connections;
263   unsigned int total_peers;
264   struct GNUNET_CONTAINER_MultiHashMap *peers_seen;
265   struct GNUNET_PeerIdentity *peer;
266   GNUNET_SCHEDULER_Task cont;
267   void *cls;
268   struct GNUNET_TIME_Relative timeout;
269 };
270
271
272 struct PeerCount
273 {
274   /** Node in the heap */
275   struct GNUNET_CONTAINER_HeapNode *heap_node;
276
277   /** Peer the count refers to */
278   struct GNUNET_PeerIdentity peer_id;
279
280   /** Count of connections this peer has */
281   unsigned int count;
282 };
283
284 /**
285  * Context for sending out find peer requests.
286  */
287 struct FindPeerContext
288 {
289   /**
290    * How long to send find peer requests, once the settle time
291    * is over don't send any more out!
292    *
293    * TODO: Add option for settle time and find peer sending time?
294    */
295   struct GNUNET_TIME_Absolute endtime;
296
297   /**
298    * Number of connections in the current topology
299    * (after this round of find peer requests has ended).
300    */
301   unsigned int current_peers;
302
303   /**
304    * Number of connections in the current topology
305    * (before this round of find peer requests started).
306    */
307   unsigned int previous_peers;
308
309   /**
310    * Number of find peer requests we have currently
311    * outstanding.
312    */
313   unsigned int outstanding;
314
315   /**
316    * Number of find peer requests to send in this round.
317    */
318   unsigned int total;
319
320   /**
321    * Number of find peer requests sent last time around.
322    */
323   unsigned int last_sent;
324
325   /**
326    * Hashmap of peers in the current topology, value
327    * is a PeerCount, with the number of connections
328    * this peer has.
329    */
330   struct GNUNET_CONTAINER_MultiHashMap *peer_hash;
331
332   /**
333    * Min heap which orders values in the peer_hash for
334    * easy lookup.
335    */
336   struct GNUNET_CONTAINER_Heap *peer_min_heap;
337
338   /**
339    * Callback for counting the peers in the current topology.
340    */
341   GNUNET_TESTING_NotifyTopology count_peers_cb;
342 };
343
344 enum DHT_ROUND_TYPES
345 {
346   /**
347    * Next full round (puts + gets).
348    */
349   DHT_ROUND_NORMAL,
350
351   /**
352    * Next round of gets.
353    */
354   DHT_ROUND_GET,
355
356   /**
357    * Next round of puts.
358    */
359   DHT_ROUND_PUT,
360
361   /**
362    * Next round of churn.
363    */
364   DHT_ROUND_CHURN
365 };
366
367
368
369 /* Globals */
370
371 /**
372  * Timeout to let all GET requests happen.
373  */
374 static struct GNUNET_TIME_Relative all_get_timeout;
375
376 /**
377  * Per get timeout
378  */
379 static struct GNUNET_TIME_Relative get_timeout;
380
381 /**
382  * Time to allow for GET requests to be sent to service.
383  */
384 static struct GNUNET_TIME_Relative get_delay;
385
386 /**
387  * Time to allow for PUT requests to be sent to service.
388  */
389 static struct GNUNET_TIME_Relative put_delay;
390
391 /**
392  * Delay between sending find peer requests (if
393  * handled by the driver, no effect if sent by service).
394  */
395 static struct GNUNET_TIME_Relative find_peer_delay;
396
397 /**
398  * Time between find peer requests
399  * (find_peer_delay / max_outstanding_find_peer)
400  */
401 static struct GNUNET_TIME_Relative find_peer_offset;
402
403 /**
404  * How many seconds to allow each peer to start.
405  */
406 static struct GNUNET_TIME_Relative seconds_per_peer_start;
407
408 /**
409  * Boolean value, should the driver issue find peer requests
410  * (GNUNET_YES) or should it be left to the service (GNUNET_NO)
411  */
412 static unsigned int do_find_peer;
413
414 /**
415  * Boolean value, should replication be done by the dht
416  * service (GNUNET_YES) or by the driver (GNUNET_NO)
417  */
418 static unsigned int in_dht_replication;
419
420 /**
421  * Size of test data to insert/retrieve during testing.
422  */
423 static unsigned long long test_data_size = DEFAULT_TEST_DATA_SIZE;
424
425 /**
426  * Maximum number of concurrent PUT requests.
427  */
428 static unsigned long long max_outstanding_puts = DEFAULT_MAX_OUTSTANDING_PUTS;
429
430 /**
431  * Maximum number of concurrent GET requests.
432  */
433 static unsigned long long max_outstanding_gets = DEFAULT_MAX_OUTSTANDING_GETS;
434
435 /**
436  * Number of nodes issuing malicious GET messages.
437  */
438 static unsigned long long malicious_getters;
439
440 /**
441  * Maximum number of concurrent find peer messages being sent.
442  */
443 static unsigned long long max_outstanding_find_peers;
444
445 /**
446  * Number of nodes issuing malicious PUT messages.
447  */
448 static unsigned long long malicious_putters;
449
450 /**
451  * Time (in seconds) to delay between rounds.
452  */
453 static unsigned long long round_delay;
454
455 /**
456  * How many malicious droppers to seed in the network.
457  */
458 static unsigned long long malicious_droppers;
459
460 /**
461  * Bloom filter to restrict malicious nodes chosen.
462  */
463 struct GNUNET_CONTAINER_BloomFilter *malicious_bloom;
464
465 /**
466  * Whether malicious droppers should be chosen based on proximity to a key.
467  */
468 static int malicious_sybil;
469
470 /**
471  * Target for the malicious sybil nodes (choose the closest to this key).
472  */
473 static GNUNET_HashCode sybil_target;
474
475 /**
476  * How often to send malicious GET messages.
477  */
478 static struct GNUNET_TIME_Relative malicious_get_frequency;
479
480 /**
481  * How often to send malicious PUT messages.
482  */
483 static struct GNUNET_TIME_Relative malicious_put_frequency;
484
485 /**
486  * How long to send find peer requests.
487  */
488 static unsigned long long settle_time;
489
490 /**
491  * Handle to the dhtlog service.
492  */
493 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
494
495 /**
496  * Replication value for GET requests.
497  */
498 static unsigned long long get_replication;
499
500 /**
501  * Replication value for PUT requests.
502  */
503 static unsigned long long put_replication;
504
505 /**
506  * If GNUNET_YES, insert data at the same peers every time.
507  * Otherwise, choose a new random peer to insert at each time.
508  */
509 static unsigned int replicate_same;
510
511 /**
512  * If GNUNET_YES, issue GET requests at the same peers every time.
513  * Otherwise, choose a new random peer/data combination to search
514  * each time.
515  */
516 static unsigned int get_from_same;
517
518 /**
519  * Should malicious peers be set after allowing for settle time?
520  * Default is to set them malicious after initial connection setup.
521  */
522 static unsigned int malicious_after_settle;
523
524 /**
525  * Number of rounds for testing (PUTS + GETS)
526  */
527 static unsigned long long total_rounds;
528
529 /**
530  * Target number of connections (will stop sending find peer
531  * messages when this number is exceeded)
532  */
533 static unsigned long long target_total_connections;
534
535 /**
536  * Number of rounds already run
537  */
538 static unsigned int rounds_finished;
539
540 /**
541  * Number of rounds of churn to read from the file (first line, should be a single number).
542  */
543 static unsigned int churn_rounds;
544
545 /**
546  * Current round we are in for churn, tells us how many peers to connect/disconnect.
547  */
548 static unsigned int current_churn_round;
549
550 /**
551  * Number of times to churn per round
552  */
553 static unsigned long long churns_per_round;
554
555 /**
556  * Array of churn values.
557  */
558 static unsigned int *churn_array;
559
560 /**
561  * Hash map of stats contexts.
562  */
563 static struct GNUNET_CONTAINER_MultiHashMap *stats_map;
564
565 /**
566  * LL of malicious settings.
567  */
568 struct MaliciousContext *all_malicious;
569
570 /**
571  * List of GETS to perform
572  */
573 struct TestGetContext *all_gets;
574
575 /**
576  * List of PUTS to perform
577  */
578 struct TestPutContext *all_puts;
579
580 /**
581  * Directory to store temporary data in, defined in config file
582  */
583 static char *test_directory;
584
585 /**
586  * Variable used to store the number of connections we should wait for.
587  */
588 static unsigned int expected_connections;
589
590 /**
591  * Variable used to keep track of how many peers aren't yet started.
592  */
593 static unsigned long long peers_left;
594
595 /**
596  * Handle to the set of all peers run for this test.
597  */
598 static struct GNUNET_TESTING_PeerGroup *pg;
599
600
601 /**
602  * Global config handle.
603  */
604 static const struct GNUNET_CONFIGURATION_Handle *config;
605
606 /**
607  * Total number of peers to run, set based on config file.
608  */
609 static unsigned long long num_peers;
610
611 /**
612  * Total number of items to insert.
613  */
614 static unsigned long long num_puts;
615
616 /**
617  * How many puts do we currently have in flight?
618  */
619 static unsigned long long outstanding_puts;
620
621 /**
622  * How many puts are done?
623  */
624 static unsigned long long puts_completed;
625
626 /**
627  * Total number of items to attempt to get.
628  */
629 static unsigned long long num_gets;
630
631 /**
632  * How many puts do we currently have in flight?
633  */
634 static unsigned long long outstanding_gets;
635
636 /**
637  * How many gets are done?
638  */
639 static unsigned long long gets_completed;
640
641 /**
642  * How many gets failed?
643  */
644 static unsigned long long gets_failed;
645
646 /**
647  * How many malicious control messages do
648  * we currently have in flight?
649  */
650 static unsigned long long outstanding_malicious;
651
652 /**
653  * How many set malicious peers are done?
654  */
655 static unsigned long long malicious_completed;
656
657 /**
658  * Global used to count how many connections we have currently
659  * been notified about (how many times has topology_callback been called
660  * with success?)
661  */
662 static unsigned int total_connections;
663
664 /**
665  * Global used to count how many failed connections we have
666  * been notified about (how many times has topology_callback
667  * been called with failure?)
668  */
669 static unsigned int failed_connections;
670
671 /* Task handle to use to schedule shutdown if something goes wrong */
672 GNUNET_SCHEDULER_TaskIdentifier die_task;
673
674 static char *blacklist_transports;
675
676 static enum GNUNET_TESTING_Topology topology;
677
678 static enum GNUNET_TESTING_Topology blacklist_topology = GNUNET_TESTING_TOPOLOGY_NONE; /* Don't do any blacklisting */
679
680 static enum GNUNET_TESTING_Topology connect_topology = GNUNET_TESTING_TOPOLOGY_NONE; /* NONE actually means connect all allowed peers */
681
682 static enum GNUNET_TESTING_TopologyOption connect_topology_option = GNUNET_TESTING_TOPOLOGY_OPTION_ALL;
683
684 static double connect_topology_option_modifier = 0.0;
685
686 static struct ProgressMeter *hostkey_meter;
687
688 static struct ProgressMeter *peer_start_meter;
689
690 static struct ProgressMeter *peer_connect_meter;
691
692 static struct ProgressMeter *put_meter;
693
694 static struct ProgressMeter *get_meter;
695
696 static GNUNET_HashCode *known_keys;
697
698 /* Global return value (0 for success, anything else for failure) */
699 static int ok;
700
701 /**
702  * Create a meter to keep track of the progress of some task.
703  *
704  * @param total the total number of items to complete
705  * @param start_string a string to prefix the meter with (if printing)
706  * @param print GNUNET_YES to print the meter, GNUNET_NO to count
707  *              internally only
708  *
709  * @return the progress meter
710  */
711 static struct ProgressMeter *
712 create_meter(unsigned int total, char * start_string, int print)
713 {
714   struct ProgressMeter *ret;
715   ret = GNUNET_malloc(sizeof(struct ProgressMeter));
716   ret->print = print;
717   ret->total = total;
718   ret->modnum = total / 4;
719   ret->dotnum = (total / 50) + 1;
720   if (start_string != NULL)
721     ret->startup_string = GNUNET_strdup(start_string);
722   else
723     ret->startup_string = GNUNET_strdup("");
724
725   return ret;
726 }
727
728 /**
729  * Update progress meter (increment by one).
730  *
731  * @param meter the meter to update and print info for
732  *
733  * @return GNUNET_YES if called the total requested,
734  *         GNUNET_NO if more items expected
735  */
736 static int
737 update_meter(struct ProgressMeter *meter)
738 {
739   if (meter->print == GNUNET_YES)
740     {
741       if (meter->completed % meter->modnum == 0)
742         {
743           if (meter->completed == 0)
744             {
745               fprintf(stdout, "%sProgress: [0%%", meter->startup_string);
746             }
747           else
748             fprintf(stdout, "%d%%", (int)(((float)meter->completed / meter->total) * 100));
749         }
750       else if (meter->completed % meter->dotnum == 0)
751         fprintf(stdout, ".");
752
753       if (meter->completed + 1 == meter->total)
754         fprintf(stdout, "%d%%]\n", 100);
755       fflush(stdout);
756     }
757   meter->completed++;
758
759   if (meter->completed == meter->total)
760     return GNUNET_YES;
761   return GNUNET_NO;
762 }
763
764 /**
765  * Reset progress meter.
766  *
767  * @param meter the meter to reset
768  *
769  * @return GNUNET_YES if meter reset,
770  *         GNUNET_SYSERR on error
771  */
772 static int
773 reset_meter(struct ProgressMeter *meter)
774 {
775   if (meter == NULL)
776     return GNUNET_SYSERR;
777
778   meter->completed = 0;
779   return GNUNET_YES;
780 }
781
782 /**
783  * Release resources for meter
784  *
785  * @param meter the meter to free
786  */
787 static void
788 free_meter(struct ProgressMeter *meter)
789 {
790   GNUNET_free_non_null (meter->startup_string);
791   GNUNET_free (meter);
792 }
793
794 /**
795  * Check whether peers successfully shut down.
796  */
797 static void 
798 shutdown_callback (void *cls,
799                    const char *emsg)
800 {
801   if (emsg != NULL)
802     {
803       if (ok == 0)
804         ok = 2;
805     }
806 }
807
808 /**
809  * Task to release DHT handles for PUT
810  */
811 static void
812 put_disconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
813 {
814   struct TestPutContext *test_put = cls;
815   test_put->disconnect_task = GNUNET_SCHEDULER_NO_TASK;
816   GNUNET_DHT_disconnect(test_put->dht_handle);
817   test_put->dht_handle = NULL;
818   if (replicate_same == GNUNET_NO)
819     test_put->daemon = GNUNET_TESTING_daemon_get(pg, GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers));
820 }
821
822 /**
823  * Function scheduled to be run on the successful completion of this
824  * testcase.
825  */
826 static void
827 finish_testing (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
828 {
829   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Ending test normally!\n", (char *)cls);
830   GNUNET_assert (pg != NULL);
831   struct TestPutContext *test_put = all_puts;
832   struct TestGetContext *test_get = all_gets;
833
834   while (test_put != NULL)
835     {
836       if (test_put->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
837         GNUNET_SCHEDULER_cancel(test_put->disconnect_task);
838       if (test_put->dht_handle != NULL)
839         GNUNET_DHT_disconnect(test_put->dht_handle);
840       test_put = test_put->next;
841     }
842
843   while (test_get != NULL)
844     {
845       if (test_get->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
846         GNUNET_SCHEDULER_cancel(test_get->disconnect_task);
847       if (test_get->get_handle != NULL)
848         GNUNET_DHT_get_stop(test_get->get_handle);
849       if (test_get->dht_handle != NULL)
850         GNUNET_DHT_disconnect(test_get->dht_handle);
851       test_get = test_get->next;
852     }
853
854   GNUNET_TESTING_daemons_stop (pg, DEFAULT_TIMEOUT, &shutdown_callback, NULL);
855
856   if (dhtlog_handle != NULL)
857     {
858       fprintf(stderr, "Update trial endtime\n");
859       dhtlog_handle->update_trial (gets_completed);
860       GNUNET_DHTLOG_disconnect(dhtlog_handle);
861       dhtlog_handle = NULL;
862     }
863
864   if (hostkey_meter != NULL)
865     free_meter(hostkey_meter);
866   if (peer_start_meter != NULL)
867     free_meter(peer_start_meter);
868   if (peer_connect_meter != NULL)
869     free_meter(peer_connect_meter);
870   if (put_meter != NULL)
871     free_meter(put_meter);
872   if (get_meter != NULL)
873     free_meter(get_meter);
874
875   ok = 0;
876 }
877
878 /**
879  * Callback for iterating over all the peer connections of a peer group.
880  */
881 static void 
882 log_topology_cb (void *cls,
883                  const struct GNUNET_PeerIdentity *first,
884                  const struct GNUNET_PeerIdentity *second,
885                  const char *emsg)
886 {
887   struct TopologyIteratorContext *topo_ctx = cls;
888   if ((first != NULL) && (second != NULL))
889     {
890       /* GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "According to CORE, peer %s is connected to %s\n", GNUNET_i2s(first), GNUNET_h2s(&second->hashPubKey));*/
891       if ((topo_ctx->peers_seen != NULL) && (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(topo_ctx->peers_seen, &first->hashPubKey)))
892         {
893           GNUNET_CONTAINER_multihashmap_put(topo_ctx->peers_seen, &first->hashPubKey, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
894           topo_ctx->total_peers++;
895         }
896       topo_ctx->total_connections++;
897       if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(config, "dht_testing", "mysql_logging"))
898         dhtlog_handle->insert_extended_topology(first, second);
899     }
900   else
901     {
902       GNUNET_assert(dhtlog_handle != NULL);
903       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Topology iteration (%u/%u) finished (%u connections, %u peers)\n", topo_ctx->current_iteration, topo_ctx->total_iterations, topo_ctx->total_connections, topo_ctx->total_peers);
904       dhtlog_handle->update_topology(topo_ctx->total_connections);
905       if (topo_ctx->cont != NULL)
906         GNUNET_SCHEDULER_add_now (topo_ctx->cont, topo_ctx->cls);
907       if (topo_ctx->peers_seen != NULL)
908         GNUNET_CONTAINER_multihashmap_destroy(topo_ctx->peers_seen);
909       GNUNET_free(topo_ctx);
910     }
911 }
912
913 /**
914  * Iterator over hash map entries.
915  *
916  * @param cls closure - always NULL
917  * @param key current key code
918  * @param value value in the hash map, a stats context
919  * @return GNUNET_YES if we should continue to
920  *         iterate,
921  *         GNUNET_NO if not.
922  */
923 static int stats_iterate (void *cls,
924                           const GNUNET_HashCode * key,
925                           void *value)
926 {
927   struct StatisticsIteratorContext *stats_ctx;
928   if (value == NULL)
929     return GNUNET_NO;
930   stats_ctx = value;
931   dhtlog_handle->insert_stat(stats_ctx->peer, stats_ctx->stat_routes, stats_ctx->stat_route_forwards, stats_ctx->stat_results,
932                              stats_ctx->stat_results_to_client, stats_ctx->stat_result_forwards, stats_ctx->stat_gets,
933                              stats_ctx->stat_puts, stats_ctx->stat_puts_inserted, stats_ctx->stat_find_peer,
934                              stats_ctx->stat_find_peer_start, stats_ctx->stat_get_start, stats_ctx->stat_put_start,
935                              stats_ctx->stat_find_peer_reply, stats_ctx->stat_get_reply, stats_ctx->stat_find_peer_answer,
936                              stats_ctx->stat_get_response_start);
937   GNUNET_free(stats_ctx);
938   return GNUNET_YES;
939 }
940
941 static void 
942 stats_finished (void *cls, int result)
943 {
944   fprintf(stderr, "Finished getting all peers statistics, iterating!\n");
945   GNUNET_CONTAINER_multihashmap_iterate(stats_map, &stats_iterate, NULL);
946   GNUNET_CONTAINER_multihashmap_destroy(stats_map);
947   GNUNET_SCHEDULER_add_now (&finish_testing, NULL);
948 }
949
950 /**
951  * Callback function to process statistic values.
952  *
953  * @param cls closure
954  * @param peer the peer the statistics belong to
955  * @param subsystem name of subsystem that created the statistic
956  * @param name the name of the datum
957  * @param value the current value
958  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
959  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
960  */
961 static int stats_handle  (void *cls,
962                           const struct GNUNET_PeerIdentity *peer,
963                           const char *subsystem,
964                           const char *name,
965                           uint64_t value,
966                           int is_persistent)
967 {
968   struct StatisticsIteratorContext *stats_ctx;
969
970   if (dhtlog_handle != NULL)
971     dhtlog_handle->add_generic_stat(peer, name, subsystem, value);
972   if (GNUNET_CONTAINER_multihashmap_contains(stats_map, &peer->hashPubKey))
973     {
974       stats_ctx = GNUNET_CONTAINER_multihashmap_get(stats_map, &peer->hashPubKey);
975     }
976   else
977     {
978       stats_ctx = GNUNET_malloc(sizeof(struct StatisticsIteratorContext));
979       stats_ctx->peer = peer;
980       GNUNET_CONTAINER_multihashmap_put(stats_map, &peer->hashPubKey, stats_ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
981     }
982   GNUNET_assert(stats_ctx != NULL);
983
984   if (strcmp(name, STAT_ROUTES) == 0)
985     stats_ctx->stat_routes = value;
986   else if (strcmp(name, STAT_ROUTE_FORWARDS) == 0)
987     stats_ctx->stat_route_forwards = value;
988   else if (strcmp(name, STAT_RESULTS) == 0)
989     stats_ctx->stat_results = value;
990   else if (strcmp(name, STAT_RESULTS_TO_CLIENT) == 0)
991     stats_ctx->stat_results_to_client = value;
992   else if (strcmp(name, STAT_RESULT_FORWARDS) == 0)
993     stats_ctx->stat_result_forwards = value;
994   else if (strcmp(name, STAT_GETS) == 0)
995     stats_ctx->stat_gets = value;
996   else if (strcmp(name, STAT_PUTS) == 0)
997     stats_ctx->stat_puts = value;
998   else if (strcmp(name, STAT_PUTS_INSERTED) == 0)
999     stats_ctx->stat_puts_inserted = value;
1000   else if (strcmp(name, STAT_FIND_PEER) == 0)
1001     stats_ctx->stat_find_peer = value;
1002   else if (strcmp(name, STAT_FIND_PEER_START) == 0)
1003     stats_ctx->stat_find_peer_start = value;
1004   else if (strcmp(name, STAT_GET_START) == 0)
1005     stats_ctx->stat_get_start = value;
1006   else if (strcmp(name, STAT_PUT_START) == 0)
1007     stats_ctx->stat_put_start = value;
1008   else if (strcmp(name, STAT_FIND_PEER_REPLY) == 0)
1009     stats_ctx->stat_find_peer_reply = value;
1010   else if (strcmp(name, STAT_GET_REPLY) == 0)
1011     stats_ctx->stat_get_reply = value;
1012   else if (strcmp(name, STAT_FIND_PEER_ANSWER) == 0)
1013     stats_ctx->stat_find_peer_answer = value;
1014   else if (strcmp(name, STAT_GET_RESPONSE_START) == 0)
1015     stats_ctx->stat_get_response_start = value;
1016
1017   return GNUNET_OK;
1018 }
1019
1020 /**
1021  * Connect to statistics service for each peer and get the appropriate
1022  * dht statistics for safe keeping.
1023  */
1024 static void
1025 log_dht_statistics (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1026 {
1027   stats_map = GNUNET_CONTAINER_multihashmap_create(num_peers);
1028   fprintf(stderr, "Starting statistics logging\n");
1029   GNUNET_TESTING_get_statistics(pg, &stats_finished, &stats_handle, NULL);
1030 }
1031
1032
1033 /**
1034  * Connect to all peers in the peer group and iterate over their
1035  * connections.
1036  */
1037 static void
1038 capture_current_topology (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1039 {
1040   struct TopologyIteratorContext *topo_ctx = cls;
1041   dhtlog_handle->insert_topology(0);
1042   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Called capture_current_topology\n");
1043   GNUNET_TESTING_get_topology (pg, &log_topology_cb, topo_ctx);
1044 }
1045
1046
1047 /**
1048  * Check if the get_handle is being used, if so stop the request.  Either
1049  * way, schedule the end_badly_cont function which actually shuts down the
1050  * test.
1051  */
1052 static void
1053 end_badly (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1054 {
1055   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Failing test with error: `%s'!\n", (char *)cls);
1056
1057   struct TestPutContext *test_put = all_puts;
1058   struct TestGetContext *test_get = all_gets;
1059
1060   while (test_put != NULL)
1061     {
1062       if (test_put->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
1063         GNUNET_SCHEDULER_cancel(test_put->disconnect_task);
1064       if (test_put->dht_handle != NULL)
1065         GNUNET_DHT_disconnect(test_put->dht_handle);
1066       test_put = test_put->next;
1067     }
1068
1069   while (test_get != NULL)
1070     {
1071       if (test_get->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
1072         GNUNET_SCHEDULER_cancel(test_get->disconnect_task);
1073       if (test_get->get_handle != NULL)
1074         GNUNET_DHT_get_stop(test_get->get_handle);
1075       if (test_get->dht_handle != NULL)
1076         GNUNET_DHT_disconnect(test_get->dht_handle);
1077       test_get = test_get->next;
1078     }
1079
1080   GNUNET_TESTING_daemons_stop (pg, DEFAULT_TIMEOUT, &shutdown_callback, NULL);
1081
1082   if (dhtlog_handle != NULL)
1083     {
1084       fprintf(stderr, "Update trial endtime\n");
1085       dhtlog_handle->update_trial (gets_completed);
1086       GNUNET_DHTLOG_disconnect(dhtlog_handle);
1087       dhtlog_handle = NULL;
1088     }
1089
1090   if (hostkey_meter != NULL)
1091     free_meter(hostkey_meter);
1092   if (peer_start_meter != NULL)
1093     free_meter(peer_start_meter);
1094   if (peer_connect_meter != NULL)
1095     free_meter(peer_connect_meter);
1096   if (put_meter != NULL)
1097     free_meter(put_meter);
1098   if (get_meter != NULL)
1099     free_meter(get_meter);
1100
1101   ok = 1;
1102 }
1103
1104 /**
1105  * Forward declaration.
1106  */
1107 static void
1108 do_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc);
1109
1110 /**
1111  * Forward declaration.
1112  */
1113 static void
1114 do_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc);
1115
1116 /**
1117  * Iterator over hash map entries.
1118  *
1119  * @param cls closure
1120  * @param key current key code
1121  * @param value value in the hash map
1122  * @return GNUNET_YES if we should continue to
1123  *         iterate,
1124  *         GNUNET_NO if not.
1125  */
1126 static int remove_peer_count (void *cls,
1127                               const GNUNET_HashCode * key,
1128                               void *value)
1129 {
1130   struct FindPeerContext *find_peer_ctx = cls;
1131   struct PeerCount *peer_count = value;
1132   GNUNET_CONTAINER_heap_remove_node(find_peer_ctx->peer_min_heap, peer_count->heap_node);
1133   GNUNET_free(peer_count);
1134
1135   return GNUNET_YES;
1136 }
1137
1138 /**
1139  * Connect to all peers in the peer group and iterate over their
1140  * connections.
1141  */
1142 static void
1143 count_new_peers (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1144 {
1145   struct FindPeerContext *find_peer_context = cls;
1146   find_peer_context->previous_peers = find_peer_context->current_peers;
1147   find_peer_context->current_peers = 0;
1148   GNUNET_TESTING_get_topology (pg, find_peer_context->count_peers_cb, find_peer_context);
1149 }
1150
1151 static void
1152 decrement_find_peers (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1153 {
1154   struct TestFindPeer *test_find_peer = cls;
1155   GNUNET_assert(test_find_peer->find_peer_context->outstanding > 0);
1156   test_find_peer->find_peer_context->outstanding--;
1157   test_find_peer->find_peer_context->total--;
1158   if (0 == test_find_peer->find_peer_context->total)
1159   {
1160     GNUNET_SCHEDULER_add_now(&count_new_peers, test_find_peer->find_peer_context);
1161   }
1162   GNUNET_free(test_find_peer);
1163 }
1164
1165 /**
1166  * A find peer request has been sent to the server, now we will schedule a task
1167  * to wait the appropriate time to allow the request to go out and back.
1168  *
1169  * @param cls closure - a TestFindPeer struct
1170  * @param tc context the task is being called with
1171  */
1172 static void
1173 handle_find_peer_sent (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1174 {
1175   struct TestFindPeer *test_find_peer = cls;
1176
1177   GNUNET_DHT_disconnect(test_find_peer->dht_handle);
1178   GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_divide(find_peer_delay, 2), &decrement_find_peers, test_find_peer);
1179 }
1180
1181
1182 static void
1183 send_find_peer_request (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1184 {
1185   struct TestFindPeer *test_find_peer = cls;
1186
1187   if (test_find_peer->find_peer_context->outstanding > max_outstanding_find_peers)
1188   {
1189     GNUNET_SCHEDULER_add_delayed(find_peer_offset, &send_find_peer_request, test_find_peer);
1190     return;
1191   }
1192
1193   test_find_peer->find_peer_context->outstanding++;
1194   if (GNUNET_TIME_absolute_get_remaining(test_find_peer->find_peer_context->endtime).rel_value == 0)
1195   {
1196     GNUNET_SCHEDULER_add_now(&decrement_find_peers, test_find_peer);
1197     return;
1198   }
1199
1200   test_find_peer->dht_handle = GNUNET_DHT_connect(test_find_peer->daemon->cfg, 1);
1201   GNUNET_assert(test_find_peer->dht_handle != NULL);
1202   GNUNET_DHT_find_peers (test_find_peer->dht_handle,
1203                          &handle_find_peer_sent, test_find_peer);
1204 }
1205
1206
1207 /**
1208  * Add a connection to the find_peer_context given.  This may
1209  * be complete overkill, but allows us to choose the peers with
1210  * the least connections to initiate find peer requests from.
1211  */
1212 static void add_new_connection(struct FindPeerContext *find_peer_context,
1213                                const struct GNUNET_PeerIdentity *first,
1214                                const struct GNUNET_PeerIdentity *second)
1215 {
1216   struct PeerCount *first_count;
1217   struct PeerCount *second_count;
1218
1219   if (GNUNET_CONTAINER_multihashmap_contains(find_peer_context->peer_hash, &first->hashPubKey))
1220   {
1221     first_count = GNUNET_CONTAINER_multihashmap_get(find_peer_context->peer_hash, &first->hashPubKey);
1222     GNUNET_assert(first_count != NULL);
1223     first_count->count++;
1224     GNUNET_CONTAINER_heap_update_cost(find_peer_context->peer_min_heap, first_count->heap_node, first_count->count);
1225   }
1226   else
1227   {
1228     first_count = GNUNET_malloc(sizeof(struct PeerCount));
1229     first_count->count = 1;
1230     memcpy(&first_count->peer_id, first, sizeof(struct GNUNET_PeerIdentity));
1231     first_count->heap_node = GNUNET_CONTAINER_heap_insert(find_peer_context->peer_min_heap, first_count, first_count->count);
1232     GNUNET_CONTAINER_multihashmap_put(find_peer_context->peer_hash, &first->hashPubKey, first_count, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1233   }
1234
1235   if (GNUNET_CONTAINER_multihashmap_contains(find_peer_context->peer_hash, &second->hashPubKey))
1236   {
1237     second_count = GNUNET_CONTAINER_multihashmap_get(find_peer_context->peer_hash, &second->hashPubKey);
1238     GNUNET_assert(second_count != NULL);
1239     second_count->count++;
1240     GNUNET_CONTAINER_heap_update_cost(find_peer_context->peer_min_heap, second_count->heap_node, second_count->count);
1241   }
1242   else
1243   {
1244     second_count = GNUNET_malloc(sizeof(struct PeerCount));
1245     second_count->count = 1;
1246     memcpy(&second_count->peer_id, second, sizeof(struct GNUNET_PeerIdentity));
1247     second_count->heap_node = GNUNET_CONTAINER_heap_insert(find_peer_context->peer_min_heap, second_count, second_count->count);
1248     GNUNET_CONTAINER_multihashmap_put(find_peer_context->peer_hash, &second->hashPubKey, second_count, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1249   }
1250 }
1251
1252
1253 /**
1254  * Iterate over min heap of connections per peer.  For any
1255  * peer that has 0 connections, attempt to connect them to
1256  * some random peer.
1257  *
1258  * @param cls closure a struct FindPeerContext
1259  * @param node internal node of the heap
1260  * @param element value stored, a struct PeerCount
1261  * @param cost cost associated with the node
1262  * @return GNUNET_YES if we should continue to iterate,
1263  *         GNUNET_NO if not.
1264  */
1265 static int iterate_min_heap_peers (void *cls,
1266                                    struct GNUNET_CONTAINER_HeapNode *node,
1267                                    void *element,
1268                                    GNUNET_CONTAINER_HeapCostType cost)
1269 {
1270   struct FindPeerContext *find_peer_context = cls;
1271   struct PeerCount *peer_count = element;
1272   struct GNUNET_TESTING_Daemon *d1;
1273   struct GNUNET_TESTING_Daemon *d2;
1274   struct GNUNET_TIME_Relative timeout;
1275   if (cost == 0)
1276     {
1277       d1 = GNUNET_TESTING_daemon_get_by_id (pg, &peer_count->peer_id);
1278       GNUNET_assert(d1 != NULL);
1279       d2 = d1;
1280       while ((d2 == d1) || (GNUNET_YES != GNUNET_TESTING_daemon_running(d2)))
1281         {
1282           d2 = GNUNET_TESTING_daemon_get(pg, GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers));
1283           GNUNET_assert(d2 != NULL);
1284         }
1285
1286       /** Just try to connect the peers, don't worry about callbacks, etc. **/
1287       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer %s has 0 connections.  Trying to connect to %s...\n", GNUNET_i2s(&peer_count->peer_id), d2->shortname);
1288       timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, DEFAULT_CONNECT_TIMEOUT);
1289       if (GNUNET_TIME_relative_to_absolute(timeout).abs_value > find_peer_context->endtime.abs_value)
1290         {
1291           timeout = GNUNET_TIME_absolute_get_remaining(find_peer_context->endtime);
1292         }
1293       GNUNET_TESTING_daemons_connect(d1, d2, timeout, DEFAULT_RECONNECT_ATTEMPTS, NULL, NULL);
1294     }
1295   if (GNUNET_TIME_absolute_get_remaining(find_peer_context->endtime).rel_value > 0)
1296     return GNUNET_YES;
1297   else
1298     return GNUNET_NO;
1299 }
1300
1301 /**
1302  * Forward declaration.
1303  */
1304 static void
1305 schedule_churn_find_peer_requests (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc);
1306
1307 /**
1308  * Callback for iterating over all the peer connections of a peer group.
1309  * Used after we have churned on some peers to find which ones have zero
1310  * connections so we can make them issue find peer requests.
1311  */
1312 static void 
1313 count_peers_churn_cb (void *cls,
1314                       const struct GNUNET_PeerIdentity *first,
1315                       const struct GNUNET_PeerIdentity *second,
1316                       const char *emsg)
1317 {
1318   struct FindPeerContext *find_peer_context = cls;
1319   struct TopologyIteratorContext *topo_ctx;
1320   struct PeerCount *peer_count;
1321
1322   if ((first != NULL) && (second != NULL))
1323     {
1324       add_new_connection(find_peer_context, first, second);
1325       find_peer_context->current_peers++;
1326     }
1327   else
1328     {
1329       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer count finished (%u connections)\n",
1330                                             find_peer_context->current_peers);
1331       peer_count = GNUNET_CONTAINER_heap_peek(find_peer_context->peer_min_heap);
1332       GNUNET_assert(peer_count != NULL);
1333       /* WAIT. When peers are churned they will come back with their peers (at least in peerinfo), because the HOSTS file doesn't likely get removed. CRAP. */
1334       /* NO they won't, because we have disabled peerinfo writing to disk (remember?) so we WILL have to give them new connections */
1335       /* Best course of action: have DHT automatically try to add peers from peerinfo on startup. This way IF peerinfo writes to file
1336        * then some peers will end up connected.
1337        *
1338        * Also, find any peers that have zero connections here and set up a task to choose at random another peer in the network to
1339        * connect to.  Of course, if they are blacklisted from that peer they won't be able to connect, so we will have to keep trying
1340        * until they get a peer.
1341        */
1342       /* However, they won't automatically be connected to any of their previous peers... How can we handle that? */
1343       /* So now we have choices: do we want them to come back with all their connections?  Probably not, but it solves this mess. */
1344
1345       /* Second problem, which is still a problem, is that a FIND_PEER request won't work when a peer has no connections */
1346
1347       /**
1348        * Okay, so here's how this *should* work now.
1349        *
1350        * 1. We check the min heap for any peers that have 0 connections.
1351        *    a. If any are found, we iterate over the heap and just randomly
1352        *       choose another peer and ask testing to please connect the two.
1353        *       This takes care of the case that a peer just randomly joins the
1354        *       network.  However, if there are strict topology restrictions
1355        *       (imagine a ring) choosing randomly most likely won't help.
1356        *       We make sure the connection attempt doesn't take longer than
1357        *       the total timeout, but don't care too much about the result.
1358        *    b. After that, we still schedule the find peer requests (concurrently
1359        *       with the connect attempts most likely).  This handles the case
1360        *       that the DHT iterates over peerinfo and just needs to try to send
1361        *       a message to get connected.  This should handle the case that the
1362        *       topology is very strict.
1363        *
1364        * 2. If all peers have > 0 connections, we still send find peer requests
1365        *    as long as possible (until timeout is reached) to help out those
1366        *    peers that were newly churned and need more connections.  This is because
1367        *    once all new peers have established a single connection, they won't be
1368        *    well connected.
1369        *
1370        * 3. Once we reach the timeout, we can do no more.  We must schedule the
1371        *    next iteration of get requests regardless of connections that peers
1372        *    may or may not have.
1373        *
1374        * Caveat: it would be nice to get peers to take data offline with them and
1375        *         come back with it (or not) based on the testing framework.  The
1376        *         same goes for remembering previous connections, but putting either
1377        *         into the general testing churn options seems like overkill because
1378        *         these are very specialized cases.
1379        */
1380       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Out of %u peers, fewest connections is %d\n", GNUNET_CONTAINER_heap_get_size(find_peer_context->peer_min_heap), peer_count->count);
1381       if ((peer_count->count == 0) && (GNUNET_TIME_absolute_get_remaining(find_peer_context->endtime).rel_value > 0))
1382         {
1383           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Found peer with no connections, will choose some peer(s) at random to connect to!\n");
1384           GNUNET_CONTAINER_heap_iterate (find_peer_context->peer_min_heap, &iterate_min_heap_peers, find_peer_context);
1385           GNUNET_SCHEDULER_add_now(&schedule_churn_find_peer_requests, find_peer_context);
1386         }
1387       else if ((GNUNET_TIME_absolute_get_remaining(find_peer_context->endtime).rel_value > 0) && (find_peer_context->last_sent != 0))
1388         {
1389           GNUNET_SCHEDULER_add_now(&schedule_churn_find_peer_requests, find_peer_context);
1390         }
1391       else
1392         {
1393           GNUNET_CONTAINER_multihashmap_iterate(find_peer_context->peer_hash, &remove_peer_count, find_peer_context);
1394           GNUNET_CONTAINER_multihashmap_destroy(find_peer_context->peer_hash);
1395           GNUNET_CONTAINER_heap_destroy(find_peer_context->peer_min_heap);
1396           GNUNET_free(find_peer_context);
1397           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Churn round %u of %llu finished, scheduling next GET round.\n", current_churn_round, churn_rounds);
1398           if (dhtlog_handle != NULL)
1399             {
1400               topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
1401               topo_ctx->cont = &do_get;
1402               topo_ctx->cls = all_gets;
1403               topo_ctx->timeout = DEFAULT_GET_TIMEOUT;
1404               topo_ctx->peers_seen = GNUNET_CONTAINER_multihashmap_create(num_peers);
1405               die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_add(GNUNET_TIME_relative_add(DEFAULT_GET_TIMEOUT, all_get_timeout), DEFAULT_TOPOLOGY_CAPTURE_TIMEOUT),
1406                                                        &end_badly, "from do gets (count_peers_churn_cb)");
1407               GNUNET_SCHEDULER_add_now(&capture_current_topology, topo_ctx);
1408             }
1409           else
1410             {
1411               die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_add(GNUNET_TIME_relative_add(DEFAULT_GET_TIMEOUT, all_get_timeout), DEFAULT_TOPOLOGY_CAPTURE_TIMEOUT),
1412                                                        &end_badly, "from do gets (count_peers_churn_cb)");
1413               GNUNET_SCHEDULER_add_now(&do_get, all_gets);
1414             }
1415         }
1416     }
1417 }
1418
1419 /**
1420  * Set up a single find peer request for each peer in the topology.  Do this
1421  * until the settle time is over, limited by the number of outstanding requests
1422  * and the time allowed for each one!
1423  */
1424 static void
1425 schedule_churn_find_peer_requests (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1426 {
1427   struct FindPeerContext *find_peer_ctx = cls;
1428   struct TestFindPeer *test_find_peer;
1429   struct PeerCount *peer_count;
1430   uint32_t i;
1431
1432   if (find_peer_ctx->previous_peers == 0) /* First time, go slowly */
1433     find_peer_ctx->total = 1;
1434   else if (find_peer_ctx->current_peers - find_peer_ctx->previous_peers < MIN_FIND_PEER_CUTOFF)
1435     find_peer_ctx->total = find_peer_ctx->total / 2;
1436   else if (find_peer_ctx->current_peers - find_peer_ctx->previous_peers > MAX_FIND_PEER_CUTOFF) /* Found LOTS of peers, still go slowly */
1437     find_peer_ctx->total = find_peer_ctx->last_sent - (find_peer_ctx->last_sent / 4);
1438   else
1439     find_peer_ctx->total = find_peer_ctx->last_sent * 4;
1440
1441   if (find_peer_ctx->total > max_outstanding_find_peers)
1442     find_peer_ctx->total = max_outstanding_find_peers;
1443
1444   find_peer_ctx->last_sent = find_peer_ctx->total;
1445   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending %u find peer messages (after churn)\n", find_peer_ctx->total);
1446
1447   if (find_peer_ctx->total > 0)
1448     find_peer_offset = GNUNET_TIME_relative_divide(find_peer_delay, find_peer_ctx->total);
1449   else
1450     {
1451       find_peer_ctx->previous_peers = find_peer_ctx->current_peers;
1452       find_peer_ctx->current_peers = 0;
1453       GNUNET_TESTING_get_topology (pg, &count_peers_churn_cb, find_peer_ctx);
1454     }
1455
1456
1457   for (i = 0; i < find_peer_ctx->total; i++)
1458     {
1459       test_find_peer = GNUNET_malloc(sizeof(struct TestFindPeer));
1460       /* If we have sent requests, choose peers with a low number of connections to send requests from */
1461       peer_count = GNUNET_CONTAINER_heap_remove_root(find_peer_ctx->peer_min_heap);
1462       GNUNET_assert(peer_count != NULL);
1463       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending find peer request from peer with %u connections\n", peer_count->count);
1464       GNUNET_CONTAINER_multihashmap_remove(find_peer_ctx->peer_hash, &peer_count->peer_id.hashPubKey, peer_count);
1465       test_find_peer->daemon = GNUNET_TESTING_daemon_get_by_id(pg, &peer_count->peer_id);
1466       GNUNET_assert(test_find_peer->daemon != NULL);
1467       test_find_peer->find_peer_context = find_peer_ctx;
1468       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(find_peer_offset, i), &send_find_peer_request, test_find_peer);
1469     }
1470
1471   if ((find_peer_ctx->peer_hash == NULL) && (find_peer_ctx->peer_min_heap == NULL))
1472     {
1473       find_peer_ctx->peer_hash = GNUNET_CONTAINER_multihashmap_create(num_peers);
1474       find_peer_ctx->peer_min_heap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
1475     }
1476   else
1477     {
1478       GNUNET_CONTAINER_multihashmap_iterate(find_peer_ctx->peer_hash, &remove_peer_count, find_peer_ctx);
1479       GNUNET_CONTAINER_multihashmap_destroy(find_peer_ctx->peer_hash);
1480       find_peer_ctx->peer_hash = GNUNET_CONTAINER_multihashmap_create(num_peers);
1481     }
1482
1483   GNUNET_assert(0 == GNUNET_CONTAINER_multihashmap_size(find_peer_ctx->peer_hash));
1484   GNUNET_assert(0 == GNUNET_CONTAINER_heap_get_size(find_peer_ctx->peer_min_heap));
1485 }
1486
1487 static void schedule_churn_get_topology (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1488 {
1489   struct FindPeerContext *find_peer_context = cls;
1490   GNUNET_TESTING_get_topology (pg, &count_peers_churn_cb, find_peer_context);
1491 }
1492
1493 /**
1494  * Called when churning of the topology has finished.
1495  *
1496  * @param cls closure unused
1497  * @param emsg NULL on success, or a printable error on failure
1498  */
1499 static void churn_complete (void *cls, const char *emsg)
1500 {
1501   struct FindPeerContext *find_peer_context = cls;
1502   struct PeerCount *peer_count;
1503   unsigned int i;
1504   struct GNUNET_TESTING_Daemon *temp_daemon;
1505   struct TopologyIteratorContext *topo_ctx;
1506   struct GNUNET_TIME_Relative calc_timeout;
1507   int count_added;
1508
1509   if (emsg != NULL)
1510     {
1511       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Ending test, churning of peers failed with error `%s'", emsg);
1512       GNUNET_SCHEDULER_add_now(&end_badly, (void *)emsg);
1513       return;
1514     }
1515
1516   /**
1517    * If we switched any peers on, we have to somehow force connect the new peer to
1518    * SOME bootstrap peer in the network.  First schedule a task to find all peers
1519    * with no connections, then choose a random peer for each and connect them.
1520    */
1521   if (find_peer_context != NULL)
1522     {
1523       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "We have churned on some peers, so we must schedule find peer requests for them!\n");
1524       count_added = 0;
1525       for (i = 0; i < num_peers; i ++)
1526         {
1527           temp_daemon = GNUNET_TESTING_daemon_get(pg, i);
1528           if (GNUNET_YES == GNUNET_TESTING_daemon_running(temp_daemon))
1529             {
1530               peer_count = GNUNET_malloc (sizeof(struct PeerCount));
1531               memcpy(&peer_count->peer_id, &temp_daemon->id, sizeof(struct GNUNET_PeerIdentity));
1532               GNUNET_assert(peer_count->count == 0);
1533               peer_count->heap_node = GNUNET_CONTAINER_heap_insert(find_peer_context->peer_min_heap, peer_count, peer_count->count);
1534               GNUNET_CONTAINER_multihashmap_put(find_peer_context->peer_hash, &temp_daemon->id.hashPubKey, peer_count, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1535               count_added++;
1536             }
1537         }
1538       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Added %d peers to heap, total size %d\n", count_added, GNUNET_CONTAINER_heap_get_size(find_peer_context->peer_min_heap));
1539       GNUNET_SCHEDULER_add_delayed(DEFAULT_PEER_DISCONNECT_TIMEOUT, &schedule_churn_get_topology, find_peer_context);
1540       //GNUNET_TESTING_get_topology (pg, &count_peers_churn_cb, find_peer_context);
1541     }
1542   else
1543     {
1544       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Only churned off peers, no find peer requests, scheduling more gets (after allowing time for peers to disconnect properly!)...\n");
1545       if (dhtlog_handle != NULL)
1546         {
1547           topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
1548           topo_ctx->cont = &do_get;
1549           topo_ctx->cls = all_gets;
1550           topo_ctx->timeout = DEFAULT_GET_TIMEOUT;
1551           topo_ctx->peers_seen = GNUNET_CONTAINER_multihashmap_create(num_peers);
1552           calc_timeout = GNUNET_TIME_relative_add(DEFAULT_GET_TIMEOUT, all_get_timeout);
1553           calc_timeout = GNUNET_TIME_relative_add(calc_timeout, DEFAULT_TOPOLOGY_CAPTURE_TIMEOUT);
1554           calc_timeout = GNUNET_TIME_relative_add(calc_timeout, DEFAULT_PEER_DISCONNECT_TIMEOUT);
1555           die_task = GNUNET_SCHEDULER_add_delayed (calc_timeout,
1556                                                    &end_badly, "from do gets (churn_complete)");
1557           GNUNET_SCHEDULER_add_delayed(DEFAULT_PEER_DISCONNECT_TIMEOUT, &capture_current_topology, topo_ctx);
1558         }
1559       else
1560         {
1561           calc_timeout = GNUNET_TIME_relative_add(DEFAULT_GET_TIMEOUT, all_get_timeout);
1562           calc_timeout = GNUNET_TIME_relative_add(calc_timeout, DEFAULT_PEER_DISCONNECT_TIMEOUT);
1563           die_task = GNUNET_SCHEDULER_add_delayed (calc_timeout,
1564                                                    &end_badly, "from do gets (churn_complete)");
1565           if (dhtlog_handle != NULL)
1566             dhtlog_handle->insert_round(DHT_ROUND_GET, rounds_finished);
1567           GNUNET_SCHEDULER_add_delayed(DEFAULT_PEER_DISCONNECT_TIMEOUT, &do_get, all_gets);
1568         }
1569     }
1570 }
1571
1572 /**
1573  * Decide how many peers to turn on or off in this round, make sure the
1574  * numbers actually make sense, then do so.  This function sets in motion
1575  * churn, find peer requests for newly joined peers, and issuing get
1576  * requests once the new peers have done so.
1577  *
1578  * @param cls closure (unused)
1579  * @param tc task context (unused)
1580  */
1581 static void
1582 churn_peers (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1583 {
1584   unsigned int count_running;
1585   unsigned int churn_up;
1586   unsigned int churn_down;
1587   struct GNUNET_TIME_Relative timeout;
1588   struct FindPeerContext *find_peer_context;
1589
1590   churn_up = churn_down = 0;
1591   count_running = GNUNET_TESTING_daemons_running(pg);
1592   if (count_running > churn_array[current_churn_round])
1593     churn_down = count_running - churn_array[current_churn_round];
1594   else if (count_running < churn_array[current_churn_round])
1595     churn_up = churn_array[current_churn_round] - count_running;
1596   else
1597     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Not churning any peers, topology unchanged.\n");
1598
1599   if (churn_up > num_peers - count_running)
1600     {
1601       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Churn file specified %u peers (up); only have %u!", churn_array[current_churn_round], num_peers);
1602       churn_up = num_peers - count_running;
1603     }
1604   else if (churn_down > count_running)
1605     {
1606       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Churn file specified %u peers (down); only have %u!", churn_array[current_churn_round], count_running);
1607       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "This will leave NO peers running (mistake in churn configuration?)!");
1608       churn_down = count_running;
1609     }
1610   //timeout = GNUNET_TIME_relative_multiply(seconds_per_peer_start, churn_up > 0 ? churn_up : churn_down);
1611   //timeout = GNUNET_TIME_relative_multiply (seconds_per_peer_start, churn_up > 0 ? churn_up : churn_down);
1612   timeout = GNUNET_TIME_relative_multiply(DEFAULT_TIMEOUT, 2); /* FIXME: Lack of intelligent choice here */
1613   find_peer_context = NULL;
1614   if (churn_up > 0) /* Only need to do find peer requests if we turned new peers on */
1615     {
1616       find_peer_context = GNUNET_malloc(sizeof(struct FindPeerContext));
1617       find_peer_context->count_peers_cb = &count_peers_churn_cb;
1618       find_peer_context->previous_peers = 0;
1619       find_peer_context->current_peers = 0;
1620       find_peer_context->endtime = GNUNET_TIME_relative_to_absolute(timeout);
1621       find_peer_context->peer_hash = GNUNET_CONTAINER_multihashmap_create(num_peers);
1622       find_peer_context->peer_min_heap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
1623     }
1624   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "churn_peers: want %u total, %u running, starting %u, stopping %u\n",
1625              churn_array[current_churn_round], count_running, churn_up, churn_down);
1626   GNUNET_TESTING_daemons_churn (pg, churn_down, churn_up, timeout, &churn_complete, find_peer_context);
1627   current_churn_round++;
1628 }
1629
1630 /**
1631  * Task to release DHT handle associated with GET request.
1632  */
1633 static void
1634 get_stop_finished (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1635 {
1636   struct TestGetContext *test_get = cls;
1637   struct TopologyIteratorContext *topo_ctx;
1638
1639   /* The dht_handle may be null if this get was scheduled from a down peer */
1640   if (test_get->dht_handle != NULL)
1641     {
1642       GNUNET_DHT_disconnect(test_get->dht_handle);
1643       outstanding_gets--; /* GET is really finished */
1644       test_get->dht_handle = NULL;
1645     }
1646
1647   /* Reset the uid (which item to search for) and the daemon (which peer to search from) for later get request iterations */
1648   if (get_from_same == GNUNET_NO)
1649     {
1650       test_get->uid = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_puts);
1651       test_get->daemon = GNUNET_TESTING_daemon_get(pg, GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers));
1652     }
1653
1654 #if VERBOSE > 1
1655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%d gets succeeded, %d gets failed!\n", gets_completed, gets_failed);
1656 #endif
1657   update_meter(get_meter);
1658   if ((gets_completed + gets_failed == num_gets) && (outstanding_gets == 0))
1659     {
1660       fprintf(stderr, "Canceling die task (get_stop_finished) %llu gets completed, %llu gets failed\n", gets_completed, gets_failed);
1661       GNUNET_SCHEDULER_cancel(die_task);
1662       reset_meter(put_meter);
1663       reset_meter(get_meter);
1664       /**
1665        *  Handle all cases:
1666        *    1) Testing is completely finished, call the topology iteration dealy and die
1667        *    2) Testing is not finished, churn the network and do gets again (current_churn_round < churn_rounds)
1668        *    3) Testing is not finished, reschedule all the PUTS *and* GETS again (num_rounds > 1)
1669        */
1670       if (rounds_finished == total_rounds - 1) /* Everything is finished, end testing */
1671         {
1672           if (dhtlog_handle != NULL)
1673             {
1674               topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
1675               topo_ctx->cont = &log_dht_statistics;
1676               topo_ctx->peers_seen = GNUNET_CONTAINER_multihashmap_create(num_peers);
1677               GNUNET_SCHEDULER_add_now(&capture_current_topology, topo_ctx);
1678             }
1679           else
1680             GNUNET_SCHEDULER_add_now (&finish_testing, NULL);
1681         }
1682       else if (current_churn_round < churns_per_round * (rounds_finished + 1)) /* Do next round of churn */
1683         {
1684           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Current churn round %u, real round %u, scheduling next round of churn.\n", current_churn_round, rounds_finished + 1);
1685           gets_completed = 0;
1686           gets_failed = 0;
1687
1688           if (dhtlog_handle != NULL)
1689             dhtlog_handle->insert_round(DHT_ROUND_CHURN, rounds_finished);
1690
1691           GNUNET_SCHEDULER_add_now(&churn_peers, NULL);
1692         }
1693       else if (rounds_finished < total_rounds - 1) /* Start a new complete round */
1694         {
1695           rounds_finished++;
1696           gets_completed = 0;
1697           gets_failed = 0;
1698           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Round %u of %llu finished, scheduling next round.\n", rounds_finished, total_rounds);
1699
1700           /** We reset the peer daemon for puts and gets on each disconnect, so all we need to do is start another round! */
1701           if (GNUNET_YES == in_dht_replication) /* Replication done in DHT, don't redo puts! */
1702             {
1703               if (dhtlog_handle != NULL)
1704                 dhtlog_handle->insert_round(DHT_ROUND_GET, rounds_finished);
1705
1706               die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_add(GNUNET_TIME_relative_add(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, round_delay), all_get_timeout), DEFAULT_TOPOLOGY_CAPTURE_TIMEOUT),
1707                                                        &end_badly, "from do gets (next round)");
1708               GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, round_delay), &do_get, all_gets);
1709             }
1710           else
1711             {
1712               if (dhtlog_handle != NULL)
1713                 dhtlog_handle->insert_round(DHT_ROUND_NORMAL, rounds_finished);
1714               die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_add(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, round_delay), GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, num_puts * 2)),
1715                                                        &end_badly, "from do puts");
1716               GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, round_delay), &do_put, all_puts);
1717             }
1718         }
1719     }
1720 }
1721
1722 /**
1723  * Task to release get handle.
1724  */
1725 static void
1726 get_stop_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1727 {
1728   struct TestGetContext *test_get = cls;
1729
1730   if (tc->reason == GNUNET_SCHEDULER_REASON_TIMEOUT)
1731     gets_failed++;
1732   GNUNET_assert(test_get->get_handle != NULL);
1733   GNUNET_DHT_get_stop(test_get->get_handle);
1734   test_get->get_handle = NULL;
1735   test_get->disconnect_task = GNUNET_SCHEDULER_NO_TASK;
1736   GNUNET_SCHEDULER_add_now (&get_stop_finished, test_get);
1737 }
1738
1739 /**
1740  * Iterator called if the GET request initiated returns a response.
1741  *
1742  * @param cls closure
1743  * @param exp when will this value expire
1744  * @param key key of the result
1745  * @param get_path NULL-terminated array of pointers
1746  *                 to the peers on reverse GET path (or NULL if not recorded)
1747  * @param put_path NULL-terminated array of pointers
1748  *                 to the peers on the PUT path (or NULL if not recorded)
1749  * @param type type of the result
1750  * @param size number of bytes in data
1751  * @param data pointer to the result data
1752  */
1753 static void 
1754 get_result_iterator (void *cls,
1755                      struct GNUNET_TIME_Absolute exp,
1756                      const GNUNET_HashCode * key,
1757                      const struct GNUNET_PeerIdentity * const *get_path,
1758                      const struct GNUNET_PeerIdentity * const *put_path,
1759                      enum GNUNET_BLOCK_Type type,
1760                      size_t size,
1761                      const void *data)
1762 {
1763   struct TestGetContext *test_get = cls;
1764
1765   if (test_get->succeeded == GNUNET_YES)
1766     return; /* Get has already been successful, probably ending now */
1767
1768   if (0 != memcmp(&known_keys[test_get->uid], key, sizeof (GNUNET_HashCode))) /* || (0 != memcmp(original_data, data, sizeof(original_data))))*/
1769     {
1770       gets_completed++;
1771       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Key or data is not the same as was inserted!\n");
1772     }
1773   else
1774     {
1775       gets_completed++;
1776       test_get->succeeded = GNUNET_YES;
1777     }
1778 #if VERBOSE > 1
1779   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received correct GET response!\n");
1780 #endif
1781   GNUNET_SCHEDULER_cancel(test_get->disconnect_task);
1782   GNUNET_SCHEDULER_add_continuation(&get_stop_task, test_get, GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1783 }
1784
1785
1786
1787 /**
1788  * Set up some data, and call API PUT function
1789  */
1790 static void
1791 do_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1792 {
1793   struct TestGetContext *test_get = cls;
1794
1795   if (num_gets == 0)
1796     {
1797       GNUNET_SCHEDULER_cancel(die_task);
1798       GNUNET_SCHEDULER_add_now(&finish_testing, NULL);
1799     }
1800
1801   if (test_get == NULL)
1802     return; /* End of the list */
1803
1804   /* Set this here in case we are re-running gets */
1805   test_get->succeeded = GNUNET_NO;
1806
1807   if (GNUNET_YES != GNUNET_TESTING_daemon_running(test_get->daemon)) /* If the peer has been churned off, don't try issuing request from it! */
1808     {
1809       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Peer we should issue get request from is down, skipping.\n");
1810       gets_failed++;
1811       GNUNET_SCHEDULER_add_now (&get_stop_finished, test_get);
1812       GNUNET_SCHEDULER_add_now (&do_get, test_get->next);
1813       return;
1814     }
1815
1816   /* Check if more gets are outstanding than should be */
1817   if (outstanding_gets > max_outstanding_gets)
1818     {
1819       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 200), &do_get, test_get);
1820       return;
1821     }
1822
1823   /* Connect to the first peer's DHT */
1824   test_get->dht_handle = GNUNET_DHT_connect(test_get->daemon->cfg, 10);
1825   GNUNET_assert(test_get->dht_handle != NULL);
1826   outstanding_gets++;
1827
1828   /* Insert the data at the first peer */
1829   test_get->get_handle = GNUNET_DHT_get_start(test_get->dht_handle,
1830                                               get_delay,
1831                                               GNUNET_BLOCK_TYPE_TEST,
1832                                               &known_keys[test_get->uid],
1833                                               get_replication,
1834                                               GNUNET_DHT_RO_NONE,
1835                                               NULL, 0,
1836                                               NULL, 0,
1837                                               &get_result_iterator,
1838                                               test_get);
1839
1840 #if VERBOSE > 1
1841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting get for uid %u from peer %s\n",
1842              test_get->uid,
1843              test_get->daemon->shortname);
1844 #endif
1845   test_get->disconnect_task = GNUNET_SCHEDULER_add_delayed(get_timeout, &get_stop_task, test_get);
1846
1847   /* Schedule the next request in the linked list of get requests */
1848   GNUNET_SCHEDULER_add_now (&do_get, test_get->next);
1849 }
1850
1851 /**
1852  * Called when the PUT request has been transmitted to the DHT service.
1853  * Schedule the GET request for some time in the future.
1854  */
1855 static void
1856 put_finished (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1857 {
1858   struct TestPutContext *test_put = cls;
1859   struct TopologyIteratorContext *topo_ctx;
1860   outstanding_puts--;
1861   puts_completed++;
1862
1863   if (tc->reason == GNUNET_SCHEDULER_REASON_TIMEOUT)
1864     fprintf(stderr, "PUT Request failed!\n");
1865
1866   /* Reset the daemon (which peer to insert at) for later put request iterations */
1867   if (replicate_same == GNUNET_NO)
1868     test_put->daemon = GNUNET_TESTING_daemon_get(pg, GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers));
1869
1870   GNUNET_SCHEDULER_cancel(test_put->disconnect_task);
1871   test_put->disconnect_task = GNUNET_SCHEDULER_add_now(&put_disconnect_task, test_put);
1872   if (GNUNET_YES == update_meter(put_meter))
1873     {
1874       GNUNET_assert(outstanding_puts == 0);
1875       GNUNET_SCHEDULER_cancel (die_task);
1876       if (dhtlog_handle != NULL)
1877         {
1878           topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
1879           topo_ctx->cont = &do_get;
1880           topo_ctx->cls = all_gets;
1881           topo_ctx->timeout = DEFAULT_GET_TIMEOUT;
1882           topo_ctx->peers_seen = GNUNET_CONTAINER_multihashmap_create(num_peers);
1883           die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_add(GNUNET_TIME_relative_add(DEFAULT_GET_TIMEOUT, all_get_timeout), DEFAULT_TOPOLOGY_CAPTURE_TIMEOUT),
1884                                                    &end_badly, "from do gets (put finished)");
1885           GNUNET_SCHEDULER_add_now(&capture_current_topology, topo_ctx);
1886         }
1887       else
1888         {
1889           fprintf(stderr, "Scheduling die task (put finished)\n");
1890           die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_add(DEFAULT_GET_TIMEOUT, all_get_timeout),
1891                                                    &end_badly, "from do gets (put finished)");
1892           GNUNET_SCHEDULER_add_delayed(DEFAULT_GET_TIMEOUT, &do_get, all_gets);
1893         }
1894       return;
1895     }
1896 }
1897
1898 /**
1899  * Set up some data, and call API PUT function
1900  */
1901 static void
1902 do_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
1903 {
1904   struct TestPutContext *test_put = cls;
1905   char data[test_data_size]; /* Made up data to store */
1906   uint32_t rand;
1907   int i;
1908
1909   if (test_put == NULL)
1910     return; /* End of list */
1911
1912   if (GNUNET_YES != GNUNET_TESTING_daemon_running(test_put->daemon)) /* If the peer has been churned off, don't try issuing request from it! */
1913     {
1914       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Peer we should issue put request at is down, skipping.\n");
1915       update_meter(put_meter);
1916       GNUNET_SCHEDULER_add_now (&do_put, test_put->next);
1917       return;
1918     }
1919
1920   for (i = 0; i < sizeof(data); i++)
1921     {
1922       memset(&data[i], GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX), 1);
1923     }
1924
1925   if (outstanding_puts > max_outstanding_puts)
1926     {
1927       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 200), &do_put, test_put);
1928       return;
1929     }
1930
1931 #if VERBOSE > 1
1932     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting put for uid %u from peer %s\n",
1933                 test_put->uid,
1934                 test_put->daemon->shortname);
1935 #endif
1936   test_put->dht_handle = GNUNET_DHT_connect(test_put->daemon->cfg, 10);
1937
1938   GNUNET_assert(test_put->dht_handle != NULL);
1939   outstanding_puts++;
1940   GNUNET_DHT_put(test_put->dht_handle,
1941                  &known_keys[test_put->uid],
1942                  put_replication,
1943                  GNUNET_DHT_RO_NONE,
1944                  GNUNET_BLOCK_TYPE_TEST,
1945                  sizeof(data), data,
1946                  GNUNET_TIME_UNIT_FOREVER_ABS,
1947                  put_delay,
1948                  &put_finished, test_put);
1949   test_put->disconnect_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_get_forever(), &put_disconnect_task, test_put);
1950   rand = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 2);
1951   GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, rand), &do_put, test_put->next);
1952 }
1953
1954 static void
1955 schedule_find_peer_requests (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc);
1956
1957 static void
1958 setup_malicious_peers (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc);
1959
1960 /**
1961  * Given a number of total peers and a bucket size, estimate the number of
1962  * connections in a perfect kademlia topology.
1963  */
1964 static unsigned int connection_estimate(unsigned int peer_count, unsigned int bucket_size)
1965 {
1966   unsigned int i;
1967   unsigned int filled;
1968   i = num_peers;
1969
1970   filled = 0;
1971   while (i >= bucket_size)
1972     {
1973       filled++;
1974       i = i/2;
1975     }
1976   filled++; /* Add one filled bucket to account for one "half full" and some miscellaneous */
1977   return filled * bucket_size * peer_count;
1978
1979 }
1980
1981
1982 /**
1983  * Callback for iterating over all the peer connections of a peer group.
1984  */
1985 static void 
1986 count_peers_cb (void *cls,
1987                 const struct GNUNET_PeerIdentity *first,
1988                 const struct GNUNET_PeerIdentity *second,
1989                 const char *emsg)
1990 {
1991   struct FindPeerContext *find_peer_context = cls;
1992   if ((first != NULL) && (second != NULL))
1993     {
1994       add_new_connection(find_peer_context, first, second);
1995       find_peer_context->current_peers++;
1996     }
1997   else
1998     {
1999       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer count finished (%u connections), %u new peers, connection estimate %u (target %u)\n",
2000                                             find_peer_context->current_peers,
2001                                             find_peer_context->current_peers - find_peer_context->previous_peers,
2002                                             connection_estimate(num_peers, DEFAULT_BUCKET_SIZE),
2003                                             target_total_connections);
2004
2005       if ((find_peer_context->last_sent < 8) ||
2006           ((find_peer_context->current_peers - find_peer_context->previous_peers > FIND_PEER_THRESHOLD) &&
2007           (find_peer_context->current_peers < 2 * connection_estimate(num_peers, DEFAULT_BUCKET_SIZE)) &&
2008           (GNUNET_TIME_absolute_get_remaining(find_peer_context->endtime).rel_value > 0) &&
2009           (find_peer_context->current_peers < target_total_connections)))
2010         {
2011           GNUNET_SCHEDULER_add_now(&schedule_find_peer_requests, find_peer_context);
2012         }
2013       else
2014         {
2015           GNUNET_CONTAINER_multihashmap_iterate(find_peer_context->peer_hash, &remove_peer_count, find_peer_context);
2016           GNUNET_CONTAINER_multihashmap_destroy(find_peer_context->peer_hash);
2017           GNUNET_CONTAINER_heap_destroy(find_peer_context->peer_min_heap);
2018           GNUNET_free(find_peer_context);
2019           fprintf(stderr, "Not sending any more find peer requests.\n");
2020
2021 #if HAVE_MALICIOUS
2022           if (GNUNET_YES == malicious_after_settle)
2023           {
2024             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "calling setup_malicious_peers\n");
2025             GNUNET_SCHEDULER_add_now(&setup_malicious_peers, NULL);
2026           }
2027 #endif
2028         }
2029     }
2030 }
2031
2032
2033 /**
2034  * Set up a single find peer request for each peer in the topology.  Do this
2035  * until the settle time is over, limited by the number of outstanding requests
2036  * and the time allowed for each one!
2037  */
2038 static void
2039 schedule_find_peer_requests (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
2040 {
2041   struct FindPeerContext *find_peer_ctx = cls;
2042   struct TestFindPeer *test_find_peer;
2043   struct PeerCount *peer_count;
2044   uint32_t i;
2045   uint32_t random;
2046
2047   if (find_peer_ctx->previous_peers == 0) /* First time, go slowly */
2048     find_peer_ctx->total = 1;
2049   else if (find_peer_ctx->current_peers - find_peer_ctx->previous_peers > MAX_FIND_PEER_CUTOFF) /* Found LOTS of peers, still go slowly */
2050     find_peer_ctx->total = find_peer_ctx->last_sent - (find_peer_ctx->last_sent / 8);
2051   else
2052     find_peer_ctx->total = find_peer_ctx->last_sent * 2;
2053
2054   if (find_peer_ctx->total > max_outstanding_find_peers)
2055     find_peer_ctx->total = max_outstanding_find_peers;
2056
2057   if (find_peer_ctx->total > num_peers) /* Don't try to send more messages than we have peers! */
2058     find_peer_ctx->total = num_peers;
2059
2060   find_peer_ctx->last_sent = find_peer_ctx->total;
2061   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending %u find peer messages (goal at least %u connections)\n", find_peer_ctx->total, target_total_connections);
2062
2063   find_peer_offset = GNUNET_TIME_relative_divide(find_peer_delay, find_peer_ctx->total);
2064   for (i = 0; i < find_peer_ctx->total; i++)
2065     {
2066       test_find_peer = GNUNET_malloc(sizeof(struct TestFindPeer));
2067       if (find_peer_ctx->previous_peers == 0) /* If we haven't sent any requests yet, choose random peers */
2068         {
2069           /**
2070            * Attempt to spread find peer requests across even sections of the peer address
2071            * space.  Choose basically 1 peer in every num_peers / max_outstanding_requests
2072            * each time, then offset it by a randomish value.
2073            *
2074            * For instance, if num_peers is 100 and max_outstanding is 10, first chosen peer
2075            * will be between 0 - 10, second between 10 - 20, etc.
2076            */
2077           random = (num_peers / find_peer_ctx->total) * i;
2078           random = random + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (num_peers / find_peer_ctx->total));
2079           if (random >= num_peers)
2080             {
2081               random = random - num_peers;
2082             }
2083 #if REAL_RANDOM
2084           random = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
2085 #endif
2086           test_find_peer->daemon = GNUNET_TESTING_daemon_get(pg, random);
2087         }
2088       else /* If we have sent requests, choose peers with a low number of connections to send requests from */
2089         {
2090           peer_count = GNUNET_CONTAINER_heap_remove_root(find_peer_ctx->peer_min_heap);
2091           GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(find_peer_ctx->peer_hash, &peer_count->peer_id.hashPubKey, peer_count));
2092           test_find_peer->daemon = GNUNET_TESTING_daemon_get_by_id(pg, &peer_count->peer_id);
2093           GNUNET_assert(test_find_peer->daemon != NULL);
2094         }
2095
2096       test_find_peer->find_peer_context = find_peer_ctx;
2097       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(find_peer_offset, i), &send_find_peer_request, test_find_peer);
2098     }
2099
2100   if ((find_peer_ctx->peer_hash == NULL) && (find_peer_ctx->peer_min_heap == NULL))
2101     {
2102       find_peer_ctx->peer_hash = GNUNET_CONTAINER_multihashmap_create(num_peers);
2103       find_peer_ctx->peer_min_heap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
2104     }
2105   else
2106     {
2107       GNUNET_CONTAINER_multihashmap_iterate(find_peer_ctx->peer_hash, &remove_peer_count, find_peer_ctx);
2108       GNUNET_CONTAINER_multihashmap_destroy(find_peer_ctx->peer_hash);
2109       find_peer_ctx->peer_hash = GNUNET_CONTAINER_multihashmap_create(num_peers);
2110     }
2111
2112   GNUNET_assert(0 == GNUNET_CONTAINER_multihashmap_size(find_peer_ctx->peer_hash));
2113   GNUNET_assert(0 == GNUNET_CONTAINER_heap_get_size(find_peer_ctx->peer_min_heap));
2114
2115 }
2116
2117 /**
2118  * Convert unique ID to hash code.
2119  *
2120  * @param uid unique ID to convert
2121  * @param hash set to uid (extended with zeros)
2122  */
2123 static void
2124 hash_from_uid (uint32_t uid, GNUNET_HashCode *hash)
2125 {
2126   memset (hash, 0, sizeof (GNUNET_HashCode));
2127   *((uint32_t *) hash) = uid;
2128 }
2129
2130
2131 /**
2132  * Set up all of the put and get operations we want to do
2133  * in the current round.  Allocate data structure for each,
2134  * add to list, then schedule the actual PUT operations.
2135  */
2136 static void
2137 setup_puts_and_gets (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
2138 {
2139   int i;
2140   struct TestPutContext *test_put;
2141   struct TestGetContext *test_get;
2142   uint32_t temp_peer;
2143   GNUNET_HashCode uid_hash;
2144   int count;
2145 #if REMEMBER
2146   int remember[num_puts][num_peers];
2147   memset(&remember, 0, sizeof(int) * num_puts * num_peers);
2148 #endif
2149   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "in setup_puts_and_gets\n");
2150   known_keys = GNUNET_malloc(sizeof(GNUNET_HashCode) * num_puts);
2151   for (i = 0; i < num_puts; i++)
2152     {
2153       test_put = GNUNET_malloc(sizeof(struct TestPutContext));
2154       test_put->uid = i;
2155       GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_WEAK, &known_keys[i]);
2156       /* Set first X bits to match the chosen sybil location if we want to do the sybil attack! */
2157       if (GNUNET_YES == malicious_sybil)
2158         {
2159           memcpy(&known_keys[i], &sybil_target, sizeof(GNUNET_HashCode) / 2);
2160           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Distance between sybil location and key is %d\n", GNUNET_CRYPTO_hash_matching_bits(&known_keys[i], &sybil_target));
2161         }
2162       temp_peer = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
2163       test_put->daemon = GNUNET_TESTING_daemon_get(pg, temp_peer);
2164       /* Don't start PUTs at malicious peers! */
2165       if (malicious_bloom != NULL)
2166         {
2167           count = 0;
2168           hash_from_uid(temp_peer, &uid_hash);
2169           while ((GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(malicious_bloom, &uid_hash)) && (count < num_peers))
2170           {
2171             temp_peer = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
2172             hash_from_uid(temp_peer, &uid_hash);
2173             test_put->daemon = GNUNET_TESTING_daemon_get(pg, temp_peer);
2174             count++;
2175           }
2176           if (count == num_peers)
2177             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Couldn't find peer not in malicious bloom to select!\n");
2178         }
2179
2180       test_put->next = all_puts;
2181       all_puts = test_put;
2182     }
2183
2184   for (i = 0; i < num_gets; i++)
2185     {
2186       test_get = GNUNET_malloc(sizeof(struct TestGetContext));
2187       test_get->uid = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_puts);
2188 #if REMEMBER
2189       while (remember[test_get->uid][temp_daemon] == 1) 
2190         temp_daemon = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);  
2191       remember[test_get->uid][temp_daemon] = 1;
2192 #endif
2193       temp_peer = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
2194       test_get->daemon = GNUNET_TESTING_daemon_get(pg, temp_peer);
2195       /* Don't start GETs at malicious peers! */
2196       if (malicious_bloom != NULL)
2197         {
2198           hash_from_uid(temp_peer, &uid_hash);
2199           count = 0;
2200           while ((GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(malicious_bloom, &uid_hash)) && (count < num_peers))
2201           {
2202             temp_peer = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
2203             hash_from_uid(temp_peer, &uid_hash);
2204             test_get->daemon = GNUNET_TESTING_daemon_get(pg, temp_peer);
2205             count++;
2206           }
2207           if (count == num_peers)
2208             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Couldn't find peer not in malicious bloom to select!\n");
2209         }
2210       test_get->next = all_gets;
2211       all_gets = test_get;
2212     }
2213
2214   /*GNUNET_SCHEDULER_cancel (die_task);*/
2215   die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, num_puts * 2),
2216                                            &end_badly, "from do puts");
2217   GNUNET_SCHEDULER_add_now (&do_put, all_puts);
2218
2219 }
2220
2221 /**
2222  * Set up some all of the put and get operations we want
2223  * to do.  Allocate data structure for each, add to list,
2224  * then call actual insert functions.
2225  */
2226 static void
2227 continue_puts_and_gets (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
2228 {
2229   int i;
2230   int max;
2231   struct TopologyIteratorContext *topo_ctx;
2232   struct FindPeerContext *find_peer_context;
2233   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "In continue_puts_and_gets\n");
2234   if (dhtlog_handle != NULL)
2235     {
2236       if (settle_time >= 180 * 2)
2237         max = (settle_time / 180) - 2;
2238       else
2239         max = 1;
2240       for (i = 1; i < max; i++)
2241         {
2242           topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
2243           topo_ctx->current_iteration = i;
2244           topo_ctx->total_iterations = max;
2245           topo_ctx->peers_seen = GNUNET_CONTAINER_multihashmap_create(num_peers);
2246           //fprintf(stderr, "scheduled topology iteration in %d minutes\n", i);
2247           GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, i * 3), &capture_current_topology, topo_ctx);
2248         }
2249       topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
2250       topo_ctx->cont = &setup_puts_and_gets;
2251       topo_ctx->peers_seen = GNUNET_CONTAINER_multihashmap_create(num_peers);
2252       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "setting setup_puts_and_gets for %d seconds in the future\n", settle_time + 90);
2253       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, (settle_time + 90)), &capture_current_topology, topo_ctx);
2254     }
2255   else
2256     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, (settle_time + 90)), &setup_puts_and_gets, NULL);
2257
2258   if (dhtlog_handle != NULL)
2259     dhtlog_handle->insert_round(DHT_ROUND_NORMAL, rounds_finished);
2260
2261 #if HAVE_MALICIOUS
2262   if (GNUNET_YES != malicious_after_settle)
2263     {
2264       GNUNET_SCHEDULER_add_now(&setup_malicious_peers, NULL);
2265     }
2266 #endif
2267
2268   if (GNUNET_YES == do_find_peer)
2269     {
2270       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling find peer requests during \"settle\" time.\n");
2271       find_peer_context = GNUNET_malloc(sizeof(struct FindPeerContext));
2272       find_peer_context->count_peers_cb = &count_peers_cb;
2273       find_peer_context->endtime = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, settle_time));
2274       GNUNET_SCHEDULER_add_now(&schedule_find_peer_requests, find_peer_context);
2275     }
2276   else
2277     {
2278       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Assuming automatic DHT find peer requests.\n");
2279     }
2280 }
2281
2282 /**
2283  * Task to release DHT handles
2284  */
2285 static void
2286 malicious_disconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
2287 {
2288   struct MaliciousContext *ctx = cls;
2289   outstanding_malicious--;
2290   malicious_completed++;
2291   ctx->disconnect_task = GNUNET_SCHEDULER_NO_TASK;
2292   GNUNET_DHT_disconnect(ctx->dht_handle);
2293   ctx->dht_handle = NULL;
2294   GNUNET_free(ctx);
2295
2296   if (malicious_completed == malicious_getters + malicious_putters + malicious_droppers)
2297     {
2298       fprintf(stderr, "Finished setting all malicious peers up!\n");
2299     }
2300
2301 }
2302
2303 /**
2304  * Task to release DHT handles
2305  */
2306 static void
2307 malicious_done_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
2308 {
2309   struct MaliciousContext *ctx = cls;
2310   GNUNET_SCHEDULER_cancel(ctx->disconnect_task);
2311   GNUNET_SCHEDULER_add_now(&malicious_disconnect_task, ctx);
2312 }
2313
2314 /**
2315  * Set up some data, and call API PUT function
2316  */
2317 static void
2318 set_malicious (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
2319 {
2320   struct MaliciousContext *ctx = cls;
2321
2322   if (outstanding_malicious > DEFAULT_MAX_OUTSTANDING_GETS)
2323     {
2324       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100), &set_malicious, ctx);
2325       return;
2326     }
2327
2328   if (ctx->dht_handle == NULL)
2329     {
2330       ctx->dht_handle = GNUNET_DHT_connect(ctx->daemon->cfg, 1);
2331       outstanding_malicious++;
2332     }
2333
2334   GNUNET_assert(ctx->dht_handle != NULL);
2335
2336
2337 #if VERBOSE > 1
2338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Setting peer %s malicious type %d\n",
2339                 ctx->daemon->shortname, ctx->malicious_type);
2340 #endif
2341
2342   switch (ctx->malicious_type)
2343   {
2344   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
2345     GNUNET_DHT_set_malicious_getter(ctx->dht_handle, malicious_get_frequency);
2346     GNUNET_SCHEDULER_add_now (&malicious_done_task, ctx);
2347     break;
2348   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
2349     GNUNET_DHT_set_malicious_putter(ctx->dht_handle, malicious_put_frequency);
2350     GNUNET_SCHEDULER_add_now (&malicious_done_task, ctx);
2351     break;
2352   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
2353     GNUNET_DHT_set_malicious_dropper(ctx->dht_handle);
2354     GNUNET_SCHEDULER_add_now (&malicious_done_task, ctx);
2355     break;
2356   default:
2357     break;
2358   }
2359
2360   ctx->disconnect_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_FOREVER_REL,
2361                                                       &malicious_disconnect_task, ctx);
2362 }
2363
2364
2365 #if HAVE_MALICIOUS
2366 /**
2367  * Choose the next peer from the peer group to set as malicious.
2368  * If we are doing a sybil attack, find the nearest peer to the
2369  * sybil location that has not already been set malicious.  Otherwise
2370  * just choose a random not already chosen peer.
2371  *
2372  * @param pg the peer group
2373  * @param bloom the bloomfilter which contains all peer already
2374  *        chosen to be malicious
2375  */
2376 static uint32_t
2377 choose_next_malicious (struct GNUNET_TESTING_PeerGroup *pg, struct GNUNET_CONTAINER_BloomFilter *bloom)
2378 {
2379   int i;
2380   int nearest;
2381   int bits_match;
2382   int curr_distance;
2383   int count;
2384   struct GNUNET_TESTING_Daemon *temp_daemon;
2385   GNUNET_HashCode uid_hash;
2386
2387   curr_distance = 0;
2388   nearest = 0;
2389   GNUNET_assert (bloom != NULL);
2390
2391   if (GNUNET_YES == malicious_sybil)
2392     {
2393       for (i = 0; i < num_peers; i++)
2394         {
2395           temp_daemon = GNUNET_TESTING_daemon_get(pg, i);
2396           hash_from_uid(i, &uid_hash);
2397           /* Check if this peer matches the bloomfilter */
2398           if ((GNUNET_NO == GNUNET_TESTING_daemon_running(temp_daemon)) || (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &uid_hash)))
2399             continue;
2400
2401           bits_match = GNUNET_CRYPTO_hash_matching_bits (&temp_daemon->id.hashPubKey, &sybil_target);
2402           if (bits_match >= curr_distance)
2403             {
2404               GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Found nearer peer %s to %s, old matching bits %d, new %d\n", GNUNET_i2s(&temp_daemon->id), GNUNET_h2s(&sybil_target), curr_distance, bits_match);
2405               nearest = i;
2406               curr_distance = bits_match;
2407             }
2408         }
2409     }
2410   else
2411     {
2412       nearest = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
2413       hash_from_uid(nearest, &uid_hash);
2414       while ((GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &uid_hash)) && (count < num_peers))
2415         {
2416           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Peer %d already in bloom (tried %d times)\n", nearest, count);
2417           nearest = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers);
2418           hash_from_uid(nearest, &uid_hash);
2419           count++;
2420         }
2421       if (count == num_peers)
2422         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Tried %d times to find a peer, selecting %d at random!!\n", count, nearest);
2423     }
2424
2425   return nearest;
2426 }
2427
2428 /**
2429  * Select randomly from set of known peers,
2430  * set the desired number of peers to the
2431  * proper malicious types.
2432  */
2433 static void
2434 setup_malicious_peers (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
2435 {
2436   struct MaliciousContext *ctx;
2437   int i;
2438   uint32_t temp_daemon;
2439   GNUNET_HashCode uid_hash;
2440
2441   for (i = 0; i < malicious_getters; i++)
2442     {
2443       ctx = GNUNET_malloc(sizeof(struct MaliciousContext));
2444       temp_daemon = choose_next_malicious(pg, malicious_bloom);
2445       ctx->daemon = GNUNET_TESTING_daemon_get(pg, temp_daemon);
2446       hash_from_uid(temp_daemon, &uid_hash);
2447       GNUNET_CONTAINER_bloomfilter_add(malicious_bloom, &uid_hash);
2448       ctx->malicious_type = GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET;
2449       GNUNET_SCHEDULER_add_now (&set_malicious, ctx);
2450
2451     }
2452
2453   for (i = 0; i < malicious_putters; i++)
2454     {
2455       ctx = GNUNET_malloc(sizeof(struct MaliciousContext));
2456       temp_daemon = choose_next_malicious(pg, malicious_bloom);
2457       ctx->daemon = GNUNET_TESTING_daemon_get(pg, temp_daemon);
2458       hash_from_uid(temp_daemon, &uid_hash);
2459       GNUNET_CONTAINER_bloomfilter_add(malicious_bloom, &uid_hash);
2460       ctx->malicious_type = GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT;
2461       GNUNET_SCHEDULER_add_now (&set_malicious, ctx);
2462
2463     }
2464
2465   for (i = 0; i < malicious_droppers; i++)
2466     {
2467       ctx = GNUNET_malloc(sizeof(struct MaliciousContext));
2468       temp_daemon = choose_next_malicious(pg, malicious_bloom);
2469       ctx->daemon = GNUNET_TESTING_daemon_get(pg, temp_daemon);
2470       hash_from_uid(temp_daemon, &uid_hash);
2471       GNUNET_CONTAINER_bloomfilter_add(malicious_bloom, &uid_hash);
2472       ctx->malicious_type = GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP;
2473       GNUNET_SCHEDULER_add_now (&set_malicious, ctx);
2474     }
2475 }
2476 #endif
2477
2478 /**
2479  * This function is called whenever a connection attempt is finished between two of
2480  * the started peers (started with GNUNET_TESTING_daemons_start).  The total
2481  * number of times this function is called should equal the number returned
2482  * from the GNUNET_TESTING_connect_topology call.
2483  *
2484  * The emsg variable is NULL on success (peers connected), and non-NULL on
2485  * failure (peers failed to connect).
2486  */
2487 static void
2488 topology_callback (void *cls,
2489                    const struct GNUNET_PeerIdentity *first,
2490                    const struct GNUNET_PeerIdentity *second,
2491                    uint32_t distance,
2492                    const struct GNUNET_CONFIGURATION_Handle *first_cfg,
2493                    const struct GNUNET_CONFIGURATION_Handle *second_cfg,
2494                    struct GNUNET_TESTING_Daemon *first_daemon,
2495                    struct GNUNET_TESTING_Daemon *second_daemon,
2496                    const char *emsg)
2497 {
2498   struct TopologyIteratorContext *topo_ctx;
2499   if (emsg == NULL)
2500     {
2501       total_connections++;
2502 #if VERBOSE > 1
2503       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connected peer %s to peer %s, distance %u\n",
2504                  first_daemon->shortname,
2505                  second_daemon->shortname,
2506                  distance);
2507 #endif
2508     }
2509   else
2510     {
2511       failed_connections++;
2512       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Failed to connect peer %s to peer %s with error :\n%s\n",
2513                   first_daemon->shortname,
2514                   second_daemon->shortname, emsg);
2515 #if VERBOSE
2516       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failed to connect peer %s to peer %s with error :\n%s\n",
2517                   first_daemon->shortname,
2518                   second_daemon->shortname, emsg);
2519 #endif
2520     }
2521
2522   GNUNET_assert(peer_connect_meter != NULL);
2523   if (GNUNET_YES == update_meter(peer_connect_meter))
2524     {
2525 #if VERBOSE
2526       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2527                   "Created %d total connections, which is our target number!  Starting next phase of testing.\n",
2528                   total_connections);
2529 #endif
2530       if (failed_connections > 0)
2531         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "While connecting, had %u failed connections.\n", failed_connections);
2532       if (dhtlog_handle != NULL)
2533         {
2534           dhtlog_handle->update_connections (total_connections);
2535           dhtlog_handle->insert_topology(expected_connections);
2536         }
2537
2538       GNUNET_SCHEDULER_cancel (die_task);
2539
2540       if ((dhtlog_handle != NULL) && (settle_time > 0))
2541         {
2542           topo_ctx = GNUNET_malloc(sizeof(struct TopologyIteratorContext));
2543           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Setting continue gets and puts as topo_cont\n");
2544           topo_ctx->cont = &continue_puts_and_gets;
2545           topo_ctx->peers_seen = GNUNET_CONTAINER_multihashmap_create(num_peers);
2546           GNUNET_SCHEDULER_add_now(&capture_current_topology, topo_ctx);
2547         }
2548       else
2549         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "For some reason, NOT scheduling final topology capture (settle_time %d, dhtlog_handle %s)!\n", settle_time, dhtlog_handle);
2550     }
2551   else if (total_connections + failed_connections == expected_connections)
2552     {
2553       GNUNET_SCHEDULER_cancel (die_task);
2554       die_task = GNUNET_SCHEDULER_add_now (&end_badly, "from topology_callback (too many failed connections)");
2555     }
2556 }
2557
2558 static void
2559 peers_started_callback (void *cls,
2560        const struct GNUNET_PeerIdentity *id,
2561        const struct GNUNET_CONFIGURATION_Handle *cfg,
2562        struct GNUNET_TESTING_Daemon *d, const char *emsg)
2563 {
2564   if (emsg != NULL)
2565     {
2566       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failed to start daemon with error: `%s'\n",
2567                   emsg);
2568       return;
2569     }
2570   GNUNET_assert (id != NULL);
2571
2572 #if VERBOSE > 1
2573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Started daemon %llu out of %llu\n",
2574               (num_peers - peers_left) + 1, num_peers);
2575 #endif
2576
2577   peers_left--;
2578
2579   if (GNUNET_YES == update_meter(peer_start_meter))
2580     {
2581 #if VERBOSE
2582       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2583                   "All %d daemons started, now connecting peers!\n",
2584                   num_peers);
2585 #endif
2586       GNUNET_SCHEDULER_cancel (die_task);
2587
2588       expected_connections = UINT_MAX;
2589       if ((pg != NULL) && (peers_left == 0))
2590         {
2591           expected_connections = GNUNET_TESTING_connect_topology (pg, connect_topology, connect_topology_option, connect_topology_option_modifier, NULL, NULL);
2592
2593           peer_connect_meter = create_meter(expected_connections, "Peer connection ", GNUNET_YES);
2594           fprintf(stderr, "Have %d expected connections\n", expected_connections);
2595         }
2596
2597       if (expected_connections == GNUNET_SYSERR)
2598         {
2599           die_task = GNUNET_SCHEDULER_add_now (&end_badly, "from connect topology (bad return)");
2600         }
2601
2602       die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, DEFAULT_CONNECT_TIMEOUT * expected_connections),
2603                                                &end_badly, "from connect topology (timeout)");
2604
2605       ok = 0;
2606     }
2607 }
2608
2609 static void
2610 create_topology ()
2611 {
2612   peers_left = num_peers; /* Reset counter */
2613   if (GNUNET_TESTING_create_topology (pg, topology, blacklist_topology, blacklist_transports) != GNUNET_SYSERR)
2614     {
2615 #if VERBOSE
2616       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2617                   "Topology set up, now starting peers!\n");
2618 #endif
2619       GNUNET_TESTING_daemons_continue_startup(pg);
2620     }
2621   else
2622     {
2623       GNUNET_SCHEDULER_cancel (die_task);
2624       die_task = GNUNET_SCHEDULER_add_now (&end_badly, "from create topology (bad return)");
2625     }
2626   GNUNET_free_non_null(blacklist_transports);
2627   GNUNET_SCHEDULER_cancel (die_task);
2628   die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(seconds_per_peer_start, num_peers),
2629                                            &end_badly, "from continue startup (timeout)");
2630 }
2631
2632 /**
2633  * Callback indicating that the hostkey was created for a peer.
2634  *
2635  * @param cls NULL
2636  * @param id the peer identity
2637  * @param d the daemon handle (pretty useless at this point, remove?)
2638  * @param emsg non-null on failure
2639  */
2640 static void 
2641 hostkey_callback (void *cls,
2642                   const struct GNUNET_PeerIdentity *id,
2643                   struct GNUNET_TESTING_Daemon *d,
2644                   const char *emsg)
2645 {
2646   if (emsg != NULL)
2647     {
2648       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Hostkey callback received error: %s\n", emsg);
2649     }
2650
2651 #if VERBOSE > 1
2652     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2653                 "Hostkey (%d/%d) created for peer `%s'\n",
2654                 num_peers - peers_left, num_peers, GNUNET_i2s(id));
2655 #endif
2656
2657     peers_left--;
2658     if (GNUNET_YES == update_meter(hostkey_meter))
2659       {
2660 #if VERBOSE
2661         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2662                     "All %d hostkeys created, now creating topology!\n",
2663                     num_peers);
2664 #endif
2665         GNUNET_SCHEDULER_cancel (die_task);
2666         /* Set up task in case topology creation doesn't finish
2667          * within a reasonable amount of time */
2668         die_task = GNUNET_SCHEDULER_add_delayed (DEFAULT_TOPOLOGY_TIMEOUT,
2669                                                  &end_badly, "from create_topology");
2670         GNUNET_SCHEDULER_add_now(&create_topology, NULL);
2671         ok = 0;
2672       }
2673 }
2674
2675
2676 static void
2677 run (void *cls,
2678      char *const *args,
2679      const char *cfgfile, const struct GNUNET_CONFIGURATION_Handle *cfg)
2680 {
2681   struct stat frstat;
2682   struct GNUNET_DHTLOG_TrialInfo trial_info;
2683   struct GNUNET_TESTING_Host *hosts;
2684   struct GNUNET_TESTING_Host *temphost;
2685   struct GNUNET_TESTING_Host *tempnext;
2686   char *topology_str;
2687   char *connect_topology_str;
2688   char *blacklist_topology_str;
2689   char *connect_topology_option_str;
2690   char *connect_topology_option_modifier_string;
2691   char *trialmessage;
2692   char *topology_percentage_str;
2693   float topology_percentage;
2694   char *topology_probability_str;
2695   char *hostfile;
2696   float topology_probability;
2697   unsigned long long temp_config_number;
2698   unsigned long long trial_to_run;
2699   int stop_closest;
2700   int stop_found;
2701   int strict_kademlia;
2702   char *buf;
2703   char *data;
2704   char *churn_data;
2705   char *churn_filename;
2706   int count;
2707   int ret;
2708   int line_number;
2709
2710
2711   config = cfg;
2712   rounds_finished = 0;
2713   memset(&trial_info, 0, sizeof(struct GNUNET_DHTLOG_TrialInfo));
2714   /* Get path from configuration file */
2715   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_string(cfg, "paths", "servicehome", &test_directory))
2716     {
2717       ok = 404;
2718       return;
2719     }
2720
2721   /* Get number of peers to start from configuration */
2722   if (GNUNET_SYSERR ==
2723       GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "num_peers",
2724                                              &num_peers))
2725     {
2726       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2727                   "Number of peers must be specified in section %s option %s\n", "TESTING", "NUM_PEERS");
2728     }
2729   GNUNET_assert(num_peers > 0 && num_peers < ULONG_MAX);
2730
2731   /**
2732    * Get DHT specific testing options.
2733    */
2734   if ((GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging")) ||
2735       (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging_extended")))
2736     {
2737       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
2738       if (dhtlog_handle == NULL)
2739         {
2740           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2741                       "Could not connect to mysql server for logging, will NOT log dht operations!");
2742           ok = 3306;
2743           return;
2744         }
2745     }
2746
2747   stop_closest = GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht", "stop_on_closest");
2748   if (stop_closest == GNUNET_SYSERR)
2749     stop_closest = GNUNET_NO;
2750
2751   stop_found = GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht", "stop_found");
2752   if (stop_found == GNUNET_SYSERR)
2753     stop_found = GNUNET_NO;
2754
2755   strict_kademlia = GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht", "strict_kademlia");
2756   if (strict_kademlia == GNUNET_SYSERR)
2757     strict_kademlia = GNUNET_NO;
2758
2759   if (GNUNET_OK !=
2760       GNUNET_CONFIGURATION_get_value_string (cfg, "dht_testing", "comment",
2761                                              &trialmessage))
2762     trialmessage = NULL;
2763
2764   churn_data = NULL;
2765   /** Check for a churn file to do churny simulation */
2766   if (GNUNET_OK ==
2767       GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "churn_file",
2768                                             &churn_filename))
2769     {
2770       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Reading churn data from %s\n", churn_filename);
2771       if (GNUNET_OK != GNUNET_DISK_file_test (churn_filename))
2772         {
2773           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Error reading churn file!\n");
2774           GNUNET_free_non_null(trialmessage);
2775           GNUNET_free(churn_filename);
2776           return;
2777         }
2778       if ((0 != STAT (churn_filename, &frstat)) || (frstat.st_size == 0))
2779         {
2780           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2781                       "Could not open file specified for churn data, ending test!");
2782           ok = 1119;
2783           GNUNET_free_non_null(trialmessage);
2784           GNUNET_free(churn_filename);
2785           return;
2786         }
2787
2788       churn_data = GNUNET_malloc_large (frstat.st_size);
2789       GNUNET_assert(churn_data != NULL);
2790       if (frstat.st_size !=
2791           GNUNET_DISK_fn_read (churn_filename, churn_data, frstat.st_size))
2792         {
2793           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2794                     "Could not read file %s specified for churn, ending test!", churn_filename);
2795           GNUNET_free (churn_filename);
2796           GNUNET_free (churn_data);
2797           GNUNET_free_non_null(trialmessage);
2798           return;
2799         }
2800
2801       GNUNET_free_non_null(churn_filename);
2802
2803       buf = churn_data;
2804       count = 0;
2805       /* Read the first line */
2806       while (count < frstat.st_size)
2807         {
2808           count++;
2809           if (((churn_data[count] == '\n')) && (buf != &churn_data[count]))
2810             {
2811               churn_data[count] = '\0';
2812               if (1 != sscanf(buf, "%u", &churn_rounds))
2813                 {
2814                   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read number of rounds from churn file, ending test!\n");
2815                   ret = 4200;
2816                   GNUNET_free_non_null(trialmessage);
2817                   GNUNET_free_non_null(churn_data);
2818                   return;
2819                 }
2820               GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Read %u rounds from churn file\n", churn_rounds);
2821               buf = &churn_data[count + 1];
2822               churn_array = GNUNET_malloc(sizeof(unsigned int) * churn_rounds);
2823               break; /* Done with this part */
2824             }
2825         }
2826
2827       if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, "dht_testing", "churns_per_round", &churns_per_round))
2828         {
2829           churns_per_round = (unsigned long long)churn_rounds;
2830         }
2831
2832       line_number = 0;
2833       while ((count < frstat.st_size) && (line_number < churn_rounds))
2834         {
2835           count++;
2836           if (((churn_data[count] == '\n')) && (buf != &churn_data[count]))
2837             {
2838               churn_data[count] = '\0';
2839
2840               ret = sscanf(buf, "%u", &churn_array[line_number]);
2841               if (1 == ret)
2842                 {
2843                   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Read %u peers in round %u\n", churn_array[line_number], line_number);
2844                   line_number++;
2845                 }
2846               else
2847                 {
2848                   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Error reading line `%s' in hostfile\n", buf);
2849                   buf = &churn_data[count + 1];
2850                   continue;
2851                 }
2852               buf = &churn_data[count + 1];
2853             }
2854           else if (churn_data[count] == '\n') /* Blank line */
2855             buf = &churn_data[count + 1];
2856         }
2857     }
2858   GNUNET_free_non_null(churn_data);
2859
2860   /* Check for a hostfile containing user@host:port triples */
2861   if (GNUNET_OK !=
2862       GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "hostfile",
2863                                              &hostfile))
2864     hostfile = NULL;
2865
2866   hosts = NULL;
2867   temphost = NULL;
2868   data = NULL;
2869   if (hostfile != NULL)
2870     {
2871       if (GNUNET_OK != GNUNET_DISK_file_test (hostfile))
2872           GNUNET_DISK_fn_write (hostfile, NULL, 0, GNUNET_DISK_PERM_USER_READ
2873             | GNUNET_DISK_PERM_USER_WRITE);
2874       if ((0 != STAT (hostfile, &frstat)) || (frstat.st_size == 0))
2875         {
2876           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2877                       "Could not open file specified for host list, ending test!");
2878           ok = 1119;
2879           GNUNET_free_non_null(trialmessage);
2880           GNUNET_free(hostfile);
2881           return;
2882         }
2883
2884     data = GNUNET_malloc_large (frstat.st_size);
2885     GNUNET_assert(data != NULL);
2886     if (frstat.st_size !=
2887         GNUNET_DISK_fn_read (hostfile, data, frstat.st_size))
2888       {
2889         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2890                   "Could not read file %s specified for host list, ending test!", hostfile);
2891         GNUNET_free (hostfile);
2892         GNUNET_free (data);
2893         GNUNET_free_non_null(trialmessage);
2894         return;
2895       }
2896
2897     GNUNET_free_non_null(hostfile);
2898
2899     buf = data;
2900     count = 0;
2901     while (count < frstat.st_size - 1)
2902       {
2903         count++;
2904         /* if (((data[count] == '\n') || (data[count] == '\0')) && (buf != &data[count]))*/
2905         if (((data[count] == '\n')) && (buf != &data[count]))
2906           {
2907             data[count] = '\0';
2908             temphost = GNUNET_malloc(sizeof(struct GNUNET_TESTING_Host));
2909             ret = sscanf(buf, "%a[a-zA-Z0-9]@%a[a-zA-Z0-9.]:%hd", &temphost->username, &temphost->hostname, &temphost->port);
2910             if (3 == ret)
2911               {
2912                 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Successfully read host %s, port %d and user %s from file\n", temphost->hostname, temphost->port, temphost->username);
2913               }
2914             else
2915               {
2916                 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Error reading line `%s' in hostfile\n", buf);
2917                 GNUNET_free(temphost);
2918                 buf = &data[count + 1];
2919                 continue;
2920               }
2921             /* temphost->hostname = buf; */
2922             temphost->next = hosts;
2923             hosts = temphost;
2924             buf = &data[count + 1];
2925           }
2926         else if ((data[count] == '\n') || (data[count] == '\0'))
2927           buf = &data[count + 1];
2928       }
2929     }
2930   GNUNET_free_non_null(data);
2931   if (GNUNET_OK !=
2932           GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "malicious_getters",
2933                                                  &malicious_getters))
2934     malicious_getters = 0;
2935
2936   if (GNUNET_OK !=
2937           GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "malicious_putters",
2938                                                  &malicious_putters))
2939     malicious_putters = 0;
2940
2941   if (GNUNET_OK !=
2942             GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "malicious_droppers",
2943                                                    &malicious_droppers))
2944     malicious_droppers = 0;
2945
2946   if (GNUNET_OK !=
2947       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "settle_time",
2948                                                  &settle_time))
2949     settle_time = 0;
2950
2951   if (GNUNET_SYSERR ==
2952       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "num_puts",
2953                                              &num_puts))
2954     num_puts = num_peers;
2955
2956   if (GNUNET_SYSERR ==
2957       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "put_replication",
2958                                              &put_replication))
2959     put_replication = DEFAULT_PUT_REPLICATION;
2960
2961   if (GNUNET_SYSERR ==
2962       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "num_gets",
2963                                              &num_gets))
2964     num_gets = num_peers;
2965
2966   if (GNUNET_SYSERR ==
2967         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "get_replication",
2968                                                &get_replication))
2969       get_replication = DEFAULT_GET_REPLICATION;
2970
2971   if (GNUNET_OK ==
2972         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "find_peer_delay",
2973                                                &temp_config_number))
2974     find_peer_delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
2975   else
2976     find_peer_delay = DEFAULT_FIND_PEER_DELAY;
2977
2978   if (GNUNET_OK ==
2979         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "concurrent_find_peers",
2980                                                &temp_config_number))
2981     max_outstanding_find_peers = temp_config_number;
2982   else
2983     max_outstanding_find_peers = DEFAULT_MAX_OUTSTANDING_FIND_PEERS;
2984
2985   if (GNUNET_OK ==
2986         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "get_timeout",
2987                                                &temp_config_number))
2988     get_timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
2989   else
2990     get_timeout = DEFAULT_GET_TIMEOUT;
2991
2992   if (GNUNET_OK ==
2993         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "concurrent_puts",
2994                                                &temp_config_number))
2995     max_outstanding_puts = temp_config_number;
2996   else
2997     max_outstanding_puts = DEFAULT_MAX_OUTSTANDING_PUTS;
2998
2999   if (GNUNET_OK ==
3000         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "concurrent_gets",
3001                                                &temp_config_number))
3002     max_outstanding_gets = temp_config_number;
3003   else
3004     max_outstanding_gets = DEFAULT_MAX_OUTSTANDING_GETS;
3005
3006   if (GNUNET_OK ==
3007         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "timeout",
3008                                                &temp_config_number))
3009     all_get_timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
3010   else
3011     all_get_timeout.rel_value = get_timeout.rel_value * num_gets;
3012
3013   if (GNUNET_OK ==
3014         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "get_delay",
3015                                                &temp_config_number))
3016     get_delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
3017   else
3018     get_delay = DEFAULT_GET_DELAY;
3019
3020   if (GNUNET_OK ==
3021         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "put_delay",
3022                                                &temp_config_number))
3023     put_delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
3024   else
3025     put_delay = DEFAULT_PUT_DELAY;
3026
3027   if (GNUNET_OK ==
3028       GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "peer_start_timeout",
3029                                              &temp_config_number))
3030     seconds_per_peer_start = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
3031   else
3032     seconds_per_peer_start = DEFAULT_SECONDS_PER_PEER_START;
3033
3034   if (GNUNET_OK ==
3035         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "data_size",
3036                                                &temp_config_number))
3037     test_data_size = temp_config_number;
3038   else
3039     test_data_size = DEFAULT_TEST_DATA_SIZE;
3040
3041   /**
3042    * Get testing related options.
3043    */
3044   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "DHT_TESTING", "REPLICATE_SAME"))
3045     replicate_same = GNUNET_YES;
3046
3047   /**
3048    * Get testing related options.
3049    */
3050   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "DHT_TESTING", "GET_FROM_SAME"))
3051     get_from_same = GNUNET_YES;
3052
3053
3054   if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_time (cfg, "DHT_TESTING",
3055                                                         "MALICIOUS_GET_FREQUENCY",
3056                                                         &malicious_get_frequency))
3057     malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3058
3059
3060   if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_time (cfg, "DHT_TESTING",
3061                                                         "MALICIOUS_PUT_FREQUENCY",
3062                                                         &malicious_put_frequency))
3063     malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3064
3065   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "DHT_TESTING", "MALICIOUS_AFTER_SETTLE"))
3066     malicious_after_settle = GNUNET_YES;
3067
3068   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "DHT_TESTING", "MALICIOUS_SYBIL"))
3069     {
3070       /* Set up the malicious target at random for this round */
3071       GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_WEAK, &sybil_target);
3072       malicious_sybil = GNUNET_YES;
3073     }
3074
3075   /* Create the bloomfilter for choosing which peers to set malicious */
3076   malicious_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3077
3078   /* The normal behavior of the DHT is to do find peer requests
3079    * on its own.  Only if this is explicitly turned off should
3080    * the testing driver issue find peer requests (even though
3081    * this is likely the default when testing).
3082    */
3083   if (GNUNET_NO ==
3084         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3085                                              "do_find_peer"))
3086     {
3087       do_find_peer = GNUNET_YES;
3088     }
3089
3090   if (GNUNET_YES ==
3091         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3092                                              "republish"))
3093     {
3094       in_dht_replication = GNUNET_YES;
3095     }
3096
3097   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT_TESTING",
3098                                                           "TRIAL_TO_RUN",
3099                                                           &trial_to_run))
3100     {
3101       trial_to_run = 0;
3102     }
3103
3104   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT_TESTING",
3105                                                           "FIND_PEER_DELAY",
3106                                                           &temp_config_number))
3107     {
3108       find_peer_delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, temp_config_number);
3109     }
3110   else
3111     find_peer_delay = DEFAULT_FIND_PEER_DELAY;
3112
3113   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number(cfg, "DHT_TESTING", "ROUND_DELAY", &round_delay))
3114     round_delay = 0;
3115
3116   if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT_TESTING",
3117                                                             "OUTSTANDING_FIND_PEERS",
3118                                                             &max_outstanding_find_peers))
3119       max_outstanding_find_peers = DEFAULT_MAX_OUTSTANDING_FIND_PEERS;
3120
3121   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht", "strict_kademlia"))
3122     max_outstanding_find_peers = max_outstanding_find_peers * 1;
3123
3124   find_peer_offset = GNUNET_TIME_relative_divide (find_peer_delay, max_outstanding_find_peers);
3125
3126   if (GNUNET_SYSERR ==
3127         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "num_rounds",
3128                                                &total_rounds))
3129     {
3130       total_rounds = 1;
3131     }
3132
3133   if ((GNUNET_SYSERR ==
3134         GNUNET_CONFIGURATION_get_value_number (cfg, "dht_testing", "target_total_connections",
3135                                                &target_total_connections)) ||
3136                                                (target_total_connections == 0))
3137     {
3138       target_total_connections = connection_estimate(num_peers, DEFAULT_BUCKET_SIZE);
3139     }
3140
3141   topology_str = NULL;
3142   if ((GNUNET_YES ==
3143       GNUNET_CONFIGURATION_get_value_string(cfg, "testing", "topology",
3144                                             &topology_str)) && (GNUNET_NO == GNUNET_TESTING_topology_get(&topology, topology_str)))
3145     {
3146       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3147                   "Invalid topology `%s' given for section %s option %s\n", topology_str, "TESTING", "TOPOLOGY");
3148       topology = GNUNET_TESTING_TOPOLOGY_CLIQUE; /* Defaults to NONE, so set better default here */
3149     }
3150
3151   if (GNUNET_OK !=
3152       GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "percentage",
3153                                                  &topology_percentage_str))
3154     topology_percentage = 0.5;
3155   else
3156     {
3157       topology_percentage = atof (topology_percentage_str);
3158       GNUNET_free(topology_percentage_str);
3159     }
3160
3161   if (GNUNET_OK !=
3162       GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "probability",
3163                                                  &topology_probability_str))
3164     topology_probability = 0.5;
3165   else
3166     {
3167      topology_probability = atof (topology_probability_str);
3168      GNUNET_free(topology_probability_str);
3169     }
3170
3171   if ((GNUNET_YES ==
3172       GNUNET_CONFIGURATION_get_value_string(cfg, "testing", "connect_topology",
3173                                             &connect_topology_str)) && (GNUNET_NO == GNUNET_TESTING_topology_get(&connect_topology, connect_topology_str)))
3174     {
3175       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3176                   "Invalid connect topology `%s' given for section %s option %s\n", connect_topology_str, "TESTING", "CONNECT_TOPOLOGY");
3177     }
3178   GNUNET_free_non_null(connect_topology_str);
3179
3180   if ((GNUNET_YES ==
3181       GNUNET_CONFIGURATION_get_value_string(cfg, "testing", "connect_topology_option",
3182                                             &connect_topology_option_str)) && (GNUNET_NO == GNUNET_TESTING_topology_option_get(&connect_topology_option, connect_topology_option_str)))
3183     {
3184       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3185                   "Invalid connect topology option `%s' given for section %s option %s\n", connect_topology_option_str, "TESTING", "CONNECT_TOPOLOGY_OPTION");
3186       connect_topology_option = GNUNET_TESTING_TOPOLOGY_OPTION_ALL; /* Defaults to NONE, set to ALL */
3187     }
3188   GNUNET_free_non_null(connect_topology_option_str);
3189
3190   if (GNUNET_YES ==
3191         GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "connect_topology_option_modifier",
3192                                                &connect_topology_option_modifier_string))
3193     {
3194       if (sscanf(connect_topology_option_modifier_string, "%lf", &connect_topology_option_modifier) != 1)
3195       {
3196         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3197         _("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
3198         connect_topology_option_modifier_string,
3199         "connect_topology_option_modifier",
3200         "TESTING");
3201       }
3202       GNUNET_free (connect_topology_option_modifier_string);
3203     }
3204
3205   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "blacklist_transports",
3206                                          &blacklist_transports))
3207     blacklist_transports = NULL;
3208
3209   if ((GNUNET_YES ==
3210       GNUNET_CONFIGURATION_get_value_string(cfg, "testing", "blacklist_topology",
3211                                             &blacklist_topology_str)) &&
3212       (GNUNET_NO == GNUNET_TESTING_topology_get(&blacklist_topology, blacklist_topology_str)))
3213     {
3214       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3215                   "Invalid topology `%s' given for section %s option %s\n", topology_str, "TESTING", "BLACKLIST_TOPOLOGY");
3216     }
3217   GNUNET_free_non_null(topology_str);
3218   GNUNET_free_non_null(blacklist_topology_str);
3219
3220   /* Set peers_left so we know when all peers started */
3221   peers_left = num_peers;
3222
3223
3224   /* Set up a task to end testing if peer start fails */
3225   die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(seconds_per_peer_start, num_peers),
3226                                            &end_badly, "didn't generate all hostkeys within allowed startup time!");
3227
3228   if (dhtlog_handle == NULL)
3229     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3230                 "dhtlog_handle is NULL!");
3231
3232   trial_info.other_identifier = (unsigned int)trial_to_run;
3233   trial_info.num_nodes = peers_left;
3234   trial_info.topology = topology;
3235   trial_info.blacklist_topology = blacklist_topology;
3236   trial_info.connect_topology = connect_topology;
3237   trial_info.connect_topology_option = connect_topology_option;
3238   trial_info.connect_topology_option_modifier = connect_topology_option_modifier;
3239   trial_info.topology_percentage = topology_percentage;
3240   trial_info.topology_probability = topology_probability;
3241   trial_info.puts = num_puts;
3242   trial_info.gets = num_gets;
3243   trial_info.concurrent = max_outstanding_gets;
3244   trial_info.settle_time = settle_time;
3245   trial_info.num_rounds = total_rounds;
3246   trial_info.malicious_getters = malicious_getters;
3247   trial_info.malicious_putters = malicious_putters;
3248   trial_info.malicious_droppers = malicious_droppers;
3249   trial_info.malicious_get_frequency = malicious_get_frequency.rel_value;
3250   trial_info.malicious_put_frequency = malicious_put_frequency.rel_value;
3251   trial_info.stop_closest = stop_closest;
3252   trial_info.stop_found = stop_found;
3253   trial_info.strict_kademlia = strict_kademlia;
3254
3255   if (trialmessage != NULL)
3256     trial_info.message = trialmessage;
3257   else
3258     trial_info.message = "";
3259
3260   if (dhtlog_handle != NULL)
3261     dhtlog_handle->insert_trial(&trial_info);
3262
3263   GNUNET_free_non_null(trialmessage);
3264
3265   hostkey_meter = create_meter(peers_left, "Hostkeys created ", GNUNET_YES);
3266   peer_start_meter = create_meter(peers_left, "Peers started ", GNUNET_YES);
3267
3268   put_meter = create_meter(num_puts, "Puts completed ", GNUNET_YES);
3269   get_meter = create_meter(num_gets, "Gets completed ", GNUNET_YES);
3270   pg = GNUNET_TESTING_daemons_start (cfg,
3271                                      peers_left,
3272                                      GNUNET_TIME_relative_multiply(seconds_per_peer_start, num_peers),
3273                                      &hostkey_callback, NULL,
3274                                      &peers_started_callback, NULL,
3275                                      &topology_callback, NULL,
3276                                      hosts);
3277   temphost = hosts;
3278   while (temphost != NULL)
3279     {
3280       tempnext = temphost->next;
3281       GNUNET_free (temphost->username);
3282       GNUNET_free (temphost->hostname);
3283       GNUNET_free (temphost);
3284       temphost = tempnext;
3285     }
3286 }
3287
3288 int
3289 main (int argc, char *argv[])
3290 {
3291   int ret;
3292   struct GNUNET_GETOPT_CommandLineOption options[] = {
3293       GNUNET_GETOPT_OPTION_END
3294     };
3295
3296   ret = GNUNET_PROGRAM_run (argc,
3297                             argv, "gnunet-dht-driver", "nohelp",
3298                             options, &run, &ok);
3299
3300   if (malicious_bloom != NULL)
3301     GNUNET_CONTAINER_bloomfilter_free (malicious_bloom);
3302
3303   if (ret != GNUNET_OK)
3304     {
3305       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "`gnunet-dht-driver': Failed with error code %d\n", ret);
3306     }
3307
3308   /**
3309    * Need to remove base directory, subdirectories taken care
3310    * of by the testing framework.
3311    */
3312   if (GNUNET_DISK_directory_remove (test_directory) != GNUNET_OK)
3313     {
3314       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to remove testing directory %s\n", test_directory);
3315     }
3316   return ret;
3317 }
3318
3319 /* end of gnunet-dht-driver.c */