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