-merge
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_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_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_connection.h"
28 #include "gnunet-service-cadet_tunnels.h"
29 #include "gnunet-service-cadet_peer.h"
30 #include "gnunet-service-cadet_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   GNUNET_assert (NULL != cc);
157   entry->cc = cc;
158 }
159
160
161
162 /**
163  * Notify @a path that it is no longer used for connection @a cc which
164  * ended at the path's offset @a off.
165  *
166  * @param path the path to forget the @a cc
167  * @param off the offset where the @a cc ended
168  * @param cc the connection to forget
169  */
170 void
171 GCPP_del_connection (struct CadetPeerPath *path,
172                      unsigned int off,
173                      struct CadetConnection *cc)
174 {
175   struct CadetPeerPathEntry *entry;
176
177   LOG (GNUNET_ERROR_TYPE_DEBUG,
178        "Removing connection %s to path %s at offset %u\n",
179        GCC_2s (cc),
180        GCPP_2s (path),
181        off);
182   GNUNET_assert (off < path->entries_length);
183   entry = path->entries[off];
184   GNUNET_assert (cc == entry->cc);
185   entry->cc = NULL;
186 }
187
188
189 /**
190  * Tries to attach @a path to a peer, working backwards from the end
191  * and stopping at @a stop_at. If path->hn is NULL on return then the
192  * path was not attached and you can assume that path->entries_length
193  * is equal to @a stop_at.
194  *
195  * @param path the path to attach
196  * @param stop_at the path length at which to stop trying
197  */
198 static void
199 attach_path (struct CadetPeerPath *path, unsigned int stop_at)
200 {
201   GNUNET_assert (NULL == path->hn);
202
203   /* Try to attach this path to a peer, working backwards from the end. */
204   while (path->entries_length > stop_at)
205   {
206     unsigned int end = path->entries_length - 1;
207     struct CadetPeerPathEntry *entry = path->entries[end];
208     int force = GNUNET_NO;
209
210     recalculate_path_desirability (path);
211     /* If the entry already has a connection using it, force attach. */
212     if (NULL != entry->cc)
213       force = GNUNET_YES;
214     path->hn = GCP_attach_path (entry->peer,
215                                 path,
216                                 end,
217                                 force);
218     if (NULL != path->hn)
219       break;
220
221     /* Attach failed, trim this entry from the path. */
222     GNUNET_assert (NULL == entry->cc);
223     GCP_path_entry_remove (entry->peer,
224                            entry,
225                            end);
226     GNUNET_free (entry);
227     path->entries[end] = NULL;
228     path->entries_length--;
229   }
230
231   /* Shrink array to actual path length. */
232   GNUNET_array_grow (path->entries,
233                      path->entries_length,
234                      path->entries_length);
235 }
236
237
238 /**
239  * The owning peer of this path is no longer interested in maintaining
240  * it, so the path should be discarded or shortened (in case a
241  * previous peer on the path finds the path desirable).
242  *
243  * @param path the path that is being released
244  */
245 void
246 GCPP_release (struct CadetPeerPath *path)
247 {
248   struct CadetPeerPathEntry *entry;
249
250   LOG (GNUNET_ERROR_TYPE_DEBUG,
251        "Owner releases path %s\n",
252        GCPP_2s (path));
253   path->hn = NULL;
254   entry = path->entries[path->entries_length - 1];
255   GNUNET_assert (path == entry->path);
256   GNUNET_assert (NULL == entry->cc);
257   /* cut 'off' end of path */
258   GCP_path_entry_remove (entry->peer,
259                          entry,
260                          path->entries_length - 1);
261   GNUNET_free (entry);
262   path->entries[path->entries_length - 1] = NULL;
263   path->entries_length--;
264   /* see if new peer at the end likes this path any better */
265   attach_path (path, 0);
266   if (NULL == path->hn)
267   {
268     /* nobody wants us, discard the path */
269     GNUNET_assert (0 == path->entries_length);
270     GNUNET_assert (NULL == path->entries);
271     GNUNET_free (path);
272   }
273 }
274
275
276 /**
277  * Updates the score for an entry on the path based
278  * on our experiences with using @a path.
279  *
280  * @param path the path to update
281  * @param off offset of the entry to update
282  * @param delta change in the score to apply
283  */
284 void
285 GCPP_update_score (struct CadetPeerPath *path,
286                    unsigned int off,
287                    int delta)
288 {
289   struct CadetPeerPathEntry *entry;
290
291   GNUNET_assert (off < path->entries_length);
292   entry = path->entries[off];
293
294   /* Add delta, with checks for overflows */
295   if (delta >= 0)
296   {
297     if (delta + entry->score < entry->score)
298       entry->score = INT_MAX;
299     else
300       entry->score += delta;
301   }
302   else
303   {
304     if (delta + entry->score > entry->score)
305       entry->score = INT_MIN;
306     else
307       entry->score += delta;
308   }
309   recalculate_path_desirability (path);
310 }
311
312
313 /**
314  * Closure for #find_peer_at() and #check_match().
315  */
316 struct CheckMatchContext
317 {
318
319   /**
320    * Set to a matching path, if any.
321    */
322   struct CadetPeerPath *match;
323
324   /**
325    * Array the combined paths.
326    */
327   struct CadetPeer **cpath;
328
329   /**
330    * How long is the @e cpath array?
331    */
332   unsigned int cpath_length;
333
334 };
335
336
337 /**
338  * Check if the given path is identical on all of the
339  * hops until @a off, and not longer than @a off.  If the
340  * @a path matches, store it in `match`.
341  *
342  * @param cls the `struct CheckMatchContext` to check against
343  * @param path the path to check
344  * @param off offset to check at
345  * @return #GNUNET_YES (continue to iterate), or if found #GNUNET_NO
346  */
347 static int
348 check_match (void *cls,
349              struct CadetPeerPath *path,
350              unsigned int off)
351 {
352   struct CheckMatchContext *cm_ctx = cls;
353
354   GNUNET_assert (path->entries_length > off);
355   if ( (path->entries_length != off + 1) &&
356        (off + 1 != cm_ctx->cpath_length) )
357   {
358     LOG (GNUNET_ERROR_TYPE_DEBUG,
359          "check_match missmatch because path %s is too long (%u vs. %u vs. %u)\n",
360          GCPP_2s (path),
361          path->entries_length,
362          off + 1,
363          cm_ctx->cpath_length);
364     return GNUNET_YES; /* too long, goes somewhere else already, thus cannot be useful */
365   }
366   for (unsigned int i=0;i<off;i++)
367     if (cm_ctx->cpath[i] !=
368         GCPP_get_peer_at_offset (path,
369                                  i))
370     {
371       LOG (GNUNET_ERROR_TYPE_DEBUG,
372            "check_match path %s missmatches at offset %u\n",
373            GCPP_2s (path),
374            i);
375       return GNUNET_YES; /* missmatch, ignore */
376     }
377   LOG (GNUNET_ERROR_TYPE_DEBUG,
378        "check_match found match with path %s\n",
379        GCPP_2s (path));
380   cm_ctx->match = path;
381   return GNUNET_NO; /* match, we are done! */
382 }
383
384
385 /**
386  * Extend path @a path by the @a num_peers from the @a peers
387  * array, assuming the owners past the current owner want it.
388  *
389  * @param path path to extend
390  * @param peers list of peers beyond the end of @a path
391  * @param num_peers length of the @a peers array
392  * @param force force attachment, even if we have other
393  *        paths already
394  */
395 static void
396 extend_path (struct CadetPeerPath *path,
397              struct CadetPeer **peers,
398              unsigned int num_peers,
399              int force)
400 {
401   unsigned int old_len = path->entries_length;
402   int i;
403
404   /* Expand path */
405   GNUNET_array_grow (path->entries,
406                      path->entries_length,
407                      old_len + num_peers);
408   for (i=num_peers-1;i >= 0;i--)
409   {
410     struct CadetPeerPathEntry *entry = GNUNET_new (struct CadetPeerPathEntry);
411
412     path->entries[old_len + i] = entry;
413     entry->peer = peers[i];
414     entry->path = path;
415   }
416   for (i=num_peers-1;i >= 0;i--)
417   {
418     struct CadetPeerPathEntry *entry = path->entries[old_len + i];
419
420     GCP_path_entry_add (entry->peer,
421                         entry,
422                         old_len + i);
423   }
424
425   /* If we extend an existing path, detach it from the
426      old owner and re-attach to the new one */
427   GCP_detach_path (path->entries[old_len-1]->peer,
428                    path,
429                    path->hn);
430   path->hn = NULL;
431   path->entries_length = old_len + num_peers;
432   attach_path (path, old_len);
433   if (NULL == path->hn)
434   {
435     /* none of the peers is interested in this path;
436        re-attach. */
437     GNUNET_assert (old_len == path->entries_length);
438     path->hn = GCP_attach_path (path->entries[old_len - 1]->peer,
439                                 path,
440                                 old_len - 1,
441                                 GNUNET_YES);
442     GNUNET_assert (NULL != path->hn);
443     return;
444   }
445   LOG (GNUNET_ERROR_TYPE_DEBUG,
446        "Extended path %s\n",
447        GCPP_2s (path));
448 }
449
450
451 /**
452  * Create a peer path based on the result of a DHT lookup.  If we
453  * already know this path, or one that is longer, simply return NULL.
454  * Otherwise, we try to extend an existing path, or create a new one
455  * if applicable.
456  *
457  * @param get_path path of the get request
458  * @param get_path_length lenght of @a get_path
459  * @param put_path path of the put request
460  * @param put_path_length length of the @a put_path
461  * @return a path through the network
462  */
463 void
464 GCPP_try_path_from_dht (const struct GNUNET_PeerIdentity *get_path,
465                         unsigned int get_path_length,
466                         const struct GNUNET_PeerIdentity *put_path,
467                         unsigned int put_path_length)
468 {
469   struct CadetPeer *cpath[get_path_length + put_path_length];
470   struct CheckMatchContext cm_ctx;
471   struct CadetPeerPath *path;
472   int i;
473   unsigned int skip;
474   unsigned int total_len;
475
476   /* precompute 'cpath' so we can avoid doing the lookups lots of times */
477   skip = 0;
478   memset (cpath,
479           0,
480           sizeof (cpath)); /* Just to trigger harder errors later. */
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 - 1]
488       : &put_path[get_path_length + put_path_length - off - 1];
489     /* Check that I am not in the path */
490     if (0 == memcmp (&my_full_id,
491                      pid,
492                      sizeof (struct GNUNET_PeerIdentity)))
493     {
494       skip = off + 1;
495       continue;
496     }
497     cpath[off - skip] = GCP_get (pid,
498                                  GNUNET_YES);
499     /* Check that no peer is twice on the path */
500     for (unsigned int i=0;i<off - skip;i++)
501     {
502      if (cpath[i] == cpath[off - skip])
503       {
504         skip = off - i;
505         break;
506       }
507     }
508   }
509   if (skip >= total_len)
510   {
511     LOG (GNUNET_ERROR_TYPE_DEBUG,
512          "Path discovered from DHT is one big cycle?\n");
513     return;
514   }
515   total_len -= skip;
516
517   /* First figure out if this path is a subset of an existing path, an
518      extension of an existing path, or a new path. */
519   cm_ctx.cpath_length = total_len;
520   cm_ctx.cpath = cpath;
521   cm_ctx.match = NULL;
522   for (i=total_len-1;i>=0;i--)
523   {
524     GCP_iterate_paths_at (cpath[i],
525                           (unsigned int) i,
526                           &check_match,
527                           &cm_ctx);
528     if (NULL != cm_ctx.match)
529     {
530       if (i == total_len - 1)
531       {
532         /* Existing path includes this one, nothing to do! */
533         LOG (GNUNET_ERROR_TYPE_DEBUG,
534              "Path discovered from DHT is already known\n");
535         return;
536       }
537       if (cm_ctx.match->entries_length == i + 1)
538       {
539         /* Existing path ends in the middle of new path, extend it! */
540         LOG (GNUNET_ERROR_TYPE_DEBUG,
541              "Trying to extend existing path %s by additional links discovered from DHT\n",
542              GCPP_2s (cm_ctx.match));
543         extend_path (cm_ctx.match,
544                      &cpath[i + 1],
545                      total_len - i - 1,
546                      GNUNET_NO);
547         return;
548       }
549     }
550   }
551
552   /* No match at all, create completely new path */
553   path = GNUNET_new (struct CadetPeerPath);
554   path->entries_length = total_len;
555   path->entries = GNUNET_new_array (path->entries_length,
556                                     struct CadetPeerPathEntry *);
557   for (i=path->entries_length-1;i>=0;i--)
558   {
559     struct CadetPeerPathEntry *entry = GNUNET_new (struct CadetPeerPathEntry);
560
561     path->entries[i] = entry;
562     entry->peer = cpath[i];
563     entry->path = path;
564   }
565   for (i=path->entries_length-1;i>=0;i--)
566   {
567     struct CadetPeerPathEntry *entry = path->entries[i];
568
569     GCP_path_entry_add (entry->peer,
570                         entry,
571                         i);
572   }
573
574   /* Finally, try to attach it */
575   attach_path (path, 0);
576   if (NULL == path->hn)
577   {
578     /* None of the peers on the path care about it. */
579     LOG (GNUNET_ERROR_TYPE_DEBUG,
580          "Path discovered from DHT is not interesting to us\n");
581     GNUNET_assert (0 == path->entries_length);
582     GNUNET_assert (NULL == path->entries);
583     GNUNET_free (path);
584     return;
585   }
586   LOG (GNUNET_ERROR_TYPE_DEBUG,
587        "Created new path %s based on information from DHT\n",
588        GCPP_2s (path));
589 }
590
591
592 /**
593  * We got an incoming connection, obtain the corresponding path.
594  *
595  * @param path_length number of segments on the @a path
596  * @param pids path through the network, in reverse order (we are at the end at index @a path_length)
597  * @return corresponding path object
598  */
599 struct CadetPeerPath *
600 GCPP_get_path_from_route (unsigned int path_length,
601                           const struct GNUNET_PeerIdentity *pids)
602 {
603   struct CheckMatchContext cm_ctx;
604   struct CadetPeer *cpath[path_length];
605   struct CadetPeerPath *path;
606
607   /* precompute inverted 'cpath' so we can avoid doing the lookups and
608      have the correct order */
609   for (unsigned int off=0;off<path_length;off++)
610     cpath[off] = GCP_get (&pids[path_length - 1 - off],
611                           GNUNET_YES);
612
613   /* First figure out if this path is a subset of an existing path, an
614      extension of an existing path, or a new path. */
615   cm_ctx.cpath = cpath;
616   cm_ctx.cpath_length = path_length;
617   cm_ctx.match = NULL;
618   for (int i=path_length-1;i>=0;i--)
619   {
620     GCP_iterate_paths_at (cpath[i],
621                           (unsigned int) i,
622                           &check_match,
623                           &cm_ctx);
624     if (NULL != cm_ctx.match)
625     {
626       if (i == path_length - 1)
627       {
628         /* Existing path includes this one, return the match! */
629         LOG (GNUNET_ERROR_TYPE_DEBUG,
630              "Returning existing path %s as inverse for incoming connection\n",
631              GCPP_2s (cm_ctx.match));
632         return cm_ctx.match;
633       }
634       if (cm_ctx.match->entries_length == i + 1)
635       {
636         /* Existing path ends in the middle of new path, extend it! */
637         LOG (GNUNET_ERROR_TYPE_DEBUG,
638              "Extending existing path %s to create inverse for incoming connection\n",
639              GCPP_2s (cm_ctx.match));
640         extend_path (cm_ctx.match,
641                      &cpath[i + 1],
642                      path_length - i - 1,
643                      GNUNET_YES);
644         /* Check that extension was successful */
645         GNUNET_assert (cm_ctx.match->entries_length == path_length);
646         return cm_ctx.match;
647       }
648       /* Eh, we found a match but couldn't use it? Something is wrong. */
649       GNUNET_break (0);
650     }
651   }
652
653   /* No match at all, create completely new path */
654   path = GNUNET_new (struct CadetPeerPath);
655   path->entries_length = path_length;
656   path->entries = GNUNET_new_array (path->entries_length,
657                                     struct CadetPeerPathEntry *);
658   for (int i=path_length-1;i>=0;i--)
659   {
660     struct CadetPeerPathEntry *entry = GNUNET_new (struct CadetPeerPathEntry);
661
662     path->entries[i] = entry;
663     entry->peer = cpath[i];
664     entry->path = path;
665   }
666   for (int i=path_length-1;i>=0;i--)
667   {
668     struct CadetPeerPathEntry *entry = path->entries[i];
669
670     GCP_path_entry_add (entry->peer,
671                         entry,
672                         i);
673   }
674   recalculate_path_desirability (path);
675   LOG (GNUNET_ERROR_TYPE_DEBUG,
676        "Created new path %s to create inverse for incoming connection\n",
677        GCPP_2s (path));
678   path->hn = GCP_attach_path (cpath[path_length - 1],
679                               path,
680                               path_length - 1,
681                               GNUNET_YES);
682   return path;
683 }
684
685
686 /**
687  * Return the length of the path.  Excludes one end of the
688  * path, so the loopback path has length 0.
689  *
690  * @param path path to return the length for
691  * @return number of peers on the path
692  */
693 unsigned int
694 GCPP_get_length (struct CadetPeerPath *path)
695 {
696   return path->entries_length;
697 }
698
699
700 /**
701  * Find peer's offset on path.
702  *
703  * @param path path to search
704  * @param cp peer to look for
705  * @return offset of @a cp on @a path, or UINT_MAX if not found
706  */
707 unsigned int
708 GCPP_find_peer (struct CadetPeerPath *path,
709                 struct CadetPeer *cp)
710 {
711   for (unsigned int off = 0;
712        off < path->entries_length;
713        off++)
714     if (cp == GCPP_get_peer_at_offset (path,
715                                        off))
716       return off;
717   return UINT_MAX;
718 }
719
720
721 /**
722  * Obtain the peer at offset @a off in @a path.
723  *
724  * @param path peer path to inspect
725  * @param off offset to return, must be smaller than path length
726  * @return the peer at offset @a off
727  */
728 struct CadetPeer *
729 GCPP_get_peer_at_offset (struct CadetPeerPath *path,
730                          unsigned int off)
731 {
732   GNUNET_assert (off < path->entries_length);
733   return path->entries[off]->peer;
734 }
735
736
737 /**
738  * Convert a path to a human-readable string.
739  *
740  * @param path path to convert
741  * @return string, to be freed by caller (unlike other *_2s APIs!)
742  */
743 const char *
744 GCPP_2s (struct CadetPeerPath *path)
745 {
746   static char buf[2048];
747   size_t off;
748   const unsigned int max_plen = (sizeof(buf) - 16) / 5 - 2; /* 5 characters per entry */
749
750   off = 0;
751   for (unsigned int i = 0;
752        i < path->entries_length;
753        i++)
754   {
755     if ( (path->entries_length > max_plen) &&
756          (i == max_plen / 2) )
757       off += GNUNET_snprintf (&buf[off],
758                               sizeof (buf) - off,
759                               "...-");
760     if ( (path->entries_length > max_plen) &&
761          (i > max_plen / 2) &&
762          (i < path->entries_length - max_plen / 2) )
763       continue;
764     off += GNUNET_snprintf (&buf[off],
765                             sizeof (buf) - off,
766                             "%s%s",
767                             GNUNET_i2s (GCP_get_id (GCPP_get_peer_at_offset (path,
768                                                                              i))),
769                             (i == path->entries_length -1) ? "" : "-");
770   }
771   GNUNET_snprintf (&buf[off],
772                    sizeof (buf) - off,
773                    "(%p)",
774                    path);
775   return buf;
776 }
777
778
779 /* end of gnunet-service-cadet-new_paths.c */