Merge branch 'fix_social'
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_core.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 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 /**
22  * @file cadet/gnunet-service-cadet_core.c
23  * @brief cadet service; interaction with CORE service
24  * @author Bartlomiej Polot
25  * @author Christian Grothoff
26  *
27  * All functions in this file should use the prefix GCO (Gnunet Cadet cOre (bottom))
28  *
29  * TODO:
30  * - Optimization: given BROKEN messages, destroy paths (?)
31  */
32 #include "platform.h"
33 #include "gnunet-service-cadet_core.h"
34 #include "gnunet-service-cadet_paths.h"
35 #include "gnunet-service-cadet_peer.h"
36 #include "gnunet-service-cadet_connection.h"
37 #include "gnunet-service-cadet_tunnels.h"
38 #include "gnunet_core_service.h"
39 #include "gnunet_statistics_service.h"
40 #include "cadet_protocol.h"
41
42
43 #define LOG(level, ...) GNUNET_log_from(level,"cadet-cor",__VA_ARGS__)
44
45 /**
46  * Information we keep per direction for a route.
47  */
48 struct RouteDirection;
49
50
51 /**
52  * Set of CadetRoutes that have exactly the same number of messages
53  * in their buffer.  Used so we can efficiently find all of those
54  * routes that have the current maximum of messages in the buffer (in
55  * case we have to purge).
56  */
57 struct Rung
58 {
59
60   /**
61    * Rung of RouteDirections with one more buffer entry each.
62    */
63   struct Rung *next;
64
65   /**
66    * Rung of RouteDirections with one less buffer entry each.
67    */
68   struct Rung *prev;
69
70   /**
71    * DLL of route directions with a number of buffer entries matching this rung.
72    */
73   struct RouteDirection *rd_head;
74
75   /**
76    * DLL of route directions with a number of buffer entries matching this rung.
77    */
78   struct RouteDirection *rd_tail;
79
80   /**
81    * Total number of route directions in this rung.
82    */
83   unsigned int num_routes;
84
85   /**
86    * Number of messages route directions at this rung have
87    * in their buffer.
88    */
89   unsigned int rung_off;
90 };
91
92
93 /**
94  * Information we keep per direction for a route.
95  */
96 struct RouteDirection
97 {
98
99   /**
100    * DLL of other route directions within the same `struct Rung`.
101    */
102   struct RouteDirection *prev;
103
104   /**
105    * DLL of other route directions within the same `struct Rung`.
106    */
107   struct RouteDirection *next;
108
109   /**
110    * Rung of this route direction (matches length of the buffer DLL).
111    */
112   struct Rung *rung;
113
114   /**
115    * Head of DLL of envelopes we have in the buffer for this direction.
116    */
117   struct GNUNET_MQ_Envelope *env_head;
118
119   /**
120    * Tail of DLL of envelopes we have in the buffer for this direction.
121    */
122   struct GNUNET_MQ_Envelope *env_tail;
123
124   /**
125    * Target peer.
126    */
127   struct CadetPeer *hop;
128
129   /**
130    * Route this direction is part of.
131    */
132   struct CadetRoute *my_route;
133
134   /**
135    * Message queue manager for @e hop.
136    */
137   struct GCP_MessageQueueManager *mqm;
138
139   /**
140    * Is @e mqm currently ready for transmission?
141    */
142   int is_ready;
143
144 };
145
146
147 /**
148  * Description of a segment of a `struct CadetConnection` at the
149  * intermediate peers.  Routes are basically entries in a peer's
150  * routing table for forwarding traffic.  At both endpoints, the
151  * routes are terminated by a `struct CadetConnection`, which knows
152  * the complete `struct CadetPath` that is formed by the individual
153  * routes.
154  */
155 struct CadetRoute
156 {
157
158   /**
159    * Information about the next hop on this route.
160    */
161   struct RouteDirection next;
162
163   /**
164    * Information about the previous hop on this route.
165    */
166   struct RouteDirection prev;
167
168   /**
169    * Unique identifier for the connection that uses this route.
170    */
171   struct GNUNET_CADET_ConnectionTunnelIdentifier cid;
172
173   /**
174    * When was this route last in use?
175    */
176   struct GNUNET_TIME_Absolute last_use;
177
178   /**
179    * Position of this route in the #route_heap.
180    */
181   struct GNUNET_CONTAINER_HeapNode *hn;
182
183   /**
184    * Options for the route, control buffering.
185    */
186   enum GNUNET_CADET_ChannelOption options;
187 };
188
189
190 /**
191  * Handle to the CORE service.
192  */
193 static struct GNUNET_CORE_Handle *core;
194
195 /**
196  * Routes on which this peer is an intermediate.
197  */
198 static struct GNUNET_CONTAINER_MultiShortmap *routes;
199
200 /**
201  * Heap of routes, MIN-sorted by last activity.
202  */
203 static struct GNUNET_CONTAINER_Heap *route_heap;
204
205 /**
206  * Rung zero (always pointed to by #rung_head).
207  */
208 static struct Rung rung_zero;
209
210 /**
211  * DLL of rungs, with the head always point to a rung of
212  * route directions with no messages in the queue.
213  */
214 static struct Rung *rung_head = &rung_zero;
215
216 /**
217  * Tail of the #rung_head DLL.
218  */
219 static struct Rung *rung_tail = &rung_zero;
220
221 /**
222  * Maximum number of concurrent routes this peer will support.
223  */
224 static unsigned long long max_routes;
225
226 /**
227  * Maximum number of envelopes we will buffer at this peer.
228  */
229 static unsigned long long max_buffers;
230
231 /**
232  * Current number of envelopes we have buffered at this peer.
233  */
234 static unsigned long long cur_buffers;
235
236 /**
237  * Task to timeout routes.
238  */
239 static struct GNUNET_SCHEDULER_Task *timeout_task;
240
241
242 /**
243  * Get the route corresponding to a hash.
244  *
245  * @param cid hash generated from the connection identifier
246  */
247 static struct CadetRoute *
248 get_route (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid)
249 {
250   return GNUNET_CONTAINER_multishortmap_get (routes,
251                                              &cid->connection_of_tunnel);
252 }
253
254
255 /**
256  * Lower the rung in which @a dir is by 1.
257  *
258  * @param dir direction to lower in rung.
259  */
260 static void
261 lower_rung (struct RouteDirection *dir)
262 {
263   struct Rung *rung = dir->rung;
264   struct Rung *prev;
265
266   GNUNET_CONTAINER_DLL_remove (rung->rd_head,
267                                rung->rd_tail,
268                                dir);
269   prev = rung->prev;
270   GNUNET_assert (NULL != prev);
271   if (prev->rung_off != rung->rung_off - 1)
272   {
273     prev = GNUNET_new (struct Rung);
274     prev->rung_off = rung->rung_off - 1;
275     GNUNET_CONTAINER_DLL_insert_after (rung_head,
276                                        rung_tail,
277                                        rung->prev,
278                                        prev);
279   }
280   GNUNET_assert (NULL != prev);
281   GNUNET_CONTAINER_DLL_insert (prev->rd_head,
282                                prev->rd_tail,
283                                dir);
284   dir->rung = prev;
285 }
286
287
288 /**
289  * Discard the buffer @a env from the route direction @a dir and
290  * move @a dir down a rung.
291  *
292  * @param dir direction that contains the @a env in the buffer
293  * @param env envelope to discard
294  */
295 static void
296 discard_buffer (struct RouteDirection *dir,
297                 struct GNUNET_MQ_Envelope *env)
298 {
299   GNUNET_MQ_dll_remove (&dir->env_head,
300                         &dir->env_tail,
301                         env);
302   cur_buffers--;
303   GNUNET_MQ_discard (env);
304   lower_rung (dir);
305   GNUNET_STATISTICS_set (stats,
306                          "# buffer use",
307                          cur_buffers,
308                          GNUNET_NO);
309 }
310
311
312 /**
313  * Discard all messages from the highest rung, to make space.
314  */
315 static void
316 discard_all_from_rung_tail ()
317 {
318   struct Rung *tail = rung_tail;
319   struct RouteDirection *dir;
320
321   while (NULL != (dir = tail->rd_head))
322   {
323     LOG (GNUNET_ERROR_TYPE_DEBUG,
324          "Queue full due new message %s on connection %s, dropping old message\n",
325          GNUNET_sh2s (&dir->my_route->cid.connection_of_tunnel));
326     GNUNET_STATISTICS_update (stats,
327                               "# messages dropped due to full buffer",
328                               1,
329                               GNUNET_NO);
330     discard_buffer (dir,
331                     dir->env_head);
332   }
333   GNUNET_CONTAINER_DLL_remove (rung_head,
334                                rung_tail,
335                                tail);
336   GNUNET_free (tail);
337 }
338
339
340 /**
341  * We message @a msg from @a prev.  Find its route by @a cid and
342  * forward to the next hop.  Drop and signal broken route if we do not
343  * have a route.
344  *
345  * @param prev previous hop (sender)
346  * @param cid connection identifier, tells us which route to use
347  * @param msg the message to forward
348  */
349 static void
350 route_message (struct CadetPeer *prev,
351                const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
352                const struct GNUNET_MessageHeader *msg)
353 {
354   struct CadetRoute *route;
355   struct RouteDirection *dir;
356   struct Rung *rung;
357   struct Rung *nxt;
358   struct GNUNET_MQ_Envelope *env;
359
360   route = get_route (cid);
361   if (NULL == route)
362   {
363     struct GNUNET_MQ_Envelope *env;
364     struct GNUNET_CADET_ConnectionBrokenMessage *bm;
365
366     LOG (GNUNET_ERROR_TYPE_DEBUG,
367          "Failed to route message of type %u from %s on connection %s: no route\n",
368          ntohs (msg->type),
369          GCP_2s (prev),
370          GNUNET_sh2s (&cid->connection_of_tunnel));
371     switch (ntohs (msg->type))
372     {
373     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
374     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
375       /* No need to respond to these! */
376       return;
377     }
378     env = GNUNET_MQ_msg (bm,
379                          GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN);
380     bm->cid = *cid;
381     bm->peer1 = my_full_id;
382     GCP_send_ooo (prev,
383                   env);
384     return;
385   }
386   route->last_use = GNUNET_TIME_absolute_get ();
387   GNUNET_CONTAINER_heap_update_cost (route->hn,
388                                      route->last_use.abs_value_us);
389   dir = (prev == route->prev.hop) ? &route->next : &route->prev;
390   if (GNUNET_YES == dir->is_ready)
391   {
392     LOG (GNUNET_ERROR_TYPE_DEBUG,
393          "Routing message of type %u from %s to %s on connection %s\n",
394          ntohs (msg->type),
395          GCP_2s (prev),
396          GNUNET_i2s (GCP_get_id (dir->hop)),
397          GNUNET_sh2s (&cid->connection_of_tunnel));
398     dir->is_ready = GNUNET_NO;
399     GCP_send (dir->mqm,
400               GNUNET_MQ_msg_copy (msg));
401     return;
402   }
403   /* Check if buffering is disallowed, and if so, make sure we only queue
404      one message per direction. */
405   if ( (0 != (route->options & GNUNET_CADET_OPTION_NOBUFFER)) &&
406        (NULL != dir->env_head) )
407     discard_buffer (dir,
408                     dir->env_head);
409   rung = dir->rung;
410   if (cur_buffers == max_buffers)
411   {
412     /* Need to make room. */
413     if (NULL != rung->next)
414     {
415       /* Easy case, drop messages from route directions in highest rung */
416       discard_all_from_rung_tail ();
417     }
418     else
419     {
420       /* We are in the highest rung, drop our own! */
421       LOG (GNUNET_ERROR_TYPE_DEBUG,
422            "Queue full due new message %s on connection %s, dropping old message\n",
423            GNUNET_sh2s (&dir->my_route->cid.connection_of_tunnel));
424       GNUNET_STATISTICS_update (stats,
425                                 "# messages dropped due to full buffer",
426                                 1,
427                                 GNUNET_NO);
428       discard_buffer (dir,
429                       dir->env_head);
430       rung = dir->rung;
431     }
432   }
433   /* remove 'dir' from current rung */
434   GNUNET_CONTAINER_DLL_remove (rung->rd_head,
435                                rung->rd_tail,
436                                dir);
437   /* make 'nxt' point to the next higher rung, creat if necessary */
438   nxt = rung->next;
439   if ( (NULL == nxt) ||
440        (rung->rung_off + 1 != nxt->rung_off) )
441   {
442     nxt = GNUNET_new (struct Rung);
443     nxt->rung_off = rung->rung_off + 1;
444     GNUNET_CONTAINER_DLL_insert_after (rung_head,
445                                        rung_tail,
446                                        rung,
447                                        nxt);
448   }
449   /* insert 'dir' into next higher rung */
450   GNUNET_CONTAINER_DLL_insert (nxt->rd_head,
451                                nxt->rd_tail,
452                                dir);
453   dir->rung = nxt;
454
455   /* add message into 'dir' buffer */
456   LOG (GNUNET_ERROR_TYPE_DEBUG,
457        "Queueing new message of type %u from %s to %s on connection %s\n",
458        ntohs (msg->type),
459        GCP_2s (prev),
460        GNUNET_i2s (GCP_get_id (dir->hop)),
461        GNUNET_sh2s (&cid->connection_of_tunnel));
462   env = GNUNET_MQ_msg_copy (msg);
463   GNUNET_MQ_dll_insert_tail (&dir->env_head,
464                              &dir->env_tail,
465                              env);
466   cur_buffers++;
467   GNUNET_STATISTICS_set (stats,
468                          "# buffer use",
469                          cur_buffers,
470                          GNUNET_NO);
471   /* Clean up 'rung' if now empty (and not head) */
472   if ( (NULL == rung->rd_head) &&
473        (rung != rung_head) )
474   {
475     GNUNET_CONTAINER_DLL_remove (rung_head,
476                                  rung_tail,
477                                  rung);
478     GNUNET_free (rung);
479   }
480 }
481
482
483 /**
484  * Check if the create_connection message has the appropriate size.
485  *
486  * @param cls Closure (unused).
487  * @param msg Message to check.
488  *
489  * @return #GNUNET_YES if size is correct, #GNUNET_NO otherwise.
490  */
491 static int
492 check_connection_create (void *cls,
493                          const struct GNUNET_CADET_ConnectionCreateMessage *msg)
494 {
495   uint16_t size = ntohs (msg->header.size) - sizeof (*msg);
496
497   if (0 != (size % sizeof (struct GNUNET_PeerIdentity)))
498   {
499     GNUNET_break_op (0);
500     return GNUNET_NO;
501   }
502   return GNUNET_YES;
503 }
504
505
506 /**
507  * Free internal data of a route direction.
508  *
509  * @param dir direction to destroy (do NOT free memory of 'dir' itself)
510  */
511 static void
512 destroy_direction (struct RouteDirection *dir)
513 {
514   struct GNUNET_MQ_Envelope *env;
515
516   while (NULL != (env = dir->env_head))
517   {
518     GNUNET_STATISTICS_update (stats,
519                               "# messages dropped due to route destruction",
520                               1,
521                               GNUNET_NO);
522     discard_buffer (dir,
523                     env);
524   }
525   if (NULL != dir->mqm)
526   {
527     GCP_request_mq_cancel (dir->mqm,
528                            NULL);
529     dir->mqm = NULL;
530   }
531   GNUNET_CONTAINER_DLL_remove (rung_head->rd_head,
532                                rung_head->rd_tail,
533                                dir);
534 }
535
536
537 /**
538  * Destroy our state for @a route.
539  *
540  * @param route route to destroy
541  */
542 static void
543 destroy_route (struct CadetRoute *route)
544 {
545   LOG (GNUNET_ERROR_TYPE_DEBUG,
546        "Destroying route from %s to %s of connection %s\n",
547        GNUNET_i2s  (GCP_get_id (route->prev.hop)),
548        GNUNET_i2s2 (GCP_get_id (route->next.hop)),
549        GNUNET_sh2s (&route->cid.connection_of_tunnel));
550   GNUNET_assert (route ==
551                  GNUNET_CONTAINER_heap_remove_node (route->hn));
552   GNUNET_assert (GNUNET_YES ==
553                  GNUNET_CONTAINER_multishortmap_remove (routes,
554                                                         &route->cid.connection_of_tunnel,
555                                                         route));
556   GNUNET_STATISTICS_set (stats,
557                          "# routes",
558                          GNUNET_CONTAINER_multishortmap_size (routes),
559                          GNUNET_NO);
560   destroy_direction (&route->prev);
561   destroy_direction (&route->next);
562   GNUNET_free (route);
563 }
564
565
566 /**
567  * Send message that a route is broken between @a peer1 and @a peer2.
568  *
569  * @param target where to send the message
570  * @param cid connection identifier to use
571  * @param peer1 one of the peers where a link is broken
572  * @param peer2 another one of the peers where a link is broken
573  */
574 static void
575 send_broken (struct RouteDirection *target,
576              const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
577              const struct GNUNET_PeerIdentity *peer1,
578              const struct GNUNET_PeerIdentity *peer2)
579 {
580   struct GNUNET_MQ_Envelope *env;
581   struct GNUNET_CADET_ConnectionBrokenMessage *bm;
582
583   if (NULL == target->mqm)
584     return; /* Can't send notification, connection is down! */
585   LOG (GNUNET_ERROR_TYPE_DEBUG,
586        "Notifying %s about BROKEN route at %s-%s of connection %s\n",
587        GCP_2s (target->hop),
588        GNUNET_i2s (peer1),
589        GNUNET_i2s2 (peer2),
590        GNUNET_sh2s (&cid->connection_of_tunnel));
591
592   env = GNUNET_MQ_msg (bm,
593                        GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN);
594   bm->cid = *cid;
595   if (NULL != peer1)
596     bm->peer1 = *peer1;
597   if (NULL != peer2)
598     bm->peer2 = *peer2;
599   GCP_request_mq_cancel (target->mqm,
600                          env);
601   target->mqm = NULL;
602 }
603
604
605 /**
606  * Function called to check if any routes have timed out, and if
607  * so, to clean them up.  Finally, schedules itself again at the
608  * earliest time where there might be more work.
609  *
610  * @param cls NULL
611  */
612 static void
613 timeout_cb (void *cls)
614 {
615   struct CadetRoute *r;
616   struct GNUNET_TIME_Relative linger;
617   struct GNUNET_TIME_Absolute exp;
618
619   timeout_task = NULL;
620   linger = GNUNET_TIME_relative_multiply (keepalive_period,
621                                           3);
622   while (NULL != (r = GNUNET_CONTAINER_heap_peek (route_heap)))
623   {
624     exp = GNUNET_TIME_absolute_add (r->last_use,
625                                     linger);
626     if (0 != GNUNET_TIME_absolute_get_duration (exp).rel_value_us)
627     {
628       /* Route not yet timed out, wait until it does. */
629       timeout_task = GNUNET_SCHEDULER_add_at (exp,
630                                               &timeout_cb,
631                                               NULL);
632       return;
633     }
634     send_broken (&r->prev,
635                  &r->cid,
636                  NULL,
637                  NULL);
638     send_broken (&r->next,
639                  &r->cid,
640                  NULL,
641                  NULL);
642     destroy_route (r);
643   }
644   /* No more routes left, so no need for a #timeout_task */
645 }
646
647
648 /**
649  * Function called when the message queue to the previous hop
650  * becomes available/unavailable.  We expect this function to
651  * be called immediately when we register, and then again
652  * later if the connection ever goes down.
653  *
654  * @param cls the `struct RouteDirection`
655  * @param available #GNUNET_YES if sending is now possible,
656  *                  #GNUNET_NO if sending is no longer possible
657  *                  #GNUNET_SYSERR if sending is no longer possible
658  *                                 and the last envelope was discarded
659  */
660 static void
661 dir_ready_cb (void *cls,
662               int ready)
663 {
664   struct RouteDirection *dir = cls;
665   struct CadetRoute *route = dir->my_route;
666   struct RouteDirection *odir;
667
668   if (GNUNET_YES == ready)
669   {
670     struct GNUNET_MQ_Envelope *env;
671
672     dir->is_ready = GNUNET_YES;
673     if (NULL != (env = dir->env_head))
674     {
675       GNUNET_MQ_dll_remove (&dir->env_head,
676                             &dir->env_tail,
677                             env);
678       cur_buffers--;
679       GNUNET_STATISTICS_set (stats,
680                              "# buffer use",
681                              cur_buffers,
682                              GNUNET_NO);
683       lower_rung (dir);
684       dir->is_ready = GNUNET_NO;
685       GCP_send (dir->mqm,
686                 env);
687     }
688     return;
689   }
690   odir = (dir == &route->next) ? &route->prev : &route->next;
691   send_broken (&route->next,
692                &route->cid,
693                GCP_get_id (odir->hop),
694                &my_full_id);
695   destroy_route (route);
696 }
697
698
699 /**
700  * Initialize one of the directions of a route.
701  *
702  * @param route route the direction belongs to
703  * @param dir direction to initialize
704  * @param hop next hop on in the @a dir
705  */
706 static void
707 dir_init (struct RouteDirection *dir,
708           struct CadetRoute *route,
709           struct CadetPeer *hop)
710 {
711   dir->hop = hop;
712   dir->my_route = route;
713   dir->mqm = GCP_request_mq (hop,
714                              &dir_ready_cb,
715                              dir);
716   GNUNET_CONTAINER_DLL_insert (rung_head->rd_head,
717                                rung_head->rd_tail,
718                                dir);
719   dir->rung = rung_head;
720   GNUNET_assert (GNUNET_YES == dir->is_ready);
721 }
722
723
724 /**
725  * We could not create the desired route.  Send a
726  * #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN
727  * message to @a target.
728  *
729  * @param target who should receive the message
730  * @param cid identifier of the connection/route that failed
731  * @param failure_at neighbour with which we failed to route,
732  *        or NULL.
733  */
734 static void
735 send_broken_without_mqm (struct CadetPeer *target,
736                          const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
737                          const struct GNUNET_PeerIdentity *failure_at)
738 {
739   struct GNUNET_MQ_Envelope *env;
740   struct GNUNET_CADET_ConnectionBrokenMessage *bm;
741
742   env = GNUNET_MQ_msg (bm,
743                        GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN);
744   bm->cid = *cid;
745   bm->peer1 = my_full_id;
746   if (NULL != failure_at)
747     bm->peer2 = *failure_at;
748   GCP_send_ooo (target,
749                 env);
750 }
751
752
753 /**
754  * Handle for #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE
755  *
756  * @param cls Closure (CadetPeer for neighbor that sent the message).
757  * @param msg Message itself.
758  */
759 static void
760 handle_connection_create (void *cls,
761                           const struct GNUNET_CADET_ConnectionCreateMessage *msg)
762 {
763   struct CadetPeer *sender = cls;
764   struct CadetPeer *next;
765   const struct GNUNET_PeerIdentity *pids = (const struct GNUNET_PeerIdentity *) &msg[1];
766   struct CadetRoute *route;
767   uint16_t size = ntohs (msg->header.size) - sizeof (*msg);
768   unsigned int path_length;
769   unsigned int off;
770   enum GNUNET_CADET_ChannelOption options;
771
772   options = (enum GNUNET_CADET_ChannelOption) ntohl (msg->options);
773   path_length = size / sizeof (struct GNUNET_PeerIdentity);
774   if (0 == path_length)
775   {
776     LOG (GNUNET_ERROR_TYPE_DEBUG,
777       "Dropping CADET_CONNECTION_CREATE with empty path\n");
778     GNUNET_break_op (0);
779     return;
780   }
781   /* Check for loops */
782   struct GNUNET_CONTAINER_MultiPeerMap *map;
783   map = GNUNET_CONTAINER_multipeermap_create (path_length * 2,
784                                               GNUNET_YES);
785   GNUNET_assert (NULL != map);
786   for (off = 0; off < path_length; off++) {
787     if (GNUNET_SYSERR ==
788         GNUNET_CONTAINER_multipeermap_put (map,
789                                            &pids[off],
790                                            NULL,
791                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) {
792       /* bogus request */
793       GNUNET_CONTAINER_multipeermap_destroy (map);
794       LOG (GNUNET_ERROR_TYPE_DEBUG,
795         "Dropping CADET_CONNECTION_CREATE with cyclic path\n");
796       GNUNET_break_op (0);
797       return;
798     }
799   }
800   GNUNET_CONTAINER_multipeermap_destroy (map);
801   /* Initiator is at offset 0. */
802   for (off=1;off<path_length;off++)
803     if (0 == memcmp (&my_full_id,
804                      &pids[off],
805                      sizeof (struct GNUNET_PeerIdentity)))
806       break;
807   if (off == path_length)
808   {
809     LOG (GNUNET_ERROR_TYPE_DEBUG,
810       "Dropping CADET_CONNECTION_CREATE without us in the path\n");
811     GNUNET_break_op (0);
812     return;
813   }
814   /* Check previous hop */
815   if (sender != GCP_get (&pids[off - 1],
816                          GNUNET_NO))
817   {
818     LOG (GNUNET_ERROR_TYPE_DEBUG,
819       "Dropping CADET_CONNECTION_CREATE without sender in the path\n");
820     GNUNET_break_op (0);
821     return;
822   }
823   if (NULL !=
824       get_route (&msg->cid))
825   {
826     /* Duplicate CREATE, pass it on, previous one might have been lost! */
827     LOG (GNUNET_ERROR_TYPE_DEBUG,
828          "Passing on duplicate CADET_CONNECTION_CREATE message on connection %s\n",
829          GNUNET_sh2s (&msg->cid.connection_of_tunnel));
830     route_message (sender,
831                    &msg->cid,
832                    &msg->header);
833     return;
834   }
835   if (off == path_length - 1)
836   {
837     /* We are the destination, create connection */
838     struct CadetConnection *cc;
839     struct CadetPeerPath *path;
840     struct CadetPeer *origin;
841
842     cc = GCC_lookup (&msg->cid);
843     if (NULL != cc)
844     {
845       LOG (GNUNET_ERROR_TYPE_DEBUG,
846            "Received duplicate CADET_CONNECTION_CREATE message on connection %s\n",
847            GNUNET_sh2s (&msg->cid.connection_of_tunnel));
848       GCC_handle_duplicate_create (cc);
849       return;
850     }
851
852     origin = GCP_get (&pids[0],
853                       GNUNET_YES);
854     LOG (GNUNET_ERROR_TYPE_DEBUG,
855          "Received CADET_CONNECTION_CREATE message from %s for connection %s, building inverse path\n",
856          GCP_2s (origin),
857          GNUNET_sh2s (&msg->cid.connection_of_tunnel));
858     path = GCPP_get_path_from_route (path_length - 1,
859                                      pids);
860     if (GNUNET_OK !=
861         GCT_add_inbound_connection (GCP_get_tunnel (origin,
862                                                     GNUNET_YES),
863                                     &msg->cid,
864                                     (enum GNUNET_CADET_ChannelOption) ntohl (msg->options),
865                                     path))
866     {
867       /* Send back BROKEN: duplicate connection on the same path,
868          we will use the other one. */
869       LOG (GNUNET_ERROR_TYPE_DEBUG,
870            "Received CADET_CONNECTION_CREATE from %s for %s, but %s already has a connection. Sending BROKEN\n",
871            GCP_2s (sender),
872            GNUNET_sh2s (&msg->cid.connection_of_tunnel),
873            GCPP_2s (path));
874       send_broken_without_mqm (sender,
875                                &msg->cid,
876                                NULL);
877       return;
878     }
879     return;
880   }
881   /* We are merely a hop on the way, check if we can support the route */
882   next = GCP_get (&pids[off + 1],
883                   GNUNET_NO);
884   if ( (NULL == next) ||
885        (GNUNET_NO == GCP_has_core_connection (next)) )
886   {
887     /* unworkable, send back BROKEN notification */
888     LOG (GNUNET_ERROR_TYPE_DEBUG,
889          "Received CADET_CONNECTION_CREATE from %s for %s. Next hop %s:%u is down. Sending BROKEN\n",
890          GCP_2s (sender),
891          GNUNET_sh2s (&msg->cid.connection_of_tunnel),
892          GNUNET_i2s (&pids[off + 1]),
893          off + 1);
894     send_broken_without_mqm (sender,
895                              &msg->cid,
896                              &pids[off + 1]);
897     return;
898   }
899   if (max_routes <= GNUNET_CONTAINER_multishortmap_size (routes))
900   {
901     LOG (GNUNET_ERROR_TYPE_DEBUG,
902          "Received CADET_CONNECTION_CREATE from %s for %s. We have reached our route limit. Sending BROKEN\n",
903          GCP_2s (sender),
904          GNUNET_sh2s (&msg->cid.connection_of_tunnel));
905     send_broken_without_mqm (sender,
906                              &msg->cid,
907                              &pids[off - 1]);
908     return;
909   }
910
911   /* Workable route, create routing entry */
912   LOG (GNUNET_ERROR_TYPE_DEBUG,
913        "Received CADET_CONNECTION_CREATE from %s for %s. Next hop %s:%u is up. Creating route\n",
914        GCP_2s (sender),
915        GNUNET_sh2s (&msg->cid.connection_of_tunnel),
916        GNUNET_i2s (&pids[off + 1]),
917        off + 1);
918   route = GNUNET_new (struct CadetRoute);
919   route->options = options;
920   route->cid = msg->cid;
921   route->last_use = GNUNET_TIME_absolute_get ();
922   dir_init (&route->prev,
923             route,
924             sender);
925   dir_init (&route->next,
926             route,
927             next);
928   GNUNET_assert (GNUNET_OK ==
929                  GNUNET_CONTAINER_multishortmap_put (routes,
930                                                      &route->cid.connection_of_tunnel,
931                                                      route,
932                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
933   GNUNET_STATISTICS_set (stats,
934                          "# routes",
935                          GNUNET_CONTAINER_multishortmap_size (routes),
936                          GNUNET_NO);
937   route->hn = GNUNET_CONTAINER_heap_insert (route_heap,
938                                             route,
939                                             route->last_use.abs_value_us);
940   if (NULL == timeout_task)
941     timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (keepalive_period,
942                                                                                 3),
943                                                  &timeout_cb,
944                                                  NULL);
945 }
946
947
948 /**
949  * Handle for #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE_ACK
950  *
951  * @param cls Closure (CadetPeer for neighbor that sent the message).
952  * @param msg Message itself.
953  */
954 static void
955 handle_connection_create_ack (void *cls,
956                               const struct GNUNET_CADET_ConnectionCreateAckMessage *msg)
957 {
958   struct CadetPeer *peer = cls;
959   struct CadetConnection *cc;
960
961   /* First, check if ACK belongs to a connection that ends here. */
962   cc = GCC_lookup (&msg->cid);
963   if (NULL != cc)
964   {
965     /* verify ACK came from the right direction */
966     struct CadetPeerPath *path = GCC_get_path (cc);
967
968     if (peer !=
969         GCPP_get_peer_at_offset (path,
970                                  0))
971     {
972       /* received ACK from unexpected direction, ignore! */
973       GNUNET_break_op (0);
974       return;
975     }
976     LOG (GNUNET_ERROR_TYPE_DEBUG,
977          "Received CONNECTION_CREATE_ACK for connection %s.\n",
978          GNUNET_sh2s (&msg->cid.connection_of_tunnel));
979     GCC_handle_connection_create_ack (cc);
980     return;
981   }
982
983   /* We're just an intermediary peer, route the message along its path */
984   route_message (peer,
985                  &msg->cid,
986                  &msg->header);
987 }
988
989
990 /**
991  * Handle for #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN
992  *
993  * @param cls Closure (CadetPeer for neighbor that sent the message).
994  * @param msg Message itself.
995  * @deprecated duplicate logic with #handle_destroy(); dedup!
996  */
997 static void
998 handle_connection_broken (void *cls,
999                           const struct GNUNET_CADET_ConnectionBrokenMessage *msg)
1000 {
1001   struct CadetPeer *peer = cls;
1002   struct CadetConnection *cc;
1003   struct CadetRoute *route;
1004
1005   /* First, check if message belongs to a connection that ends here. */
1006   cc = GCC_lookup (&msg->cid);
1007   if (NULL != cc)
1008   {
1009     /* verify message came from the right direction */
1010     struct CadetPeerPath *path = GCC_get_path (cc);
1011
1012     if (peer !=
1013         GCPP_get_peer_at_offset (path,
1014                                  0))
1015     {
1016       /* received message from unexpected direction, ignore! */
1017       GNUNET_break_op (0);
1018       return;
1019     }
1020     LOG (GNUNET_ERROR_TYPE_DEBUG,
1021          "Received CONNECTION_BROKEN for connection %s. Destroying it.\n",
1022          GNUNET_sh2s (&msg->cid.connection_of_tunnel));
1023     GCC_destroy_without_core (cc);
1024
1025     /* FIXME: also destroy the path up to the specified link! */
1026     return;
1027   }
1028
1029   /* We're just an intermediary peer, route the message along its path */
1030   route_message (peer,
1031                  &msg->cid,
1032                  &msg->header);
1033   route = get_route (&msg->cid);
1034   if (NULL != route)
1035     destroy_route (route);
1036   /* FIXME: also destroy paths we MAY have up to the specified link! */
1037 }
1038
1039
1040 /**
1041  * Handle for #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY
1042  *
1043  * @param cls Closure (CadetPeer for neighbor that sent the message).
1044  * @param msg Message itself.
1045  */
1046 static void
1047 handle_connection_destroy (void *cls,
1048                            const struct GNUNET_CADET_ConnectionDestroyMessage *msg)
1049 {
1050   struct CadetPeer *peer = cls;
1051   struct CadetConnection *cc;
1052   struct CadetRoute *route;
1053
1054   /* First, check if message belongs to a connection that ends here. */
1055   cc = GCC_lookup (&msg->cid);
1056   if (NULL != cc)
1057   {
1058     /* verify message came from the right direction */
1059     struct CadetPeerPath *path = GCC_get_path (cc);
1060
1061     if (peer !=
1062         GCPP_get_peer_at_offset (path,
1063                                  0))
1064     {
1065       /* received message from unexpected direction, ignore! */
1066       GNUNET_break_op (0);
1067       return;
1068     }
1069     LOG (GNUNET_ERROR_TYPE_DEBUG,
1070          "Received CONNECTION_DESTROY for connection %s. Destroying connection.\n",
1071          GNUNET_sh2s (&msg->cid.connection_of_tunnel));
1072
1073     GCC_destroy_without_core (cc);
1074     return;
1075   }
1076
1077   /* We're just an intermediary peer, route the message along its path */
1078   LOG (GNUNET_ERROR_TYPE_DEBUG,
1079        "Received CONNECTION_DESTROY for connection %s. Destroying route.\n",
1080        GNUNET_sh2s (&msg->cid.connection_of_tunnel));
1081   route_message (peer,
1082                  &msg->cid,
1083                  &msg->header);
1084   route = get_route (&msg->cid);
1085   if (NULL != route)
1086     destroy_route (route);
1087 }
1088
1089
1090 /**
1091  * Handle for #GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX
1092  *
1093  * @param cls Closure (CadetPeer for neighbor that sent the message).
1094  * @param msg Message itself.
1095  */
1096 static void
1097 handle_tunnel_kx (void *cls,
1098                   const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1099 {
1100   struct CadetPeer *peer = cls;
1101   struct CadetConnection *cc;
1102
1103   /* First, check if message belongs to a connection that ends here. */
1104   cc = GCC_lookup (&msg->cid);
1105   if (NULL != cc)
1106   {
1107     /* verify message came from the right direction */
1108     struct CadetPeerPath *path = GCC_get_path (cc);
1109
1110     if (peer !=
1111         GCPP_get_peer_at_offset (path,
1112                                  0))
1113     {
1114       /* received message from unexpected direction, ignore! */
1115       GNUNET_break_op (0);
1116       return;
1117     }
1118     GCC_handle_kx (cc,
1119                    msg);
1120     return;
1121   }
1122
1123   /* We're just an intermediary peer, route the message along its path */
1124   route_message (peer,
1125                  &msg->cid,
1126                  &msg->header);
1127 }
1128
1129
1130 /**
1131  * Handle for #GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH
1132  *
1133  * @param cls Closure (CadetPeer for neighbor that sent the message).
1134  * @param msg Message itself.
1135  */
1136 static void
1137 handle_tunnel_kx_auth (void *cls,
1138                        const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1139 {
1140   struct CadetPeer *peer = cls;
1141   struct CadetConnection *cc;
1142
1143   /* First, check if message belongs to a connection that ends here. */
1144   cc = GCC_lookup (&msg->kx.cid);
1145   if (NULL != cc)
1146   {
1147     /* verify message came from the right direction */
1148     struct CadetPeerPath *path = GCC_get_path (cc);
1149
1150     if (peer !=
1151         GCPP_get_peer_at_offset (path,
1152                                  0))
1153     {
1154       /* received message from unexpected direction, ignore! */
1155       GNUNET_break_op (0);
1156       return;
1157     }
1158     GCC_handle_kx_auth (cc,
1159                         msg);
1160     return;
1161   }
1162
1163   /* We're just an intermediary peer, route the message along its path */
1164   route_message (peer,
1165                  &msg->kx.cid,
1166                  &msg->kx.header);
1167 }
1168
1169
1170 /**
1171  * Check if the encrypted message has the appropriate size.
1172  *
1173  * @param cls Closure (unused).
1174  * @param msg Message to check.
1175  *
1176  * @return #GNUNET_YES if size is correct, #GNUNET_NO otherwise.
1177  */
1178 static int
1179 check_tunnel_encrypted (void *cls,
1180                         const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
1181 {
1182   return GNUNET_YES;
1183 }
1184
1185
1186 /**
1187  * Handle for #GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED.
1188  *
1189  * @param cls Closure (CadetPeer for neighbor that sent the message).
1190  * @param msg Message itself.
1191  */
1192 static void
1193 handle_tunnel_encrypted (void *cls,
1194                          const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
1195 {
1196   struct CadetPeer *peer = cls;
1197   struct CadetConnection *cc;
1198
1199   /* First, check if message belongs to a connection that ends here. */
1200   cc = GCC_lookup (&msg->cid);
1201   if (NULL != cc)
1202   {
1203     /* verify message came from the right direction */
1204     struct CadetPeerPath *path = GCC_get_path (cc);
1205
1206     if (peer !=
1207         GCPP_get_peer_at_offset (path,
1208                                  0))
1209     {
1210       /* received message from unexpected direction, ignore! */
1211       GNUNET_break_op (0);
1212       return;
1213     }
1214     GCC_handle_encrypted (cc,
1215                           msg);
1216     return;
1217   }
1218   /* We're just an intermediary peer, route the message along its path */
1219   route_message (peer,
1220                  &msg->cid,
1221                  &msg->header);
1222 }
1223
1224
1225 /**
1226  * Function called after #GNUNET_CORE_connect has succeeded (or failed
1227  * for good).  Note that the private key of the peer is intentionally
1228  * not exposed here; if you need it, your process should try to read
1229  * the private key file directly (which should work if you are
1230  * authorized...).  Implementations of this function must not call
1231  * #GNUNET_CORE_disconnect (other than by scheduling a new task to
1232  * do this later).
1233  *
1234  * @param cls closure
1235  * @param my_identity ID of this peer, NULL if we failed
1236  */
1237 static void
1238 core_init_cb (void *cls,
1239               const struct GNUNET_PeerIdentity *my_identity)
1240 {
1241   if (NULL == my_identity)
1242   {
1243     GNUNET_break (0);
1244     return;
1245   }
1246   GNUNET_break (0 ==
1247                 memcmp (my_identity,
1248                         &my_full_id,
1249                         sizeof (struct GNUNET_PeerIdentity)));
1250 }
1251
1252
1253 /**
1254  * Method called whenever a given peer connects.
1255  *
1256  * @param cls closure
1257  * @param peer peer identity this notification is about
1258  */
1259 static void *
1260 core_connect_cb (void *cls,
1261                  const struct GNUNET_PeerIdentity *peer,
1262                  struct GNUNET_MQ_Handle *mq)
1263 {
1264   struct CadetPeer *cp;
1265
1266   LOG (GNUNET_ERROR_TYPE_DEBUG,
1267        "CORE connection to peer %s was established.\n",
1268        GNUNET_i2s (peer));
1269   cp = GCP_get (peer,
1270                 GNUNET_YES);
1271   GCP_set_mq (cp,
1272               mq);
1273   return cp;
1274 }
1275
1276
1277 /**
1278  * Method called whenever a peer disconnects.
1279  *
1280  * @param cls closure
1281  * @param peer peer identity this notification is about
1282  */
1283 static void
1284 core_disconnect_cb (void *cls,
1285                     const struct GNUNET_PeerIdentity *peer,
1286                     void *peer_cls)
1287 {
1288   struct CadetPeer *cp = peer_cls;
1289
1290   LOG (GNUNET_ERROR_TYPE_DEBUG,
1291        "CORE connection to peer %s went down.\n",
1292        GNUNET_i2s (peer));
1293   GCP_set_mq (cp,
1294               NULL);
1295 }
1296
1297
1298 /**
1299  * Initialize the CORE subsystem.
1300  *
1301  * @param c Configuration.
1302  */
1303 void
1304 GCO_init (const struct GNUNET_CONFIGURATION_Handle *c)
1305 {
1306   struct GNUNET_MQ_MessageHandler handlers[] = {
1307     GNUNET_MQ_hd_var_size (connection_create,
1308                            GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE,
1309                            struct GNUNET_CADET_ConnectionCreateMessage,
1310                            NULL),
1311     GNUNET_MQ_hd_fixed_size (connection_create_ack,
1312                              GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE_ACK,
1313                              struct GNUNET_CADET_ConnectionCreateAckMessage,
1314                              NULL),
1315     GNUNET_MQ_hd_fixed_size (connection_broken,
1316                              GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN,
1317                              struct GNUNET_CADET_ConnectionBrokenMessage,
1318                              NULL),
1319     GNUNET_MQ_hd_fixed_size (connection_destroy,
1320                              GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY,
1321                              struct GNUNET_CADET_ConnectionDestroyMessage,
1322                              NULL),
1323     GNUNET_MQ_hd_fixed_size (tunnel_kx,
1324                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX,
1325                              struct GNUNET_CADET_TunnelKeyExchangeMessage,
1326                              NULL),
1327     GNUNET_MQ_hd_fixed_size (tunnel_kx_auth,
1328                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH,
1329                              struct GNUNET_CADET_TunnelKeyExchangeAuthMessage,
1330                              NULL),
1331     GNUNET_MQ_hd_var_size (tunnel_encrypted,
1332                            GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED,
1333                            struct GNUNET_CADET_TunnelEncryptedMessage,
1334                            NULL),
1335     GNUNET_MQ_handler_end ()
1336   };
1337
1338   if (GNUNET_OK !=
1339       GNUNET_CONFIGURATION_get_value_number (c,
1340                                              "CADET",
1341                                              "MAX_ROUTES",
1342                                              &max_routes))
1343     max_routes = 5000;
1344   if (GNUNET_OK !=
1345       GNUNET_CONFIGURATION_get_value_number (c,
1346                                              "CADET",
1347                                              "MAX_MSGS_QUEUE",
1348                                              &max_buffers))
1349     max_buffers = 10000;
1350   routes = GNUNET_CONTAINER_multishortmap_create (1024,
1351                                                   GNUNET_NO);
1352   route_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1353   core = GNUNET_CORE_connect (c,
1354                               NULL,
1355                               &core_init_cb,
1356                               &core_connect_cb,
1357                               &core_disconnect_cb,
1358                               handlers);
1359 }
1360
1361
1362 /**
1363  * Shut down the CORE subsystem.
1364  */
1365 void
1366 GCO_shutdown ()
1367 {
1368   if (NULL != core)
1369   {
1370     GNUNET_CORE_disconnect (core);
1371     core = NULL;
1372   }
1373   GNUNET_assert (0 == GNUNET_CONTAINER_multishortmap_size (routes));
1374   GNUNET_CONTAINER_multishortmap_destroy (routes);
1375   routes = NULL;
1376   GNUNET_CONTAINER_heap_destroy (route_heap);
1377   route_heap = NULL;
1378   if (NULL != timeout_task)
1379   {
1380     GNUNET_SCHEDULER_cancel (timeout_task);
1381     timeout_task = NULL;
1382   }
1383 }
1384
1385 /* end of gnunet-cadet-service_core.c */