- debug info
[oweals/gnunet.git] / src / dht / gnunet-service-dht_neighbours.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2013 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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file dht/gnunet-service-dht_neighbours.c
23  * @brief GNUnet DHT service's bucket and neighbour management code
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_block_lib.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_nse_service.h"
34 #include "gnunet_ats_service.h"
35 #include "gnunet_core_service.h"
36 #include "gnunet_datacache_lib.h"
37 #include "gnunet_transport_service.h"
38 #include "gnunet_hello_lib.h"
39 #include "gnunet_dht_service.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet-service-dht.h"
42 #include "gnunet-service-dht_clients.h"
43 #include "gnunet-service-dht_datacache.h"
44 #include "gnunet-service-dht_hello.h"
45 #include "gnunet-service-dht_neighbours.h"
46 #include "gnunet-service-dht_nse.h"
47 #include "gnunet-service-dht_routing.h"
48 #include "dht.h"
49
50 #define LOG_TRAFFIC(kind,...) GNUNET_log_from (kind, "dht-traffic",__VA_ARGS__)
51
52 /**
53  * How many buckets will we allow total.
54  */
55 #define MAX_BUCKETS sizeof (struct GNUNET_HashCode) * 8
56
57 /**
58  * What is the maximum number of peers in a given bucket.
59  */
60 #define DEFAULT_BUCKET_SIZE 8
61
62 /**
63  * Desired replication level for FIND PEER requests
64  */
65 #define FIND_PEER_REPLICATION_LEVEL 4
66
67 /**
68  * Maximum allowed replication level for all requests.
69  */
70 #define MAXIMUM_REPLICATION_LEVEL 16
71
72 /**
73  * Maximum allowed number of pending messages per peer.
74  */
75 #define MAXIMUM_PENDING_PER_PEER 64
76
77 /**
78  * How often to update our preference levels for peers in our routing tables.
79  */
80 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
81
82 /**
83  * How long at least to wait before sending another find peer request.
84  */
85 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
86
87 /**
88  * How long at most to wait before sending another find peer request.
89  */
90 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
91
92 /**
93  * How long at most to wait for transmission of a GET request to another peer?
94  */
95 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
96
97 /**
98  * Hello address expiration
99  */
100 extern struct GNUNET_TIME_Relative hello_expiration;
101
102
103 GNUNET_NETWORK_STRUCT_BEGIN
104
105 /**
106  * P2P PUT message
107  */
108 struct PeerPutMessage
109 {
110   /**
111    * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
112    */
113   struct GNUNET_MessageHeader header;
114
115   /**
116    * Processing options
117    */
118   uint32_t options GNUNET_PACKED;
119
120   /**
121    * Content type.
122    */
123   uint32_t type GNUNET_PACKED;
124
125   /**
126    * Hop count
127    */
128   uint32_t hop_count GNUNET_PACKED;
129
130   /**
131    * Replication level for this message
132    */
133   uint32_t desired_replication_level GNUNET_PACKED;
134
135   /**
136    * Length of the PUT path that follows (if tracked).
137    */
138   uint32_t put_path_length GNUNET_PACKED;
139
140   /**
141    * When does the content expire?
142    */
143   struct GNUNET_TIME_AbsoluteNBO expiration_time;
144
145   /**
146    * Bloomfilter (for peer identities) to stop circular routes
147    */
148   char bloomfilter[DHT_BLOOM_SIZE];
149
150   /**
151    * The key we are storing under.
152    */
153   struct GNUNET_HashCode key;
154
155   /* put path (if tracked) */
156
157   /* Payload */
158
159 };
160
161
162 /**
163  * P2P Result message
164  */
165 struct PeerResultMessage
166 {
167   /**
168    * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
169    */
170   struct GNUNET_MessageHeader header;
171
172   /**
173    * Content type.
174    */
175   uint32_t type GNUNET_PACKED;
176
177   /**
178    * Length of the PUT path that follows (if tracked).
179    */
180   uint32_t put_path_length GNUNET_PACKED;
181
182   /**
183    * Length of the GET path that follows (if tracked).
184    */
185   uint32_t get_path_length GNUNET_PACKED;
186
187   /**
188    * When does the content expire?
189    */
190   struct GNUNET_TIME_AbsoluteNBO expiration_time;
191
192   /**
193    * The key of the corresponding GET request.
194    */
195   struct GNUNET_HashCode key;
196
197   /* put path (if tracked) */
198
199   /* get path (if tracked) */
200
201   /* Payload */
202
203 };
204
205
206 /**
207  * P2P GET message
208  */
209 struct PeerGetMessage
210 {
211   /**
212    * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET
213    */
214   struct GNUNET_MessageHeader header;
215
216   /**
217    * Processing options
218    */
219   uint32_t options GNUNET_PACKED;
220
221   /**
222    * Desired content type.
223    */
224   uint32_t type GNUNET_PACKED;
225
226   /**
227    * Hop count
228    */
229   uint32_t hop_count GNUNET_PACKED;
230
231   /**
232    * Desired replication level for this request.
233    */
234   uint32_t desired_replication_level GNUNET_PACKED;
235
236   /**
237    * Size of the extended query.
238    */
239   uint32_t xquery_size;
240
241   /**
242    * Bloomfilter mutator.
243    */
244   uint32_t bf_mutator;
245
246   /**
247    * Bloomfilter (for peer identities) to stop circular routes
248    */
249   char bloomfilter[DHT_BLOOM_SIZE];
250
251   /**
252    * The key we are looking for.
253    */
254   struct GNUNET_HashCode key;
255
256   /* xquery */
257
258   /* result bloomfilter */
259
260 };
261 GNUNET_NETWORK_STRUCT_END
262
263 /**
264  * Linked list of messages to send to a particular other peer.
265  */
266 struct P2PPendingMessage
267 {
268   /**
269    * Pointer to next item in the list
270    */
271   struct P2PPendingMessage *next;
272
273   /**
274    * Pointer to previous item in the list
275    */
276   struct P2PPendingMessage *prev;
277
278   /**
279    * Message importance level.  FIXME: used? useful?
280    */
281   unsigned int importance;
282
283   /**
284    * When does this message time out?
285    */
286   struct GNUNET_TIME_Absolute timeout;
287
288   /**
289    * Actual message to be sent, allocated at the end of the struct:
290    * // msg = (cast) &pm[1];
291    * // memcpy (&pm[1], data, len);
292    */
293   const struct GNUNET_MessageHeader *msg;
294
295 };
296
297
298 /**
299  * Entry for a peer in a bucket.
300  */
301 struct PeerInfo
302 {
303   /**
304    * Next peer entry (DLL)
305    */
306   struct PeerInfo *next;
307
308   /**
309    *  Prev peer entry (DLL)
310    */
311   struct PeerInfo *prev;
312
313   /**
314    * Count of outstanding messages for peer.
315    */
316   unsigned int pending_count;
317
318   /**
319    * Head of pending messages to be sent to this peer.
320    */
321   struct P2PPendingMessage *head;
322
323   /**
324    * Tail of pending messages to be sent to this peer.
325    */
326   struct P2PPendingMessage *tail;
327
328   /**
329    * Core handle for sending messages to this peer.
330    */
331   struct GNUNET_CORE_TransmitHandle *th;
332
333   /**
334    * Task for scheduling preference updates
335    */
336   struct GNUNET_SCHEDULER_Task * preference_task;
337
338   /**
339    * What is the identity of the peer?
340    */
341   struct GNUNET_PeerIdentity id;
342
343 #if 0
344   /**
345    * What is the average latency for replies received?
346    */
347   struct GNUNET_TIME_Relative latency;
348
349   /**
350    * Transport level distance to peer.
351    */
352   unsigned int distance;
353 #endif
354
355 };
356
357
358 /**
359  * Peers are grouped into buckets.
360  */
361 struct PeerBucket
362 {
363   /**
364    * Head of DLL
365    */
366   struct PeerInfo *head;
367
368   /**
369    * Tail of DLL
370    */
371   struct PeerInfo *tail;
372
373   /**
374    * Number of peers in the bucket.
375    */
376   unsigned int peers_size;
377 };
378
379
380 /**
381  * Do we cache all results that we are routing in the local datacache?
382  */
383 static int cache_results;
384
385 /**
386  * Should routing details be logged to stderr (for debugging)?
387  */
388 static int log_route_details_stderr;
389
390 /**
391  * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
392  */
393 static unsigned int closest_bucket;
394
395 /**
396  * How many peers have we added since we sent out our last
397  * find peer request?
398  */
399 static unsigned int newly_found_peers;
400
401 /**
402  * Option for testing that disables the 'connect' function of the DHT.
403  */
404 static int disable_try_connect;
405
406 /**
407  * The buckets.  Array of size MAX_BUCKET_SIZE.  Offset 0 means 0 bits matching.
408  */
409 static struct PeerBucket k_buckets[MAX_BUCKETS];
410
411 /**
412  * Hash map of all known peers, for easy removal from k_buckets on disconnect.
413  */
414 static struct GNUNET_CONTAINER_MultiPeerMap *all_known_peers;
415
416 /**
417  * Maximum size for each bucket.
418  */
419 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
420
421 /**
422  * Task that sends FIND PEER requests.
423  */
424 static struct GNUNET_SCHEDULER_Task * find_peer_task;
425
426 /**
427  * Identity of this peer.
428  */
429 static struct GNUNET_PeerIdentity my_identity;
430
431 /**
432  * Hash of the identity of this peer.
433  */
434 static struct GNUNET_HashCode my_identity_hash;
435
436 /**
437  * Handle to CORE.
438  */
439 static struct GNUNET_CORE_Handle *core_api;
440
441 /**
442  * Handle to ATS.
443  */
444 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
445
446
447
448 /**
449  * Find the optimal bucket for this key.
450  *
451  * @param hc the hashcode to compare our identity to
452  * @return the proper bucket index, or GNUNET_SYSERR
453  *         on error (same hashcode)
454  */
455 static int
456 find_bucket (const struct GNUNET_HashCode *hc)
457 {
458   unsigned int bits;
459
460   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, hc);
461   if (bits == MAX_BUCKETS)
462   {
463     /* How can all bits match? Got my own ID? */
464     GNUNET_break (0);
465     return GNUNET_SYSERR;
466   }
467   return MAX_BUCKETS - bits - 1;
468 }
469
470
471 /**
472  * Let GNUnet core know that we like the given peer.
473  *
474  * @param cls the `struct PeerInfo` of the peer
475  * @param tc scheduler context.
476  */
477 static void
478 update_core_preference (void *cls,
479                         const struct GNUNET_SCHEDULER_TaskContext *tc)
480 {
481   struct PeerInfo *peer = cls;
482   uint64_t preference;
483   unsigned int matching;
484   int bucket;
485   struct GNUNET_HashCode phash;
486
487   peer->preference_task = NULL;
488   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
489     return;
490   GNUNET_CRYPTO_hash (&peer->id,
491                       sizeof (struct GNUNET_PeerIdentity),
492                       &phash);
493   matching =
494       GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash,
495                                         &phash);
496   if (matching >= 64)
497     matching = 63;
498   bucket = find_bucket (&phash);
499   if (bucket == GNUNET_SYSERR)
500     preference = 0;
501   else
502   {
503     GNUNET_assert (k_buckets[bucket].peers_size != 0);
504     preference = (1LL << matching) / k_buckets[bucket].peers_size;
505   }
506   if (preference == 0)
507   {
508     peer->preference_task =
509         GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
510                                       &update_core_preference, peer);
511     return;
512   }
513   GNUNET_STATISTICS_update (GDS_stats,
514                             gettext_noop ("# Preference updates given to core"),
515                             1, GNUNET_NO);
516   GNUNET_ATS_performance_change_preference (atsAPI, &peer->id,
517                                 GNUNET_ATS_PREFERENCE_BANDWIDTH,
518                                 (double) preference, GNUNET_ATS_PREFERENCE_END);
519   peer->preference_task =
520       GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
521                                     &update_core_preference, peer);
522
523
524 }
525
526
527 /**
528  * Closure for 'add_known_to_bloom'.
529  */
530 struct BloomConstructorContext
531 {
532   /**
533    * Bloom filter under construction.
534    */
535   struct GNUNET_CONTAINER_BloomFilter *bloom;
536
537   /**
538    * Mutator to use.
539    */
540   uint32_t bf_mutator;
541 };
542
543
544 /**
545  * Add each of the peers we already know to the bloom filter of
546  * the request so that we don't get duplicate HELLOs.
547  *
548  * @param cls the 'struct BloomConstructorContext'.
549  * @param key peer identity to add to the bloom filter
550  * @param value value the peer information (unused)
551  * @return #GNUNET_YES (we should continue to iterate)
552  */
553 static int
554 add_known_to_bloom (void *cls,
555                     const struct GNUNET_PeerIdentity *key,
556                     void *value)
557 {
558   struct BloomConstructorContext *ctx = cls;
559   struct GNUNET_HashCode key_hash;
560   struct GNUNET_HashCode mh;
561
562   GNUNET_CRYPTO_hash (key, sizeof (struct GNUNET_PeerIdentity), &key_hash);
563   GNUNET_BLOCK_mingle_hash (&key_hash, ctx->bf_mutator, &mh);
564   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
565               "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
566               GNUNET_i2s (key), ctx->bf_mutator);
567   GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
568   return GNUNET_YES;
569 }
570
571
572 /**
573  * Task to send a find peer message for our own peer identifier
574  * so that we can find the closest peers in the network to ourselves
575  * and attempt to connect to them.
576  *
577  * @param cls closure for this task
578  * @param tc the context under which the task is running
579  */
580 static void
581 send_find_peer_message (void *cls,
582                         const struct GNUNET_SCHEDULER_TaskContext *tc)
583 {
584   struct GNUNET_TIME_Relative next_send_time;
585   struct BloomConstructorContext bcc;
586   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
587
588   find_peer_task = NULL;
589   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
590     return;
591   if (newly_found_peers > bucket_size)
592   {
593     /* If we are finding many peers already, no need to send out our request right now! */
594     find_peer_task =
595         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
596                                       &send_find_peer_message, NULL);
597     newly_found_peers = 0;
598     return;
599   }
600   bcc.bf_mutator =
601       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
602   bcc.bloom =
603       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
604                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
605   GNUNET_CONTAINER_multipeermap_iterate (all_known_peers, &add_known_to_bloom,
606                                          &bcc);
607   GNUNET_STATISTICS_update (GDS_stats,
608                             gettext_noop ("# FIND PEER messages initiated"), 1,
609                             GNUNET_NO);
610   peer_bf =
611       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
612                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
613   // FIXME: pass priority!?
614   GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
615                              GNUNET_DHT_RO_FIND_PEER,
616                              FIND_PEER_REPLICATION_LEVEL, 0,
617                              &my_identity_hash, NULL, 0, bcc.bloom,
618                              bcc.bf_mutator, peer_bf);
619   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
620   GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
621   /* schedule next round */
622   next_send_time.rel_value_us =
623       DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us +
624       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
625                                 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us /
626                                 (newly_found_peers + 1));
627   newly_found_peers = 0;
628   find_peer_task =
629       GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
630                                     NULL);
631 }
632
633
634 /**
635  * Method called whenever a peer connects.
636  *
637  * @param cls closure
638  * @param peer peer identity this notification is about
639  */
640 static void
641 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
642 {
643   struct PeerInfo *ret;
644   struct GNUNET_HashCode phash;
645   int peer_bucket;
646
647   /* Check for connect to self message */
648   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
649     return;
650   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
651               "Connected to %s\n",
652               GNUNET_i2s (peer));
653   if (GNUNET_YES ==
654       GNUNET_CONTAINER_multipeermap_contains (all_known_peers,
655                                               peer))
656   {
657     GNUNET_break (0);
658     return;
659   }
660   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
661                             GNUNET_NO);
662   GNUNET_CRYPTO_hash (peer,
663                       sizeof (struct GNUNET_PeerIdentity),
664                       &phash);
665   peer_bucket = find_bucket (&phash);
666   GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
667   ret = GNUNET_new (struct PeerInfo);
668 #if 0
669   ret->latency = latency;
670   ret->distance = distance;
671 #endif
672   ret->id = *peer;
673   GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
674                                     k_buckets[peer_bucket].tail, ret);
675   k_buckets[peer_bucket].peers_size++;
676   closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
677   if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
678   {
679     ret->preference_task =
680         GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
681     newly_found_peers++;
682   }
683   GNUNET_assert (GNUNET_OK ==
684                  GNUNET_CONTAINER_multipeermap_put (all_known_peers,
685                                                     peer, ret,
686                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
687   if (1 == GNUNET_CONTAINER_multipeermap_size (all_known_peers) &&
688       (GNUNET_YES != disable_try_connect))
689   {
690     /* got a first connection, good time to start with FIND PEER requests... */
691     find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
692   }
693 }
694
695
696 /**
697  * Method called whenever a peer disconnects.
698  *
699  * @param cls closure
700  * @param peer peer identity this notification is about
701  */
702 static void
703 handle_core_disconnect (void *cls,
704                         const struct GNUNET_PeerIdentity *peer)
705 {
706   struct PeerInfo *to_remove;
707   int current_bucket;
708   struct P2PPendingMessage *pos;
709   unsigned int discarded;
710   struct GNUNET_HashCode phash;
711
712   /* Check for disconnect from self message */
713   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
714     return;
715   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
716               "Disconnected %s\n",
717               GNUNET_i2s (peer));
718   to_remove =
719       GNUNET_CONTAINER_multipeermap_get (all_known_peers, peer);
720   if (NULL == to_remove)
721   {
722     GNUNET_break (0);
723     return;
724   }
725   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), -1,
726                             GNUNET_NO);
727   GNUNET_assert (GNUNET_YES ==
728                  GNUNET_CONTAINER_multipeermap_remove (all_known_peers,
729                                                        peer,
730                                                        to_remove));
731   if (NULL != to_remove->preference_task)
732   {
733     GNUNET_SCHEDULER_cancel (to_remove->preference_task);
734     to_remove->preference_task = NULL;
735   }
736   GNUNET_CRYPTO_hash (peer,
737                       sizeof (struct GNUNET_PeerIdentity),
738                       &phash);
739   current_bucket = find_bucket (&phash);
740   GNUNET_assert (current_bucket >= 0);
741   GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
742                                k_buckets[current_bucket].tail, to_remove);
743   GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
744   k_buckets[current_bucket].peers_size--;
745   while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
746     closest_bucket--;
747
748   if (to_remove->th != NULL)
749   {
750     GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
751     to_remove->th = NULL;
752   }
753   discarded = 0;
754   while (NULL != (pos = to_remove->head))
755   {
756     GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
757     discarded++;
758     GNUNET_free (pos);
759   }
760   GNUNET_STATISTICS_update (GDS_stats,
761                             gettext_noop
762                             ("# Queued messages discarded (peer disconnected)"),
763                             discarded, GNUNET_NO);
764   GNUNET_free (to_remove);
765 }
766
767
768 /**
769  * Called when core is ready to send a message we asked for
770  * out to the destination.
771  *
772  * @param cls the 'struct PeerInfo' of the target peer
773  * @param size number of bytes available in buf
774  * @param buf where the callee should write the message
775  * @return number of bytes written to buf
776  */
777 static size_t
778 core_transmit_notify (void *cls, size_t size, void *buf)
779 {
780   struct PeerInfo *peer = cls;
781   char *cbuf = buf;
782   struct P2PPendingMessage *pending;
783   size_t off;
784   size_t msize;
785
786   peer->th = NULL;
787   while ((NULL != (pending = peer->head)) &&
788          (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
789   {
790     GNUNET_STATISTICS_update (GDS_stats,
791                               gettext_noop
792                               ("# Messages dropped (CORE timeout)"),
793                               1,
794                               GNUNET_NO);
795     peer->pending_count--;
796     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
797     GNUNET_free (pending);
798   }
799   if (NULL == pending)
800   {
801     /* no messages pending */
802     return 0;
803   }
804   if (NULL == buf)
805   {
806     peer->th =
807         GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
808                                            GNUNET_CORE_PRIO_BEST_EFFORT,
809                                            GNUNET_TIME_absolute_get_remaining
810                                            (pending->timeout), &peer->id,
811                                            ntohs (pending->msg->size),
812                                            &core_transmit_notify, peer);
813     GNUNET_break (NULL != peer->th);
814     return 0;
815   }
816   off = 0;
817   while ((NULL != (pending = peer->head)) &&
818          (size - off >= (msize = ntohs (pending->msg->size))))
819   {
820     GNUNET_STATISTICS_update (GDS_stats,
821                               gettext_noop
822                               ("# Bytes transmitted to other peers"), msize,
823                               GNUNET_NO);
824     memcpy (&cbuf[off], pending->msg, msize);
825     off += msize;
826     peer->pending_count--;
827     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
828     GNUNET_free (pending);
829   }
830   if (peer->head != NULL)
831   {
832     peer->th =
833         GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
834                                            GNUNET_CORE_PRIO_BEST_EFFORT,
835                                            GNUNET_TIME_absolute_get_remaining
836                                            (pending->timeout), &peer->id, msize,
837                                            &core_transmit_notify, peer);
838     GNUNET_break (NULL != peer->th);
839   }
840   return off;
841 }
842
843
844 /**
845  * Transmit all messages in the peer's message queue.
846  *
847  * @param peer message queue to process
848  */
849 static void
850 process_peer_queue (struct PeerInfo *peer)
851 {
852   struct P2PPendingMessage *pending;
853
854   if (NULL == (pending = peer->head))
855     return;
856   if (NULL != peer->th)
857     return;
858   GNUNET_STATISTICS_update (GDS_stats,
859                             gettext_noop
860                             ("# Bytes of bandwidth requested from core"),
861                             ntohs (pending->msg->size), GNUNET_NO);
862   peer->th =
863       GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
864                                          GNUNET_CORE_PRIO_BEST_EFFORT,
865                                          GNUNET_TIME_absolute_get_remaining
866                                          (pending->timeout), &peer->id,
867                                          ntohs (pending->msg->size),
868                                          &core_transmit_notify, peer);
869   GNUNET_break (NULL != peer->th);
870 }
871
872
873 /**
874  * To how many peers should we (on average) forward the request to
875  * obtain the desired target_replication count (on average).
876  *
877  * @param hop_count number of hops the message has traversed
878  * @param target_replication the number of total paths desired
879  * @return Some number of peers to forward the message to
880  */
881 static unsigned int
882 get_forward_count (uint32_t hop_count, uint32_t target_replication)
883 {
884   uint32_t random_value;
885   uint32_t forward_count;
886   float target_value;
887
888   if (hop_count > GDS_NSE_get () * 4.0)
889   {
890     /* forcefully terminate */
891     GNUNET_STATISTICS_update (GDS_stats,
892                               gettext_noop ("# requests TTL-dropped"),
893                               1, GNUNET_NO);
894     return 0;
895   }
896   if (hop_count > GDS_NSE_get () * 2.0)
897   {
898     /* Once we have reached our ideal number of hops, only forward to 1 peer */
899     return 1;
900   }
901   /* bound by system-wide maximum */
902   target_replication =
903       GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
904   target_value =
905       1 + (target_replication - 1.0) / (GDS_NSE_get () +
906                                         ((float) (target_replication - 1.0) *
907                                          hop_count));
908   /* Set forward count to floor of target_value */
909   forward_count = (uint32_t) target_value;
910   /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
911   target_value = target_value - forward_count;
912   random_value =
913       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
914   if (random_value < (target_value * UINT32_MAX))
915     forward_count++;
916   return forward_count;
917 }
918
919
920 /**
921  * Compute the distance between have and target as a 32-bit value.
922  * Differences in the lower bits must count stronger than differences
923  * in the higher bits.
924  *
925  * @param target
926  * @param have
927  * @return 0 if have==target, otherwise a number
928  *           that is larger as the distance between
929  *           the two hash codes increases
930  */
931 static unsigned int
932 get_distance (const struct GNUNET_HashCode *target,
933               const struct GNUNET_HashCode *have)
934 {
935   unsigned int bucket;
936   unsigned int msb;
937   unsigned int lsb;
938   unsigned int i;
939
940   /* We have to represent the distance between two 2^9 (=512)-bit
941    * numbers as a 2^5 (=32)-bit number with "0" being used for the
942    * two numbers being identical; furthermore, we need to
943    * guarantee that a difference in the number of matching
944    * bits is always represented in the result.
945    *
946    * We use 2^32/2^9 numerical values to distinguish between
947    * hash codes that have the same LSB bit distance and
948    * use the highest 2^9 bits of the result to signify the
949    * number of (mis)matching LSB bits; if we have 0 matching
950    * and hence 512 mismatching LSB bits we return -1 (since
951    * 512 itself cannot be represented with 9 bits) */
952
953   /* first, calculate the most significant 9 bits of our
954    * result, aka the number of LSBs */
955   bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
956   /* bucket is now a value between 0 and 512 */
957   if (bucket == 512)
958     return 0;                   /* perfect match */
959   if (bucket == 0)
960     return (unsigned int) -1;   /* LSB differs; use max (if we did the bit-shifting
961                                  * below, we'd end up with max+1 (overflow)) */
962
963   /* calculate the most significant bits of the final result */
964   msb = (512 - bucket) << (32 - 9);
965   /* calculate the 32-9 least significant bits of the final result by
966    * looking at the differences in the 32-9 bits following the
967    * mismatching bit at 'bucket' */
968   lsb = 0;
969   for (i = bucket + 1;
970        (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
971   {
972     if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
973         GNUNET_CRYPTO_hash_get_bit (have, i))
974       lsb |= (1 << (bucket + 32 - 9 - i));      /* first bit set will be 10,
975                                                  * last bit set will be 31 -- if
976                                                  * i does not reach 512 first... */
977   }
978   return msb | lsb;
979 }
980
981
982 /**
983  * Check whether my identity is closer than any known peers.  If a
984  * non-null bloomfilter is given, check if this is the closest peer
985  * that hasn't already been routed to.
986  *
987  * @param key hash code to check closeness to
988  * @param bloom bloomfilter, exclude these entries from the decision
989  * @return #GNUNET_YES if node location is closest,
990  *         #GNUNET_NO otherwise.
991  */
992 static int
993 am_closest_peer (const struct GNUNET_HashCode *key,
994                  const struct GNUNET_CONTAINER_BloomFilter *bloom)
995 {
996   int bits;
997   int other_bits;
998   int bucket_num;
999   int count;
1000   struct PeerInfo *pos;
1001   struct GNUNET_HashCode phash;
1002
1003   if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1004     return GNUNET_YES;
1005   bucket_num = find_bucket (key);
1006   GNUNET_assert (bucket_num >= 0);
1007   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, key);
1008   pos = k_buckets[bucket_num].head;
1009   count = 0;
1010   while ((pos != NULL) && (count < bucket_size))
1011   {
1012     GNUNET_CRYPTO_hash (&pos->id,
1013                         sizeof (struct GNUNET_PeerIdentity),
1014                         &phash);
1015     if ((bloom != NULL) &&
1016         (GNUNET_YES ==
1017          GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1018     {
1019       pos = pos->next;
1020       continue;                 /* Skip already checked entries */
1021     }
1022     other_bits = GNUNET_CRYPTO_hash_matching_bits (&phash, key);
1023     if (other_bits > bits)
1024       return GNUNET_NO;
1025     if (other_bits == bits)     /* We match the same number of bits */
1026       return GNUNET_YES;
1027     pos = pos->next;
1028   }
1029   /* No peers closer, we are the closest! */
1030   return GNUNET_YES;
1031 }
1032
1033
1034 /**
1035  * Select a peer from the routing table that would be a good routing
1036  * destination for sending a message for "key".  The resulting peer
1037  * must not be in the set of blocked peers.<p>
1038  *
1039  * Note that we should not ALWAYS select the closest peer to the
1040  * target, peers further away from the target should be chosen with
1041  * exponentially declining probability.
1042  *
1043  * FIXME: double-check that this is fine
1044  *
1045  *
1046  * @param key the key we are selecting a peer to route to
1047  * @param bloom a bloomfilter containing entries this request has seen already
1048  * @param hops how many hops has this message traversed thus far
1049  * @return Peer to route to, or NULL on error
1050  */
1051 static struct PeerInfo *
1052 select_peer (const struct GNUNET_HashCode * key,
1053              const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1054 {
1055   unsigned int bc;
1056   unsigned int count;
1057   unsigned int selected;
1058   struct PeerInfo *pos;
1059   unsigned int dist;
1060   unsigned int smallest_distance;
1061   struct PeerInfo *chosen;
1062   struct GNUNET_HashCode phash;
1063
1064   if (hops >= GDS_NSE_get ())
1065   {
1066     /* greedy selection (closest peer that is not in bloomfilter) */
1067     smallest_distance = UINT_MAX;
1068     chosen = NULL;
1069     for (bc = 0; bc <= closest_bucket; bc++)
1070     {
1071       pos = k_buckets[bc].head;
1072       count = 0;
1073       while ((pos != NULL) && (count < bucket_size))
1074       {
1075         GNUNET_CRYPTO_hash (&pos->id,
1076                             sizeof (struct GNUNET_PeerIdentity),
1077                             &phash);
1078         if ((bloom == NULL) ||
1079             (GNUNET_NO ==
1080              GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1081         {
1082           dist = get_distance (key, &phash);
1083           if (dist < smallest_distance)
1084           {
1085             chosen = pos;
1086             smallest_distance = dist;
1087           }
1088         }
1089         else
1090         {
1091           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1092                       "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1093                       GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1094           GNUNET_STATISTICS_update (GDS_stats,
1095                                     gettext_noop
1096                                     ("# Peers excluded from routing due to Bloomfilter"),
1097                                     1, GNUNET_NO);
1098           dist = get_distance (key, &phash);
1099           if (dist < smallest_distance)
1100           {
1101             chosen = NULL;
1102             smallest_distance = dist;
1103           }
1104         }
1105         count++;
1106         pos = pos->next;
1107       }
1108     }
1109     if (NULL == chosen)
1110       GNUNET_STATISTICS_update (GDS_stats,
1111                                 gettext_noop ("# Peer selection failed"), 1,
1112                                 GNUNET_NO);
1113     return chosen;
1114   }
1115
1116   /* select "random" peer */
1117   /* count number of peers that are available and not filtered */
1118   count = 0;
1119   for (bc = 0; bc <= closest_bucket; bc++)
1120   {
1121     pos = k_buckets[bc].head;
1122     while ((pos != NULL) && (count < bucket_size))
1123     {
1124       GNUNET_CRYPTO_hash (&pos->id,
1125                           sizeof (struct GNUNET_PeerIdentity),
1126                           &phash);
1127       if ((bloom != NULL) &&
1128           (GNUNET_YES ==
1129            GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1130       {
1131         GNUNET_STATISTICS_update (GDS_stats,
1132                                   gettext_noop
1133                                   ("# Peers excluded from routing due to Bloomfilter"),
1134                                   1, GNUNET_NO);
1135         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1136                     "Excluded peer `%s' due to BF match in random routing for %s\n",
1137                     GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1138         pos = pos->next;
1139         continue;               /* Ignore bloomfiltered peers */
1140       }
1141       count++;
1142       pos = pos->next;
1143     }
1144   }
1145   if (0 == count)               /* No peers to select from! */
1146   {
1147     GNUNET_STATISTICS_update (GDS_stats,
1148                               gettext_noop ("# Peer selection failed"), 1,
1149                               GNUNET_NO);
1150     return NULL;
1151   }
1152   /* Now actually choose a peer */
1153   selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1154   count = 0;
1155   for (bc = 0; bc <= closest_bucket; bc++)
1156   {
1157     for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1158     {
1159       GNUNET_CRYPTO_hash (&pos->id,
1160                           sizeof (struct GNUNET_PeerIdentity),
1161                           &phash);
1162       if ((bloom != NULL) &&
1163           (GNUNET_YES ==
1164            GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1165       {
1166         continue;               /* Ignore bloomfiltered peers */
1167       }
1168       if (0 == selected--)
1169         return pos;
1170     }
1171   }
1172   GNUNET_break (0);
1173   return NULL;
1174 }
1175
1176
1177 /**
1178  * Compute the set of peers that the given request should be
1179  * forwarded to.
1180  *
1181  * @param key routing key
1182  * @param bloom bloom filter excluding peers as targets, all selected
1183  *        peers will be added to the bloom filter
1184  * @param hop_count number of hops the request has traversed so far
1185  * @param target_replication desired number of replicas
1186  * @param targets where to store an array of target peers (to be
1187  *         free'd by the caller)
1188  * @return number of peers returned in 'targets'.
1189  */
1190 static unsigned int
1191 get_target_peers (const struct GNUNET_HashCode *key,
1192                   struct GNUNET_CONTAINER_BloomFilter *bloom,
1193                   uint32_t hop_count, uint32_t target_replication,
1194                   struct PeerInfo ***targets)
1195 {
1196   unsigned int ret;
1197   unsigned int off;
1198   struct PeerInfo **rtargets;
1199   struct PeerInfo *nxt;
1200   struct GNUNET_HashCode nhash;
1201
1202   GNUNET_assert (NULL != bloom);
1203   ret = get_forward_count (hop_count, target_replication);
1204   if (0 == ret)
1205   {
1206     *targets = NULL;
1207     return 0;
1208   }
1209   rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1210   for (off = 0; off < ret; off++)
1211   {
1212     nxt = select_peer (key, bloom, hop_count);
1213     if (NULL == nxt)
1214       break;
1215     rtargets[off] = nxt;
1216     GNUNET_CRYPTO_hash (&nxt->id,
1217                         sizeof (struct GNUNET_PeerIdentity),
1218                         &nhash);
1219     GNUNET_break (GNUNET_NO ==
1220                   GNUNET_CONTAINER_bloomfilter_test (bloom,
1221                                                      &nhash));
1222     GNUNET_CONTAINER_bloomfilter_add (bloom, &nhash);
1223   }
1224   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1225               "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1226               GNUNET_CONTAINER_multipeermap_size (all_known_peers),
1227               (unsigned int) hop_count, GNUNET_h2s (key), ret);
1228   if (0 == off)
1229   {
1230     GNUNET_free (rtargets);
1231     *targets = NULL;
1232     return 0;
1233   }
1234   *targets = rtargets;
1235   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1236               "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1237               GNUNET_h2s (key),
1238               off,
1239               ret);
1240   return off;
1241 }
1242
1243
1244 /**
1245  * Perform a PUT operation.   Forwards the given request to other
1246  * peers.   Does not store the data locally.  Does not give the
1247  * data to local clients.  May do nothing if this is the only
1248  * peer in the network (or if we are the closest peer in the
1249  * network).
1250  *
1251  * @param type type of the block
1252  * @param options routing options
1253  * @param desired_replication_level desired replication count
1254  * @param expiration_time when does the content expire
1255  * @param hop_count how many hops has this message traversed so far
1256  * @param bf Bloom filter of peers this PUT has already traversed
1257  * @param key key for the content
1258  * @param put_path_length number of entries in @a put_path
1259  * @param put_path peers this request has traversed so far (if tracked)
1260  * @param data payload to store
1261  * @param data_size number of bytes in @a data
1262  * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1263  */
1264 int
1265 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1266                            enum GNUNET_DHT_RouteOption options,
1267                            uint32_t desired_replication_level,
1268                            struct GNUNET_TIME_Absolute expiration_time,
1269                            uint32_t hop_count,
1270                            struct GNUNET_CONTAINER_BloomFilter *bf,
1271                            const struct GNUNET_HashCode *key,
1272                            unsigned int put_path_length,
1273                            struct GNUNET_PeerIdentity *put_path,
1274                            const void *data, size_t data_size)
1275 {
1276   unsigned int target_count;
1277   unsigned int i;
1278   struct PeerInfo **targets;
1279   struct PeerInfo *target;
1280   struct P2PPendingMessage *pending;
1281   size_t msize;
1282   struct PeerPutMessage *ppm;
1283   struct GNUNET_PeerIdentity *pp;
1284   struct GNUNET_HashCode thash;
1285   unsigned int skip_count;
1286
1287   GNUNET_assert (NULL != bf);
1288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1289               "Adding myself (%s) to PUT bloomfilter for %s\n",
1290               GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1291   GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity_hash);
1292   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1293                             1, GNUNET_NO);
1294   target_count =
1295       get_target_peers (key, bf, hop_count, desired_replication_level,
1296                         &targets);
1297   if (0 == target_count)
1298   {
1299     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1300                 "Routing PUT for %s terminates after %u hops at %s\n",
1301                 GNUNET_h2s (key), (unsigned int) hop_count,
1302                 GNUNET_i2s (&my_identity));
1303     return GNUNET_NO;
1304   }
1305   msize =
1306       put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1307       sizeof (struct PeerPutMessage);
1308   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1309   {
1310     put_path_length = 0;
1311     msize = data_size + sizeof (struct PeerPutMessage);
1312   }
1313   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1314   {
1315     GNUNET_break (0);
1316     GNUNET_free (targets);
1317     return GNUNET_NO;
1318   }
1319   GNUNET_STATISTICS_update (GDS_stats,
1320                             gettext_noop
1321                             ("# PUT messages queued for transmission"),
1322                             target_count, GNUNET_NO);
1323   skip_count = 0;
1324   for (i = 0; i < target_count; i++)
1325   {
1326     target = targets[i];
1327     if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1328     {
1329       /* skip */
1330       GNUNET_STATISTICS_update (GDS_stats,
1331                                 gettext_noop ("# P2P messages dropped due to full queue"),
1332                                 1, GNUNET_NO);
1333       skip_count++;
1334       continue;
1335     }
1336     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1337                 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1338                 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1339     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1340     pending->importance = 0;    /* FIXME */
1341     pending->timeout = expiration_time;
1342     ppm = (struct PeerPutMessage *) &pending[1];
1343     pending->msg = &ppm->header;
1344     ppm->header.size = htons (msize);
1345     ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1346     ppm->options = htonl (options);
1347     ppm->type = htonl (type);
1348     ppm->hop_count = htonl (hop_count + 1);
1349     ppm->desired_replication_level = htonl (desired_replication_level);
1350     ppm->put_path_length = htonl (put_path_length);
1351     ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1352     GNUNET_CRYPTO_hash (&target->id,
1353                         sizeof (struct GNUNET_PeerIdentity),
1354                         &thash);
1355     GNUNET_break (GNUNET_YES ==
1356                   GNUNET_CONTAINER_bloomfilter_test (bf,
1357                                                      &thash));
1358     GNUNET_assert (GNUNET_OK ==
1359                    GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1360                                                               ppm->bloomfilter,
1361                                                               DHT_BLOOM_SIZE));
1362     ppm->key = *key;
1363     pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1364     memcpy (pp, put_path,
1365             sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1366     memcpy (&pp[put_path_length], data, data_size);
1367     GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1368     target->pending_count++;
1369     process_peer_queue (target);
1370   }
1371   GNUNET_free (targets);
1372   return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1373 }
1374
1375
1376 /**
1377  * Perform a GET operation.  Forwards the given request to other
1378  * peers.  Does not lookup the key locally.  May do nothing if this is
1379  * the only peer in the network (or if we are the closest peer in the
1380  * network).
1381  *
1382  * @param type type of the block
1383  * @param options routing options
1384  * @param desired_replication_level desired replication count
1385  * @param hop_count how many hops did this request traverse so far?
1386  * @param key key for the content
1387  * @param xquery extended query
1388  * @param xquery_size number of bytes in @a xquery
1389  * @param reply_bf bloomfilter to filter duplicates
1390  * @param reply_bf_mutator mutator for @a reply_bf
1391  * @param peer_bf filter for peers not to select (again)
1392  * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1393  */
1394 int
1395 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1396                            enum GNUNET_DHT_RouteOption options,
1397                            uint32_t desired_replication_level,
1398                            uint32_t hop_count, const struct GNUNET_HashCode * key,
1399                            const void *xquery, size_t xquery_size,
1400                            const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1401                            uint32_t reply_bf_mutator,
1402                            struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1403 {
1404   unsigned int target_count;
1405   unsigned int i;
1406   struct PeerInfo **targets;
1407   struct PeerInfo *target;
1408   struct P2PPendingMessage *pending;
1409   size_t msize;
1410   struct PeerGetMessage *pgm;
1411   char *xq;
1412   size_t reply_bf_size;
1413   struct GNUNET_HashCode thash;
1414   unsigned int skip_count;
1415
1416   GNUNET_assert (NULL != peer_bf);
1417   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1418                             1, GNUNET_NO);
1419   target_count =
1420       get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1421                         &targets);
1422   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1423               "Adding myself (%s) to GET bloomfilter for %s\n",
1424               GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1425   GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity_hash);
1426   if (0 == target_count)
1427   {
1428     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1429                 "Routing GET for %s terminates after %u hops at %s\n",
1430                 GNUNET_h2s (key), (unsigned int) hop_count,
1431                 GNUNET_i2s (&my_identity));
1432     return GNUNET_NO;
1433   }
1434   reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1435   msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1436   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1437   {
1438     GNUNET_break (0);
1439     GNUNET_free (targets);
1440     return GNUNET_NO;
1441   }
1442   GNUNET_STATISTICS_update (GDS_stats,
1443                             gettext_noop
1444                             ("# GET messages queued for transmission"),
1445                             target_count, GNUNET_NO);
1446   /* forward request */
1447   skip_count = 0;
1448   for (i = 0; i < target_count; i++)
1449   {
1450     target = targets[i];
1451     if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1452     {
1453       /* skip */
1454       GNUNET_STATISTICS_update (GDS_stats,
1455                                 gettext_noop ("# P2P messages dropped due to full queue"),
1456                                 1, GNUNET_NO);
1457       skip_count++;
1458       continue;
1459     }
1460     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1461                 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1462                 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1463     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1464     pending->importance = 0;    /* FIXME */
1465     pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1466     pgm = (struct PeerGetMessage *) &pending[1];
1467     pending->msg = &pgm->header;
1468     pgm->header.size = htons (msize);
1469     pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1470     pgm->options = htonl (options);
1471     pgm->type = htonl (type);
1472     pgm->hop_count = htonl (hop_count + 1);
1473     pgm->desired_replication_level = htonl (desired_replication_level);
1474     pgm->xquery_size = htonl (xquery_size);
1475     pgm->bf_mutator = reply_bf_mutator;
1476     GNUNET_CRYPTO_hash (&target->id,
1477                         sizeof (struct GNUNET_PeerIdentity),
1478                         &thash);
1479     GNUNET_break (GNUNET_YES ==
1480                   GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1481                                                      &thash));
1482     GNUNET_assert (GNUNET_OK ==
1483                    GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1484                                                               pgm->bloomfilter,
1485                                                               DHT_BLOOM_SIZE));
1486     pgm->key = *key;
1487     xq = (char *) &pgm[1];
1488     memcpy (xq, xquery, xquery_size);
1489     if (NULL != reply_bf)
1490       GNUNET_assert (GNUNET_OK ==
1491                      GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1492                                                                 &xq
1493                                                                 [xquery_size],
1494                                                                 reply_bf_size));
1495     GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1496     target->pending_count++;
1497     process_peer_queue (target);
1498   }
1499   GNUNET_free (targets);
1500   return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1501 }
1502
1503
1504 /**
1505  * Handle a reply (route to origin).  Only forwards the reply back to
1506  * the given peer.  Does not do local caching or forwarding to local
1507  * clients.
1508  *
1509  * @param target neighbour that should receive the block (if still connected)
1510  * @param type type of the block
1511  * @param expiration_time when does the content expire
1512  * @param key key for the content
1513  * @param put_path_length number of entries in @a put_path
1514  * @param put_path peers the original PUT traversed (if tracked)
1515  * @param get_path_length number of entries in @a get_path
1516  * @param get_path peers this reply has traversed so far (if tracked)
1517  * @param data payload of the reply
1518  * @param data_size number of bytes in @a data
1519  */
1520 void
1521 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1522                              enum GNUNET_BLOCK_Type type,
1523                              struct GNUNET_TIME_Absolute expiration_time,
1524                              const struct GNUNET_HashCode * key,
1525                              unsigned int put_path_length,
1526                              const struct GNUNET_PeerIdentity *put_path,
1527                              unsigned int get_path_length,
1528                              const struct GNUNET_PeerIdentity *get_path,
1529                              const void *data, size_t data_size)
1530 {
1531   struct PeerInfo *pi;
1532   struct P2PPendingMessage *pending;
1533   size_t msize;
1534   struct PeerResultMessage *prm;
1535   struct GNUNET_PeerIdentity *paths;
1536
1537   msize =
1538       data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1539                                                        put_path_length) *
1540       sizeof (struct GNUNET_PeerIdentity);
1541   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1542       (get_path_length >
1543        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1544       (put_path_length >
1545        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1546       (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1547   {
1548     GNUNET_break (0);
1549     return;
1550   }
1551   pi = GNUNET_CONTAINER_multipeermap_get (all_known_peers, target);
1552   if (NULL == pi)
1553   {
1554     /* peer disconnected in the meantime, drop reply */
1555     return;
1556   }
1557   if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1558   {
1559     /* skip */
1560     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1561                               1, GNUNET_NO);
1562     return;
1563   }
1564
1565   GNUNET_STATISTICS_update (GDS_stats,
1566                             gettext_noop
1567                             ("# RESULT messages queued for transmission"), 1,
1568                             GNUNET_NO);
1569   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1570   pending->importance = 0;      /* FIXME */
1571   pending->timeout = expiration_time;
1572   prm = (struct PeerResultMessage *) &pending[1];
1573   pending->msg = &prm->header;
1574   prm->header.size = htons (msize);
1575   prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1576   prm->type = htonl (type);
1577   prm->put_path_length = htonl (put_path_length);
1578   prm->get_path_length = htonl (get_path_length);
1579   prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1580   prm->key = *key;
1581   paths = (struct GNUNET_PeerIdentity *) &prm[1];
1582   memcpy (paths, put_path,
1583           put_path_length * sizeof (struct GNUNET_PeerIdentity));
1584   memcpy (&paths[put_path_length], get_path,
1585           get_path_length * sizeof (struct GNUNET_PeerIdentity));
1586   memcpy (&paths[put_path_length + get_path_length], data, data_size);
1587   GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1588   pi->pending_count++;
1589   process_peer_queue (pi);
1590 }
1591
1592
1593 /**
1594  * To be called on core init/fail.
1595  *
1596  * @param cls service closure
1597  * @param identity the public identity of this peer
1598  */
1599 static void
1600 core_init (void *cls,
1601            const struct GNUNET_PeerIdentity *identity)
1602 {
1603   my_identity = *identity;
1604   GNUNET_CRYPTO_hash (identity,
1605                       sizeof (struct GNUNET_PeerIdentity),
1606                       &my_identity_hash);
1607 }
1608
1609
1610 /**
1611  * Core handler for p2p put requests.
1612  *
1613  * @param cls closure
1614  * @param peer sender of the request
1615  * @param message message
1616  * @param peer peer identity this notification is about
1617  * @return #GNUNET_OK to keep the connection open,
1618  *         #GNUNET_SYSERR to close it (signal serious error)
1619  */
1620 static int
1621 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1622                     const struct GNUNET_MessageHeader *message)
1623 {
1624   const struct PeerPutMessage *put;
1625   const struct GNUNET_PeerIdentity *put_path;
1626   const void *payload;
1627   uint32_t putlen;
1628   uint16_t msize;
1629   size_t payload_size;
1630   enum GNUNET_DHT_RouteOption options;
1631   struct GNUNET_CONTAINER_BloomFilter *bf;
1632   struct GNUNET_HashCode test_key;
1633   struct GNUNET_HashCode phash;
1634   int forwarded;
1635
1636   msize = ntohs (message->size);
1637   if (msize < sizeof (struct PeerPutMessage))
1638   {
1639     GNUNET_break_op (0);
1640     return GNUNET_YES;
1641   }
1642   put = (const struct PeerPutMessage *) message;
1643   putlen = ntohl (put->put_path_length);
1644   if ((msize <
1645        sizeof (struct PeerPutMessage) +
1646        putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1647       (putlen >
1648        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1649   {
1650     GNUNET_break_op (0);
1651     return GNUNET_YES;
1652   }
1653   GNUNET_STATISTICS_update (GDS_stats,
1654                             gettext_noop ("# P2P PUT requests received"), 1,
1655                             GNUNET_NO);
1656   GNUNET_STATISTICS_update (GDS_stats,
1657                             gettext_noop ("# P2P PUT bytes received"), msize,
1658                             GNUNET_NO);
1659   put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1660   payload = &put_path[putlen];
1661   options = ntohl (put->options);
1662   payload_size =
1663       msize - (sizeof (struct PeerPutMessage) +
1664                putlen * sizeof (struct GNUNET_PeerIdentity));
1665
1666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1667               GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1668   GNUNET_CRYPTO_hash (peer, sizeof (struct GNUNET_PeerIdentity), &phash);
1669   if (GNUNET_YES == log_route_details_stderr)
1670   {
1671     char *tmp;
1672
1673     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1674     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1675                  "R5N PUT %s: %s->%s (%u, %u=>%u)\n",
1676                  GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1677                  ntohl(put->hop_count),
1678                  GNUNET_CRYPTO_hash_matching_bits (&phash, &put->key),
1679                  GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &put->key)
1680                 );
1681     GNUNET_free (tmp);
1682   }
1683   switch (GNUNET_BLOCK_get_key
1684           (GDS_block_context, ntohl (put->type), payload, payload_size,
1685            &test_key))
1686   {
1687   case GNUNET_YES:
1688     if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1689     {
1690       char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
1691       GNUNET_break_op (0);
1692       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1693                   "PUT with key `%s' for block with key %s\n",
1694                   put_s, GNUNET_h2s_full (&test_key));
1695       GNUNET_free (put_s);
1696       return GNUNET_YES;
1697     }
1698     break;
1699   case GNUNET_NO:
1700     GNUNET_break_op (0);
1701     return GNUNET_YES;
1702   case GNUNET_SYSERR:
1703     /* cannot verify, good luck */
1704     break;
1705   }
1706   if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1707   {
1708     switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1709                                    ntohl (put->type),
1710                                    GNUNET_BLOCK_EO_NONE,
1711                                    NULL,    /* query */
1712                                    NULL, 0, /* bloom filer */
1713                                    NULL, 0, /* xquery */
1714                                    payload, payload_size))
1715     {
1716     case GNUNET_BLOCK_EVALUATION_OK_MORE:
1717     case GNUNET_BLOCK_EVALUATION_OK_LAST:
1718       break;
1719
1720     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1721     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1722     case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1723     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1724     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1725     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1726     default:
1727       GNUNET_break_op (0);
1728       return GNUNET_OK;
1729     }
1730   }
1731
1732   bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1733                                           GNUNET_CONSTANTS_BLOOMFILTER_K);
1734   GNUNET_break_op (GNUNET_YES ==
1735                    GNUNET_CONTAINER_bloomfilter_test (bf, &phash));
1736   {
1737     struct GNUNET_PeerIdentity pp[putlen + 1];
1738
1739     /* extend 'put path' by sender */
1740     if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1741     {
1742       memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1743       pp[putlen] = *peer;
1744       putlen++;
1745     }
1746     else
1747       putlen = 0;
1748
1749     /* give to local clients */
1750     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1751                               &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1752                               payload_size, payload);
1753     /* store locally */
1754     if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1755         (am_closest_peer (&put->key, bf)))
1756       GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1757                                 (put->expiration_time), &put->key, putlen, pp,
1758                                 ntohl (put->type), payload_size, payload);
1759     /* route to other peers */
1760     forwarded = GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1761                                            ntohl (put->desired_replication_level),
1762                                            GNUNET_TIME_absolute_ntoh (put->expiration_time),
1763                                            ntohl (put->hop_count), bf,
1764                                            &put->key, putlen,
1765                                            pp, payload, payload_size);
1766     /* notify monitoring clients */
1767     GDS_CLIENTS_process_put (options
1768                              | (GNUNET_OK == forwarded)
1769                              ? GNUNET_DHT_RO_LAST_HOP : 0,
1770                              ntohl (put->type),
1771                              ntohl (put->hop_count),
1772                              ntohl (put->desired_replication_level),
1773                              putlen, pp,
1774                              GNUNET_TIME_absolute_ntoh (put->expiration_time),
1775                              &put->key,
1776                              payload,
1777                              payload_size);
1778   }
1779   GNUNET_CONTAINER_bloomfilter_free (bf);
1780   return GNUNET_YES;
1781 }
1782
1783
1784 /**
1785  * We have received a FIND PEER request.  Send matching
1786  * HELLOs back.
1787  *
1788  * @param sender sender of the FIND PEER request
1789  * @param key peers close to this key are desired
1790  * @param bf peers matching this bf are excluded
1791  * @param bf_mutator mutator for bf
1792  */
1793 static void
1794 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1795                   const struct GNUNET_HashCode * key,
1796                   struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1797 {
1798   int bucket_idx;
1799   struct PeerBucket *bucket;
1800   struct PeerInfo *peer;
1801   unsigned int choice;
1802   struct GNUNET_HashCode phash;
1803   struct GNUNET_HashCode mhash;
1804   const struct GNUNET_HELLO_Message *hello;
1805
1806   /* first, check about our own HELLO */
1807   if (NULL != GDS_my_hello)
1808   {
1809     GNUNET_BLOCK_mingle_hash (&my_identity_hash, bf_mutator, &mhash);
1810     if ((NULL == bf) ||
1811         (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1812     {
1813       GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1814                                    GNUNET_TIME_relative_to_absolute
1815                                    (hello_expiration),
1816                                    key, 0, NULL, 0, NULL, GDS_my_hello,
1817                                    GNUNET_HELLO_size ((const struct
1818                                                        GNUNET_HELLO_Message *)
1819                                                       GDS_my_hello));
1820     }
1821     else
1822     {
1823       GNUNET_STATISTICS_update (GDS_stats,
1824                                 gettext_noop
1825                                 ("# FIND PEER requests ignored due to Bloomfilter"),
1826                                 1, GNUNET_NO);
1827     }
1828   }
1829   else
1830   {
1831     GNUNET_STATISTICS_update (GDS_stats,
1832                               gettext_noop
1833                               ("# FIND PEER requests ignored due to lack of HELLO"),
1834                               1, GNUNET_NO);
1835   }
1836
1837   /* then, also consider sending a random HELLO from the closest bucket */
1838   if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1839     bucket_idx = closest_bucket;
1840   else
1841     bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1842   if (bucket_idx == GNUNET_SYSERR)
1843     return;
1844   bucket = &k_buckets[bucket_idx];
1845   if (bucket->peers_size == 0)
1846     return;
1847   choice =
1848       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1849   peer = bucket->head;
1850   while (choice > 0)
1851   {
1852     GNUNET_assert (NULL != peer);
1853     peer = peer->next;
1854     choice--;
1855   }
1856   choice = bucket->peers_size;
1857   do
1858   {
1859     peer = peer->next;
1860     if (choice-- == 0)
1861       return;                   /* no non-masked peer available */
1862     if (peer == NULL)
1863       peer = bucket->head;
1864     GNUNET_CRYPTO_hash (&peer->id, sizeof (struct GNUNET_PeerIdentity), &phash);
1865     GNUNET_BLOCK_mingle_hash (&phash, bf_mutator, &mhash);
1866     hello = GDS_HELLO_get (&peer->id);
1867   }
1868   while ((hello == NULL) ||
1869          (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1870   GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1871                                GNUNET_TIME_relative_to_absolute
1872                                (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1873                                0, NULL, 0, NULL, hello,
1874                                GNUNET_HELLO_size (hello));
1875 }
1876
1877
1878 /**
1879  * Core handler for p2p get requests.
1880  *
1881  * @param cls closure
1882  * @param peer sender of the request
1883  * @param message message
1884  * @return #GNUNET_OK to keep the connection open,
1885  *         #GNUNET_SYSERR to close it (signal serious error)
1886  */
1887 static int
1888 handle_dht_p2p_get (void *cls,
1889                     const struct GNUNET_PeerIdentity *peer,
1890                     const struct GNUNET_MessageHeader *message)
1891 {
1892   struct PeerGetMessage *get;
1893   uint32_t xquery_size;
1894   size_t reply_bf_size;
1895   uint16_t msize;
1896   enum GNUNET_BLOCK_Type type;
1897   enum GNUNET_DHT_RouteOption options;
1898   enum GNUNET_BLOCK_EvaluationResult eval;
1899   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1900   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1901   const char *xquery;
1902   struct GNUNET_HashCode phash;
1903   int forwarded;
1904
1905   GNUNET_break (0 !=
1906                 memcmp (peer, &my_identity,
1907                         sizeof (struct GNUNET_PeerIdentity)));
1908   /* parse and validate message */
1909   msize = ntohs (message->size);
1910   if (msize < sizeof (struct PeerGetMessage))
1911   {
1912     GNUNET_break_op (0);
1913     return GNUNET_YES;
1914   }
1915   get = (struct PeerGetMessage *) message;
1916   xquery_size = ntohl (get->xquery_size);
1917   if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1918   {
1919     GNUNET_break_op (0);
1920     return GNUNET_YES;
1921   }
1922   reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1923   type = ntohl (get->type);
1924   options = ntohl (get->options);
1925   xquery = (const char *) &get[1];
1926   reply_bf = NULL;
1927   GNUNET_STATISTICS_update (GDS_stats,
1928                             gettext_noop ("# P2P GET requests received"), 1,
1929                             GNUNET_NO);
1930   GNUNET_STATISTICS_update (GDS_stats,
1931                             gettext_noop ("# P2P GET bytes received"), msize,
1932                             GNUNET_NO);
1933   GNUNET_CRYPTO_hash (peer,
1934                       sizeof (struct GNUNET_PeerIdentity),
1935                       &phash);
1936   if (GNUNET_YES == log_route_details_stderr)
1937   {
1938     char *tmp;
1939
1940     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1941     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1942                  "R5N GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
1943                  GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
1944                  ntohl(get->hop_count),
1945                  GNUNET_CRYPTO_hash_matching_bits (&phash, &get->key),
1946                  GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &get->key),
1947                  ntohl(get->xquery_size), xquery);
1948     GNUNET_free (tmp);
1949   }
1950
1951   if (reply_bf_size > 0)
1952     reply_bf =
1953         GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1954                                            GNUNET_CONSTANTS_BLOOMFILTER_K);
1955   eval =
1956       GNUNET_BLOCK_evaluate (GDS_block_context,
1957                              type,
1958                              GNUNET_BLOCK_EO_NONE,
1959                              &get->key,
1960                              &reply_bf,
1961                              get->bf_mutator,
1962                              xquery,
1963                              xquery_size,
1964                              NULL,
1965                              0);
1966   if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1967   {
1968     /* request invalid or block type not supported */
1969     GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1970     if (NULL != reply_bf)
1971       GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1972     return GNUNET_YES;
1973   }
1974   peer_bf =
1975       GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1976                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
1977   GNUNET_break_op (GNUNET_YES ==
1978                    GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1979                                                       &phash));
1980   /* remember request for routing replies */
1981   GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1982                    reply_bf, get->bf_mutator);
1983   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1984               "GET for %s at %s after %u hops\n",
1985               GNUNET_h2s (&get->key),
1986               GNUNET_i2s (&my_identity),
1987               (unsigned int) ntohl (get->hop_count));
1988   /* local lookup (this may update the reply_bf) */
1989   if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1990       (am_closest_peer (&get->key, peer_bf)))
1991   {
1992     if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1993     {
1994       GNUNET_STATISTICS_update (GDS_stats,
1995                                 gettext_noop
1996                                 ("# P2P FIND PEER requests processed"), 1,
1997                                 GNUNET_NO);
1998       handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1999     }
2000     else
2001     {
2002       eval =
2003           GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
2004                                     &reply_bf, get->bf_mutator);
2005     }
2006   }
2007   else
2008   {
2009     GNUNET_STATISTICS_update (GDS_stats,
2010                               gettext_noop ("# P2P GET requests ONLY routed"),
2011                               1, GNUNET_NO);
2012   }
2013
2014   /* P2P forwarding */
2015   forwarded = GNUNET_NO;
2016   if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
2017     forwarded = GDS_NEIGHBOURS_handle_get (type, options,
2018                                            ntohl (get->desired_replication_level),
2019                                            ntohl (get->hop_count),
2020                                            &get->key,
2021                                            xquery,
2022                                            xquery_size,
2023                                            reply_bf,
2024                                            get->bf_mutator, peer_bf);
2025   GDS_CLIENTS_process_get (options
2026                            | (GNUNET_OK == forwarded)
2027                            ? GNUNET_DHT_RO_LAST_HOP : 0,
2028                            type,
2029                            ntohl (get->hop_count),
2030                            ntohl (get->desired_replication_level),
2031                            0, NULL,
2032                            &get->key);
2033
2034
2035   /* clean up */
2036   if (NULL != reply_bf)
2037     GNUNET_CONTAINER_bloomfilter_free (reply_bf);
2038   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
2039   return GNUNET_YES;
2040 }
2041
2042
2043 /**
2044  * Core handler for p2p result messages.
2045  *
2046  * @param cls closure
2047  * @param message message
2048  * @param peer peer identity this notification is about
2049  * @return #GNUNET_YES (do not cut p2p connection)
2050  */
2051 static int
2052 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
2053                        const struct GNUNET_MessageHeader *message)
2054 {
2055   const struct PeerResultMessage *prm;
2056   const struct GNUNET_PeerIdentity *put_path;
2057   const struct GNUNET_PeerIdentity *get_path;
2058   const void *data;
2059   uint32_t get_path_length;
2060   uint32_t put_path_length;
2061   uint16_t msize;
2062   size_t data_size;
2063   enum GNUNET_BLOCK_Type type;
2064
2065   /* parse and validate message */
2066   msize = ntohs (message->size);
2067   if (msize < sizeof (struct PeerResultMessage))
2068   {
2069     GNUNET_break_op (0);
2070     return GNUNET_YES;
2071   }
2072   prm = (struct PeerResultMessage *) message;
2073   put_path_length = ntohl (prm->put_path_length);
2074   get_path_length = ntohl (prm->get_path_length);
2075   if ((msize <
2076        sizeof (struct PeerResultMessage) + (get_path_length +
2077                                             put_path_length) *
2078        sizeof (struct GNUNET_PeerIdentity)) ||
2079       (get_path_length >
2080        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
2081       (put_path_length >
2082        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
2083   {
2084     GNUNET_break_op (0);
2085     return GNUNET_YES;
2086   }
2087   put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
2088   get_path = &put_path[put_path_length];
2089   type = ntohl (prm->type);
2090   data = (const void *) &get_path[get_path_length];
2091   data_size =
2092       msize - (sizeof (struct PeerResultMessage) +
2093                (get_path_length +
2094                 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
2095   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
2096                             1, GNUNET_NO);
2097   GNUNET_STATISTICS_update (GDS_stats,
2098                             gettext_noop ("# P2P RESULT bytes received"),
2099                             msize, GNUNET_NO);
2100   if (GNUNET_YES == log_route_details_stderr)
2101   {
2102     char *tmp;
2103
2104     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2105     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "R5N RESULT %s: %s->%s (%u)\n",
2106                  GNUNET_h2s (&prm->key), GNUNET_i2s (peer), tmp,
2107                  get_path_length + 1);
2108     GNUNET_free (tmp);
2109   }
2110   /* if we got a HELLO, consider it for our own routing table */
2111   if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
2112   {
2113     const struct GNUNET_MessageHeader *h;
2114     struct GNUNET_PeerIdentity pid;
2115     int bucket;
2116
2117     /* Should be a HELLO, validate and consider using it! */
2118     if (data_size < sizeof (struct GNUNET_MessageHeader))
2119     {
2120       GNUNET_break_op (0);
2121       return GNUNET_YES;
2122     }
2123     h = data;
2124     if (data_size != ntohs (h->size))
2125     {
2126       GNUNET_break_op (0);
2127       return GNUNET_YES;
2128     }
2129     if (GNUNET_OK !=
2130         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
2131     {
2132       GNUNET_break_op (0);
2133       return GNUNET_YES;
2134     }
2135     if ((GNUNET_YES != disable_try_connect) &&
2136         0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
2137     {
2138       struct GNUNET_HashCode pid_hash;
2139
2140       GNUNET_CRYPTO_hash (&pid, sizeof (struct GNUNET_PeerIdentity), &pid_hash);
2141       bucket = find_bucket (&pid_hash);
2142       if ((bucket >= 0) &&
2143           (k_buckets[bucket].peers_size < bucket_size) &&
2144           (NULL != GDS_transport_handle))
2145       {
2146         GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
2147         GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid, NULL, NULL); /*FIXME TRY_CONNECT change */
2148       }
2149     }
2150   }
2151
2152   /* append 'peer' to 'get_path' */
2153   {
2154     struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2155
2156     memcpy (xget_path, get_path,
2157             get_path_length * sizeof (struct GNUNET_PeerIdentity));
2158     xget_path[get_path_length] = *peer;
2159     get_path_length++;
2160
2161     /* forward to local clients */
2162     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2163                               &prm->key, get_path_length, xget_path,
2164                               put_path_length, put_path, type, data_size, data);
2165     GDS_CLIENTS_process_get_resp (type,
2166                                   xget_path, get_path_length,
2167                                   put_path, put_path_length,
2168                                   GNUNET_TIME_absolute_ntoh (
2169                                     prm->expiration_time),
2170                                   &prm->key,
2171                                   data,
2172                                   data_size);
2173     if (GNUNET_YES == cache_results)
2174     {
2175       struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length];
2176
2177       memcpy (xput_path, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
2178       memcpy (&xput_path[put_path_length],
2179               xget_path,
2180               get_path_length * sizeof (struct GNUNET_PeerIdentity));
2181
2182       GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2183                                 &prm->key,
2184                                 get_path_length + put_path_length, xput_path,
2185                                 type, data_size, data);
2186     }
2187     /* forward to other peers */
2188     GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2189                          &prm->key, put_path_length, put_path, get_path_length,
2190                          xget_path, data, data_size);
2191   }
2192
2193   return GNUNET_YES;
2194 }
2195
2196
2197 /**
2198  * Initialize neighbours subsystem.
2199  *
2200  * @return GNUNET_OK on success, GNUNET_SYSERR on error
2201  */
2202 int
2203 GDS_NEIGHBOURS_init ()
2204 {
2205   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2206     {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2207     {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2208     {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2209     {NULL, 0, 0}
2210   };
2211   unsigned long long temp_config_num;
2212
2213   disable_try_connect
2214     = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2215   if (GNUNET_OK ==
2216       GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2217                                              &temp_config_num))
2218     bucket_size = (unsigned int) temp_config_num;
2219   cache_results
2220     = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "CACHE_RESULTS");
2221
2222   log_route_details_stderr =
2223     (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2224   atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2225   core_api =
2226       GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2227                            &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2228                            GNUNET_NO, core_handlers);
2229   if (core_api == NULL)
2230     return GNUNET_SYSERR;
2231   all_known_peers = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
2232   return GNUNET_OK;
2233 }
2234
2235
2236 /**
2237  * Shutdown neighbours subsystem.
2238  */
2239 void
2240 GDS_NEIGHBOURS_done ()
2241 {
2242   if (NULL == core_api)
2243     return;
2244   GNUNET_CORE_disconnect (core_api);
2245   core_api = NULL;
2246   GNUNET_ATS_performance_done (atsAPI);
2247   atsAPI = NULL;
2248   GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (all_known_peers));
2249   GNUNET_CONTAINER_multipeermap_destroy (all_known_peers);
2250   all_known_peers = NULL;
2251   if (NULL != find_peer_task)
2252   {
2253     GNUNET_SCHEDULER_cancel (find_peer_task);
2254     find_peer_task = NULL;
2255   }
2256 }
2257
2258 /**
2259  * Get the ID of the local node.
2260  *
2261  * @return identity of the local node
2262  */
2263 struct GNUNET_PeerIdentity *
2264 GDS_NEIGHBOURS_get_id ()
2265 {
2266   return &my_identity;
2267 }
2268
2269
2270 /* end of gnunet-service-dht_neighbours.c */