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