95b53beb416b3acb7ee1497f3b4c08b899bfca31
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh_connection.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2013 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/gnunet-service-mesh_connection.c
23  * @brief GNUnet MESH service connection handling
24  * @author Bartlomiej Polot
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29
30 #include "gnunet_core_service.h"
31
32 #include "gnunet-service-mesh_connection.h"
33 #include "gnunet-service-mesh_peer.h"
34 #include "gnunet-service-mesh_local.h"
35 #include "mesh_protocol_enc.h"
36 #include "mesh_path.h"
37
38
39 #define MESH_DEBUG_CONNECTION   GNUNET_NO
40 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
41                                   GNUNET_TIME_UNIT_MINUTES,\
42                                   10)
43 #define MESH_RETRANSMIT_TIME    GNUNET_TIME_UNIT_SECONDS
44 #define MESH_RETRANSMIT_MARGIN  4
45
46
47 #if MESH_DEBUG_CONNECTION
48 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
49 #else
50 #define DEBUG_CONN(...)
51 #endif
52
53
54 /**
55  * All the states a connection can be in.
56  */
57 enum MeshConnectionState
58 {
59   /**
60    * Uninitialized status, should never appear in operation.
61    */
62   MESH_CONNECTION_NEW,
63
64   /**
65    * Connection create message sent, waiting for ACK.
66    */
67   MESH_CONNECTION_SENT,
68
69   /**
70    * Connection ACK sent, waiting for ACK.
71    */
72   MESH_CONNECTION_ACK,
73
74   /**
75    * Connection confirmed, ready to carry traffic.
76    */
77   MESH_CONNECTION_READY,
78 };
79
80
81
82 /**
83  * Struct containing info about a queued transmission to this peer
84  */
85 struct MeshPeerQueue
86 {
87     /**
88       * DLL next
89       */
90   struct MeshPeerQueue *next;
91
92     /**
93       * DLL previous
94       */
95   struct MeshPeerQueue *prev;
96
97     /**
98      * Peer this transmission is directed to.
99      */
100   struct MeshPeer *peer;
101
102     /**
103      * Connection this message belongs to.
104      */
105   struct MeshConnection *c;
106
107     /**
108      * Is FWD in c?
109      */
110   int fwd;
111
112     /**
113      * Channel this message belongs to, if known.
114      */
115   struct MeshChannel *ch;
116
117     /**
118      * Pointer to info stucture used as cls.
119      */
120   void *cls;
121
122     /**
123      * Type of message
124      */
125   uint16_t type;
126
127     /**
128      * Size of the message
129      */
130   size_t size;
131 };
132
133
134 /**
135  * Struct to encapsulate all the Flow Control information to a peer to which
136  * we are directly connected (on a core level).
137  */
138 struct MeshFlowControl
139 {
140   /**
141    * Connection this controls.
142    */
143   struct MeshConnection *c;
144
145   /**
146    * How many messages are in the queue on this connection.
147    */
148   unsigned int queue_n;
149
150   /**
151    * How many messages do we accept in the queue.
152    */
153   unsigned int queue_max;
154
155   /**
156    * Next ID to use.
157    */
158   uint32_t next_pid;
159
160   /**
161    * ID of the last packet sent towards the peer.
162    */
163   uint32_t last_pid_sent;
164
165   /**
166    * ID of the last packet received from the peer.
167    */
168   uint32_t last_pid_recv;
169
170   /**
171    * Last ACK sent to the peer (peer can't send more than this PID).
172    */
173   uint32_t last_ack_sent;
174
175   /**
176    * Last ACK sent towards the origin (for traffic towards leaf node).
177    */
178   uint32_t last_ack_recv;
179
180   /**
181    * Task to poll the peer in case of a lost ACK causes stall.
182    */
183   GNUNET_SCHEDULER_TaskIdentifier poll_task;
184
185   /**
186    * How frequently to poll for ACKs.
187    */
188   struct GNUNET_TIME_Relative poll_time;
189 };
190
191
192 /**
193  * Struct containing all information regarding a connection to a peer.
194  */
195 struct MeshConnection
196 {
197   /**
198    * DLL
199    */
200   struct MeshConnection *next;
201   struct MeshConnection *prev;
202
203   /**
204    * Tunnel this connection is part of.
205    */
206   struct MeshTunnel2 *t;
207
208   /**
209    * Flow control information for traffic fwd.
210    */
211   struct MeshFlowControl fwd_fc;
212
213   /**
214    * Flow control information for traffic bck.
215    */
216   struct MeshFlowControl bck_fc;
217
218   /**
219    * ID of the connection.
220    */
221   struct GNUNET_HashCode id;
222
223   /**
224    * State of the connection.
225    */
226   enum MeshConnectionState state;
227
228   /**
229    * Path being used for the tunnel.
230    */
231   struct MeshPeerPath *path;
232
233   /**
234    * Position of the local peer in the path.
235    */
236   unsigned int own_pos;
237
238   /**
239    * Task to keep the used paths alive at the owner,
240    * time tunnel out on all the other peers.
241    */
242   GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
243
244   /**
245    * Task to keep the used paths alive at the destination,
246    * time tunnel out on all the other peers.
247    */
248   GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
249
250   /**
251    * Pending message count.
252    */
253   int pending_messages;
254
255   /**
256    * Destroy flag: if true, destroy on last message.
257    */
258   int destroy;
259 };
260
261
262 /**
263  * Connections known, indexed by cid (MeshConnection).
264  */
265 static struct GNUNET_CONTAINER_MultiHashMap *connections;
266
267 /**
268  * How many connections are we willing to maintain.
269  * Local connections are always allowed, even if there are more connections than max.
270  */
271 static unsigned long long max_connections;
272
273 /**
274  * How many messages *in total* are we willing to queue, divide by number of
275  * connections to get connection queue size.
276  */
277 static unsigned long long max_msgs_queue;
278
279 /**
280  * How often to send path keepalives. Paths timeout after 4 missed.
281  */
282 static struct GNUNET_TIME_Relative refresh_connection_time;
283
284 /**
285  * Handle to communicate with core.
286  */
287 static struct GNUNET_CORE_Handle *core_handle;
288
289 #if 0 // avoid compiler warning for unused static function
290 static void
291 fc_debug (struct MeshFlowControl *fc)
292 {
293   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    IN: %u/%u\n",
294               fc->last_pid_recv, fc->last_ack_sent);
295   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    OUT: %u/%u\n",
296               fc->last_pid_sent, fc->last_ack_recv);
297   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    QUEUE: %u/%u\n",
298               fc->queue_n, fc->queue_max);
299 }
300
301 static void
302 connection_debug (struct MeshConnection *c)
303 {
304   if (NULL == c)
305   {
306     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CONNECTION ***\n");
307     return;
308   }
309   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
310               peer2s (c->t->peer), GNUNET_h2s (&c->id));
311   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  state: %u, pending msgs: %u\n",
312               c->state, c->pending_messages);
313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
314   fc_debug (&c->fwd_fc);
315   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
316   fc_debug (&c->bck_fc);
317 }
318 #endif
319
320 /**
321  * Get string description for tunnel state.
322  *
323  * @param s Tunnel state.
324  *
325  * @return String representation.
326  */
327 static const char *
328 GMC_DEBUG_state2s (enum MeshTunnelState s)
329 {
330   switch (s)
331   {
332     case MESH_CONNECTION_NEW:
333       return "MESH_CONNECTION_NEW";
334     case MESH_CONNECTION_SENT:
335       return "MESH_CONNECTION_SENT";
336     case MESH_CONNECTION_ACK:
337       return "MESH_CONNECTION_ACK";
338     case MESH_CONNECTION_READY:
339       return "MESH_CONNECTION_READY";
340     default:
341       return "MESH_CONNECTION_STATE_ERROR";
342   }
343 }
344
345
346
347 /**
348  * Initialize a Flow Control structure to the initial state.
349  *
350  * @param fc Flow Control structure to initialize.
351  */
352 static void
353 fc_init (struct MeshFlowControl *fc)
354 {
355   fc->next_pid = 0;
356   fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
357   fc->last_pid_recv = (uint32_t) -1;
358   fc->last_ack_sent = (uint32_t) 0;
359   fc->last_ack_recv = (uint32_t) 0;
360   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
361   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
362   fc->queue_n = 0;
363   fc->queue_max = (max_msgs_queue / max_connections) + 1;
364 }
365
366
367 /**
368  * Find a connection.
369  *
370  * @param cid Connection ID.
371  */
372 static struct MeshConnection *
373 connection_get (const struct GNUNET_HashCode *cid)
374 {
375   return GNUNET_CONTAINER_multihashmap_get (connections, cid);
376 }
377
378
379 /**
380  * Sends an already built message on a connection, properly registering
381  * all used resources.
382  *
383  * @param message Message to send. Function makes a copy of it.
384  *                If message is not hop-by-hop, decrements TTL of copy.
385  * @param c Connection on which this message is transmitted.
386  * @param ch Channel on which this message is transmitted, or NULL.
387  * @param fwd Is this a fwd message?
388  */
389 static void
390 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
391                                   struct MeshConnection *c,
392                                   struct MeshChannel *ch,
393                                   int fwd)
394 {
395   void *data;
396   size_t size;
397   uint16_t type;
398
399   size = ntohs (message->size);
400   data = GNUNET_malloc (size);
401   memcpy (data, message, size);
402   type = ntohs (message->type);
403   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send %s (%u) on connection %s\n",
404               GNUNET_MESH_DEBUG_M2S (type), size, GNUNET_h2s (&c->id));
405
406   switch (type)
407   {
408     struct GNUNET_MESH_Encrypted *emsg;
409     struct GNUNET_MESH_ACK       *amsg;
410     struct GNUNET_MESH_Poll      *pmsg;
411     struct GNUNET_MESH_ConnectionDestroy *dmsg;
412     struct GNUNET_MESH_ConnectionBroken  *bmsg;
413     uint32_t ttl;
414
415     case GNUNET_MESSAGE_TYPE_MESH_FWD:
416     case GNUNET_MESSAGE_TYPE_MESH_BCK:
417       emsg = (struct GNUNET_MESH_Encrypted *) data;
418       ttl = ntohl (emsg->ttl);
419       if (0 == ttl)
420       {
421         GNUNET_break_op (0);
422         return;
423       }
424       emsg->cid = c->id;
425       emsg->ttl = htonl (ttl - 1);
426       emsg->pid = htonl (fwd ? c->fwd_fc.next_pid++ : c->bck_fc.next_pid++);
427       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " pid %u\n", ntohl (emsg->pid));
428       break;
429
430     case GNUNET_MESSAGE_TYPE_MESH_ACK:
431       amsg = (struct GNUNET_MESH_ACK *) data;
432       amsg->cid = c->id;
433       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
434       break;
435
436     case GNUNET_MESSAGE_TYPE_MESH_POLL:
437       pmsg = (struct GNUNET_MESH_Poll *) data;
438       pmsg->cid = c->id;
439       pmsg->pid = htonl (fwd ? c->fwd_fc.last_pid_sent : c->bck_fc.last_pid_sent);
440       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
441       break;
442
443     case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
444       dmsg = (struct GNUNET_MESH_ConnectionDestroy *) data;
445       dmsg->cid = c->id;
446       dmsg->reserved = 0;
447       break;
448
449     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
450       bmsg = (struct GNUNET_MESH_ConnectionBroken *) data;
451       bmsg->cid = c->id;
452       bmsg->reserved = 0;
453       break;
454
455     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
456     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
457       break;
458
459     default:
460       GNUNET_break (0);
461   }
462
463   queue_add (data,
464              type,
465              size,
466              c,
467              ch,
468              fwd);
469 }
470
471 /**
472  * Send an ACK informing the predecessor about the available buffer space.
473  *
474  * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
475  * the ACK itself goes "back" (dest->root).
476  *
477  * @param c Connection on which to send the ACK.
478  * @param buffer How much space free to advertise?
479  * @param fwd Is this FWD ACK? (Going dest->owner)
480  */
481 static void
482 connection_send_ack (struct MeshConnection *c, unsigned int buffer, int fwd)
483 {
484   struct MeshFlowControl *next_fc;
485   struct MeshFlowControl *prev_fc;
486   struct GNUNET_MESH_ACK msg;
487   uint32_t ack;
488   int delta;
489
490   next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
491   prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
492
493   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
494               "connection send %s ack on %s\n",
495               fwd ? "FWD" : "BCK", GNUNET_h2s (&c->id));
496
497   /* Check if we need to transmit the ACK */
498   if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
499   {
500     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
501     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
502                 "  last pid recv: %u, last ack sent: %u\n",
503                 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
504     return;
505   }
506
507   /* Ok, ACK might be necessary, what PID to ACK? */
508   delta = next_fc->queue_max - next_fc->queue_n;
509   ack = prev_fc->last_pid_recv + delta;
510   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
511   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
512               " last pid %u, last ack %u, qmax %u, q %u\n",
513               prev_fc->last_pid_recv, prev_fc->last_ack_sent,
514               next_fc->queue_max, next_fc->queue_n);
515   if (ack == prev_fc->last_ack_sent)
516   {
517     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
518     return;
519   }
520
521   prev_fc->last_ack_sent = ack;
522
523   /* Build ACK message and send on connection */
524   msg.header.size = htons (sizeof (msg));
525   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
526   msg.ack = htonl (ack);
527   msg.cid = c->id;
528
529   send_prebuilt_message_connection (&msg.header, c, NULL, !fwd);
530 }
531
532
533 /**
534  * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
535  * directed to us.
536  *
537  * @param connection Connection to confirm.
538  * @param fwd Is this a fwd ACK? (First is bck (SYNACK), second is fwd (ACK))
539  */
540 static void
541 send_connection_ack (struct MeshConnection *connection, int fwd)
542 {
543   struct MeshTunnel2 *t;
544
545   t = connection->t;
546   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
547   queue_add (NULL,
548              GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
549              sizeof (struct GNUNET_MESH_ConnectionACK),
550              connection,
551              NULL,
552              fwd);
553   if (MESH_TUNNEL_NEW == t->state)
554     tunnel_change_state (t, MESH_TUNNEL_WAITING);
555   if (MESH_CONNECTION_READY != connection->state)
556     connection_change_state (connection, MESH_CONNECTION_SENT);
557 }
558
559
560 /**
561  * Sends a CREATE CONNECTION message for a path to a peer.
562  * Changes the connection and tunnel states if necessary.
563  *
564  * @param connection Connection to create.
565  */
566 static void
567 send_connection_create (struct MeshConnection *connection)
568 {
569   struct MeshTunnel2 *t;
570
571   t = connection->t;
572   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
573   queue_add (NULL,
574              GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
575              sizeof (struct GNUNET_MESH_ConnectionCreate) +
576                 (connection->path->length *
577                  sizeof (struct GNUNET_PeerIdentity)),
578              connection,
579              NULL,
580              GNUNET_YES);
581   if (NULL != t &&
582       (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state))
583     tunnel_change_state (t, MESH_TUNNEL_WAITING);
584   if (MESH_CONNECTION_NEW == connection->state)
585     connection_change_state (connection, MESH_CONNECTION_SENT);
586 }
587
588
589 static void
590 connection_change_state (struct MeshConnection* c,
591                          enum MeshConnectionState state)
592 {
593   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
594               "Connection %s state was %s\n",
595               GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (c->state));
596   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
597               "Connection %s state is now %s\n",
598               GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (state));
599   c->state = state;
600 }
601
602
603
604 /**
605  * Send keepalive packets for a connection.
606  *
607  * @param c Connection to keep alive..
608  * @param fwd Is this a FWD keepalive? (owner -> dest).
609  */
610 static void
611 connection_keepalive (struct MeshConnection *c, int fwd)
612 {
613   struct GNUNET_MESH_ConnectionKeepAlive *msg;
614   size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
615   char cbuf[size];
616   uint16_t type;
617
618   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
619                GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
620
621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
622               "sending %s keepalive for connection %s[%d]\n",
623               fwd ? "FWD" : "BCK",
624               peer2s (c->t->peer),
625               c->id);
626
627   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
628   msg->header.size = htons (size);
629   msg->header.type = htons (type);
630   msg->cid = c->id;
631
632   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
633 }
634
635
636 /**
637  * Send CONNECTION_{CREATE/ACK} packets for a connection.
638  *
639  * @param c Connection for which to send the message.
640  * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
641  */
642 static void
643 connection_recreate (struct MeshConnection *c, int fwd)
644 {
645   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
646   if (fwd)
647     send_connection_create (c);
648   else
649     send_connection_ack (c, GNUNET_NO);
650 }
651
652
653 /**
654  * Generic connection timer management.
655  * Depending on the role of the peer in the connection will send the
656  * appropriate message (build or keepalive)
657  *
658  * @param c Conncetion to maintain.
659  * @param fwd Is FWD?
660  */
661 static void
662 connection_maintain (struct MeshConnection *c, int fwd)
663 {
664   if (MESH_TUNNEL_SEARCHING == c->t->state)
665   {
666     /* TODO DHT GET with RO_BART */
667     return;
668   }
669   switch (c->state)
670   {
671     case MESH_CONNECTION_NEW:
672       GNUNET_break (0);
673     case MESH_CONNECTION_SENT:
674       connection_recreate (c, fwd);
675       break;
676     case MESH_CONNECTION_READY:
677       connection_keepalive (c, fwd);
678       break;
679     default:
680       break;
681   }
682 }
683
684
685 static void
686 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
687 {
688   struct MeshConnection *c = cls;
689
690   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
691   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
692     return;
693
694   connection_maintain (c, GNUNET_YES);
695   c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
696                                                           &connection_fwd_keepalive,
697                                                           c);
698 }
699
700
701 static void
702 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
703 {
704   struct MeshConnection *c = cls;
705
706   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
707   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
708     return;
709
710   connection_maintain (c, GNUNET_NO);
711   c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
712                                                           &connection_bck_keepalive,
713                                                           c);
714 }
715
716
717 /**
718  * Send a message to all peers in this connection that the connection
719  * is no longer valid.
720  *
721  * If some peer should not receive the message, it should be zero'ed out
722  * before calling this function.
723  *
724  * @param c The connection whose peers to notify.
725  */
726 static void
727 connection_send_destroy (struct MeshConnection *c)
728 {
729   struct GNUNET_MESH_ConnectionDestroy msg;
730
731   msg.header.size = htons (sizeof (msg));
732   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
733   msg.cid = c->id;
734   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
735               "  sending connection destroy for connection %s[%X]\n",
736               peer2s (c->t->peer),
737               c->id);
738
739   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_YES))
740     send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
741   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_NO))
742     send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
743   c->destroy = GNUNET_YES;
744 }
745
746
747 /**
748  * Get free buffer space in a connection.
749  *
750  * @param c Connection.
751  * @param fwd Is query about FWD traffic?
752  *
753  * @return Free buffer space [0 - max_msgs_queue/max_connections]
754  */
755 static unsigned int
756 connection_get_buffer (struct MeshConnection *c, int fwd)
757 {
758   struct MeshFlowControl *fc;
759
760   fc = fwd ? &c->fwd_fc : &c->bck_fc;
761
762   return (fc->queue_max - fc->queue_n);
763 }
764
765
766 /**
767  * Get the first transmittable message for a connection.
768  *
769  * @param c Connection.
770  * @param fwd Is this FWD?
771  *
772  * @return First transmittable message.
773  */
774 static struct MeshPeerQueue *
775 connection_get_first_message (struct MeshConnection *c, int fwd)
776 {
777   struct MeshPeerQueue *q;
778   struct MeshPeer *p;
779
780   p = connection_get_hop (c, fwd);
781
782   for (q = p->queue_head; NULL != q; q = q->next)
783   {
784     if (q->c != c)
785       continue;
786     if (queue_is_sendable (q))
787       return q;
788   }
789
790   return NULL;
791 }
792
793
794 /**
795  * @brief Re-initiate traffic on this connection if necessary.
796  *
797  * Check if there is traffic queued towards this peer
798  * and the core transmit handle is NULL (traffic was stalled).
799  * If so, call core tmt rdy.
800  *
801  * @param c Connection on which initiate traffic.
802  * @param fwd Is this about fwd traffic?
803  */
804 static void
805 connection_unlock_queue (struct MeshConnection *c, int fwd)
806 {
807   struct MeshPeer *peer;
808   struct MeshPeerQueue *q;
809   size_t size;
810
811   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
812               "connection_unlock_queue %s on %s\n",
813               fwd ? "FWD" : "BCK", GNUNET_h2s (&c->id));
814
815   if (GMC_is_terminal (c, fwd))
816   {
817     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " is terminal!\n");
818     return;
819   }
820
821   peer = connection_get_hop (c, fwd);
822
823   if (NULL != peer->core_transmit)
824   {
825     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  already unlocked!\n");
826     return; /* Already unlocked */
827   }
828
829   q = connection_get_first_message (c, fwd);
830   if (NULL == q)
831   {
832     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  queue empty!\n");
833     return; /* Nothing to transmit */
834   }
835
836   size = q->size;
837   peer->core_transmit =
838       GNUNET_CORE_notify_transmit_ready (core_handle,
839                                          GNUNET_NO,
840                                          0,
841                                          GNUNET_TIME_UNIT_FOREVER_REL,
842                                          GNUNET_PEER_resolve2 (peer->id),
843                                          size,
844                                          &queue_send,
845                                          peer);
846 }
847
848
849 /**
850  * Cancel all transmissions that belong to a certain connection.
851  *
852  * @param c Connection which to cancel.
853  * @param fwd Cancel fwd traffic?
854  */
855 static void
856 connection_cancel_queues (struct MeshConnection *c, int fwd)
857 {
858   struct MeshPeerQueue *q;
859   struct MeshPeerQueue *next;
860   struct MeshFlowControl *fc;
861   struct MeshPeer *peer;
862
863   if (NULL == c)
864   {
865     GNUNET_break (0);
866     return;
867   }
868   fc = fwd ? &c->fwd_fc : &c->bck_fc;
869   peer = connection_get_hop (c, fwd);
870
871   for (q = peer->queue_head; NULL != q; q = next)
872   {
873     next = q->next;
874     if (q->c == c)
875     {
876       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
877                   "connection_cancel_queue %s\n",
878                   GNUNET_MESH_DEBUG_M2S (q->type));
879       queue_destroy (q, GNUNET_YES);
880     }
881   }
882   if (NULL == peer->queue_head)
883   {
884     if (NULL != peer->core_transmit)
885     {
886       GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
887       peer->core_transmit = NULL;
888     }
889     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
890     {
891       GNUNET_SCHEDULER_cancel (fc->poll_task);
892       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
893     }
894   }
895 }
896
897
898
899
900 /**
901  * Function called if a connection has been stalled for a while,
902  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
903  *
904  * @param cls Closure (poll ctx).
905  * @param tc TaskContext.
906  */
907 static void
908 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
909 {
910   struct MeshFlowControl *fc = cls;
911   struct GNUNET_MESH_Poll msg;
912   struct MeshConnection *c;
913
914   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
915   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
916   {
917     return;
918   }
919
920   c = fc->c;
921   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
922   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection [%X]\n",
923               GNUNET_h2s (&c->id));
924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ***   %s\n",
925               fc == &c->fwd_fc ? "FWD" : "BCK");
926
927   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
928   msg.header.size = htons (sizeof (msg));
929   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
930   send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
931   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
932   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
933                                                 &connection_poll, fc);
934 }
935
936
937
938
939 /**
940  * Get the previous hop in a connection
941  *
942  * @param c Connection.
943  *
944  * @return Previous peer in the connection.
945  */
946 static struct MeshPeer *
947 connection_get_prev_hop (struct MeshConnection *c)
948 {
949   GNUNET_PEER_Id id;
950
951   if (0 == c->own_pos || c->path->length < 2)
952     id = c->path->peers[0];
953   else
954     id = c->path->peers[c->own_pos - 1];
955
956   return peer_get_short (id);
957 }
958
959
960 /**
961  * Get the next hop in a connection
962  *
963  * @param c Connection.
964  *
965  * @return Next peer in the connection.
966  */
967 static struct MeshPeer *
968 connection_get_next_hop (struct MeshConnection *c)
969 {
970   GNUNET_PEER_Id id;
971
972   if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
973     id = c->path->peers[c->path->length - 1];
974   else
975     id = c->path->peers[c->own_pos + 1];
976
977   return peer_get_short (id);
978 }
979
980
981 /**
982  * Get the hop in a connection.
983  *
984  * @param c Connection.
985  * @param fwd Next hop?
986  *
987  * @return Next peer in the connection.
988  */
989 static struct MeshPeer *
990 connection_get_hop (struct MeshConnection *c, int fwd)
991 {
992   if (fwd)
993     return connection_get_next_hop (c);
994   return connection_get_prev_hop (c);
995 }
996
997
998
999
1000 /**
1001  * Timeout function due to lack of keepalive/traffic from the owner.
1002  * Destroys connection if called.
1003  *
1004  * @param cls Closure (connection to destroy).
1005  * @param tc TaskContext.
1006  */
1007 static void
1008 connection_fwd_timeout (void *cls,
1009                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1010 {
1011   struct MeshConnection *c = cls;
1012
1013   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
1014   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1015     return;
1016   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1017               "Connection %s[%X] FWD timed out. Destroying.\n",
1018               peer2s (c->t->peer),
1019               c->id);
1020
1021   if (GMC_is_origin (c, GNUNET_YES)) /* If local, leave. */
1022     return;
1023
1024   GMC_destroy (c);
1025 }
1026
1027
1028 /**
1029  * Timeout function due to lack of keepalive/traffic from the destination.
1030  * Destroys connection if called.
1031  *
1032  * @param cls Closure (connection to destroy).
1033  * @param tc TaskContext
1034  */
1035 static void
1036 connection_bck_timeout (void *cls,
1037                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1038 {
1039   struct MeshConnection *c = cls;
1040
1041   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
1042   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1043     return;
1044
1045   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1046               "Connection %s[%X] FWD timed out. Destroying.\n",
1047               peer2s (c->t->peer),
1048               c->id);
1049
1050   if (GMC_is_origin (c, GNUNET_NO)) /* If local, leave. */
1051     return;
1052
1053   GMC_destroy (c);
1054 }
1055
1056
1057 /**
1058  * Resets the connection timeout task, some other message has done the
1059  * task's job.
1060  * - For the first peer on the direction this means to send
1061  *   a keepalive or a path confirmation message (either create or ACK).
1062  * - For all other peers, this means to destroy the connection,
1063  *   due to lack of activity.
1064  * Starts the tiemout if no timeout was running (connection just created).
1065  *
1066  * @param c Connection whose timeout to reset.
1067  * @param fwd Is this forward?
1068  *
1069  * TODO use heap to improve efficiency of scheduler.
1070  */
1071 static void
1072 connection_reset_timeout (struct MeshConnection *c, int fwd)
1073 {
1074   GNUNET_SCHEDULER_TaskIdentifier *ti;
1075   GNUNET_SCHEDULER_Task f;
1076
1077   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
1078
1079   if (GNUNET_SCHEDULER_NO_TASK != *ti)
1080     GNUNET_SCHEDULER_cancel (*ti);
1081
1082   if (GMC_is_origin (c, fwd)) /* Endpoint */
1083   {
1084     f  = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
1085     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
1086   }
1087   else /* Relay */
1088   {
1089     struct GNUNET_TIME_Relative delay;
1090
1091     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
1092     f  = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
1093     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
1094   }
1095 }
1096
1097
1098
1099
1100
1101 /**
1102  * Method called whenever a given peer connects.
1103  *
1104  * @param cls closure
1105  * @param peer peer identity this notification is about
1106  */
1107 static void
1108 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
1109 {
1110   struct MeshPeer *pi;
1111   struct MeshPeerPath *path;
1112
1113   DEBUG_CONN ("Peer connected\n");
1114   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
1115   pi = peer_get (peer);
1116   if (myid == pi->id)
1117   {
1118     DEBUG_CONN ("     (self)\n");
1119     path = path_new (1);
1120   }
1121   else
1122   {
1123     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
1124     path = path_new (2);
1125     path->peers[1] = pi->id;
1126     GNUNET_PEER_change_rc (pi->id, 1);
1127     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
1128   }
1129   path->peers[0] = myid;
1130   GNUNET_PEER_change_rc (myid, 1);
1131   peer_add_path (pi, path, GNUNET_YES);
1132
1133   pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
1134   return;
1135 }
1136
1137
1138 /**
1139  * Method called whenever a peer disconnects.
1140  *
1141  * @param cls closure
1142  * @param peer peer identity this notification is about
1143  */
1144 static void
1145 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1146 {
1147   struct MeshPeer *pi;
1148
1149   DEBUG_CONN ("Peer disconnected\n");
1150   pi = GNUNET_CONTAINER_multipeermap_get (peers, peer);
1151   if (NULL == pi)
1152   {
1153     GNUNET_break (0);
1154     return;
1155   }
1156
1157   GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
1158                                          GMC_notify_broken,
1159                                          pi);
1160   GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
1161   pi->connections = NULL;
1162   if (NULL != pi->core_transmit)
1163     {
1164       GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit);
1165       pi->core_transmit = NULL;
1166     }
1167   if (myid == pi->id)
1168   {
1169     DEBUG_CONN ("     (self)\n");
1170   }
1171   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
1172
1173   return;
1174 }
1175
1176
1177
1178 /**
1179  * To be called on core init/fail.
1180  *
1181  * @param cls Closure (config)
1182  * @param identity the public identity of this peer
1183  */
1184 static void
1185 core_init (void *cls,
1186            const struct GNUNET_PeerIdentity *identity)
1187 {
1188   const struct GNUNET_CONFIGURATION_Handle *c = cls;
1189   static int i = 0;
1190
1191   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
1192   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
1193   {
1194     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
1195     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1196                 " core id %s\n",
1197                 GNUNET_i2s (identity));
1198     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1199                 " my id %s\n",
1200                 GNUNET_i2s (&my_full_id));
1201     GNUNET_CORE_disconnect (core_handle);
1202     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
1203                                        NULL,      /* Closure passed to MESH functions */
1204                                        &core_init,        /* Call core_init once connected */
1205                                        &core_connect,     /* Handle connects */
1206                                        &core_disconnect,  /* remove peers on disconnects */
1207                                        NULL,      /* Don't notify about all incoming messages */
1208                                        GNUNET_NO, /* For header only in notification */
1209                                        NULL,      /* Don't notify about all outbound messages */
1210                                        GNUNET_NO, /* For header-only out notification */
1211                                        core_handlers);    /* Register these handlers */
1212     if (10 < i++)
1213       GNUNET_abort();
1214   }
1215   GML_start ();
1216   return;
1217 }
1218
1219
1220
1221
1222
1223 /**
1224  * Core handler for connection creation.
1225  *
1226  * @param cls Closure (unused).
1227  * @param peer Sender (neighbor).
1228  * @param message Message.
1229  *
1230  * @return GNUNET_OK to keep the connection open,
1231  *         GNUNET_SYSERR to close it (signal serious error)
1232  */
1233 static int
1234 handle_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1235                const struct GNUNET_MessageHeader *message)
1236 {
1237   struct GNUNET_MESH_ConnectionCreate *msg;
1238   struct GNUNET_PeerIdentity *id;
1239   struct GNUNET_HashCode *cid;
1240   struct MeshPeerPath *path;
1241   struct MeshPeer *dest_peer;
1242   struct MeshPeer *orig_peer;
1243   struct MeshConnection *c;
1244   unsigned int own_pos;
1245   uint16_t size;
1246   uint16_t i;
1247
1248   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
1250
1251   /* Check size */
1252   size = ntohs (message->size);
1253   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
1254   {
1255     GNUNET_break_op (0);
1256     return GNUNET_OK;
1257   }
1258
1259   /* Calculate hops */
1260   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
1261   if (size % sizeof (struct GNUNET_PeerIdentity))
1262   {
1263     GNUNET_break_op (0);
1264     return GNUNET_OK;
1265   }
1266   size /= sizeof (struct GNUNET_PeerIdentity);
1267   if (1 > size)
1268   {
1269     GNUNET_break_op (0);
1270     return GNUNET_OK;
1271   }
1272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
1273
1274   /* Get parameters */
1275   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
1276   cid = &msg->cid;
1277   id = (struct GNUNET_PeerIdentity *) &msg[1];
1278   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1279               "    connection %s (%s).\n",
1280               GNUNET_h2s (cid), GNUNET_i2s (id));
1281
1282   /* Create connection */
1283   c = connection_get (cid);
1284   if (NULL == c)
1285   {
1286     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
1287     c = connection_new (cid);
1288     if (NULL == c)
1289       return GNUNET_OK;
1290     connection_reset_timeout (c, GNUNET_YES);
1291
1292     /* Create path */
1293     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
1294     path = path_new (size);
1295     own_pos = 0;
1296     for (i = 0; i < size; i++)
1297     {
1298       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
1299                   GNUNET_i2s (&id[i]));
1300       path->peers[i] = GNUNET_PEER_intern (&id[i]);
1301       if (path->peers[i] == myid)
1302         own_pos = i;
1303     }
1304     if (own_pos == 0 && path->peers[own_pos] != myid)
1305     {
1306       /* create path: self not found in path through self */
1307       GNUNET_break_op (0);
1308       path_destroy (path);
1309       connection_destroy (c);
1310       return GNUNET_OK;
1311     }
1312     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
1313     path_add_to_peers (path, GNUNET_NO);
1314     c->path = path_duplicate (path);
1315     c->own_pos = own_pos;
1316   }
1317   else
1318   {
1319     path = NULL;
1320   }
1321   if (MESH_CONNECTION_NEW == c->state)
1322     connection_change_state (c, MESH_CONNECTION_SENT);
1323
1324   /* Remember peers */
1325   dest_peer = peer_get (&id[size - 1]);
1326   orig_peer = peer_get (&id[0]);
1327
1328   /* Is it a connection to us? */
1329   if (c->own_pos == size - 1)
1330   {
1331     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
1332     peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
1333
1334     if (NULL == orig_peer->tunnel)
1335     {
1336       orig_peer->tunnel = tunnel_new ();
1337       orig_peer->tunnel->peer = orig_peer;
1338     }
1339     tunnel_add_connection (orig_peer->tunnel, c);
1340     if (MESH_TUNNEL_NEW == c->t->state)
1341       tunnel_change_state (c->t,  MESH_TUNNEL_WAITING);
1342
1343     send_connection_ack (c, GNUNET_NO);
1344     if (MESH_CONNECTION_SENT == c->state)
1345       connection_change_state (c, MESH_CONNECTION_ACK);
1346
1347     /* Keep tunnel alive in direction dest->owner*/
1348     connection_reset_timeout (c, GNUNET_NO);
1349   }
1350   else
1351   {
1352     /* It's for somebody else! Retransmit. */
1353     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
1354     peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
1355     peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
1356     send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
1357   }
1358   return GNUNET_OK;
1359 }
1360
1361
1362 /**
1363  * Core handler for path confirmations.
1364  *
1365  * @param cls closure
1366  * @param message message
1367  * @param peer peer identity this notification is about
1368  *
1369  * @return GNUNET_OK to keep the connection open,
1370  *         GNUNET_SYSERR to close it (signal serious error)
1371  */
1372 static int
1373 handle_confirm (void *cls, const struct GNUNET_PeerIdentity *peer,
1374                 const struct GNUNET_MessageHeader *message)
1375 {
1376   struct GNUNET_MESH_ConnectionACK *msg;
1377   struct MeshConnection *c;
1378   struct MeshPeerPath *p;
1379   struct MeshPeer *pi;
1380   int fwd;
1381
1382   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1383   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
1384   msg = (struct GNUNET_MESH_ConnectionACK *) message;
1385   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
1386               GNUNET_h2s (&msg->cid));
1387   c = connection_get (&msg->cid);
1388   if (NULL == c)
1389   {
1390     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1391                               1, GNUNET_NO);
1392     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
1393     return GNUNET_OK;
1394   }
1395
1396
1397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
1398               GNUNET_i2s (peer));
1399   pi = peer_get (peer);
1400   if (connection_get_next_hop (c) == pi)
1401   {
1402     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
1403     fwd = GNUNET_NO;
1404     if (MESH_CONNECTION_SENT == c->state)
1405       connection_change_state (c, MESH_CONNECTION_ACK);
1406   }
1407   else if (connection_get_prev_hop (c) == pi)
1408   {
1409     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
1410     fwd = GNUNET_YES;
1411     connection_change_state (c, MESH_CONNECTION_READY);
1412   }
1413   else
1414   {
1415     GNUNET_break_op (0);
1416     return GNUNET_OK;
1417   }
1418   connection_reset_timeout (c, fwd);
1419
1420   /* Add path to peers? */
1421   p = c->path;
1422   if (NULL != p)
1423   {
1424     path_add_to_peers (p, GNUNET_YES);
1425   }
1426   else
1427   {
1428     GNUNET_break (0);
1429   }
1430
1431   /* Message for us as creator? */
1432   if (connection_is_origin (c, GNUNET_YES))
1433   {
1434     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
1435     connection_change_state (c, MESH_CONNECTION_READY);
1436     if (MESH_TUNNEL_READY != c->t->state)
1437       tunnel_change_state (c->t, MESH_TUNNEL_READY);
1438     send_connection_ack (c, GNUNET_YES);
1439     tunnel_send_queued_data (c->t, GNUNET_YES);
1440     if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
1441     {
1442       GNUNET_DHT_get_stop (c->t->peer->dhtget);
1443       c->t->peer->dhtget = NULL;
1444     }
1445     return GNUNET_OK;
1446   }
1447
1448   /* Message for us as destination? */
1449   if (GMC_is_terminal (c, GNUNET_YES))
1450   {
1451     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
1452     if (MESH_TUNNEL_READY != c->t->state)
1453       tunnel_change_state (c->t, MESH_TUNNEL_READY);
1454     connection_change_state (c, MESH_CONNECTION_READY);
1455     tunnel_send_queued_data (c->t, GNUNET_NO);
1456     return GNUNET_OK;
1457   }
1458
1459   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1460   send_prebuilt_message_connection (message, c, NULL, fwd);
1461   return GNUNET_OK;
1462 }
1463
1464
1465 /**
1466  * Core handler for notifications of broken paths
1467  *
1468  * @param cls Closure (unused).
1469  * @param peer Peer identity of sending neighbor.
1470  * @param message Message.
1471  *
1472  * @return GNUNET_OK to keep the connection open,
1473  *         GNUNET_SYSERR to close it (signal serious error)
1474  */
1475 static int
1476 handle_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
1477                const struct GNUNET_MessageHeader *message)
1478 {
1479   struct GNUNET_MESH_ConnectionBroken *msg;
1480   struct MeshConnection *c;
1481
1482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1483               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
1484   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
1485   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1486               GNUNET_i2s (&msg->peer1));
1487   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1488               GNUNET_i2s (&msg->peer2));
1489   c = connection_get (&msg->cid);
1490   if (NULL == c)
1491   {
1492     GNUNET_break_op (0);
1493     return GNUNET_OK;
1494   }
1495   tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
1496                                    GNUNET_PEER_search (&msg->peer2));
1497   return GNUNET_OK;
1498
1499 }
1500
1501
1502 /**
1503  * Core handler for tunnel destruction
1504  *
1505  * @param cls Closure (unused).
1506  * @param peer Peer identity of sending neighbor.
1507  * @param message Message.
1508  *
1509  * @return GNUNET_OK to keep the connection open,
1510  *         GNUNET_SYSERR to close it (signal serious error)
1511  */
1512 static int
1513 handle_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
1514                 const struct GNUNET_MessageHeader *message)
1515 {
1516   struct GNUNET_MESH_ConnectionDestroy *msg;
1517   struct MeshConnection *c;
1518   GNUNET_PEER_Id id;
1519   int fwd;
1520
1521   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
1522   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1523               "Got a CONNECTION DESTROY message from %s\n",
1524               GNUNET_i2s (peer));
1525   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1526               "  for connection %s\n",
1527               GNUNET_h2s (&msg->cid));
1528   c = connection_get (&msg->cid);
1529   if (NULL == c)
1530   {
1531     /* Probably already got the message from another path,
1532      * destroyed the tunnel and retransmitted to children.
1533      * Safe to ignore.
1534      */
1535     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
1536                               1, GNUNET_NO);
1537     return GNUNET_OK;
1538   }
1539   id = GNUNET_PEER_search (peer);
1540   if (id == connection_get_prev_hop (c)->id)
1541     fwd = GNUNET_YES;
1542   else if (id == connection_get_next_hop (c)->id)
1543     fwd = GNUNET_NO;
1544   else
1545   {
1546     GNUNET_break_op (0);
1547     return GNUNET_OK;
1548   }
1549   send_prebuilt_message_connection (message, c, NULL, fwd);
1550   c->destroy = GNUNET_YES;
1551
1552   return GNUNET_OK;
1553 }
1554
1555 /**
1556  * Generic handler for mesh network encrypted traffic.
1557  *
1558  * @param peer Peer identity this notification is about.
1559  * @param message Encrypted message.
1560  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1561  *
1562  * @return GNUNET_OK to keep the connection open,
1563  *         GNUNET_SYSERR to close it (signal serious error)
1564  */
1565 static int
1566 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
1567                        const struct GNUNET_MESH_Encrypted *msg,
1568                        int fwd)
1569 {
1570   struct MeshConnection *c;
1571   struct MeshTunnel2 *t;
1572   struct MeshPeer *neighbor;
1573   struct MeshFlowControl *fc;
1574   uint32_t pid;
1575   uint32_t ttl;
1576   uint16_t type;
1577   size_t size;
1578
1579   /* Check size */
1580   size = ntohs (msg->header.size);
1581   if (size <
1582       sizeof (struct GNUNET_MESH_Encrypted) +
1583       sizeof (struct GNUNET_MessageHeader))
1584   {
1585     GNUNET_break_op (0);
1586     return GNUNET_OK;
1587   }
1588   type = ntohs (msg->header.type);
1589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
1591               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
1592
1593   /* Check connection */
1594   c = connection_get (&msg->cid);
1595   if (NULL == c)
1596   {
1597     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
1598     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
1599     return GNUNET_OK;
1600   }
1601   t = c->t;
1602   fc = fwd ? &c->bck_fc : &c->fwd_fc;
1603
1604   /* Check if origin is as expected */
1605   neighbor = connection_get_hop (c, !fwd);
1606   if (peer_get (peer)->id != neighbor->id)
1607   {
1608     GNUNET_break_op (0);
1609     return GNUNET_OK;
1610   }
1611
1612   /* Check PID */
1613   pid = ntohl (msg->pid);
1614   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
1615   {
1616     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
1617     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1618                 "WARNING Received PID %u, (prev %u), ACK %u\n",
1619                 pid, fc->last_pid_recv, fc->last_ack_sent);
1620     return GNUNET_OK;
1621   }
1622   if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
1623   {
1624     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
1625     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1626                 " Pid %u not expected (%u+), dropping!\n",
1627                 pid, fc->last_pid_recv + 1);
1628     return GNUNET_OK;
1629   }
1630   if (MESH_CONNECTION_SENT == c->state)
1631     connection_change_state (c, MESH_CONNECTION_READY);
1632   connection_reset_timeout (c, fwd);
1633   fc->last_pid_recv = pid;
1634
1635   /* Is this message for us? */
1636   if (GMC_is_terminal (c, fwd))
1637   {
1638     size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
1639     char cbuf[dsize];
1640     struct GNUNET_MessageHeader *msgh;
1641     unsigned int off;
1642
1643     /* TODO signature verification */
1644     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
1645     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
1646
1647     fc->last_pid_recv = pid;
1648     tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
1649     off = 0;
1650     while (off < dsize)
1651     {
1652       msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1653       handle_decrypted (t, msgh, fwd);
1654       off += ntohs (msgh->size);
1655     }
1656     send_ack (c, NULL, fwd);
1657     return GNUNET_OK;
1658   }
1659
1660   /* Message not for us: forward to next hop */
1661   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1662   ttl = ntohl (msg->ttl);
1663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
1664   if (ttl == 0)
1665   {
1666     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
1667     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
1668     send_ack (c, NULL, fwd);
1669     return GNUNET_OK;
1670   }
1671   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
1672
1673   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
1674
1675   return GNUNET_OK;
1676 }
1677
1678
1679 /**
1680  * Core handler for mesh network traffic going orig->dest.
1681  *
1682  * @param cls Closure (unused).
1683  * @param message Message received.
1684  * @param peer Peer who sent the message.
1685  *
1686  * @return GNUNET_OK to keep the connection open,
1687  *         GNUNET_SYSERR to close it (signal serious error)
1688  */
1689 static int
1690 handle_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
1691             const struct GNUNET_MessageHeader *message)
1692 {
1693   return handle_mesh_encrypted (peer,
1694                                 (struct GNUNET_MESH_Encrypted *)message,
1695                                 GNUNET_YES);
1696 }
1697
1698 /**
1699  * Core handler for mesh network traffic going dest->orig.
1700  *
1701  * @param cls Closure (unused).
1702  * @param message Message received.
1703  * @param peer Peer who sent the message.
1704  *
1705  * @return GNUNET_OK to keep the connection open,
1706  *         GNUNET_SYSERR to close it (signal serious error)
1707  */
1708 static int
1709 handle_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
1710             const struct GNUNET_MessageHeader *message)
1711 {
1712   return handle_mesh_encrypted (peer,
1713                                 (struct GNUNET_MESH_Encrypted *)message,
1714                                 GNUNET_NO);
1715 }
1716
1717
1718 /**
1719  * Core handler for mesh network traffic point-to-point acks.
1720  *
1721  * @param cls closure
1722  * @param message message
1723  * @param peer peer identity this notification is about
1724  *
1725  * @return GNUNET_OK to keep the connection open,
1726  *         GNUNET_SYSERR to close it (signal serious error)
1727  */
1728 static int
1729 handle_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
1730             const struct GNUNET_MessageHeader *message)
1731 {
1732   struct GNUNET_MESH_ACK *msg;
1733   struct MeshConnection *c;
1734   struct MeshFlowControl *fc;
1735   GNUNET_PEER_Id id;
1736   uint32_t ack;
1737   int fwd;
1738
1739   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1740   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
1741               GNUNET_i2s (peer));
1742   msg = (struct GNUNET_MESH_ACK *) message;
1743
1744   c = connection_get (&msg->cid);
1745
1746   if (NULL == c)
1747   {
1748     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
1749                               GNUNET_NO);
1750     return GNUNET_OK;
1751   }
1752
1753   /* Is this a forward or backward ACK? */
1754   id = GNUNET_PEER_search (peer);
1755   if (connection_get_next_hop (c)->id == id)
1756   {
1757     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
1758     fc = &c->fwd_fc;
1759     fwd = GNUNET_YES;
1760   }
1761   else if (connection_get_prev_hop (c)->id == id)
1762   {
1763     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
1764     fc = &c->bck_fc;
1765     fwd = GNUNET_NO;
1766   }
1767   else
1768   {
1769     GNUNET_break_op (0);
1770     return GNUNET_OK;
1771   }
1772
1773   ack = ntohl (msg->ack);
1774   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u (was %u)\n",
1775               ack, fc->last_ack_recv);
1776   if (GMC_is_pid_bigger (ack, fc->last_ack_recv))
1777     fc->last_ack_recv = ack;
1778
1779   /* Cancel polling if the ACK is big enough. */
1780   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
1781       GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
1782   {
1783     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
1784     GNUNET_SCHEDULER_cancel (fc->poll_task);
1785     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1786     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
1787   }
1788
1789   connection_unlock_queue (c, fwd);
1790
1791   return GNUNET_OK;
1792 }
1793
1794
1795 /**
1796  * Core handler for mesh network traffic point-to-point ack polls.
1797  *
1798  * @param cls closure
1799  * @param message message
1800  * @param peer peer identity this notification is about
1801  *
1802  * @return GNUNET_OK to keep the connection open,
1803  *         GNUNET_SYSERR to close it (signal serious error)
1804  */
1805 static int
1806 handle_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
1807              const struct GNUNET_MessageHeader *message)
1808 {
1809   struct GNUNET_MESH_Poll *msg;
1810   struct MeshConnection *c;
1811   struct MeshFlowControl *fc;
1812   GNUNET_PEER_Id id;
1813   uint32_t pid;
1814   int fwd;
1815
1816   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1817   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
1818               GNUNET_i2s (peer));
1819
1820   msg = (struct GNUNET_MESH_Poll *) message;
1821
1822   c = connection_get (&msg->cid);
1823
1824   if (NULL == c)
1825   {
1826     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
1827                               GNUNET_NO);
1828     GNUNET_break_op (0);
1829     return GNUNET_OK;
1830   }
1831
1832   /* Is this a forward or backward ACK?
1833    * Note: a poll should never be needed in a loopback case,
1834    * since there is no possiblility of packet loss there, so
1835    * this way of discerining FWD/BCK should not be a problem.
1836    */
1837   id = GNUNET_PEER_search (peer);
1838   if (connection_get_next_hop (c)->id == id)
1839   {
1840     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
1841     fc = &c->fwd_fc;
1842   }
1843   else if (connection_get_prev_hop (c)->id == id)
1844   {
1845     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
1846     fc = &c->bck_fc;
1847   }
1848   else
1849   {
1850     GNUNET_break_op (0);
1851     return GNUNET_OK;
1852   }
1853
1854   pid = ntohl (msg->pid);
1855   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n",
1856               pid, fc->last_pid_recv);
1857   fc->last_pid_recv = pid;
1858   fwd = fc == &c->fwd_fc;
1859   send_ack (c, NULL, fwd);
1860
1861   return GNUNET_OK;
1862 }
1863
1864
1865 /**
1866  * Core handler for mesh keepalives.
1867  *
1868  * @param cls closure
1869  * @param message message
1870  * @param peer peer identity this notification is about
1871  * @return GNUNET_OK to keep the connection open,
1872  *         GNUNET_SYSERR to close it (signal serious error)
1873  *
1874  * TODO: Check who we got this from, to validate route.
1875  */
1876 static int
1877 handle_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
1878                 const struct GNUNET_MessageHeader *message)
1879 {
1880   struct GNUNET_MESH_ConnectionKeepAlive *msg;
1881   struct MeshConnection *c;
1882   struct MeshPeer *neighbor;
1883   int fwd;
1884
1885   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
1886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
1887               GNUNET_i2s (peer));
1888
1889   c = connection_get (&msg->cid);
1890   if (NULL == c)
1891   {
1892     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
1893                               GNUNET_NO);
1894     return GNUNET_OK;
1895   }
1896
1897   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
1898         GNUNET_YES : GNUNET_NO;
1899
1900   /* Check if origin is as expected */
1901   neighbor = connection_get_hop (c, fwd);
1902   if (peer_get (peer)->id != neighbor->id)
1903   {
1904     GNUNET_break_op (0);
1905     return GNUNET_OK;
1906   }
1907
1908   connection_change_state (c, MESH_CONNECTION_READY);
1909   connection_reset_timeout (c, fwd);
1910
1911   if (GMC_is_terminal (c, fwd))
1912     return GNUNET_OK;
1913
1914   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
1915   send_prebuilt_message_connection (message, c, NULL, fwd);
1916
1917   return GNUNET_OK;
1918 }
1919
1920
1921 /**
1922  * Functions to handle messages from core
1923  */
1924 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1925   {&handle_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
1926     0},
1927   {&handle_confirm, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
1928     sizeof (struct GNUNET_MESH_ConnectionACK)},
1929   {&handle_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
1930     sizeof (struct GNUNET_MESH_ConnectionBroken)},
1931   {&handle_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
1932     sizeof (struct GNUNET_MESH_ConnectionDestroy)},
1933   {&handle_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
1934     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
1935   {&handle_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
1936     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
1937   {&handle_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
1938     sizeof (struct GNUNET_MESH_ACK)},
1939   {&handle_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
1940     sizeof (struct GNUNET_MESH_Poll)},
1941   {&handle_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
1942   {&handle_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
1943   {NULL, 0, 0}
1944 };
1945
1946
1947
1948 struct MeshConnection *
1949 GMC_new (const struct GNUNET_HashCode *cid)
1950 {
1951   struct MeshConnection *c;
1952   
1953   c = GNUNET_new (struct MeshConnection);
1954   c->id = *cid;
1955   GNUNET_CONTAINER_multihashmap_put (connections, &c->id, c,
1956                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1957   fc_init (&c->fwd_fc);
1958   fc_init (&c->bck_fc);
1959   c->fwd_fc.c = c;
1960   c->bck_fc.c = c;
1961   
1962   return c;
1963 }
1964
1965
1966 static void
1967 GMC_destroy (struct MeshConnection *c)
1968 {
1969   struct MeshPeer *peer;
1970
1971   if (NULL == c)
1972     return;
1973
1974   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
1975               peer2s (c->t->peer),
1976               c->id);
1977
1978   /* Cancel all traffic */
1979   connection_cancel_queues (c, GNUNET_YES);
1980   connection_cancel_queues (c, GNUNET_NO);
1981
1982   /* Cancel maintainance task (keepalive/timeout) */
1983   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
1984     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
1985   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
1986     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
1987
1988   /* Deregister from neighbors */
1989   peer = connection_get_next_hop (c);
1990   if (NULL != peer && NULL != peer->connections)
1991     GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
1992   peer = connection_get_prev_hop (c);
1993   if (NULL != peer && NULL != peer->connections)
1994     GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
1995
1996   /* Delete */
1997   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
1998   GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
1999   GNUNET_free (c);
2000 }
2001
2002
2003 /**
2004  * Iterator to notify all connections of a broken link. Mark connections
2005  * to destroy after all traffic has been sent.
2006  *
2007  * @param cls Closure (peer disconnected).
2008  * @param key Current key code (tid).
2009  * @param value Value in the hash map (connection).
2010  *
2011  * @return GNUNET_YES if we should continue to iterate,
2012  *         GNUNET_NO if not.
2013  */
2014 int
2015 GMC_notify_broken (void *cls,
2016                    const struct GNUNET_HashCode *key,
2017                    void *value)
2018 {
2019   struct MeshPeer *peer = cls;
2020   struct MeshConnection *c = value;
2021   struct GNUNET_MESH_ConnectionBroken msg;
2022   int fwd;
2023
2024   fwd = peer == connection_get_prev_hop (c);
2025
2026   connection_cancel_queues (c, !fwd);
2027   if (GMC_is_terminal (c, fwd))
2028   {
2029     /* Local shutdown, no one to notify about this. */
2030     GMC_destroy (c);
2031     return GNUNET_YES;
2032   }
2033
2034   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
2035   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
2036   msg.cid = c->id;
2037   msg.peer1 = my_full_id;
2038   msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
2039   send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
2040   c->destroy = GNUNET_YES;
2041
2042   return GNUNET_YES;
2043 }
2044
2045
2046 /**
2047  * Initialize the connections subsystem
2048  *
2049  * @param c Configuration handle.
2050  */
2051 void
2052 GMC_init (const struct GNUNET_CONFIGURATION_Handle *c)
2053 {
2054   if (GNUNET_OK !=
2055       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
2056                                              &max_msgs_queue))
2057   {
2058     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2059                                "MESH", "MAX_MSGS_QUEUE", "MISSING");
2060     GNUNET_SCHEDULER_shutdown ();
2061     return;
2062   }
2063
2064   if (GNUNET_OK !=
2065       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
2066                                              &max_connections))
2067   {
2068     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2069                                "MESH", "MAX_CONNECTIONS", "MISSING");
2070     GNUNET_SCHEDULER_shutdown ();
2071     return;
2072   }
2073
2074   if (GNUNET_OK !=
2075       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
2076                                            &refresh_connection_time))
2077   {
2078     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2079                                "MESH", "REFRESH_CONNECTION_TIME", "MISSING");
2080     GNUNET_SCHEDULER_shutdown ();
2081     return;
2082   }
2083   connections = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
2084
2085   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
2086                                      NULL,      /* Closure passed to MESH functions */
2087                                      &core_init,        /* Call core_init once connected */
2088                                      &core_connect,     /* Handle connects */
2089                                      &core_disconnect,  /* remove peers on disconnects */
2090                                      NULL,      /* Don't notify about all incoming messages */
2091                                      GNUNET_NO, /* For header only in notification */
2092                                      NULL,      /* Don't notify about all outbound messages */
2093                                      GNUNET_NO, /* For header-only out notification */
2094                                      core_handlers);    /* Register these handlers */
2095   if (NULL == core_handle)
2096   {
2097     GNUNET_break (0);
2098     GNUNET_SCHEDULER_shutdown ();
2099     return;
2100   }
2101 }
2102
2103 /**
2104  * Shut down the connections subsystem.
2105  */
2106 void
2107 GMC_shutdown (void)
2108 {
2109   if (core_handle != NULL)
2110   {
2111     GNUNET_CORE_disconnect (core_handle);
2112     core_handle = NULL;
2113   }
2114 }
2115
2116
2117 /**
2118  * Is this peer the first one on the connection?
2119  *
2120  * @param c Connection.
2121  * @param fwd Is this about fwd traffic?
2122  *
2123  * @return GNUNET_YES if origin, GNUNET_NO if relay/terminal.
2124  */
2125 int
2126 GMC_is_origin (struct MeshConnection *c, int fwd)
2127 {
2128   if (!fwd && c->path->length - 1 == c->own_pos )
2129     return GNUNET_YES;
2130   if (fwd && 0 == c->own_pos)
2131     return GNUNET_YES;
2132   return GNUNET_NO;
2133 }
2134
2135
2136 /**
2137  * Is this peer the last one on the connection?
2138  *
2139  * @param c Connection.
2140  * @param fwd Is this about fwd traffic?
2141  *            Note that the ROOT is the terminal for BCK traffic!
2142  *
2143  * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
2144  */
2145 int
2146 GMC_is_terminal (struct MeshConnection *c, int fwd)
2147 {
2148   return GMC_is_origin (c, !fwd);
2149 }
2150
2151
2152 /**
2153  * Count connections in a DLL.
2154  */
2155 unsigned int
2156 GMC_count (const struct MeshConnection *head)
2157 {
2158   unsigned int count;
2159   struct MeshConnection *iter;
2160
2161   for (count = 0, iter = head; NULL != iter; iter = iter->next, count++);
2162
2163   return count;
2164 }