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