cosmetics
[oweals/gnunet.git] / src / dht / gnunet-service-dht_routing.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011 GNUnet e.V.
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_routing.c
23  * @brief GNUnet DHT tracking of requests for routing replies
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet-service-dht_neighbours.h"
28 #include "gnunet-service-dht_routing.h"
29 #include "gnunet-service-dht.h"
30
31
32 /**
33  * Number of requests we track at most (for routing replies).
34  */
35 #define DHT_MAX_RECENT (1024 * 16)
36
37
38 /**
39  * Information we keep about all recent GET requests
40  * so that we can route replies.
41  */
42 struct RecentRequest
43 {
44
45   /**
46    * The peer this request was received from.
47    */
48   struct GNUNET_PeerIdentity peer;
49
50   /**
51    * Key of this request.
52    */
53   struct GNUNET_HashCode key;
54
55   /**
56    * Position of this node in the min heap.
57    */
58   struct GNUNET_CONTAINER_HeapNode *heap_node;
59
60   /**
61    * Bloomfilter for replies to drop.
62    */
63   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
64
65   /**
66    * Type of the requested block.
67    */
68   enum GNUNET_BLOCK_Type type;
69
70   /**
71    * extended query (see gnunet_block_lib.h).  Allocated at the
72    * end of this struct.
73    */
74   const void *xquery;
75
76   /**
77    * Number of bytes in xquery.
78    */
79   size_t xquery_size;
80
81   /**
82    * Mutator value for the reply_bf, see gnunet_block_lib.h
83    */
84   uint32_t reply_bf_mutator;
85
86   /**
87    * Request options.
88    */
89   enum GNUNET_DHT_RouteOption options;
90
91 };
92
93
94 /**
95  * Recent requests by time inserted.
96  */
97 static struct GNUNET_CONTAINER_Heap *recent_heap;
98
99 /**
100  * Recently seen requests by key.
101  */
102 static struct GNUNET_CONTAINER_MultiHashMap *recent_map;
103
104
105 /**
106  * Closure for the 'process' function.
107  */
108 struct ProcessContext
109 {
110   /**
111    * Path of the original PUT
112    */
113   const struct GNUNET_PeerIdentity *put_path;
114
115   /**
116    * Path of the reply.
117    */
118   const struct GNUNET_PeerIdentity *get_path;
119
120   /**
121    * Payload of the reply.
122    */
123   const void *data;
124
125   /**
126    * Expiration time of the result.
127    */
128   struct GNUNET_TIME_Absolute expiration_time;
129
130   /**
131    * Number of entries in 'put_path'.
132    */
133   unsigned int put_path_length;
134
135   /**
136    * Number of entries in 'get_path'.
137    */
138   unsigned int get_path_length;
139
140   /**
141    * Number of bytes in 'data'.
142    */
143   size_t data_size;
144
145   /**
146    * Type of the reply.
147    */
148   enum GNUNET_BLOCK_Type type;
149
150 };
151
152
153 /**
154  * Forward the result to the given peer if it matches the request.
155  *
156  * @param cls the `struct ProcessContext` with the result
157  * @param key the query
158  * @param value the `struct RecentRequest` with the request
159  * @return #GNUNET_OK (continue to iterate),
160  *         #GNUNET_SYSERR if the result is malformed or type unsupported
161  */
162 static int
163 process (void *cls, const struct GNUNET_HashCode * key, void *value)
164 {
165   struct ProcessContext *pc = cls;
166   struct RecentRequest *rr = value;
167   enum GNUNET_BLOCK_EvaluationResult eval;
168   unsigned int gpl;
169   unsigned int ppl;
170   struct GNUNET_HashCode hc;
171   const struct GNUNET_HashCode *eval_key;
172
173   if ((rr->type != GNUNET_BLOCK_TYPE_ANY) && (rr->type != pc->type))
174     return GNUNET_OK;           /* type missmatch */
175
176   if (0 != (rr->options & GNUNET_DHT_RO_RECORD_ROUTE))
177   {
178     gpl = pc->get_path_length;
179     ppl = pc->put_path_length;
180   }
181   else
182   {
183     gpl = 0;
184     ppl = 0;
185   }
186   if ( (0 != (rr->options & GNUNET_DHT_RO_FIND_PEER)) &&
187        (pc->type == GNUNET_BLOCK_TYPE_DHT_HELLO) )
188   {
189     /* key may not match HELLO, which is OK since
190      * the search is approximate.  Still, the evaluation
191      * would fail since the match is not exact.  So
192      * we fake it by changing the key to the actual PID ... */
193     GNUNET_BLOCK_get_key (GDS_block_context,
194                           GNUNET_BLOCK_TYPE_DHT_HELLO,
195                           pc->data, pc->data_size,
196                           &hc);
197     eval_key = &hc;
198   }
199   else
200   {
201     eval_key = key;
202   }
203   eval =
204       GNUNET_BLOCK_evaluate (GDS_block_context,
205                              pc->type,
206                              GNUNET_BLOCK_EO_NONE,
207                              eval_key,
208                              &rr->reply_bf,
209                              rr->reply_bf_mutator,
210                              rr->xquery,
211                              rr->xquery_size,
212                              pc->data,
213                              pc->data_size);
214   switch (eval)
215   {
216   case GNUNET_BLOCK_EVALUATION_OK_MORE:
217   case GNUNET_BLOCK_EVALUATION_OK_LAST:
218     GNUNET_STATISTICS_update (GDS_stats,
219                               gettext_noop
220                               ("# Good REPLIES matched against routing table"),
221                               1, GNUNET_NO);
222     GDS_NEIGHBOURS_handle_reply (&rr->peer, pc->type, pc->expiration_time, key,
223                                  ppl, pc->put_path, gpl, pc->get_path, pc->data,
224                                  pc->data_size);
225     break;
226   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
227     GNUNET_STATISTICS_update (GDS_stats,
228                               gettext_noop
229                               ("# Duplicate REPLIES matched against routing table"),
230                               1, GNUNET_NO);
231     return GNUNET_OK;
232   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
233     GNUNET_STATISTICS_update (GDS_stats,
234                               gettext_noop
235                               ("# Invalid REPLIES matched against routing table"),
236                               1, GNUNET_NO);
237     return GNUNET_SYSERR;
238   case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
239     GNUNET_STATISTICS_update (GDS_stats,
240                               gettext_noop
241                               ("# Irrelevant REPLIES matched against routing table"),
242                               1, GNUNET_NO);
243     return GNUNET_OK;
244   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
245     GNUNET_break (0);
246     return GNUNET_OK;
247   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
248     GNUNET_break (0);
249     return GNUNET_OK;
250   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
251     GNUNET_STATISTICS_update (GDS_stats,
252                               gettext_noop
253                               ("# Unsupported REPLIES matched against routing table"),
254                               1, GNUNET_NO);
255     return GNUNET_SYSERR;
256   default:
257     GNUNET_break (0);
258     return GNUNET_SYSERR;
259   }
260   return GNUNET_OK;
261 }
262
263
264 /**
265  * Handle a reply (route to origin).  Only forwards the reply back to
266  * other peers waiting for it.  Does not do local caching or
267  * forwarding to local clients.  Essentially calls
268  * GDS_NEIGHBOURS_handle_reply for all peers that sent us a matching
269  * request recently.
270  *
271  * @param type type of the block
272  * @param expiration_time when does the content expire
273  * @param key key for the content
274  * @param put_path_length number of entries in put_path
275  * @param put_path peers the original PUT traversed (if tracked)
276  * @param get_path_length number of entries in get_path
277  * @param get_path peers this reply has traversed so far (if tracked)
278  * @param data payload of the reply
279  * @param data_size number of bytes in data
280  */
281 void
282 GDS_ROUTING_process (void *cls,
283                      enum GNUNET_BLOCK_Type type,
284                      struct GNUNET_TIME_Absolute expiration_time,
285                      const struct GNUNET_HashCode *key,
286                      unsigned int put_path_length,
287                      const struct GNUNET_PeerIdentity *put_path,
288                      unsigned int get_path_length,
289                      const struct GNUNET_PeerIdentity *get_path,
290                      const void *data,
291                      size_t data_size)
292 {
293   struct ProcessContext pc;
294
295   pc.type = type;
296   pc.expiration_time = expiration_time;
297   pc.put_path_length = put_path_length;
298   pc.put_path = put_path;
299   pc.get_path_length = get_path_length;
300   pc.get_path = get_path;
301   pc.data = data;
302   pc.data_size = data_size;
303   if (NULL == data)
304   {
305     /* Some apps might have an 'empty' reply as a valid reply; however,
306        'process' will call GNUNET_BLOCK_evaluate' which treats a 'NULL'
307        reply as request-validation (but we need response-validation).
308        So we set 'data' to a 0-byte non-NULL value just to be sure */
309     GNUNET_break (0 == data_size);
310     pc.data_size = 0;
311     pc.data = ""; /* something not null */
312   }
313   GNUNET_CONTAINER_multihashmap_get_multiple (recent_map, key, &process, &pc);
314 }
315
316
317 /**
318  * Remove the oldest entry from the DHT routing table.  Must only
319  * be called if it is known that there is at least one entry
320  * in the heap and hashmap.
321  */
322 static void
323 expire_oldest_entry ()
324 {
325   struct RecentRequest *recent_req;
326
327   GNUNET_STATISTICS_update (GDS_stats,
328                             gettext_noop
329                             ("# Entries removed from routing table"), 1,
330                             GNUNET_NO);
331   recent_req = GNUNET_CONTAINER_heap_peek (recent_heap);
332   GNUNET_assert (recent_req != NULL);
333   GNUNET_CONTAINER_heap_remove_node (recent_req->heap_node);
334   GNUNET_CONTAINER_bloomfilter_free (recent_req->reply_bf);
335   GNUNET_assert (GNUNET_YES ==
336                  GNUNET_CONTAINER_multihashmap_remove (recent_map,
337                                                        &recent_req->key,
338                                                        recent_req));
339   GNUNET_free (recent_req);
340 }
341
342
343 /**
344  * Try to combine multiple recent requests for the same value
345  * (if they come from the same peer).
346  *
347  * @param cls the new 'struct RecentRequest' (to discard upon successful combination)
348  * @param key the query
349  * @param value the existing 'struct RecentRequest' (to update upon successful combination)
350  * @return GNUNET_OK (continue to iterate),
351  *         GNUNET_SYSERR if the request was successfully combined
352  */
353 static int
354 try_combine_recent (void *cls, const struct GNUNET_HashCode * key, void *value)
355 {
356   struct RecentRequest *in = cls;
357   struct RecentRequest *rr = value;
358
359   if ( (0 != memcmp (&in->peer,
360                      &rr->peer,
361                      sizeof (struct GNUNET_PeerIdentity))) ||
362        (in->type != rr->type) ||
363        (in->xquery_size != rr->xquery_size) ||
364        (0 != memcmp (in->xquery,
365                      rr->xquery,
366                      in->xquery_size)) )
367     return GNUNET_OK;
368   if (in->reply_bf_mutator != rr->reply_bf_mutator)
369   {
370     rr->reply_bf_mutator = in->reply_bf_mutator;
371     GNUNET_CONTAINER_bloomfilter_free (rr->reply_bf);
372     rr->reply_bf = in->reply_bf;
373   }
374   else
375   {
376     GNUNET_CONTAINER_bloomfilter_or2 (rr->reply_bf,
377                                       in->reply_bf);
378     GNUNET_CONTAINER_bloomfilter_free (in->reply_bf);
379   }
380   GNUNET_free (in);
381   return GNUNET_SYSERR;
382 }
383
384
385 /**
386  * Add a new entry to our routing table.
387  *
388  * @param sender peer that originated the request
389  * @param type type of the block
390  * @param options options for processing
391  * @param key key for the content
392  * @param xquery extended query
393  * @param xquery_size number of bytes in @a xquery
394  * @param reply_bf bloomfilter to filter duplicates
395  * @param reply_bf_mutator mutator for @a reply_bf
396  */
397 void
398 GDS_ROUTING_add (const struct GNUNET_PeerIdentity *sender,
399                  enum GNUNET_BLOCK_Type type,
400                  enum GNUNET_DHT_RouteOption options,
401                  const struct GNUNET_HashCode * key, const void *xquery,
402                  size_t xquery_size,
403                  const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
404                  uint32_t reply_bf_mutator)
405 {
406   struct RecentRequest *recent_req;
407
408   while (GNUNET_CONTAINER_heap_get_size (recent_heap) >= DHT_MAX_RECENT)
409     expire_oldest_entry ();
410   GNUNET_STATISTICS_update (GDS_stats,
411                             gettext_noop ("# Entries added to routing table"),
412                             1, GNUNET_NO);
413   recent_req = GNUNET_malloc (sizeof (struct RecentRequest) + xquery_size);
414   recent_req->peer = *sender;
415   recent_req->key = *key;
416   recent_req->reply_bf = GNUNET_CONTAINER_bloomfilter_copy (reply_bf);
417   recent_req->type = type;
418   recent_req->options = options;
419   recent_req->xquery = &recent_req[1];
420   GNUNET_memcpy (&recent_req[1], xquery, xquery_size);
421   recent_req->xquery_size = xquery_size;
422   recent_req->reply_bf_mutator = reply_bf_mutator;
423   if (GNUNET_SYSERR ==
424       GNUNET_CONTAINER_multihashmap_get_multiple (recent_map, key,
425                                                   &try_combine_recent, recent_req))
426   {
427     GNUNET_STATISTICS_update (GDS_stats,
428                               gettext_noop
429                               ("# DHT requests combined"),
430                               1, GNUNET_NO);
431     return;
432   }
433   recent_req->heap_node =
434       GNUNET_CONTAINER_heap_insert (recent_heap, recent_req,
435                                     GNUNET_TIME_absolute_get ().abs_value_us);
436   GNUNET_CONTAINER_multihashmap_put (recent_map, key, recent_req,
437                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
438
439
440 }
441
442
443 /**
444  * Initialize routing subsystem.
445  */
446 void
447 GDS_ROUTING_init ()
448 {
449   recent_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
450   recent_map = GNUNET_CONTAINER_multihashmap_create (DHT_MAX_RECENT * 4 / 3, GNUNET_NO);
451 }
452
453
454 /**
455  * Shutdown routing subsystem.
456  */
457 void
458 GDS_ROUTING_done ()
459 {
460   while (GNUNET_CONTAINER_heap_get_size (recent_heap) > 0)
461     expire_oldest_entry ();
462   GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (recent_heap));
463   GNUNET_CONTAINER_heap_destroy (recent_heap);
464   recent_heap = NULL;
465   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (recent_map));
466   GNUNET_CONTAINER_multihashmap_destroy (recent_map);
467   recent_map = NULL;
468 }
469
470 /* end of gnunet-service-dht_routing.c */