TUN_IFNAME is the tunnel interface, not EXIT_IFNAME
[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, 
828                                  peer->tail,
829                                  pending);
830     GNUNET_free (pending);
831   }
832   if (NULL != (pending = peer->head))
833   {
834     /* technically redundant, but easier to read and
835        avoids bogus gcc warning... */
836     msize = ntohs (pending->msg->size);
837     peer->th =
838       GNUNET_CORE_notify_transmit_ready (core_api, 
839                                          GNUNET_NO,
840                                          GNUNET_CORE_PRIO_BEST_EFFORT,
841                                          GNUNET_TIME_absolute_get_remaining (pending->timeout), 
842                                          &peer->id,
843                                          msize,
844                                          &core_transmit_notify, 
845                                          peer);
846     GNUNET_break (NULL != peer->th);
847   }
848   return off;
849 }
850
851
852 /**
853  * Transmit all messages in the peer's message queue.
854  *
855  * @param peer message queue to process
856  */
857 static void
858 process_peer_queue (struct PeerInfo *peer)
859 {
860   struct P2PPendingMessage *pending;
861
862   if (NULL == (pending = peer->head))
863     return;
864   if (NULL != peer->th)
865     return;
866   GNUNET_STATISTICS_update (GDS_stats,
867                             gettext_noop
868                             ("# Bytes of bandwidth requested from core"),
869                             ntohs (pending->msg->size), GNUNET_NO);
870   peer->th =
871       GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
872                                          GNUNET_CORE_PRIO_BEST_EFFORT,
873                                          GNUNET_TIME_absolute_get_remaining
874                                          (pending->timeout), &peer->id,
875                                          ntohs (pending->msg->size),
876                                          &core_transmit_notify, peer);
877   GNUNET_break (NULL != peer->th);
878 }
879
880
881 /**
882  * To how many peers should we (on average) forward the request to
883  * obtain the desired target_replication count (on average).
884  *
885  * @param hop_count number of hops the message has traversed
886  * @param target_replication the number of total paths desired
887  * @return Some number of peers to forward the message to
888  */
889 static unsigned int
890 get_forward_count (uint32_t hop_count, uint32_t target_replication)
891 {
892   uint32_t random_value;
893   uint32_t forward_count;
894   float target_value;
895
896   if (hop_count > GDS_NSE_get () * 4.0)
897   {
898     /* forcefully terminate */
899     GNUNET_STATISTICS_update (GDS_stats,
900                               gettext_noop ("# requests TTL-dropped"),
901                               1, GNUNET_NO);
902     return 0;
903   }
904   if (hop_count > GDS_NSE_get () * 2.0)
905   {
906     /* Once we have reached our ideal number of hops, only forward to 1 peer */
907     return 1;
908   }
909   /* bound by system-wide maximum */
910   target_replication =
911       GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
912   target_value =
913       1 + (target_replication - 1.0) / (GDS_NSE_get () +
914                                         ((float) (target_replication - 1.0) *
915                                          hop_count));
916   /* Set forward count to floor of target_value */
917   forward_count = (uint32_t) target_value;
918   /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
919   target_value = target_value - forward_count;
920   random_value =
921       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
922   if (random_value < (target_value * UINT32_MAX))
923     forward_count++;
924   return forward_count;
925 }
926
927
928 /**
929  * Compute the distance between have and target as a 32-bit value.
930  * Differences in the lower bits must count stronger than differences
931  * in the higher bits.
932  *
933  * @param target
934  * @param have
935  * @return 0 if have==target, otherwise a number
936  *           that is larger as the distance between
937  *           the two hash codes increases
938  */
939 static unsigned int
940 get_distance (const struct GNUNET_HashCode *target,
941               const struct GNUNET_HashCode *have)
942 {
943   unsigned int bucket;
944   unsigned int msb;
945   unsigned int lsb;
946   unsigned int i;
947
948   /* We have to represent the distance between two 2^9 (=512)-bit
949    * numbers as a 2^5 (=32)-bit number with "0" being used for the
950    * two numbers being identical; furthermore, we need to
951    * guarantee that a difference in the number of matching
952    * bits is always represented in the result.
953    *
954    * We use 2^32/2^9 numerical values to distinguish between
955    * hash codes that have the same LSB bit distance and
956    * use the highest 2^9 bits of the result to signify the
957    * number of (mis)matching LSB bits; if we have 0 matching
958    * and hence 512 mismatching LSB bits we return -1 (since
959    * 512 itself cannot be represented with 9 bits) */
960
961   /* first, calculate the most significant 9 bits of our
962    * result, aka the number of LSBs */
963   bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
964   /* bucket is now a value between 0 and 512 */
965   if (bucket == 512)
966     return 0;                   /* perfect match */
967   if (bucket == 0)
968     return (unsigned int) -1;   /* LSB differs; use max (if we did the bit-shifting
969                                  * below, we'd end up with max+1 (overflow)) */
970
971   /* calculate the most significant bits of the final result */
972   msb = (512 - bucket) << (32 - 9);
973   /* calculate the 32-9 least significant bits of the final result by
974    * looking at the differences in the 32-9 bits following the
975    * mismatching bit at 'bucket' */
976   lsb = 0;
977   for (i = bucket + 1;
978        (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
979   {
980     if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
981         GNUNET_CRYPTO_hash_get_bit (have, i))
982       lsb |= (1 << (bucket + 32 - 9 - i));      /* first bit set will be 10,
983                                                  * last bit set will be 31 -- if
984                                                  * i does not reach 512 first... */
985   }
986   return msb | lsb;
987 }
988
989
990 /**
991  * Check whether my identity is closer than any known peers.  If a
992  * non-null bloomfilter is given, check if this is the closest peer
993  * that hasn't already been routed to.
994  *
995  * @param key hash code to check closeness to
996  * @param bloom bloomfilter, exclude these entries from the decision
997  * @return #GNUNET_YES if node location is closest,
998  *         #GNUNET_NO otherwise.
999  */
1000 static int
1001 am_closest_peer (const struct GNUNET_HashCode *key,
1002                  const struct GNUNET_CONTAINER_BloomFilter *bloom)
1003 {
1004   int bits;
1005   int other_bits;
1006   int bucket_num;
1007   int count;
1008   struct PeerInfo *pos;
1009   struct GNUNET_HashCode phash;
1010
1011   if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1012     return GNUNET_YES;
1013   bucket_num = find_bucket (key);
1014   GNUNET_assert (bucket_num >= 0);
1015   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, key);
1016   pos = k_buckets[bucket_num].head;
1017   count = 0;
1018   while ((pos != NULL) && (count < bucket_size))
1019   {
1020     GNUNET_CRYPTO_hash (&pos->id,
1021                         sizeof (struct GNUNET_PeerIdentity),
1022                         &phash);
1023     if ((bloom != NULL) &&
1024         (GNUNET_YES ==
1025          GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1026     {
1027       pos = pos->next;
1028       continue;                 /* Skip already checked entries */
1029     }
1030     other_bits = GNUNET_CRYPTO_hash_matching_bits (&phash, key);
1031     if (other_bits > bits)
1032       return GNUNET_NO;
1033     if (other_bits == bits)     /* We match the same number of bits */
1034       return GNUNET_YES;
1035     pos = pos->next;
1036   }
1037   /* No peers closer, we are the closest! */
1038   return GNUNET_YES;
1039 }
1040
1041
1042 /**
1043  * Select a peer from the routing table that would be a good routing
1044  * destination for sending a message for "key".  The resulting peer
1045  * must not be in the set of blocked peers.<p>
1046  *
1047  * Note that we should not ALWAYS select the closest peer to the
1048  * target, peers further away from the target should be chosen with
1049  * exponentially declining probability.
1050  *
1051  * FIXME: double-check that this is fine
1052  *
1053  *
1054  * @param key the key we are selecting a peer to route to
1055  * @param bloom a bloomfilter containing entries this request has seen already
1056  * @param hops how many hops has this message traversed thus far
1057  * @return Peer to route to, or NULL on error
1058  */
1059 static struct PeerInfo *
1060 select_peer (const struct GNUNET_HashCode * key,
1061              const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1062 {
1063   unsigned int bc;
1064   unsigned int count;
1065   unsigned int selected;
1066   struct PeerInfo *pos;
1067   unsigned int dist;
1068   unsigned int smallest_distance;
1069   struct PeerInfo *chosen;
1070   struct GNUNET_HashCode phash;
1071
1072   if (hops >= GDS_NSE_get ())
1073   {
1074     /* greedy selection (closest peer that is not in bloomfilter) */
1075     smallest_distance = UINT_MAX;
1076     chosen = NULL;
1077     for (bc = 0; bc <= closest_bucket; bc++)
1078     {
1079       pos = k_buckets[bc].head;
1080       count = 0;
1081       while ((pos != NULL) && (count < bucket_size))
1082       {
1083         GNUNET_CRYPTO_hash (&pos->id,
1084                             sizeof (struct GNUNET_PeerIdentity),
1085                             &phash);
1086         if ((bloom == NULL) ||
1087             (GNUNET_NO ==
1088              GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1089         {
1090           dist = get_distance (key, &phash);
1091           if (dist < smallest_distance)
1092           {
1093             chosen = pos;
1094             smallest_distance = dist;
1095           }
1096         }
1097         else
1098         {
1099           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100                       "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1101                       GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1102           GNUNET_STATISTICS_update (GDS_stats,
1103                                     gettext_noop
1104                                     ("# Peers excluded from routing due to Bloomfilter"),
1105                                     1, GNUNET_NO);
1106           dist = get_distance (key, &phash);
1107           if (dist < smallest_distance)
1108           {
1109             chosen = NULL;
1110             smallest_distance = dist;
1111           }
1112         }
1113         count++;
1114         pos = pos->next;
1115       }
1116     }
1117     if (NULL == chosen)
1118       GNUNET_STATISTICS_update (GDS_stats,
1119                                 gettext_noop ("# Peer selection failed"), 1,
1120                                 GNUNET_NO);
1121     return chosen;
1122   }
1123
1124   /* select "random" peer */
1125   /* count number of peers that are available and not filtered */
1126   count = 0;
1127   for (bc = 0; bc <= closest_bucket; bc++)
1128   {
1129     pos = k_buckets[bc].head;
1130     while ((pos != NULL) && (count < bucket_size))
1131     {
1132       GNUNET_CRYPTO_hash (&pos->id,
1133                           sizeof (struct GNUNET_PeerIdentity),
1134                           &phash);
1135       if ((bloom != NULL) &&
1136           (GNUNET_YES ==
1137            GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1138       {
1139         GNUNET_STATISTICS_update (GDS_stats,
1140                                   gettext_noop
1141                                   ("# Peers excluded from routing due to Bloomfilter"),
1142                                   1, GNUNET_NO);
1143         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1144                     "Excluded peer `%s' due to BF match in random routing for %s\n",
1145                     GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1146         pos = pos->next;
1147         continue;               /* Ignore bloomfiltered peers */
1148       }
1149       count++;
1150       pos = pos->next;
1151     }
1152   }
1153   if (0 == count)               /* No peers to select from! */
1154   {
1155     GNUNET_STATISTICS_update (GDS_stats,
1156                               gettext_noop ("# Peer selection failed"), 1,
1157                               GNUNET_NO);
1158     return NULL;
1159   }
1160   /* Now actually choose a peer */
1161   selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1162   count = 0;
1163   for (bc = 0; bc <= closest_bucket; bc++)
1164   {
1165     for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1166     {
1167       GNUNET_CRYPTO_hash (&pos->id,
1168                           sizeof (struct GNUNET_PeerIdentity),
1169                           &phash);
1170       if ((bloom != NULL) &&
1171           (GNUNET_YES ==
1172            GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1173       {
1174         continue;               /* Ignore bloomfiltered peers */
1175       }
1176       if (0 == selected--)
1177         return pos;
1178     }
1179   }
1180   GNUNET_break (0);
1181   return NULL;
1182 }
1183
1184
1185 /**
1186  * Compute the set of peers that the given request should be
1187  * forwarded to.
1188  *
1189  * @param key routing key
1190  * @param bloom bloom filter excluding peers as targets, all selected
1191  *        peers will be added to the bloom filter
1192  * @param hop_count number of hops the request has traversed so far
1193  * @param target_replication desired number of replicas
1194  * @param targets where to store an array of target peers (to be
1195  *         free'd by the caller)
1196  * @return number of peers returned in 'targets'.
1197  */
1198 static unsigned int
1199 get_target_peers (const struct GNUNET_HashCode *key,
1200                   struct GNUNET_CONTAINER_BloomFilter *bloom,
1201                   uint32_t hop_count, uint32_t target_replication,
1202                   struct PeerInfo ***targets)
1203 {
1204   unsigned int ret;
1205   unsigned int off;
1206   struct PeerInfo **rtargets;
1207   struct PeerInfo *nxt;
1208   struct GNUNET_HashCode nhash;
1209
1210   GNUNET_assert (NULL != bloom);
1211   ret = get_forward_count (hop_count, target_replication);
1212   if (0 == ret)
1213   {
1214     *targets = NULL;
1215     return 0;
1216   }
1217   rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1218   for (off = 0; off < ret; off++)
1219   {
1220     nxt = select_peer (key, bloom, hop_count);
1221     if (NULL == nxt)
1222       break;
1223     rtargets[off] = nxt;
1224     GNUNET_CRYPTO_hash (&nxt->id,
1225                         sizeof (struct GNUNET_PeerIdentity),
1226                         &nhash);
1227     GNUNET_break (GNUNET_NO ==
1228                   GNUNET_CONTAINER_bloomfilter_test (bloom,
1229                                                      &nhash));
1230     GNUNET_CONTAINER_bloomfilter_add (bloom, &nhash);
1231   }
1232   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1233               "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1234               GNUNET_CONTAINER_multipeermap_size (all_known_peers),
1235               (unsigned int) hop_count, GNUNET_h2s (key), ret);
1236   if (0 == off)
1237   {
1238     GNUNET_free (rtargets);
1239     *targets = NULL;
1240     return 0;
1241   }
1242   *targets = rtargets;
1243   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1244               "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1245               GNUNET_h2s (key),
1246               off,
1247               ret);
1248   return off;
1249 }
1250
1251
1252 /**
1253  * Perform a PUT operation.   Forwards the given request to other
1254  * peers.   Does not store the data locally.  Does not give the
1255  * data to local clients.  May do nothing if this is the only
1256  * peer in the network (or if we are the closest peer in the
1257  * network).
1258  *
1259  * @param type type of the block
1260  * @param options routing options
1261  * @param desired_replication_level desired replication count
1262  * @param expiration_time when does the content expire
1263  * @param hop_count how many hops has this message traversed so far
1264  * @param bf Bloom filter of peers this PUT has already traversed
1265  * @param key key for the content
1266  * @param put_path_length number of entries in @a put_path
1267  * @param put_path peers this request has traversed so far (if tracked)
1268  * @param data payload to store
1269  * @param data_size number of bytes in @a data
1270  * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1271  */
1272 int
1273 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1274                            enum GNUNET_DHT_RouteOption options,
1275                            uint32_t desired_replication_level,
1276                            struct GNUNET_TIME_Absolute expiration_time,
1277                            uint32_t hop_count,
1278                            struct GNUNET_CONTAINER_BloomFilter *bf,
1279                            const struct GNUNET_HashCode *key,
1280                            unsigned int put_path_length,
1281                            struct GNUNET_PeerIdentity *put_path,
1282                            const void *data, size_t data_size)
1283 {
1284   unsigned int target_count;
1285   unsigned int i;
1286   struct PeerInfo **targets;
1287   struct PeerInfo *target;
1288   struct P2PPendingMessage *pending;
1289   size_t msize;
1290   struct PeerPutMessage *ppm;
1291   struct GNUNET_PeerIdentity *pp;
1292   struct GNUNET_HashCode thash;
1293   unsigned int skip_count;
1294
1295   GNUNET_assert (NULL != bf);
1296   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1297               "Adding myself (%s) to PUT bloomfilter for %s\n",
1298               GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1299   GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity_hash);
1300   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1301                             1, GNUNET_NO);
1302   target_count =
1303       get_target_peers (key, bf, hop_count, desired_replication_level,
1304                         &targets);
1305   if (0 == target_count)
1306   {
1307     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1308                 "Routing PUT for %s terminates after %u hops at %s\n",
1309                 GNUNET_h2s (key), (unsigned int) hop_count,
1310                 GNUNET_i2s (&my_identity));
1311     return GNUNET_NO;
1312   }
1313   msize =
1314       put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1315       sizeof (struct PeerPutMessage);
1316   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1317   {
1318     put_path_length = 0;
1319     msize = data_size + sizeof (struct PeerPutMessage);
1320   }
1321   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1322   {
1323     GNUNET_break (0);
1324     GNUNET_free (targets);
1325     return GNUNET_NO;
1326   }
1327   GNUNET_STATISTICS_update (GDS_stats,
1328                             gettext_noop
1329                             ("# PUT messages queued for transmission"),
1330                             target_count, GNUNET_NO);
1331   skip_count = 0;
1332   for (i = 0; i < target_count; i++)
1333   {
1334     target = targets[i];
1335     if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1336     {
1337       /* skip */
1338       GNUNET_STATISTICS_update (GDS_stats,
1339                                 gettext_noop ("# P2P messages dropped due to full queue"),
1340                                 1, GNUNET_NO);
1341       skip_count++;
1342       continue;
1343     }
1344     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1345                 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1346                 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1347     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1348     pending->importance = 0;    /* FIXME */
1349     pending->timeout = expiration_time;
1350     ppm = (struct PeerPutMessage *) &pending[1];
1351     pending->msg = &ppm->header;
1352     ppm->header.size = htons (msize);
1353     ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1354     ppm->options = htonl (options);
1355     ppm->type = htonl (type);
1356     ppm->hop_count = htonl (hop_count + 1);
1357     ppm->desired_replication_level = htonl (desired_replication_level);
1358     ppm->put_path_length = htonl (put_path_length);
1359     ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1360     GNUNET_CRYPTO_hash (&target->id,
1361                         sizeof (struct GNUNET_PeerIdentity),
1362                         &thash);
1363     GNUNET_break (GNUNET_YES ==
1364                   GNUNET_CONTAINER_bloomfilter_test (bf,
1365                                                      &thash));
1366     GNUNET_assert (GNUNET_OK ==
1367                    GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1368                                                               ppm->bloomfilter,
1369                                                               DHT_BLOOM_SIZE));
1370     ppm->key = *key;
1371     pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1372     memcpy (pp, put_path,
1373             sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1374     memcpy (&pp[put_path_length], data, data_size);
1375     GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1376     target->pending_count++;
1377     process_peer_queue (target);
1378   }
1379   GNUNET_free (targets);
1380   return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1381 }
1382
1383
1384 /**
1385  * Perform a GET operation.  Forwards the given request to other
1386  * peers.  Does not lookup the key locally.  May do nothing if this is
1387  * the only peer in the network (or if we are the closest peer in the
1388  * network).
1389  *
1390  * @param type type of the block
1391  * @param options routing options
1392  * @param desired_replication_level desired replication count
1393  * @param hop_count how many hops did this request traverse so far?
1394  * @param key key for the content
1395  * @param xquery extended query
1396  * @param xquery_size number of bytes in @a xquery
1397  * @param reply_bf bloomfilter to filter duplicates
1398  * @param reply_bf_mutator mutator for @a reply_bf
1399  * @param peer_bf filter for peers not to select (again)
1400  * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1401  */
1402 int
1403 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1404                            enum GNUNET_DHT_RouteOption options,
1405                            uint32_t desired_replication_level,
1406                            uint32_t hop_count, const struct GNUNET_HashCode * key,
1407                            const void *xquery, size_t xquery_size,
1408                            const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1409                            uint32_t reply_bf_mutator,
1410                            struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1411 {
1412   unsigned int target_count;
1413   unsigned int i;
1414   struct PeerInfo **targets;
1415   struct PeerInfo *target;
1416   struct P2PPendingMessage *pending;
1417   size_t msize;
1418   struct PeerGetMessage *pgm;
1419   char *xq;
1420   size_t reply_bf_size;
1421   struct GNUNET_HashCode thash;
1422   unsigned int skip_count;
1423
1424   GNUNET_assert (NULL != peer_bf);
1425   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1426                             1, GNUNET_NO);
1427   target_count =
1428       get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1429                         &targets);
1430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1431               "Adding myself (%s) to GET bloomfilter for %s\n",
1432               GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1433   GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity_hash);
1434   if (0 == target_count)
1435   {
1436     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1437                 "Routing GET for %s terminates after %u hops at %s\n",
1438                 GNUNET_h2s (key), (unsigned int) hop_count,
1439                 GNUNET_i2s (&my_identity));
1440     return GNUNET_NO;
1441   }
1442   reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1443   msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1444   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1445   {
1446     GNUNET_break (0);
1447     GNUNET_free (targets);
1448     return GNUNET_NO;
1449   }
1450   GNUNET_STATISTICS_update (GDS_stats,
1451                             gettext_noop
1452                             ("# GET messages queued for transmission"),
1453                             target_count, GNUNET_NO);
1454   /* forward request */
1455   skip_count = 0;
1456   for (i = 0; i < target_count; i++)
1457   {
1458     target = targets[i];
1459     if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1460     {
1461       /* skip */
1462       GNUNET_STATISTICS_update (GDS_stats,
1463                                 gettext_noop ("# P2P messages dropped due to full queue"),
1464                                 1, GNUNET_NO);
1465       skip_count++;
1466       continue;
1467     }
1468     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1469                 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1470                 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1471     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1472     pending->importance = 0;    /* FIXME */
1473     pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1474     pgm = (struct PeerGetMessage *) &pending[1];
1475     pending->msg = &pgm->header;
1476     pgm->header.size = htons (msize);
1477     pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1478     pgm->options = htonl (options);
1479     pgm->type = htonl (type);
1480     pgm->hop_count = htonl (hop_count + 1);
1481     pgm->desired_replication_level = htonl (desired_replication_level);
1482     pgm->xquery_size = htonl (xquery_size);
1483     pgm->bf_mutator = reply_bf_mutator;
1484     GNUNET_CRYPTO_hash (&target->id,
1485                         sizeof (struct GNUNET_PeerIdentity),
1486                         &thash);
1487     GNUNET_break (GNUNET_YES ==
1488                   GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1489                                                      &thash));
1490     GNUNET_assert (GNUNET_OK ==
1491                    GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1492                                                               pgm->bloomfilter,
1493                                                               DHT_BLOOM_SIZE));
1494     pgm->key = *key;
1495     xq = (char *) &pgm[1];
1496     memcpy (xq, xquery, xquery_size);
1497     if (NULL != reply_bf)
1498       GNUNET_assert (GNUNET_OK ==
1499                      GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1500                                                                 &xq
1501                                                                 [xquery_size],
1502                                                                 reply_bf_size));
1503     GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1504     target->pending_count++;
1505     process_peer_queue (target);
1506   }
1507   GNUNET_free (targets);
1508   return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1509 }
1510
1511
1512 /**
1513  * Handle a reply (route to origin).  Only forwards the reply back to
1514  * the given peer.  Does not do local caching or forwarding to local
1515  * clients.
1516  *
1517  * @param target neighbour that should receive the block (if still connected)
1518  * @param type type of the block
1519  * @param expiration_time when does the content expire
1520  * @param key key for the content
1521  * @param put_path_length number of entries in @a put_path
1522  * @param put_path peers the original PUT traversed (if tracked)
1523  * @param get_path_length number of entries in @a get_path
1524  * @param get_path peers this reply has traversed so far (if tracked)
1525  * @param data payload of the reply
1526  * @param data_size number of bytes in @a data
1527  */
1528 void
1529 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1530                              enum GNUNET_BLOCK_Type type,
1531                              struct GNUNET_TIME_Absolute expiration_time,
1532                              const struct GNUNET_HashCode * key,
1533                              unsigned int put_path_length,
1534                              const struct GNUNET_PeerIdentity *put_path,
1535                              unsigned int get_path_length,
1536                              const struct GNUNET_PeerIdentity *get_path,
1537                              const void *data, size_t data_size)
1538 {
1539   struct PeerInfo *pi;
1540   struct P2PPendingMessage *pending;
1541   size_t msize;
1542   struct PeerResultMessage *prm;
1543   struct GNUNET_PeerIdentity *paths;
1544
1545   msize =
1546       data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1547                                                        put_path_length) *
1548       sizeof (struct GNUNET_PeerIdentity);
1549   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1550       (get_path_length >
1551        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1552       (put_path_length >
1553        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1554       (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1555   {
1556     GNUNET_break (0);
1557     return;
1558   }
1559   pi = GNUNET_CONTAINER_multipeermap_get (all_known_peers, target);
1560   if (NULL == pi)
1561   {
1562     /* peer disconnected in the meantime, drop reply */
1563     return;
1564   }
1565   if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1566   {
1567     /* skip */
1568     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1569                               1, GNUNET_NO);
1570     return;
1571   }
1572
1573   GNUNET_STATISTICS_update (GDS_stats,
1574                             gettext_noop
1575                             ("# RESULT messages queued for transmission"), 1,
1576                             GNUNET_NO);
1577   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1578   pending->importance = 0;      /* FIXME */
1579   pending->timeout = expiration_time;
1580   prm = (struct PeerResultMessage *) &pending[1];
1581   pending->msg = &prm->header;
1582   prm->header.size = htons (msize);
1583   prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1584   prm->type = htonl (type);
1585   prm->put_path_length = htonl (put_path_length);
1586   prm->get_path_length = htonl (get_path_length);
1587   prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1588   prm->key = *key;
1589   paths = (struct GNUNET_PeerIdentity *) &prm[1];
1590   memcpy (paths, put_path,
1591           put_path_length * sizeof (struct GNUNET_PeerIdentity));
1592   memcpy (&paths[put_path_length], get_path,
1593           get_path_length * sizeof (struct GNUNET_PeerIdentity));
1594   memcpy (&paths[put_path_length + get_path_length], data, data_size);
1595   GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1596   pi->pending_count++;
1597   process_peer_queue (pi);
1598 }
1599
1600
1601 /**
1602  * To be called on core init/fail.
1603  *
1604  * @param cls service closure
1605  * @param identity the public identity of this peer
1606  */
1607 static void
1608 core_init (void *cls,
1609            const struct GNUNET_PeerIdentity *identity)
1610 {
1611   my_identity = *identity;
1612   GNUNET_CRYPTO_hash (identity,
1613                       sizeof (struct GNUNET_PeerIdentity),
1614                       &my_identity_hash);
1615 }
1616
1617
1618 /**
1619  * Core handler for p2p put requests.
1620  *
1621  * @param cls closure
1622  * @param peer sender of the request
1623  * @param message message
1624  * @param peer peer identity this notification is about
1625  * @return #GNUNET_OK to keep the connection open,
1626  *         #GNUNET_SYSERR to close it (signal serious error)
1627  */
1628 static int
1629 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1630                     const struct GNUNET_MessageHeader *message)
1631 {
1632   const struct PeerPutMessage *put;
1633   const struct GNUNET_PeerIdentity *put_path;
1634   const void *payload;
1635   uint32_t putlen;
1636   uint16_t msize;
1637   size_t payload_size;
1638   enum GNUNET_DHT_RouteOption options;
1639   struct GNUNET_CONTAINER_BloomFilter *bf;
1640   struct GNUNET_HashCode test_key;
1641   struct GNUNET_HashCode phash;
1642   int forwarded;
1643
1644   msize = ntohs (message->size);
1645   if (msize < sizeof (struct PeerPutMessage))
1646   {
1647     GNUNET_break_op (0);
1648     return GNUNET_YES;
1649   }
1650   put = (const struct PeerPutMessage *) message;
1651   putlen = ntohl (put->put_path_length);
1652   if ((msize <
1653        sizeof (struct PeerPutMessage) +
1654        putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1655       (putlen >
1656        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1657   {
1658     GNUNET_break_op (0);
1659     return GNUNET_YES;
1660   }
1661   GNUNET_STATISTICS_update (GDS_stats,
1662                             gettext_noop ("# P2P PUT requests received"), 1,
1663                             GNUNET_NO);
1664   GNUNET_STATISTICS_update (GDS_stats,
1665                             gettext_noop ("# P2P PUT bytes received"), msize,
1666                             GNUNET_NO);
1667   put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1668   payload = &put_path[putlen];
1669   options = ntohl (put->options);
1670   payload_size =
1671       msize - (sizeof (struct PeerPutMessage) +
1672                putlen * sizeof (struct GNUNET_PeerIdentity));
1673
1674   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1675               GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1676   GNUNET_CRYPTO_hash (peer, sizeof (struct GNUNET_PeerIdentity), &phash);
1677   if (GNUNET_YES == log_route_details_stderr)
1678   {
1679     char *tmp;
1680
1681     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1682     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1683                  "R5N PUT %s: %s->%s (%u, %u=>%u)\n",
1684                  GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1685                  ntohl(put->hop_count),
1686                  GNUNET_CRYPTO_hash_matching_bits (&phash, &put->key),
1687                  GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &put->key)
1688                 );
1689     GNUNET_free (tmp);
1690   }
1691   switch (GNUNET_BLOCK_get_key
1692           (GDS_block_context, ntohl (put->type), payload, payload_size,
1693            &test_key))
1694   {
1695   case GNUNET_YES:
1696     if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1697     {
1698       char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
1699       GNUNET_break_op (0);
1700       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1701                   "PUT with key `%s' for block with key %s\n",
1702                   put_s, GNUNET_h2s_full (&test_key));
1703       GNUNET_free (put_s);
1704       return GNUNET_YES;
1705     }
1706     break;
1707   case GNUNET_NO:
1708     GNUNET_break_op (0);
1709     return GNUNET_YES;
1710   case GNUNET_SYSERR:
1711     /* cannot verify, good luck */
1712     break;
1713   }
1714   if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1715   {
1716     switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1717                                    ntohl (put->type),
1718                                    GNUNET_BLOCK_EO_NONE,
1719                                    NULL,    /* query */
1720                                    NULL, 0, /* bloom filer */
1721                                    NULL, 0, /* xquery */
1722                                    payload, payload_size))
1723     {
1724     case GNUNET_BLOCK_EVALUATION_OK_MORE:
1725     case GNUNET_BLOCK_EVALUATION_OK_LAST:
1726       break;
1727
1728     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1729     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1730     case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1731     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1732     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1733     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1734     default:
1735       GNUNET_break_op (0);
1736       return GNUNET_OK;
1737     }
1738   }
1739
1740   bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1741                                           GNUNET_CONSTANTS_BLOOMFILTER_K);
1742   GNUNET_break_op (GNUNET_YES ==
1743                    GNUNET_CONTAINER_bloomfilter_test (bf, &phash));
1744   {
1745     struct GNUNET_PeerIdentity pp[putlen + 1];
1746
1747     /* extend 'put path' by sender */
1748     if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1749     {
1750       memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1751       pp[putlen] = *peer;
1752       putlen++;
1753     }
1754     else
1755       putlen = 0;
1756
1757     /* give to local clients */
1758     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1759                               &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1760                               payload_size, payload);
1761     /* store locally */
1762     if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1763         (am_closest_peer (&put->key, bf)))
1764       GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1765                                 (put->expiration_time), &put->key, putlen, pp,
1766                                 ntohl (put->type), payload_size, payload);
1767     /* route to other peers */
1768     forwarded = GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1769                                            ntohl (put->desired_replication_level),
1770                                            GNUNET_TIME_absolute_ntoh (put->expiration_time),
1771                                            ntohl (put->hop_count), bf,
1772                                            &put->key, putlen,
1773                                            pp, payload, payload_size);
1774     /* notify monitoring clients */
1775     GDS_CLIENTS_process_put (options
1776                              | (GNUNET_OK == forwarded)
1777                              ? GNUNET_DHT_RO_LAST_HOP : 0,
1778                              ntohl (put->type),
1779                              ntohl (put->hop_count),
1780                              ntohl (put->desired_replication_level),
1781                              putlen, pp,
1782                              GNUNET_TIME_absolute_ntoh (put->expiration_time),
1783                              &put->key,
1784                              payload,
1785                              payload_size);
1786   }
1787   GNUNET_CONTAINER_bloomfilter_free (bf);
1788   return GNUNET_YES;
1789 }
1790
1791
1792 /**
1793  * We have received a FIND PEER request.  Send matching
1794  * HELLOs back.
1795  *
1796  * @param sender sender of the FIND PEER request
1797  * @param key peers close to this key are desired
1798  * @param bf peers matching this bf are excluded
1799  * @param bf_mutator mutator for bf
1800  */
1801 static void
1802 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1803                   const struct GNUNET_HashCode * key,
1804                   struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1805 {
1806   int bucket_idx;
1807   struct PeerBucket *bucket;
1808   struct PeerInfo *peer;
1809   unsigned int choice;
1810   struct GNUNET_HashCode phash;
1811   struct GNUNET_HashCode mhash;
1812   const struct GNUNET_HELLO_Message *hello;
1813
1814   /* first, check about our own HELLO */
1815   if (NULL != GDS_my_hello)
1816   {
1817     GNUNET_BLOCK_mingle_hash (&my_identity_hash, bf_mutator, &mhash);
1818     if ((NULL == bf) ||
1819         (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1820     {
1821       GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1822                                    GNUNET_TIME_relative_to_absolute
1823                                    (hello_expiration),
1824                                    key, 0, NULL, 0, NULL, GDS_my_hello,
1825                                    GNUNET_HELLO_size ((const struct
1826                                                        GNUNET_HELLO_Message *)
1827                                                       GDS_my_hello));
1828     }
1829     else
1830     {
1831       GNUNET_STATISTICS_update (GDS_stats,
1832                                 gettext_noop
1833                                 ("# FIND PEER requests ignored due to Bloomfilter"),
1834                                 1, GNUNET_NO);
1835     }
1836   }
1837   else
1838   {
1839     GNUNET_STATISTICS_update (GDS_stats,
1840                               gettext_noop
1841                               ("# FIND PEER requests ignored due to lack of HELLO"),
1842                               1, GNUNET_NO);
1843   }
1844
1845   /* then, also consider sending a random HELLO from the closest bucket */
1846   if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1847     bucket_idx = closest_bucket;
1848   else
1849     bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1850   if (bucket_idx == GNUNET_SYSERR)
1851     return;
1852   bucket = &k_buckets[bucket_idx];
1853   if (bucket->peers_size == 0)
1854     return;
1855   choice =
1856       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1857   peer = bucket->head;
1858   while (choice > 0)
1859   {
1860     GNUNET_assert (NULL != peer);
1861     peer = peer->next;
1862     choice--;
1863   }
1864   choice = bucket->peers_size;
1865   do
1866   {
1867     peer = peer->next;
1868     if (choice-- == 0)
1869       return;                   /* no non-masked peer available */
1870     if (peer == NULL)
1871       peer = bucket->head;
1872     GNUNET_CRYPTO_hash (&peer->id, sizeof (struct GNUNET_PeerIdentity), &phash);
1873     GNUNET_BLOCK_mingle_hash (&phash, bf_mutator, &mhash);
1874     hello = GDS_HELLO_get (&peer->id);
1875   }
1876   while ((hello == NULL) ||
1877          (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1878   GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1879                                GNUNET_TIME_relative_to_absolute
1880                                (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1881                                0, NULL, 0, NULL, hello,
1882                                GNUNET_HELLO_size (hello));
1883 }
1884
1885
1886 /**
1887  * Core handler for p2p get requests.
1888  *
1889  * @param cls closure
1890  * @param peer sender of the request
1891  * @param message message
1892  * @return #GNUNET_OK to keep the connection open,
1893  *         #GNUNET_SYSERR to close it (signal serious error)
1894  */
1895 static int
1896 handle_dht_p2p_get (void *cls,
1897                     const struct GNUNET_PeerIdentity *peer,
1898                     const struct GNUNET_MessageHeader *message)
1899 {
1900   struct PeerGetMessage *get;
1901   uint32_t xquery_size;
1902   size_t reply_bf_size;
1903   uint16_t msize;
1904   enum GNUNET_BLOCK_Type type;
1905   enum GNUNET_DHT_RouteOption options;
1906   enum GNUNET_BLOCK_EvaluationResult eval;
1907   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1908   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1909   const char *xquery;
1910   struct GNUNET_HashCode phash;
1911   int forwarded;
1912
1913   GNUNET_break (0 !=
1914                 memcmp (peer, &my_identity,
1915                         sizeof (struct GNUNET_PeerIdentity)));
1916   /* parse and validate message */
1917   msize = ntohs (message->size);
1918   if (msize < sizeof (struct PeerGetMessage))
1919   {
1920     GNUNET_break_op (0);
1921     return GNUNET_YES;
1922   }
1923   get = (struct PeerGetMessage *) message;
1924   xquery_size = ntohl (get->xquery_size);
1925   if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1926   {
1927     GNUNET_break_op (0);
1928     return GNUNET_YES;
1929   }
1930   reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1931   type = ntohl (get->type);
1932   options = ntohl (get->options);
1933   xquery = (const char *) &get[1];
1934   reply_bf = NULL;
1935   GNUNET_STATISTICS_update (GDS_stats,
1936                             gettext_noop ("# P2P GET requests received"), 1,
1937                             GNUNET_NO);
1938   GNUNET_STATISTICS_update (GDS_stats,
1939                             gettext_noop ("# P2P GET bytes received"), msize,
1940                             GNUNET_NO);
1941   GNUNET_CRYPTO_hash (peer,
1942                       sizeof (struct GNUNET_PeerIdentity),
1943                       &phash);
1944   if (GNUNET_YES == log_route_details_stderr)
1945   {
1946     char *tmp;
1947
1948     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1949     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1950                  "R5N GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
1951                  GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
1952                  ntohl(get->hop_count),
1953                  GNUNET_CRYPTO_hash_matching_bits (&phash, &get->key),
1954                  GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &get->key),
1955                  ntohl(get->xquery_size), xquery);
1956     GNUNET_free (tmp);
1957   }
1958
1959   if (reply_bf_size > 0)
1960     reply_bf =
1961         GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1962                                            GNUNET_CONSTANTS_BLOOMFILTER_K);
1963   eval =
1964       GNUNET_BLOCK_evaluate (GDS_block_context,
1965                              type,
1966                              GNUNET_BLOCK_EO_NONE,
1967                              &get->key,
1968                              &reply_bf,
1969                              get->bf_mutator,
1970                              xquery,
1971                              xquery_size,
1972                              NULL,
1973                              0);
1974   if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1975   {
1976     /* request invalid or block type not supported */
1977     GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1978     if (NULL != reply_bf)
1979       GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1980     return GNUNET_YES;
1981   }
1982   peer_bf =
1983       GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1984                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
1985   GNUNET_break_op (GNUNET_YES ==
1986                    GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1987                                                       &phash));
1988   /* remember request for routing replies */
1989   GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1990                    reply_bf, get->bf_mutator);
1991   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1992               "GET for %s at %s after %u hops\n",
1993               GNUNET_h2s (&get->key),
1994               GNUNET_i2s (&my_identity),
1995               (unsigned int) ntohl (get->hop_count));
1996   /* local lookup (this may update the reply_bf) */
1997   if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1998       (am_closest_peer (&get->key, peer_bf)))
1999   {
2000     if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
2001     {
2002       GNUNET_STATISTICS_update (GDS_stats,
2003                                 gettext_noop
2004                                 ("# P2P FIND PEER requests processed"), 1,
2005                                 GNUNET_NO);
2006       handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
2007     }
2008     else
2009     {
2010       eval =
2011           GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
2012                                     &reply_bf, get->bf_mutator);
2013     }
2014   }
2015   else
2016   {
2017     GNUNET_STATISTICS_update (GDS_stats,
2018                               gettext_noop ("# P2P GET requests ONLY routed"),
2019                               1, GNUNET_NO);
2020   }
2021
2022   /* P2P forwarding */
2023   forwarded = GNUNET_NO;
2024   if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
2025     forwarded = GDS_NEIGHBOURS_handle_get (type, options,
2026                                            ntohl (get->desired_replication_level),
2027                                            ntohl (get->hop_count),
2028                                            &get->key,
2029                                            xquery,
2030                                            xquery_size,
2031                                            reply_bf,
2032                                            get->bf_mutator, peer_bf);
2033   GDS_CLIENTS_process_get (options
2034                            | (GNUNET_OK == forwarded)
2035                            ? GNUNET_DHT_RO_LAST_HOP : 0,
2036                            type,
2037                            ntohl (get->hop_count),
2038                            ntohl (get->desired_replication_level),
2039                            0, NULL,
2040                            &get->key);
2041
2042
2043   /* clean up */
2044   if (NULL != reply_bf)
2045     GNUNET_CONTAINER_bloomfilter_free (reply_bf);
2046   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
2047   return GNUNET_YES;
2048 }
2049
2050
2051 /**
2052  * Core handler for p2p result messages.
2053  *
2054  * @param cls closure
2055  * @param message message
2056  * @param peer peer identity this notification is about
2057  * @return #GNUNET_YES (do not cut p2p connection)
2058  */
2059 static int
2060 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
2061                        const struct GNUNET_MessageHeader *message)
2062 {
2063   const struct PeerResultMessage *prm;
2064   const struct GNUNET_PeerIdentity *put_path;
2065   const struct GNUNET_PeerIdentity *get_path;
2066   const void *data;
2067   uint32_t get_path_length;
2068   uint32_t put_path_length;
2069   uint16_t msize;
2070   size_t data_size;
2071   enum GNUNET_BLOCK_Type type;
2072
2073   /* parse and validate message */
2074   msize = ntohs (message->size);
2075   if (msize < sizeof (struct PeerResultMessage))
2076   {
2077     GNUNET_break_op (0);
2078     return GNUNET_YES;
2079   }
2080   prm = (struct PeerResultMessage *) message;
2081   put_path_length = ntohl (prm->put_path_length);
2082   get_path_length = ntohl (prm->get_path_length);
2083   if ((msize <
2084        sizeof (struct PeerResultMessage) + (get_path_length +
2085                                             put_path_length) *
2086        sizeof (struct GNUNET_PeerIdentity)) ||
2087       (get_path_length >
2088        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
2089       (put_path_length >
2090        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
2091   {
2092     GNUNET_break_op (0);
2093     return GNUNET_YES;
2094   }
2095   put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
2096   get_path = &put_path[put_path_length];
2097   type = ntohl (prm->type);
2098   data = (const void *) &get_path[get_path_length];
2099   data_size =
2100       msize - (sizeof (struct PeerResultMessage) +
2101                (get_path_length +
2102                 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
2103   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
2104                             1, GNUNET_NO);
2105   GNUNET_STATISTICS_update (GDS_stats,
2106                             gettext_noop ("# P2P RESULT bytes received"),
2107                             msize, GNUNET_NO);
2108   if (GNUNET_YES == log_route_details_stderr)
2109   {
2110     char *tmp;
2111
2112     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2113     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "R5N RESULT %s: %s->%s (%u)\n",
2114                  GNUNET_h2s (&prm->key), GNUNET_i2s (peer), tmp,
2115                  get_path_length + 1);
2116     GNUNET_free (tmp);
2117   }
2118   /* if we got a HELLO, consider it for our own routing table */
2119   if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
2120   {
2121     const struct GNUNET_MessageHeader *h;
2122     struct GNUNET_PeerIdentity pid;
2123     int bucket;
2124
2125     /* Should be a HELLO, validate and consider using it! */
2126     if (data_size < sizeof (struct GNUNET_MessageHeader))
2127     {
2128       GNUNET_break_op (0);
2129       return GNUNET_YES;
2130     }
2131     h = data;
2132     if (data_size != ntohs (h->size))
2133     {
2134       GNUNET_break_op (0);
2135       return GNUNET_YES;
2136     }
2137     if (GNUNET_OK !=
2138         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
2139     {
2140       GNUNET_break_op (0);
2141       return GNUNET_YES;
2142     }
2143     if ((GNUNET_YES != disable_try_connect) &&
2144         0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
2145     {
2146       struct GNUNET_HashCode pid_hash;
2147
2148       GNUNET_CRYPTO_hash (&pid, sizeof (struct GNUNET_PeerIdentity), &pid_hash);
2149       bucket = find_bucket (&pid_hash);
2150       if ((bucket >= 0) &&
2151           (k_buckets[bucket].peers_size < bucket_size) &&
2152           (NULL != GDS_transport_handle))
2153       {
2154         GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
2155         GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid, NULL, NULL); /*FIXME TRY_CONNECT change */
2156       }
2157     }
2158   }
2159
2160   /* append 'peer' to 'get_path' */
2161   {
2162     struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2163
2164     memcpy (xget_path, get_path,
2165             get_path_length * sizeof (struct GNUNET_PeerIdentity));
2166     xget_path[get_path_length] = *peer;
2167     get_path_length++;
2168
2169     /* forward to local clients */
2170     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2171                               &prm->key, get_path_length, xget_path,
2172                               put_path_length, put_path, type, data_size, data);
2173     GDS_CLIENTS_process_get_resp (type,
2174                                   xget_path, get_path_length,
2175                                   put_path, put_path_length,
2176                                   GNUNET_TIME_absolute_ntoh (
2177                                     prm->expiration_time),
2178                                   &prm->key,
2179                                   data,
2180                                   data_size);
2181     if (GNUNET_YES == cache_results)
2182     {
2183       struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length];
2184
2185       memcpy (xput_path, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
2186       memcpy (&xput_path[put_path_length],
2187               xget_path,
2188               get_path_length * sizeof (struct GNUNET_PeerIdentity));
2189
2190       GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2191                                 &prm->key,
2192                                 get_path_length + put_path_length, xput_path,
2193                                 type, data_size, data);
2194     }
2195     /* forward to other peers */
2196     GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2197                          &prm->key, put_path_length, put_path, get_path_length,
2198                          xget_path, data, data_size);
2199   }
2200
2201   return GNUNET_YES;
2202 }
2203
2204
2205 /**
2206  * Initialize neighbours subsystem.
2207  *
2208  * @return GNUNET_OK on success, GNUNET_SYSERR on error
2209  */
2210 int
2211 GDS_NEIGHBOURS_init ()
2212 {
2213   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2214     {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2215     {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2216     {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2217     {NULL, 0, 0}
2218   };
2219   unsigned long long temp_config_num;
2220
2221   disable_try_connect
2222     = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2223   if (GNUNET_OK ==
2224       GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2225                                              &temp_config_num))
2226     bucket_size = (unsigned int) temp_config_num;
2227   cache_results
2228     = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "CACHE_RESULTS");
2229
2230   log_route_details_stderr =
2231     (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2232   atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2233   core_api =
2234       GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2235                            &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2236                            GNUNET_NO, core_handlers);
2237   if (core_api == NULL)
2238     return GNUNET_SYSERR;
2239   all_known_peers = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
2240   return GNUNET_OK;
2241 }
2242
2243
2244 /**
2245  * Shutdown neighbours subsystem.
2246  */
2247 void
2248 GDS_NEIGHBOURS_done ()
2249 {
2250   if (NULL == core_api)
2251     return;
2252   GNUNET_CORE_disconnect (core_api);
2253   core_api = NULL;
2254   GNUNET_ATS_performance_done (atsAPI);
2255   atsAPI = NULL;
2256   GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (all_known_peers));
2257   GNUNET_CONTAINER_multipeermap_destroy (all_known_peers);
2258   all_known_peers = NULL;
2259   if (NULL != find_peer_task)
2260   {
2261     GNUNET_SCHEDULER_cancel (find_peer_task);
2262     find_peer_task = NULL;
2263   }
2264 }
2265
2266 /**
2267  * Get the ID of the local node.
2268  *
2269  * @return identity of the local node
2270  */
2271 struct GNUNET_PeerIdentity *
2272 GDS_NEIGHBOURS_get_id ()
2273 {
2274   return &my_identity;
2275 }
2276
2277
2278 /* end of gnunet-service-dht_neighbours.c */