fair, global message buffer implemented
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_paths.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-2017 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  * @file cadet/gnunet-service-cadet-new_paths.c
22  * @brief Information we track per path.
23  * @author Bartlomiej Polot
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet-service-cadet-new_connection.h"
28 #include "gnunet-service-cadet-new_tunnels.h"
29 #include "gnunet-service-cadet-new_peer.h"
30 #include "gnunet-service-cadet-new_paths.h"
31
32
33 #define LOG(level, ...) GNUNET_log_from(level,"cadet-pat",__VA_ARGS__)
34
35
36 /**
37  * Information regarding a possible path to reach a peer.
38  */
39 struct CadetPeerPath
40 {
41
42   /**
43    * Array of all the peers on the path.  If @e hn is non-NULL, the
44    * last one is our owner.
45    */
46   struct CadetPeerPathEntry **entries;
47
48   /**
49    * Node of this path in the owner's heap.  Used to update our position
50    * in the heap whenever our @e desirability changes.
51    */
52   struct GNUNET_CONTAINER_HeapNode *hn;
53
54   /**
55    * Desirability of the path. How unique is it for the various peers
56    * on it?
57    */
58   GNUNET_CONTAINER_HeapCostType desirability;
59
60   /**
61    * Length of the @e entries array.
62    */
63   unsigned int entries_length;
64
65 };
66
67
68 /**
69  * Calculate the path's desirability score.
70  *
71  * @param path path to calculate the score for
72  */
73 static void
74 recalculate_path_desirability (struct CadetPeerPath *path)
75 {
76   double result = 0.0;
77
78   for (unsigned int i=0;i<path->entries_length;i++)
79   {
80     struct CadetPeer *cp = path->entries[i]->peer;
81
82     result += GCP_get_desirability_of_path (cp,
83                                             i);
84   }
85   path->desirability = (GNUNET_CONTAINER_HeapCostType) result;
86 }
87
88
89 /**
90  * Return how much we like keeping the path.  This is an aggregate
91  * score based on various factors, including the age of the path
92  * (older == better), and the value of this path to all of its ajacent
93  * peers.  For example, long paths that end at a peer that we have no
94  * shorter way to reach are very desirable, while long paths that end
95  * at a peer for which we have a shorter way as well are much less
96  * desirable.  Higher values indicate more valuable paths.  The
97  * returned value should be used to decide which paths to remember.
98  *
99  * @param path path to return the length for
100  * @return desirability of the path, larger is more desirable
101  */
102 GNUNET_CONTAINER_HeapCostType
103 GCPP_get_desirability (const struct CadetPeerPath *path)
104 {
105   return path->desirability;
106 }
107
108
109 /**
110  * Return connection to @a destination using @a path, or return
111  * NULL if no such connection exists.
112  *
113  * @param path path to traverse
114  * @param destination destination node to get to, must be on path
115  * @param off offset of @a destination on @a path
116  * @return NULL if we have no existing connection
117  *         otherwise connection from us to @a destination via @a path
118  */
119 struct CadetConnection *
120 GCPP_get_connection (struct CadetPeerPath *path,
121                      struct CadetPeer *destination,
122                      unsigned int off)
123 {
124   struct CadetPeerPathEntry *entry;
125
126   GNUNET_assert (off < path->entries_length);
127   entry = path->entries[off];
128   GNUNET_assert (entry->peer == destination);
129   return entry->cc;
130 }
131
132
133 /**
134  * Notify @a path that it is used for connection @a cc
135  * which ends at the path's offset @a off.
136  *
137  * @param path the path to remember the @a cc
138  * @param off the offset where the @a cc ends
139  * @param cc the connection to remember
140  */
141 void
142 GCPP_add_connection (struct CadetPeerPath *path,
143                      unsigned int off,
144                      struct CadetConnection *cc)
145 {
146   struct CadetPeerPathEntry *entry;
147
148   LOG (GNUNET_ERROR_TYPE_DEBUG,
149        "Adding connection %s to path %s at offset %u\n",
150        GCC_2s (cc),
151        GCPP_2s (path),
152        off);
153   GNUNET_assert (off < path->entries_length);
154   entry = path->entries[off];
155   GNUNET_assert (NULL == entry->cc);
156   entry->cc = cc;
157 }
158
159
160
161 /**
162  * Notify @a path that it is no longer used for connection @a cc which
163  * ended at the path's offset @a off.
164  *
165  * @param path the path to forget the @a cc
166  * @param off the offset where the @a cc ended
167  * @param cc the connection to forget
168  */
169 void
170 GCPP_del_connection (struct CadetPeerPath *path,
171                      unsigned int off,
172                      struct CadetConnection *cc)
173 {
174   struct CadetPeerPathEntry *entry;
175
176   LOG (GNUNET_ERROR_TYPE_DEBUG,
177        "Removing connection %s to path %s at offset %u\n",
178        GCC_2s (cc),
179        GCPP_2s (path),
180        off);
181   GNUNET_assert (off < path->entries_length);
182   entry = path->entries[off];
183   GNUNET_assert (cc == entry->cc);
184   entry->cc = NULL;
185 }
186
187
188 /**
189  * This path is no longer needed, free resources.
190  *
191  * @param path path resources to free
192  */
193 static void
194 path_destroy (struct CadetPeerPath *path)
195 {
196   LOG (GNUNET_ERROR_TYPE_DEBUG,
197        "Destroying path %s\n",
198        GCPP_2s (path));
199   for (unsigned int i=0;i<path->entries_length;i++)
200   {
201     struct CadetPeerPathEntry *entry = path->entries[i];
202
203     if (NULL != entry->cc)
204     {
205       struct CadetTConnection *ct;
206
207       ct = GCC_get_ct (entry->cc);
208       if (NULL != ct)
209         GCT_connection_lost (ct);
210       GCC_destroy_without_tunnel (entry->cc);
211     }
212     GNUNET_free (entry);
213   }
214   GNUNET_free (path->entries);
215   GNUNET_free (path);
216 }
217
218
219 /**
220  * The owning peer of this path is no longer interested in maintaining
221  * it, so the path should be discarded or shortened (in case a
222  * previous peer on the path finds the path desirable).
223  *
224  * @param path the path that is being released
225  */
226 void
227 GCPP_release (struct CadetPeerPath *path)
228 {
229   struct CadetPeerPathEntry *entry;
230
231   LOG (GNUNET_ERROR_TYPE_DEBUG,
232        "Owner releases path %s\n",
233        GCPP_2s (path));
234   path->hn = NULL;
235   entry = path->entries[path->entries_length - 1];
236   while (1)
237   {
238     /* cut 'off' end of path */
239     GCP_path_entry_remove (entry->peer,
240                            entry,
241                            path->entries_length - 1);
242     path->entries_length--; /* We don't bother shrinking the 'entries' array,
243                                as it's probably not worth it. */
244     GNUNET_free (entry);
245     if (0 == path->entries_length)
246       break; /* the end */
247
248     /* see if new peer at the end likes this path any better */
249     entry = path->entries[path->entries_length - 1];
250     path->hn = GCP_attach_path (entry->peer,
251                                 path,
252                                 path->entries_length - 1,
253                                 GNUNET_NO);
254     if (NULL != path->hn)
255       return; /* yep, got attached, we are done. */
256   }
257
258   /* nobody wants us, discard the path */
259   path_destroy (path);
260 }
261
262
263 /**
264  * Updates the score for an entry on the path based
265  * on our experiences with using @a path.
266  *
267  * @param path the path to update
268  * @param off offset of the entry to update
269  * @param delta change in the score to apply
270  */
271 void
272 GCPP_update_score (struct CadetPeerPath *path,
273                    unsigned int off,
274                    int delta)
275 {
276   struct CadetPeerPathEntry *entry;
277
278   GNUNET_assert (off < path->entries_length);
279   entry = path->entries[off];
280
281   /* Add delta, with checks for overflows */
282   if (delta >= 0)
283   {
284     if (delta + entry->score < entry->score)
285       entry->score = INT_MAX;
286     else
287       entry->score += delta;
288   }
289   else
290   {
291     if (delta + entry->score > entry->score)
292       entry->score = INT_MIN;
293     else
294       entry->score += delta;
295   }
296   recalculate_path_desirability (path);
297 }
298
299
300 /**
301  * Closure for #find_peer_at() and #check_match().
302  */
303 struct CheckMatchContext
304 {
305
306   /**
307    * Set to a matching path, if any.
308    */
309   struct CadetPeerPath *match;
310
311   /**
312    * Array the combined paths.
313    */
314   struct CadetPeer **cpath;
315
316   /**
317    * How long is the @e cpath array?
318    */
319   unsigned int cpath_length;
320
321 };
322
323
324 /**
325  * Check if the given path is identical on all of the
326  * hops until @a off, and not longer than @a off.  If the
327  * @a path matches, store it in `match`.
328  *
329  * @param cls the `struct CheckMatchContext` to check against
330  * @param path the path to check
331  * @param off offset to check at
332  * @return #GNUNET_YES (continue to iterate), or if found #GNUNET_NO
333  */
334 static int
335 check_match (void *cls,
336              struct CadetPeerPath *path,
337              unsigned int off)
338 {
339   struct CheckMatchContext *cm_ctx = cls;
340
341   GNUNET_assert (path->entries_length > off);
342   if ( (path->entries_length != off + 1) &&
343        (off + 1 != cm_ctx->cpath_length) )
344   {
345     LOG (GNUNET_ERROR_TYPE_DEBUG,
346          "check_match missmatch because path %s is too long (%u vs. %u vs. %u)\n",
347          GCPP_2s (path),
348          path->entries_length,
349          off + 1,
350          cm_ctx->cpath_length);
351     return GNUNET_YES; /* too long, goes somewhere else already, thus cannot be useful */
352   }
353   for (unsigned int i=0;i<off;i++)
354     if (cm_ctx->cpath[i] !=
355         GCPP_get_peer_at_offset (path,
356                                  i))
357     {
358       LOG (GNUNET_ERROR_TYPE_DEBUG,
359            "check_match path %s missmatches at offset %u\n",
360            GCPP_2s (path),
361            i);
362       return GNUNET_YES; /* missmatch, ignore */
363     }
364   LOG (GNUNET_ERROR_TYPE_DEBUG,
365        "check_match found match with path %s\n",
366        GCPP_2s (path));
367   cm_ctx->match = path;
368   return GNUNET_NO; /* match, we are done! */
369 }
370
371
372 /**
373  * Extend path @a path by the @a num_peers from the @a peers
374  * array, assuming the owners past the current owner want it.
375  *
376  * @param path path to extend
377  * @param peers list of peers beyond the end of @a path
378  * @param num_peers length of the @a peers array
379  * @param force force attachment, even if we have other
380  *        paths already
381  */
382 static void
383 extend_path (struct CadetPeerPath *path,
384              struct CadetPeer **peers,
385              unsigned int num_peers,
386              int force)
387 {
388   unsigned int old_len = path->entries_length;
389   struct GNUNET_CONTAINER_HeapNode *hn;
390   int i;
391
392   /* Expand path */
393   GNUNET_array_grow (path->entries,
394                      path->entries_length,
395                      old_len + num_peers);
396   for (i=num_peers-1;i >= 0;i--)
397   {
398     struct CadetPeerPathEntry *entry = GNUNET_new (struct CadetPeerPathEntry);
399
400     path->entries[old_len + i] = entry;
401     entry->peer = peers[i];
402     entry->path = path;
403   }
404   for (i=num_peers-1;i >= 0;i--)
405   {
406     struct CadetPeerPathEntry *entry = path->entries[old_len + i];
407
408     GCP_path_entry_add (entry->peer,
409                         entry,
410                         old_len + i);
411   }
412
413   /* If we extend an existing path, detach it from the
414      old owner and re-attach to the new one */
415   hn = NULL;
416   for (i=num_peers-1;i>=0;i--)
417   {
418     struct CadetPeerPathEntry *entry = path->entries[old_len + i];
419
420     path->entries_length = old_len + i + 1;
421     recalculate_path_desirability (path);
422     hn = GCP_attach_path (peers[i],
423                           path,
424                           old_len + (unsigned int) i,
425                           GNUNET_YES);
426     if (NULL != hn)
427       break;
428     GCP_path_entry_remove (entry->peer,
429                            entry,
430                            old_len + i);
431     GNUNET_free (entry);
432     path->entries[old_len + i] = NULL;
433   }
434   if (NULL == hn)
435   {
436     /* none of the peers is interested in this path;
437        shrink path back */
438     GNUNET_array_grow (path->entries,
439                        path->entries_length,
440                        old_len);
441     return;
442   }
443   GCP_detach_path (path->entries[old_len-1]->peer,
444                    path,
445                    path->hn);
446   path->hn = hn;
447   LOG (GNUNET_ERROR_TYPE_DEBUG,
448        "Extended path %s\n",
449        GCPP_2s (path));
450 }
451
452
453 /**
454  * Create a peer path based on the result of a DHT lookup.  If we
455  * already know this path, or one that is longer, simply return NULL.
456  * Otherwise, we try to extend an existing path, or create a new one
457  * if applicable.
458  *
459  * @param get_path path of the get request
460  * @param get_path_length lenght of @a get_path
461  * @param put_path path of the put request
462  * @param put_path_length length of the @a put_path
463  * @return a path through the network
464  */
465 void
466 GCPP_try_path_from_dht (const struct GNUNET_PeerIdentity *get_path,
467                         unsigned int get_path_length,
468                         const struct GNUNET_PeerIdentity *put_path,
469                         unsigned int put_path_length)
470 {
471   struct CadetPeer *cpath[get_path_length + put_path_length];
472   struct CheckMatchContext cm_ctx;
473   struct CadetPeerPath *path;
474   struct GNUNET_CONTAINER_HeapNode *hn;
475   int i;
476   unsigned int skip;
477   unsigned int total_len;
478
479   /* precompute 'cpath' so we can avoid doing the lookups lots of times */
480   skip = 0;
481   total_len = get_path_length + put_path_length;
482   for (unsigned int off=0;off<total_len;off++)
483   {
484     const struct GNUNET_PeerIdentity *pid;
485
486     pid = (off < get_path_length)
487       ? &get_path[get_path_length - off]
488       : &put_path[get_path_length + put_path_length - off];
489     cpath[off - skip] = GCP_get (pid,
490                                  GNUNET_YES);
491     /* Check that no peer is twice on the path */
492     for (unsigned int i=0;i<off;i++)
493     {
494       if (cpath[i] == cpath[off])
495       {
496         skip = off - i;
497         break;
498       }
499     }
500   }
501   total_len -= skip;
502
503   /* First figure out if this path is a subset of an existing path, an
504      extension of an existing path, or a new path. */
505   cm_ctx.cpath_length = total_len;
506   cm_ctx.cpath = cpath;
507   cm_ctx.match = NULL;
508   for (i=total_len-1;i>=0;i--)
509   {
510     GCP_iterate_paths_at (cpath[i],
511                           (unsigned int) i,
512                           &check_match,
513                           &cm_ctx);
514     if (NULL != cm_ctx.match)
515     {
516       if (i == total_len - 1)
517       {
518         /* Existing path includes this one, nothing to do! */
519         LOG (GNUNET_ERROR_TYPE_DEBUG,
520              "Path discovered from DHT is already known\n");
521         return;
522       }
523       if (cm_ctx.match->entries_length == i + 1)
524       {
525         /* Existing path ends in the middle of new path, extend it! */
526         LOG (GNUNET_ERROR_TYPE_DEBUG,
527              "Trying to extend existing path %s by additional links discovered from DHT\n",
528              GCPP_2s (cm_ctx.match));
529         extend_path (cm_ctx.match,
530                      &cpath[i + 1],
531                      total_len - i - 1,
532                      GNUNET_NO);
533         return;
534       }
535     }
536   }
537
538   /* No match at all, create completely new path */
539   path = GNUNET_new (struct CadetPeerPath);
540   path->entries_length = total_len;
541   path->entries = GNUNET_new_array (path->entries_length,
542                                     struct CadetPeerPathEntry *);
543   for (i=path->entries_length-1;i>=0;i--)
544   {
545     struct CadetPeerPathEntry *entry = GNUNET_new (struct CadetPeerPathEntry);
546
547     path->entries[i] = entry;
548     entry->peer = cpath[i];
549     entry->path = path;
550   }
551   for (i=path->entries_length-1;i>=0;i--)
552   {
553     struct CadetPeerPathEntry *entry = path->entries[i];
554
555     GCP_path_entry_add (entry->peer,
556                         entry,
557                         i);
558   }
559
560   /* Finally, try to attach it */
561   hn = NULL;
562   for (i=total_len-1;i>=0;i--)
563   {
564     struct CadetPeerPathEntry *entry = path->entries[i];
565
566     path->entries_length = i + 1;
567     recalculate_path_desirability (path);
568     hn = GCP_attach_path (cpath[i],
569                           path,
570                           (unsigned int) i,
571                           GNUNET_NO);
572     if (NULL != hn)
573       break;
574     GCP_path_entry_remove (entry->peer,
575                            entry,
576                            i);
577     GNUNET_free (entry);
578     path->entries[i] = NULL;
579   }
580   if (NULL == hn)
581   {
582     /* None of the peers on the path care about it. */
583     LOG (GNUNET_ERROR_TYPE_DEBUG,
584          "Path discovered from DHT is not interesting to us\n");
585     GNUNET_free (path->entries);
586     GNUNET_free (path);
587     return;
588   }
589   path->hn = hn;
590   /* Shrink path to actual useful length */
591   GNUNET_array_grow (path->entries,
592                      path->entries_length,
593                      i + 1);
594   LOG (GNUNET_ERROR_TYPE_DEBUG,
595        "Created new path %s based on information from DHT\n",
596        GCPP_2s (path));
597 }
598
599
600 /**
601  * We got an incoming connection, obtain the corresponding path.
602  *
603  * @param path_length number of segments on the @a path
604  * @param pids path through the network, in reverse order (we are at the end at index @a path_length)
605  * @return corresponding path object
606  */
607 struct CadetPeerPath *
608 GCPP_get_path_from_route (unsigned int path_length,
609                           const struct GNUNET_PeerIdentity *pids)
610 {
611   struct CheckMatchContext cm_ctx;
612   struct CadetPeer *cpath[path_length];
613   struct CadetPeerPath *path;
614
615   /* precompute inverted 'cpath' so we can avoid doing the lookups and
616      have the correct order */
617   for (unsigned int off=0;off<path_length;off++)
618     cpath[off] = GCP_get (&pids[path_length - 1 - off],
619                           GNUNET_YES);
620
621   /* First figure out if this path is a subset of an existing path, an
622      extension of an existing path, or a new path. */
623   cm_ctx.cpath = cpath;
624   cm_ctx.cpath_length = path_length;
625   cm_ctx.match = NULL;
626   for (int i=path_length-1;i>=0;i--)
627   {
628     GCP_iterate_paths_at (cpath[i],
629                           (unsigned int) i,
630                           &check_match,
631                           &cm_ctx);
632     if (NULL != cm_ctx.match)
633     {
634       if (i == path_length - 1)
635       {
636         /* Existing path includes this one, return the match! */
637         LOG (GNUNET_ERROR_TYPE_DEBUG,
638              "Returning existing path %s as inverse for incoming connection\n",
639              GCPP_2s (cm_ctx.match));
640         return cm_ctx.match;
641       }
642       if (cm_ctx.match->entries_length == i + 1)
643       {
644         /* Existing path ends in the middle of new path, extend it! */
645         LOG (GNUNET_ERROR_TYPE_DEBUG,
646              "Extending existing path %s to create inverse for incoming connection\n",
647              GCPP_2s (cm_ctx.match));
648         extend_path (cm_ctx.match,
649                      &cpath[i + 1],
650                      path_length - i - 1,
651                      GNUNET_YES);
652         /* Check that extension was successful */
653         GNUNET_assert (cm_ctx.match->entries_length == path_length);
654         return cm_ctx.match;
655       }
656       /* Eh, we found a match but couldn't use it? Something is wrong. */
657       GNUNET_break (0);
658     }
659   }
660
661   /* No match at all, create completely new path */
662   path = GNUNET_new (struct CadetPeerPath);
663   path->entries_length = path_length;
664   path->entries = GNUNET_new_array (path->entries_length,
665                                     struct CadetPeerPathEntry *);
666   for (int i=path_length-1;i>=0;i--)
667   {
668     struct CadetPeerPathEntry *entry = GNUNET_new (struct CadetPeerPathEntry);
669
670     path->entries[i] = entry;
671     entry->peer = cpath[i];
672     entry->path = path;
673   }
674   for (int i=path_length-1;i>=0;i--)
675   {
676     struct CadetPeerPathEntry *entry = path->entries[i];
677
678     GCP_path_entry_add (entry->peer,
679                         entry,
680                         i);
681   }
682   recalculate_path_desirability (path);
683   LOG (GNUNET_ERROR_TYPE_DEBUG,
684        "Created new path %s to create inverse for incoming connection\n",
685        GCPP_2s (path));
686   path->hn = GCP_attach_path (cpath[path_length - 1],
687                               path,
688                               path_length - 1,
689                               GNUNET_YES);
690   return path;
691 }
692
693
694 /**
695  * Return the length of the path.  Excludes one end of the
696  * path, so the loopback path has length 0.
697  *
698  * @param path path to return the length for
699  * @return number of peers on the path
700  */
701 unsigned int
702 GCPP_get_length (struct CadetPeerPath *path)
703 {
704   return path->entries_length;
705 }
706
707
708 /**
709  * Find peer's offset on path.
710  *
711  * @param path path to search
712  * @param cp peer to look for
713  * @return offset of @a cp on @a path, or UINT_MAX if not found
714  */
715 unsigned int
716 GCPP_find_peer (struct CadetPeerPath *path,
717                 struct CadetPeer *cp)
718 {
719   for (unsigned int off = 0;
720        off < path->entries_length;
721        off++)
722     if (cp == GCPP_get_peer_at_offset (path,
723                                        off))
724       return off;
725   return UINT_MAX;
726 }
727
728
729 /**
730  * Obtain the peer at offset @a off in @a path.
731  *
732  * @param path peer path to inspect
733  * @param off offset to return, must be smaller than path length
734  * @return the peer at offset @a off
735  */
736 struct CadetPeer *
737 GCPP_get_peer_at_offset (struct CadetPeerPath *path,
738                          unsigned int off)
739 {
740   GNUNET_assert (off < path->entries_length);
741   return path->entries[off]->peer;
742 }
743
744
745 /**
746  * Convert a path to a human-readable string.
747  *
748  * @param path path to convert
749  * @return string, to be freed by caller (unlike other *_2s APIs!)
750  */
751 const char *
752 GCPP_2s (struct CadetPeerPath *path)
753 {
754   static char buf[2048];
755   size_t off;
756   const unsigned int max_plen = (sizeof(buf) - 16) / 5 - 2; /* 5 characters per entry */
757
758   off = 0;
759   for (unsigned int i = 0;
760        i < path->entries_length;
761        i++)
762   {
763     if ( (path->entries_length > max_plen) &&
764          (i == max_plen / 2) )
765       off += GNUNET_snprintf (&buf[off],
766                               sizeof (buf) - off,
767                               "...-");
768     if ( (path->entries_length > max_plen) &&
769          (i > max_plen / 2) &&
770          (i < path->entries_length - max_plen / 2) )
771       continue;
772     off += GNUNET_snprintf (&buf[off],
773                             sizeof (buf) - off,
774                             "%s%s",
775                             GNUNET_i2s (GCP_get_id (GCPP_get_peer_at_offset (path,
776                                                                              i))),
777                             (i == path->entries_length -1) ? "" : "-");
778   }
779   GNUNET_snprintf (&buf[off],
780                    sizeof (buf) - off,
781                    "(%p)",
782                    path);
783   return buf;
784 }
785
786
787 /* end of gnunet-service-cadet-new_paths.c */