- fix NPE
[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_statistics_service.h"
31
32 #include "mesh_path.h"
33 #include "mesh_protocol_enc.h"
34 #include "mesh_enc.h"
35 #include "gnunet-service-mesh_connection.h"
36 #include "gnunet-service-mesh_peer.h"
37 #include "gnunet-service-mesh_tunnel.h"
38
39
40 #define LOG(level, ...) GNUNET_log_from (level,"mesh-con",__VA_ARGS__)
41
42 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
43                                   GNUNET_TIME_UNIT_MINUTES,\
44                                   10)
45 #define AVG_MSGS                32
46
47
48 /******************************************************************************/
49 /********************************   STRUCTS  **********************************/
50 /******************************************************************************/
51
52 /**
53  * Struct to encapsulate all the Flow Control information to a peer to which
54  * we are directly connected (on a core level).
55  */
56 struct MeshFlowControl
57 {
58   /**
59    * Connection this controls.
60    */
61   struct MeshConnection *c;
62
63   /**
64    * How many messages are in the queue on this connection.
65    */
66   unsigned int queue_n;
67
68   /**
69    * How many messages do we accept in the queue.
70    */
71   unsigned int queue_max;
72
73   /**
74    * Next ID to use.
75    */
76   uint32_t next_pid;
77
78   /**
79    * ID of the last packet sent towards the peer.
80    */
81   uint32_t last_pid_sent;
82
83   /**
84    * ID of the last packet received from the peer.
85    */
86   uint32_t last_pid_recv;
87
88   /**
89    * Last ACK sent to the peer (peer can't send more than this PID).
90    */
91   uint32_t last_ack_sent;
92
93   /**
94    * Last ACK sent towards the origin (for traffic towards leaf node).
95    */
96   uint32_t last_ack_recv;
97
98   /**
99    * Task to poll the peer in case of a lost ACK causes stall.
100    */
101   GNUNET_SCHEDULER_TaskIdentifier poll_task;
102
103   /**
104    * How frequently to poll for ACKs.
105    */
106   struct GNUNET_TIME_Relative poll_time;
107
108   /**
109    * Queued poll message, to cancel if not necessary anymore (got ACK).
110    */
111   struct MeshConnectionQueue *poll_msg;
112
113   /**
114    * Queued poll message, to cancel if not necessary anymore (got ACK).
115    */
116   struct MeshConnectionQueue *ack_msg;
117 };
118
119 /**
120  * Keep a record of the last messages sent on this connection.
121  */
122 struct MeshConnectionPerformance
123 {
124   /**
125    * Circular buffer for storing measurements.
126    */
127   double usecsperbyte[AVG_MSGS];
128
129   /**
130    * Running average of @c usecsperbyte.
131    */
132   double avg;
133
134   /**
135    * How many values of @c usecsperbyte are valid.
136    */
137   uint16_t size;
138
139   /**
140    * Index of the next "free" position in @c usecsperbyte.
141    */
142   uint16_t idx;
143 };
144
145
146 /**
147  * Struct containing all information regarding a connection to a peer.
148  */
149 struct MeshConnection
150 {
151   /**
152    * Tunnel this connection is part of.
153    */
154   struct MeshTunnel3 *t;
155
156   /**
157    * Flow control information for traffic fwd.
158    */
159   struct MeshFlowControl fwd_fc;
160
161   /**
162    * Flow control information for traffic bck.
163    */
164   struct MeshFlowControl bck_fc;
165
166   /**
167    * Measure connection performance on the endpoint.
168    */
169   struct MeshConnectionPerformance *perf;
170
171   /**
172    * ID of the connection.
173    */
174   struct GNUNET_HashCode id;
175
176   /**
177    * State of the connection.
178    */
179   enum MeshConnectionState state;
180
181   /**
182    * Path being used for the tunnel.
183    */
184   struct MeshPeerPath *path;
185
186   /**
187    * Position of the local peer in the path.
188    */
189   unsigned int own_pos;
190
191   /**
192    * Task to keep the used paths alive at the owner,
193    * time tunnel out on all the other peers.
194    */
195   GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
196
197   /**
198    * Task to keep the used paths alive at the destination,
199    * time tunnel out on all the other peers.
200    */
201   GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
202
203   /**
204    * Pending message count.
205    */
206   int pending_messages;
207
208   /**
209    * Destroy flag: if true, destroy on last message.
210    */
211   int destroy;
212 };
213
214 /**
215  * Handle for messages queued but not yet sent.
216  */
217 struct MeshConnectionQueue
218 {
219   struct MeshPeerQueue *q;
220   GMC_sent cont;
221   void *cont_cls;
222 };
223
224 /******************************************************************************/
225 /*******************************   GLOBALS  ***********************************/
226 /******************************************************************************/
227
228 /**
229  * Global handle to the statistics service.
230  */
231 extern struct GNUNET_STATISTICS_Handle *stats;
232
233 /**
234  * Local peer own ID (memory efficient handle).
235  */
236 extern GNUNET_PEER_Id myid;
237
238 /**
239  * Local peer own ID (full value).
240  */
241 extern struct GNUNET_PeerIdentity my_full_id;
242
243 /**
244  * Connections known, indexed by cid (MeshConnection).
245  */
246 static struct GNUNET_CONTAINER_MultiHashMap *connections;
247
248 /**
249  * How many connections are we willing to maintain.
250  * Local connections are always allowed, even if there are more connections than max.
251  */
252 static unsigned long long max_connections;
253
254 /**
255  * How many messages *in total* are we willing to queue, divide by number of
256  * connections to get connection queue size.
257  */
258 static unsigned long long max_msgs_queue;
259
260 /**
261  * How often to send path keepalives. Paths timeout after 4 missed.
262  */
263 static struct GNUNET_TIME_Relative refresh_connection_time;
264
265
266 /******************************************************************************/
267 /********************************   STATIC  ***********************************/
268 /******************************************************************************/
269
270 #if 0 // avoid compiler warning for unused static function
271 static void
272 fc_debug (struct MeshFlowControl *fc)
273 {
274   LOG (GNUNET_ERROR_TYPE_DEBUG, "    IN: %u/%u\n",
275               fc->last_pid_recv, fc->last_ack_sent);
276   LOG (GNUNET_ERROR_TYPE_DEBUG, "    OUT: %u/%u\n",
277               fc->last_pid_sent, fc->last_ack_recv);
278   LOG (GNUNET_ERROR_TYPE_DEBUG, "    QUEUE: %u/%u\n",
279               fc->queue_n, fc->queue_max);
280 }
281
282 static void
283 connection_debug (struct MeshConnection *c)
284 {
285   if (NULL == c)
286   {
287     LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CONNECTION ***\n");
288     return;
289   }
290   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
291               peer2s (c->t->peer), GMC_2s (c));
292   LOG (GNUNET_ERROR_TYPE_DEBUG, "  state: %u, pending msgs: %u\n",
293               c->state, c->pending_messages);
294   LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
295   fc_debug (&c->fwd_fc);
296   LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
297   fc_debug (&c->bck_fc);
298 }
299 #endif
300
301 /**
302  * Get string description for tunnel state.
303  *
304  * @param s Tunnel state.
305  *
306  * @return String representation.
307  */
308 static const char *
309 GMC_state2s (enum MeshConnectionState s)
310 {
311   switch (s)
312   {
313     case MESH_CONNECTION_NEW:
314       return "MESH_CONNECTION_NEW";
315     case MESH_CONNECTION_SENT:
316       return "MESH_CONNECTION_SENT";
317     case MESH_CONNECTION_ACK:
318       return "MESH_CONNECTION_ACK";
319     case MESH_CONNECTION_READY:
320       return "MESH_CONNECTION_READY";
321     default:
322       return "MESH_CONNECTION_STATE_ERROR";
323   }
324 }
325
326
327 /**
328  * Initialize a Flow Control structure to the initial state.
329  *
330  * @param fc Flow Control structure to initialize.
331  */
332 static void
333 fc_init (struct MeshFlowControl *fc)
334 {
335   fc->next_pid = 0;
336   fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
337   fc->last_pid_recv = (uint32_t) -1;
338   fc->last_ack_sent = (uint32_t) 0;
339   fc->last_ack_recv = (uint32_t) 0;
340   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
341   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
342   fc->queue_n = 0;
343   fc->queue_max = (max_msgs_queue / max_connections) + 1;
344 }
345
346
347 /**
348  * Find a connection.
349  *
350  * @param cid Connection ID.
351  */
352 static struct MeshConnection *
353 connection_get (const struct GNUNET_HashCode *cid)
354 {
355   return GNUNET_CONTAINER_multihashmap_get (connections, cid);
356 }
357
358
359 static void
360 connection_change_state (struct MeshConnection* c,
361                          enum MeshConnectionState state)
362 {
363   LOG (GNUNET_ERROR_TYPE_DEBUG,
364               "Connection %s state was %s\n",
365               GMC_2s (c), GMC_state2s (c->state));
366   LOG (GNUNET_ERROR_TYPE_DEBUG,
367               "Connection %s state is now %s\n",
368               GMC_2s (c), GMC_state2s (state));
369   c->state = state;
370 }
371
372
373 /**
374  * Callback called when a queued ACK message is sent.
375  *
376  * @param cls Closure (FC).
377  * @param c Connection this message was on.
378  * @param type Type of message sent.
379  * @param fwd Was this a FWD going message?
380  * @param size Size of the message.
381  */
382 static void
383 ack_sent (void *cls,
384           struct MeshConnection *c,
385           struct MeshConnectionQueue *q,
386           uint16_t type, int fwd, size_t size)
387 {
388   struct MeshFlowControl *fc = cls;
389
390   fc->ack_msg = NULL;
391 }
392
393
394 /**
395  * Send an ACK on the connection, informing the predecessor about
396  * the available buffer space. Should not be called in case the peer
397  * is origin (no predecessor) in the @c fwd direction.
398  *
399  * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
400  * the ACK itself goes "back" (dest->root).
401  *
402  * @param c Connection on which to send the ACK.
403  * @param buffer How much space free to advertise?
404  * @param fwd Is this FWD ACK? (Going dest -> root)
405  * @param force Don't optimize out.
406  */
407 static void
408 send_ack (struct MeshConnection *c, unsigned int buffer, int fwd, int force)
409 {
410   struct MeshFlowControl *next_fc;
411   struct MeshFlowControl *prev_fc;
412   struct GNUNET_MESH_ACK msg;
413   uint32_t ack;
414   int delta;
415
416   /* If origin, there is no connection to send ACKs. Wrong function! */
417   if (GMC_is_origin (c, fwd))
418   {
419     GNUNET_break (0);
420     return;
421   }
422
423   next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
424   prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
425
426   LOG (GNUNET_ERROR_TYPE_DEBUG,
427               "connection send %s ack on %s\n",
428               fwd ? "FWD" : "BCK", GMC_2s (c));
429
430   /* Check if we need to transmit the ACK. */
431   delta = prev_fc->last_ack_sent - prev_fc->last_pid_recv;
432   if (3 < delta && buffer < delta && GNUNET_NO == force)
433   {
434     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
435     LOG (GNUNET_ERROR_TYPE_DEBUG,
436          "  last pid recv: %u, last ack sent: %u\n",
437          prev_fc->last_pid_recv, prev_fc->last_ack_sent);
438     return;
439   }
440
441   /* Ok, ACK might be necessary, what PID to ACK? */
442   ack = prev_fc->last_pid_recv + buffer;
443   LOG (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
444   LOG (GNUNET_ERROR_TYPE_DEBUG,
445        " last pid %u, last ack %u, qmax %u, q %u\n",
446        prev_fc->last_pid_recv, prev_fc->last_ack_sent,
447        next_fc->queue_max, next_fc->queue_n);
448   if (ack == prev_fc->last_ack_sent && GNUNET_NO == force)
449   {
450     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
451     return;
452   }
453
454   /* Check if message is already in queue */
455   if (NULL != prev_fc->ack_msg)
456   {
457     if (GMC_is_pid_bigger (ack, prev_fc->last_ack_sent))
458     {
459       LOG (GNUNET_ERROR_TYPE_DEBUG, " canceling old ACK\n");
460       GMC_cancel (prev_fc->ack_msg);
461       /* GMC_cancel triggers ack_sent(), which clears fc->ack_msg */
462     }
463     else
464     {
465       LOG (GNUNET_ERROR_TYPE_DEBUG, " same ACK already in queue\n");
466       return;
467     }
468   }
469
470   prev_fc->last_ack_sent = ack;
471
472   /* Build ACK message and send on connection */
473   msg.header.size = htons (sizeof (msg));
474   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
475   msg.ack = htonl (ack);
476   msg.cid = c->id;
477
478   prev_fc->ack_msg = GMC_send_prebuilt_message (&msg.header, c, !fwd,
479                                                 &ack_sent, prev_fc);
480 }
481
482
483 /**
484  * Callback called when a queued message is sent.
485  *
486  * Calculates the average time and connection packet tracking.
487  *
488  * @param cls Closure (ConnectionQueue Handle).
489  * @param c Connection this message was on.
490  * @param type Type of message sent.
491  * @param fwd Was this a FWD going message?
492  * @param size Size of the message.
493  * @param wait Time spent waiting for core (only the time for THIS message)
494  */
495 static void 
496 message_sent (void *cls,
497               struct MeshConnection *c, uint16_t type,
498               int fwd, size_t size,
499               struct GNUNET_TIME_Relative wait)
500 {
501   struct MeshConnectionPerformance *p;
502   struct MeshFlowControl *fc;
503   struct MeshConnectionQueue *q = cls;
504   double usecsperbyte;
505
506   fc = fwd ? &c->fwd_fc : &c->bck_fc;
507   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  sent %s\n", GNUNET_MESH_DEBUG_M2S (type));
508   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  C_P- %p %u\n", c, c->pending_messages);
509   if (NULL != q && NULL != q->cont)
510   {
511     LOG (GNUNET_ERROR_TYPE_DEBUG, "!  calling cont\n");
512     q->cont (q->cont_cls, c, q, type, fwd, size);
513     GNUNET_free (q);
514   }
515   c->pending_messages--;
516   if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
517   {
518     LOG (GNUNET_ERROR_TYPE_DEBUG, "!  destroying connection!\n");
519     GMC_destroy (c);
520     return;
521   }
522   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
523   switch (type)
524   {
525     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
526       fc->last_pid_sent++;
527       LOG (GNUNET_ERROR_TYPE_DEBUG, "!  Q_N- %p %u\n", fc, fc->queue_n);
528       fc->queue_n--;
529       LOG (GNUNET_ERROR_TYPE_DEBUG,
530            "!   accounting pid %u\n",
531            fc->last_pid_sent);
532       GMC_send_ack (c, fwd, GNUNET_NO);
533       break;
534
535     case GNUNET_MESSAGE_TYPE_MESH_POLL:
536       fc->poll_msg = NULL;
537       break;
538
539     case GNUNET_MESSAGE_TYPE_MESH_ACK:
540       fc->ack_msg = NULL;
541       break;
542
543     default:
544       break;
545   }
546   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  message sent!\n");
547
548   if (NULL == c->perf)
549     return; /* Only endpoints are interested in timing. */
550
551   p = c->perf;
552   usecsperbyte = ((double) wait.rel_value_us) / size;
553   if (p->size == AVG_MSGS)
554   {
555     /* Array is full. Substract oldest value, add new one and store. */
556     p->avg -= (p->usecsperbyte[p->idx] / AVG_MSGS);
557     p->usecsperbyte[p->idx] = usecsperbyte;
558     p->avg += (p->usecsperbyte[p->idx] / AVG_MSGS);
559   }
560   else
561   {
562     /* Array not yet full. Add current value to avg and store. */
563     p->usecsperbyte[p->idx] = usecsperbyte;
564     p->avg *= p->size;
565     p->avg += p->usecsperbyte[p->idx];
566     p->size++;
567     p->avg /= p->size;
568   }
569   p->idx = (p->idx + 1) % AVG_MSGS;
570 }
571
572
573 /**
574  * Get the previous hop in a connection
575  *
576  * @param c Connection.
577  *
578  * @return Previous peer in the connection.
579  */
580 static struct MeshPeer *
581 get_prev_hop (const struct MeshConnection *c)
582 {
583   GNUNET_PEER_Id id;
584
585   LOG (GNUNET_ERROR_TYPE_DEBUG, "Get prev hop, own pos %u\n", c->own_pos);
586   if (0 == c->own_pos || c->path->length < 2)
587     id = c->path->peers[0];
588   else
589     id = c->path->peers[c->own_pos - 1];
590
591   return GMP_get_short (id);
592 }
593
594
595 /**
596  * Get the next hop in a connection
597  *
598  * @param c Connection.
599  *
600  * @return Next peer in the connection.
601  */
602 static struct MeshPeer *
603 get_next_hop (const struct MeshConnection *c)
604 {
605   GNUNET_PEER_Id id;
606
607   if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
608     id = c->path->peers[c->path->length - 1];
609   else
610     id = c->path->peers[c->own_pos + 1];
611
612   return GMP_get_short (id);
613 }
614
615
616 /**
617  * Get the hop in a connection.
618  *
619  * @param c Connection.
620  * @param fwd Next hop?
621  *
622  * @return Next peer in the connection.
623  */
624 static struct MeshPeer *
625 get_hop (struct MeshConnection *c, int fwd)
626 {
627   if (fwd)
628     return get_next_hop (c);
629   return get_prev_hop (c);
630 }
631
632
633 /**
634  * Is traffic coming from this sender 'FWD' traffic?
635  *
636  * @param c Connection to check.
637  * @param sender Peer identity of neighbor.
638  *
639  * @return #GNUNET_YES in case the sender is the 'prev' hop and therefore
640  *         the traffic is 'FWD'.
641  *         #GNUNET_NO for BCK.
642  *         #GNUNET_SYSERR for errors.
643  */
644 static int 
645 is_fwd (const struct MeshConnection *c,
646         const struct GNUNET_PeerIdentity *sender)
647 {
648   GNUNET_PEER_Id id;
649
650   id = GNUNET_PEER_search (sender);
651   if (GMP_get_short_id (get_prev_hop (c)) == id)
652     return GNUNET_YES;
653
654   if (GMP_get_short_id (get_next_hop (c)) == id)
655     return GNUNET_NO;
656
657   GNUNET_break (0);
658   return GNUNET_SYSERR;
659 }
660
661
662 /**
663  * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
664  * or a first CONNECTION_ACK directed to us.
665  *
666  * @param connection Connection to confirm.
667  * @param fwd Should we send it FWD? (root->dest)
668  *            (First (~SYNACK) goes BCK, second (~ACK) goes FWD)
669  */
670 static void
671 send_connection_ack (struct MeshConnection *connection, int fwd)
672 {
673   struct MeshTunnel3 *t;
674
675   t = connection->t;
676   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send connection %s ACK\n",
677        !fwd ? "FWD" : "BCK");
678   GMP_queue_add (get_hop (connection, fwd), NULL,
679                  GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
680                  sizeof (struct GNUNET_MESH_ConnectionACK),
681                  connection, fwd, &message_sent, NULL);
682   connection->pending_messages++;
683   if (MESH_TUNNEL3_NEW == GMT_get_state (t))
684     GMT_change_state (t, MESH_TUNNEL3_WAITING);
685   if (MESH_CONNECTION_READY != connection->state)
686     connection_change_state (connection, MESH_CONNECTION_SENT);
687 }
688
689
690 /**
691  * Send a notification that a connection is broken.
692  *
693  * @param c Connection that is broken.
694  * @param id1 Peer that has disconnected.
695  * @param id2 Peer that has disconnected.
696  * @param fwd Direction towards which to send it.
697  */
698 static void
699 send_broken (struct MeshConnection *c,
700              const struct GNUNET_PeerIdentity *id1,
701              const struct GNUNET_PeerIdentity *id2,
702              int fwd)
703 {
704   struct GNUNET_MESH_ConnectionBroken msg;
705
706   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
707   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
708   msg.cid = c->id;
709   msg.peer1 = *id1;
710   msg.peer2 = *id2;
711   GMC_send_prebuilt_message (&msg.header, c, fwd, NULL, NULL);
712 }
713
714
715
716 /**
717  * Send keepalive packets for a connection.
718  *
719  * @param c Connection to keep alive..
720  * @param fwd Is this a FWD keepalive? (owner -> dest).
721  */
722 static void
723 connection_keepalive (struct MeshConnection *c, int fwd)
724 {
725   struct GNUNET_MESH_ConnectionKeepAlive *msg;
726   size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
727   char cbuf[size];
728   uint16_t type;
729
730   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
731                GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
732
733   LOG (GNUNET_ERROR_TYPE_DEBUG,
734        "sending %s keepalive for connection %s]\n",
735        fwd ? "FWD" : "BCK", GMC_2s (c));
736
737   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
738   msg->header.size = htons (size);
739   msg->header.type = htons (type);
740   msg->cid = c->id;
741
742   GMC_send_prebuilt_message (&msg->header, c, fwd, NULL, NULL);
743 }
744
745
746 /**
747  * Send CONNECTION_{CREATE/ACK} packets for a connection.
748  *
749  * @param c Connection for which to send the message.
750  * @param fwd If #GNUNET_YES, send CREATE, otherwise send ACK.
751  */
752 static void
753 connection_recreate (struct MeshConnection *c, int fwd)
754 {
755   LOG (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
756   if (fwd)
757     GMC_send_create (c);
758   else
759     send_connection_ack (c, GNUNET_NO);
760 }
761
762
763 /**
764  * Generic connection timer management.
765  * Depending on the role of the peer in the connection will send the
766  * appropriate message (build or keepalive)
767  *
768  * @param c Conncetion to maintain.
769  * @param fwd Is FWD?
770  */
771 static void
772 connection_maintain (struct MeshConnection *c, int fwd)
773 {
774   if (MESH_TUNNEL3_SEARCHING == GMT_get_state (c->t))
775   {
776     /* TODO DHT GET with RO_BART */
777     return;
778   }
779   switch (c->state)
780   {
781     case MESH_CONNECTION_NEW:
782       GNUNET_break (0);
783     case MESH_CONNECTION_SENT:
784       connection_recreate (c, fwd);
785       break;
786     case MESH_CONNECTION_READY:
787       connection_keepalive (c, fwd);
788       break;
789     default:
790       break;
791   }
792 }
793
794
795 static void
796 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
797 {
798   struct MeshConnection *c = cls;
799
800   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
801   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
802     return;
803
804   connection_maintain (c, GNUNET_YES);
805   c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
806                                                           &connection_fwd_keepalive,
807                                                           c);
808 }
809
810
811 static void
812 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
813 {
814   struct MeshConnection *c = cls;
815
816   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
817   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
818     return;
819
820   connection_maintain (c, GNUNET_NO);
821   c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
822                                                           &connection_bck_keepalive,
823                                                           c);
824 }
825
826
827 /**
828  * @brief Re-initiate traffic on this connection if necessary.
829  *
830  * Check if there is traffic queued towards this peer
831  * and the core transmit handle is NULL (traffic was stalled).
832  * If so, call core tmt rdy.
833  *
834  * @param c Connection on which initiate traffic.
835  * @param fwd Is this about fwd traffic?
836  */
837 static void
838 connection_unlock_queue (struct MeshConnection *c, int fwd)
839 {
840   struct MeshPeer *peer;
841
842   LOG (GNUNET_ERROR_TYPE_DEBUG,
843               "connection_unlock_queue %s on %s\n",
844               fwd ? "FWD" : "BCK", GMC_2s (c));
845
846   if (GMC_is_terminal (c, fwd))
847   {
848     LOG (GNUNET_ERROR_TYPE_DEBUG, " is terminal!\n");
849     return;
850   }
851
852   peer = get_hop (c, fwd);
853   GMP_queue_unlock (peer, c);
854 }
855
856
857 /**
858  * Cancel all transmissions that belong to a certain connection.
859  * 
860  * If the connection is scheduled for destruction and no more messages are left,
861  * the connection will be destroyed by the continuation call.
862  *
863  * @param c Connection which to cancel. Might be destroyed during this call.
864  * @param fwd Cancel fwd traffic?
865  */
866 static void
867 connection_cancel_queues (struct MeshConnection *c, int fwd)
868 {
869   struct MeshFlowControl *fc;
870   struct MeshPeer *peer;
871
872   if (NULL == c)
873   {
874     GNUNET_break (0);
875     return;
876   }
877
878   fc = fwd ? &c->fwd_fc : &c->bck_fc;
879   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
880   {
881     GNUNET_SCHEDULER_cancel (fc->poll_task);
882     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
883   }
884   peer = get_hop (c, fwd);
885   GMP_queue_cancel (peer, c);
886 }
887
888
889 /**
890  * Function called if a connection has been stalled for a while,
891  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
892  *
893  * @param cls Closure (poll ctx).
894  * @param tc TaskContext.
895  */
896 static void
897 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
898
899
900 /**
901  * Callback called when a queued POLL message is sent.
902  *
903  * @param cls Closure (FC).
904  * @param c Connection this message was on.
905  * @param type Type of message sent.
906  * @param fwd Was this a FWD going message?
907  * @param size Size of the message.
908  */
909 static void
910 poll_sent (void *cls,
911            struct MeshConnection *c,
912            struct MeshConnectionQueue *q,
913            uint16_t type, int fwd, size_t size)
914 {
915   struct MeshFlowControl *fc = cls;
916
917   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL sent, scheduling new one!\n");
918   fc->poll_msg = NULL;
919   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
920   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
921                                                 &connection_poll, fc);
922 }
923
924 /**
925  * Function called if a connection has been stalled for a while,
926  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
927  *
928  * @param cls Closure (poll ctx).
929  * @param tc TaskContext.
930  */
931 static void
932 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
933 {
934   struct MeshFlowControl *fc = cls;
935   struct GNUNET_MESH_Poll msg;
936   struct MeshConnection *c;
937
938   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
939   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
940   {
941     return;
942   }
943
944   c = fc->c;
945   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
946   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** connection [%s]\n", GMC_2s (c));
947   LOG (GNUNET_ERROR_TYPE_DEBUG, " ***   %s\n",
948        fc == &c->fwd_fc ? "FWD" : "BCK");
949
950   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
951   msg.header.size = htons (sizeof (msg));
952   msg.pid = htonl (fc->last_pid_sent);
953   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** last pid sent: %u!\n", fc->last_pid_sent);
954   fc->poll_msg = GMC_send_prebuilt_message (&msg.header, c, fc == &c->fwd_fc,
955                                             &poll_sent, fc);
956 }
957
958
959 /**
960  * Timeout function due to lack of keepalive/traffic from the owner.
961  * Destroys connection if called.
962  *
963  * @param cls Closure (connection to destroy).
964  * @param tc TaskContext.
965  */
966 static void
967 connection_fwd_timeout (void *cls,
968                         const struct GNUNET_SCHEDULER_TaskContext *tc)
969 {
970   struct MeshConnection *c = cls;
971
972   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
973   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
974     return;
975   LOG (GNUNET_ERROR_TYPE_DEBUG,
976               "Connection %s[%X] FWD timed out. Destroying.\n",
977               GMT_2s (c->t),
978               c->id);
979
980   if (GMC_is_origin (c, GNUNET_YES)) /* If local, leave. */
981     return;
982
983   GMC_destroy (c);
984 }
985
986
987 /**
988  * Timeout function due to lack of keepalive/traffic from the destination.
989  * Destroys connection if called.
990  *
991  * @param cls Closure (connection to destroy).
992  * @param tc TaskContext
993  */
994 static void
995 connection_bck_timeout (void *cls,
996                         const struct GNUNET_SCHEDULER_TaskContext *tc)
997 {
998   struct MeshConnection *c = cls;
999
1000   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
1001   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1002     return;
1003
1004   LOG (GNUNET_ERROR_TYPE_DEBUG,
1005               "Connection %s[%X] FWD timed out. Destroying.\n",
1006               GMT_2s (c->t), c->id);
1007
1008   if (GMC_is_origin (c, GNUNET_NO)) /* If local, leave. */
1009     return;
1010
1011   GMC_destroy (c);
1012 }
1013
1014
1015 /**
1016  * Resets the connection timeout task, some other message has done the
1017  * task's job.
1018  * - For the first peer on the direction this means to send
1019  *   a keepalive or a path confirmation message (either create or ACK).
1020  * - For all other peers, this means to destroy the connection,
1021  *   due to lack of activity.
1022  * Starts the tiemout if no timeout was running (connection just created).
1023  *
1024  * @param c Connection whose timeout to reset.
1025  * @param fwd Is this forward?
1026  *
1027  * TODO use heap to improve efficiency of scheduler.
1028  */
1029 static void
1030 connection_reset_timeout (struct MeshConnection *c, int fwd)
1031 {
1032   GNUNET_SCHEDULER_TaskIdentifier *ti;
1033   GNUNET_SCHEDULER_Task f;
1034
1035   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
1036
1037   if (GNUNET_SCHEDULER_NO_TASK != *ti)
1038     GNUNET_SCHEDULER_cancel (*ti);
1039
1040   if (GMC_is_origin (c, fwd)) /* Endpoint */
1041   {
1042     f  = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
1043     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
1044   }
1045   else /* Relay */
1046   {
1047     struct GNUNET_TIME_Relative delay;
1048
1049     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
1050     f  = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
1051     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
1052   }
1053 }
1054
1055
1056 /**
1057  * Add the connection to the list of both neighbors.
1058  *
1059  * @param c Connection.
1060  */
1061 static void
1062 register_neighbors (struct MeshConnection *c)
1063 {
1064   struct MeshPeer *peer;
1065
1066   peer = get_next_hop (c);
1067   if (GNUNET_NO == GMP_is_neighbor (peer))
1068   {
1069     GMC_destroy (c);
1070     return;
1071   }
1072   GMP_add_connection (peer, c);
1073   peer = get_prev_hop (c);
1074   if (GNUNET_NO == GMP_is_neighbor (peer))
1075   {
1076     GMC_destroy (c);
1077     return;
1078   }
1079   GMP_add_connection (peer, c);
1080 }
1081
1082
1083 /**
1084  * Remove the connection from the list of both neighbors.
1085  *
1086  * @param c Connection.
1087  */
1088 static void
1089 unregister_neighbors (struct MeshConnection *c)
1090 {
1091   struct MeshPeer *peer;
1092
1093   peer = get_next_hop (c);
1094   GMP_remove_connection (peer, c);
1095
1096   peer = get_prev_hop (c);
1097   GMP_remove_connection (peer, c);
1098
1099 }
1100
1101
1102 /**
1103  * Bind the connection to the peer and the tunnel to that peer.
1104  *
1105  * If the peer has no tunnel, create one. Update tunnel and connection
1106  * data structres to reflect new status.
1107  *
1108  * @param c Connection.
1109  * @param peer Peer.
1110  */
1111 static void
1112 add_to_peer (struct MeshConnection *c, struct MeshPeer *peer)
1113 {
1114   GMP_add_tunnel (peer);
1115   c->t = GMP_get_tunnel (peer);
1116   GMT_add_connection (c->t, c);
1117 }
1118
1119 /******************************************************************************/
1120 /********************************    API    ***********************************/
1121 /******************************************************************************/
1122
1123 /**
1124  * Core handler for connection creation.
1125  *
1126  * @param cls Closure (unused).
1127  * @param peer Sender (neighbor).
1128  * @param message Message.
1129  *
1130  * @return GNUNET_OK to keep the connection open,
1131  *         GNUNET_SYSERR to close it (signal serious error)
1132  */
1133 int
1134 GMC_handle_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1135                    const struct GNUNET_MessageHeader *message)
1136 {
1137   struct GNUNET_MESH_ConnectionCreate *msg;
1138   struct GNUNET_PeerIdentity *id;
1139   struct GNUNET_HashCode *cid;
1140   struct MeshPeerPath *path;
1141   struct MeshPeer *dest_peer;
1142   struct MeshPeer *orig_peer;
1143   struct MeshConnection *c;
1144   unsigned int own_pos;
1145   uint16_t size;
1146   uint16_t i;
1147
1148   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1149   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
1150
1151   /* Check size */
1152   size = ntohs (message->size);
1153   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
1154   {
1155     GNUNET_break_op (0);
1156     return GNUNET_OK;
1157   }
1158
1159   /* Calculate hops */
1160   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
1161   if (size % sizeof (struct GNUNET_PeerIdentity))
1162   {
1163     GNUNET_break_op (0);
1164     return GNUNET_OK;
1165   }
1166   size /= sizeof (struct GNUNET_PeerIdentity);
1167   if (1 > size)
1168   {
1169     GNUNET_break_op (0);
1170     return GNUNET_OK;
1171   }
1172   LOG (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
1173
1174   /* Get parameters */
1175   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
1176   cid = &msg->cid;
1177   id = (struct GNUNET_PeerIdentity *) &msg[1];
1178   LOG (GNUNET_ERROR_TYPE_DEBUG,
1179               "    connection %s (%s).\n",
1180               GNUNET_h2s (cid), GNUNET_i2s (id));
1181
1182   /* Create connection */
1183   c = connection_get (cid);
1184   if (NULL == c)
1185   {
1186     /* Create path */
1187     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
1188     path = path_new (size);
1189     own_pos = 0;
1190     for (i = 0; i < size; i++)
1191     {
1192       LOG (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
1193                   GNUNET_i2s (&id[i]));
1194       path->peers[i] = GNUNET_PEER_intern (&id[i]);
1195       if (path->peers[i] == myid)
1196         own_pos = i;
1197     }
1198     if (own_pos == 0 && path->peers[own_pos] != myid)
1199     {
1200       /* create path: self not found in path through self */
1201       GNUNET_break_op (0);
1202       path_destroy (path);
1203       return GNUNET_OK;
1204     }
1205     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
1206     GMP_add_path_to_all (path, GNUNET_NO);
1207         LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
1208     c = GMC_new (cid, NULL, path_duplicate (path), own_pos);
1209     if (NULL == c)
1210       return GNUNET_OK;
1211     connection_reset_timeout (c, GNUNET_YES);
1212   }
1213   else
1214   {
1215     path = NULL;
1216   }
1217   if (MESH_CONNECTION_NEW == c->state)
1218     connection_change_state (c, MESH_CONNECTION_SENT);
1219
1220   /* Remember peers */
1221   dest_peer = GMP_get (&id[size - 1]);
1222   orig_peer = GMP_get (&id[0]);
1223
1224   /* Is it a connection to us? */
1225   if (c->own_pos == size - 1)
1226   {
1227     LOG (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
1228     GMP_add_path_to_origin (orig_peer, path, GNUNET_YES);
1229
1230     add_to_peer (c, orig_peer);
1231     if (MESH_TUNNEL3_NEW == GMT_get_state (c->t))
1232       GMT_change_state (c->t,  MESH_TUNNEL3_WAITING);
1233
1234     send_connection_ack (c, GNUNET_NO);
1235     if (MESH_CONNECTION_SENT == c->state)
1236       connection_change_state (c, MESH_CONNECTION_ACK);
1237
1238     /* Keep tunnel alive in direction dest->owner*/
1239     connection_reset_timeout (c, GNUNET_NO);
1240   }
1241   else
1242   {
1243     /* It's for somebody else! Retransmit. */
1244     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
1245     GMP_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
1246     GMP_add_path_to_origin (orig_peer, path, GNUNET_NO);
1247     GMC_send_prebuilt_message (message, c, GNUNET_YES, NULL, NULL);
1248   }
1249   return GNUNET_OK;
1250 }
1251
1252
1253 /**
1254  * Core handler for path confirmations.
1255  *
1256  * @param cls closure
1257  * @param message message
1258  * @param peer peer identity this notification is about
1259  *
1260  * @return GNUNET_OK to keep the connection open,
1261  *         GNUNET_SYSERR to close it (signal serious error)
1262  */
1263 int
1264 GMC_handle_confirm (void *cls, const struct GNUNET_PeerIdentity *peer,
1265                     const struct GNUNET_MessageHeader *message)
1266 {
1267   struct GNUNET_MESH_ConnectionACK *msg;
1268   struct MeshConnection *c;
1269   struct MeshPeerPath *p;
1270   struct MeshPeer *pi;
1271   int fwd;
1272
1273   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1274   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
1275   msg = (struct GNUNET_MESH_ConnectionACK *) message;
1276   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
1277               GNUNET_h2s (&msg->cid));
1278   c = connection_get (&msg->cid);
1279   if (NULL == c)
1280   {
1281     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1282                               1, GNUNET_NO);
1283     LOG (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
1284     return GNUNET_OK;
1285   }
1286
1287
1288   LOG (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
1289               GNUNET_i2s (peer));
1290   pi = GMP_get (peer);
1291   if (get_next_hop (c) == pi)
1292   {
1293     LOG (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
1294     fwd = GNUNET_NO;
1295     if (MESH_CONNECTION_SENT == c->state)
1296       connection_change_state (c, MESH_CONNECTION_ACK);
1297   }
1298   else if (get_prev_hop (c) == pi)
1299   {
1300     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
1301     fwd = GNUNET_YES;
1302     connection_change_state (c, MESH_CONNECTION_READY);
1303   }
1304   else
1305   {
1306     GNUNET_break_op (0);
1307     return GNUNET_OK;
1308   }
1309   connection_reset_timeout (c, fwd);
1310
1311   /* Add path to peers? */
1312   p = c->path;
1313   if (NULL != p)
1314   {
1315     GMP_add_path_to_all (p, GNUNET_YES);
1316   }
1317   else
1318   {
1319     GNUNET_break (0);
1320   }
1321
1322   /* Message for us as creator? */
1323   if (GMC_is_origin (c, GNUNET_YES))
1324   {
1325     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
1326     connection_change_state (c, MESH_CONNECTION_READY);
1327     if (MESH_TUNNEL3_WAITING == GMT_get_state (c->t))
1328       GMT_change_state (c->t, MESH_TUNNEL3_READY);
1329     send_connection_ack (c, GNUNET_YES);
1330     return GNUNET_OK;
1331   }
1332
1333   /* Message for us as destination? */
1334   if (GMC_is_terminal (c, GNUNET_YES))
1335   {
1336     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
1337     connection_change_state (c, MESH_CONNECTION_READY);
1338     if (MESH_TUNNEL3_WAITING == GMT_get_state (c->t))
1339       GMT_change_state (c->t, MESH_TUNNEL3_READY);
1340     return GNUNET_OK;
1341   }
1342
1343   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1344   GMC_send_prebuilt_message (message, c, fwd, NULL, NULL);
1345   return GNUNET_OK;
1346 }
1347
1348
1349 /**
1350  * Core handler for notifications of broken paths
1351  *
1352  * @param cls Closure (unused).
1353  * @param id Peer identity of sending neighbor.
1354  * @param message Message.
1355  *
1356  * @return GNUNET_OK to keep the connection open,
1357  *         GNUNET_SYSERR to close it (signal serious error)
1358  */
1359 int
1360 GMC_handle_broken (void* cls,
1361                    const struct GNUNET_PeerIdentity* id,
1362                    const struct GNUNET_MessageHeader* message)
1363 {
1364   struct GNUNET_MESH_ConnectionBroken *msg;
1365   struct MeshConnection *c;
1366   int fwd;
1367
1368   LOG (GNUNET_ERROR_TYPE_DEBUG,
1369               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (id));
1370   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
1371   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1372               GNUNET_i2s (&msg->peer1));
1373   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1374               GNUNET_i2s (&msg->peer2));
1375   c = connection_get (&msg->cid);
1376   if (NULL == c)
1377   {
1378     GNUNET_break_op (0);
1379     return GNUNET_OK;
1380   }
1381
1382   fwd = is_fwd (c, id);
1383   connection_cancel_queues (c, !fwd);
1384   if (GMC_is_terminal (c, fwd))
1385   {
1386     if (0 < c->pending_messages)
1387       c->destroy = GNUNET_YES;
1388     else
1389       GMC_destroy (c);
1390   }
1391   else
1392   {
1393     GMC_send_prebuilt_message (message, c, fwd, NULL, NULL);
1394     c->destroy = GNUNET_YES;
1395   }
1396
1397   return GNUNET_OK;
1398
1399 }
1400
1401
1402 /**
1403  * Core handler for tunnel destruction
1404  *
1405  * @param cls Closure (unused).
1406  * @param peer Peer identity of sending neighbor.
1407  * @param message Message.
1408  *
1409  * @return GNUNET_OK to keep the connection open,
1410  *         GNUNET_SYSERR to close it (signal serious error)
1411  */
1412 int
1413 GMC_handle_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
1414                     const struct GNUNET_MessageHeader *message)
1415 {
1416   struct GNUNET_MESH_ConnectionDestroy *msg;
1417   struct MeshConnection *c;
1418   int fwd;
1419
1420   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
1421   LOG (GNUNET_ERROR_TYPE_DEBUG,
1422               "Got a CONNECTION DESTROY message from %s\n",
1423               GNUNET_i2s (peer));
1424   LOG (GNUNET_ERROR_TYPE_DEBUG,
1425               "  for connection %s\n",
1426               GNUNET_h2s (&msg->cid));
1427   c = connection_get (&msg->cid);
1428   if (NULL == c)
1429   {
1430     /* Probably already got the message from another path,
1431      * destroyed the tunnel and retransmitted to children.
1432      * Safe to ignore.
1433      */
1434     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
1435                               1, GNUNET_NO);
1436     return GNUNET_OK;
1437   }
1438   fwd = is_fwd (c, peer);
1439   if (GNUNET_SYSERR == fwd)
1440   {
1441     GNUNET_break_op (0);
1442     return GNUNET_OK;
1443   }
1444   GMC_send_prebuilt_message (message, c, fwd, NULL, NULL);
1445   c->destroy = GNUNET_YES;
1446
1447   return GNUNET_OK;
1448 }
1449
1450 /**
1451  * Generic handler for mesh network encrypted traffic.
1452  *
1453  * @param peer Peer identity this notification is about.
1454  * @param msg Encrypted message.
1455  *
1456  * @return GNUNET_OK to keep the connection open,
1457  *         GNUNET_SYSERR to close it (signal serious error)
1458  */
1459 static int
1460 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
1461                        const struct GNUNET_MESH_Encrypted *msg)
1462 {
1463   struct MeshConnection *c;
1464   struct MeshPeer *neighbor;
1465   struct MeshFlowControl *fc;
1466   GNUNET_PEER_Id peer_id;
1467   uint32_t pid;
1468   uint32_t ttl;
1469   uint16_t type;
1470   size_t size;
1471   int fwd;
1472
1473   /* Check size */
1474   size = ntohs (msg->header.size);
1475   if (size <
1476       sizeof (struct GNUNET_MESH_Encrypted) +
1477       sizeof (struct GNUNET_MessageHeader))
1478   {
1479     GNUNET_break_op (0);
1480     return GNUNET_OK;
1481   }
1482   type = ntohs (msg->header.type);
1483   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1484   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
1485               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
1486
1487   /* Check connection */
1488   c = connection_get (&msg->cid);
1489   if (NULL == c)
1490   {
1491     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
1492     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
1493     return GNUNET_OK;
1494   }
1495
1496   /* Check if origin is as expected */
1497   neighbor = get_prev_hop (c);
1498   peer_id = GNUNET_PEER_search (peer);
1499   if (peer_id == GMP_get_short_id (neighbor))
1500   {
1501     fwd = GNUNET_YES;
1502   }
1503   else
1504   {
1505     neighbor = get_next_hop (c);
1506     if (peer_id == GMP_get_short_id (neighbor))
1507     {
1508       fwd = GNUNET_NO;
1509     }
1510     else
1511     {
1512       /* Unexpected peer sending traffic on a connection. */
1513       GNUNET_break_op (0);
1514       return GNUNET_OK;
1515     }
1516   }
1517
1518   /* Check PID */
1519   fc = fwd ? &c->bck_fc : &c->fwd_fc;
1520   pid = ntohl (msg->pid);
1521   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
1522   {
1523     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
1524     LOG (GNUNET_ERROR_TYPE_DEBUG,
1525                 "WARNING Received PID %u, (prev %u), ACK %u\n",
1526                 pid, fc->last_pid_recv, fc->last_ack_sent);
1527     return GNUNET_OK;
1528   }
1529   if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
1530   {
1531     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
1532     LOG (GNUNET_ERROR_TYPE_DEBUG,
1533                 " Pid %u not expected (%u+), dropping!\n",
1534                 pid, fc->last_pid_recv + 1);
1535     return GNUNET_OK;
1536   }
1537   if (MESH_CONNECTION_SENT == c->state || MESH_CONNECTION_ACK == c->state)
1538     connection_change_state (c, MESH_CONNECTION_READY);
1539   connection_reset_timeout (c, fwd);
1540   fc->last_pid_recv = pid;
1541
1542   /* Is this message for us? */
1543   if (GMC_is_terminal (c, fwd))
1544   {
1545     /* TODO signature verification */
1546     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
1547     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
1548
1549     if (NULL == c->t)
1550     {
1551       GNUNET_break (0);
1552       return GNUNET_OK;
1553     }
1554     fc->last_pid_recv = pid;
1555     GMT_handle_encrypted (c->t, msg);
1556     GMC_send_ack (c, fwd, GNUNET_NO);
1557     return GNUNET_OK;
1558   }
1559
1560   /* Message not for us: forward to next hop */
1561   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1562   ttl = ntohl (msg->ttl);
1563   LOG (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
1564   if (ttl == 0)
1565   {
1566     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
1567     LOG (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
1568     GMC_send_ack (c, fwd, GNUNET_NO);
1569     return GNUNET_OK;
1570   }
1571
1572   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
1573   GMC_send_prebuilt_message (&msg->header, c, fwd, NULL, NULL);
1574
1575   return GNUNET_OK;
1576 }
1577
1578 /**
1579  * Generic handler for mesh network encrypted traffic.
1580  *
1581  * @param peer Peer identity this notification is about.
1582  * @param msg Encrypted message.
1583  *
1584  * @return GNUNET_OK to keep the connection open,
1585  *         GNUNET_SYSERR to close it (signal serious error)
1586  */
1587 static int
1588 handle_mesh_kx (const struct GNUNET_PeerIdentity *peer,
1589                 const struct GNUNET_MESH_KX *msg)
1590 {
1591   struct MeshConnection *c;
1592   struct MeshPeer *neighbor;
1593   GNUNET_PEER_Id peer_id;
1594   size_t size;
1595   uint16_t type;
1596   int fwd;
1597
1598   /* Check size */
1599   size = ntohs (msg->header.size);
1600   if (size <
1601       sizeof (struct GNUNET_MESH_Encrypted) +
1602       sizeof (struct GNUNET_MessageHeader))
1603   {
1604     GNUNET_break_op (0);
1605     return GNUNET_OK;
1606   }
1607   type = ntohs (msg->header.type);
1608   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1609   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
1610               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
1611
1612   /* Check connection */
1613   c = connection_get (&msg->cid);
1614   if (NULL == c)
1615   {
1616     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
1617     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
1618     return GNUNET_OK;
1619   }
1620
1621   /* Check if origin is as expected */
1622   neighbor = get_prev_hop (c);
1623   peer_id = GNUNET_PEER_search (peer);
1624   if (peer_id == GMP_get_short_id (neighbor))
1625   {
1626     fwd = GNUNET_YES;
1627   }
1628   else
1629   {
1630     neighbor = get_next_hop (c);
1631     if (peer_id == GMP_get_short_id (neighbor))
1632     {
1633       fwd = GNUNET_NO;
1634     }
1635     else
1636     {
1637       /* Unexpected peer sending traffic on a connection. */
1638       GNUNET_break_op (0);
1639       return GNUNET_OK;
1640     }
1641   }
1642
1643   /* Count as connection confirmation. */
1644   if (MESH_CONNECTION_SENT == c->state || MESH_CONNECTION_ACK == c->state)
1645     connection_change_state (c, MESH_CONNECTION_READY);
1646   connection_reset_timeout (c, fwd);
1647   if (NULL != c->t)
1648   {
1649     if (MESH_TUNNEL3_WAITING == GMT_get_state (c->t))
1650       GMT_change_state (c->t, MESH_TUNNEL3_READY);
1651   }
1652
1653   /* Is this message for us? */
1654   if (GMC_is_terminal (c, fwd))
1655   {
1656     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
1657     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
1658     if (NULL == c->t)
1659     {
1660       GNUNET_break (0);
1661       return GNUNET_OK;
1662     }
1663     GMT_handle_kx (c->t, &msg[1].header);
1664     return GNUNET_OK;
1665   }
1666
1667   /* Message not for us: forward to next hop */
1668   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1669   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
1670   GMC_send_prebuilt_message (&msg->header, c, fwd, NULL, NULL);
1671
1672   return GNUNET_OK;
1673 }
1674
1675
1676 /**
1677  * Core handler for encrypted mesh network traffic (channel mgmt, data).
1678  *
1679  * @param cls Closure (unused).
1680  * @param message Message received.
1681  * @param peer Peer who sent the message.
1682  *
1683  * @return GNUNET_OK to keep the connection open,
1684  *         GNUNET_SYSERR to close it (signal serious error)
1685  */
1686 int
1687 GMC_handle_encrypted (void *cls, const struct GNUNET_PeerIdentity *peer,
1688                       const struct GNUNET_MessageHeader *message)
1689 {
1690   return handle_mesh_encrypted (peer,
1691                                 (struct GNUNET_MESH_Encrypted *)message);
1692 }
1693
1694
1695 /**
1696  * Core handler for key exchange traffic (ephemeral key, ping, pong).
1697  *
1698  * @param cls Closure (unused).
1699  * @param message Message received.
1700  * @param peer Peer who sent the message.
1701  *
1702  * @return GNUNET_OK to keep the connection open,
1703  *         GNUNET_SYSERR to close it (signal serious error)
1704  */
1705 int
1706 GMC_handle_kx (void *cls, const struct GNUNET_PeerIdentity *peer,
1707                const struct GNUNET_MessageHeader *message)
1708 {
1709   return handle_mesh_kx (peer,
1710                          (struct GNUNET_MESH_KX *) message);
1711 }
1712
1713
1714 /**
1715  * Core handler for mesh network traffic point-to-point acks.
1716  *
1717  * @param cls closure
1718  * @param message message
1719  * @param peer peer identity this notification is about
1720  *
1721  * @return GNUNET_OK to keep the connection open,
1722  *         GNUNET_SYSERR to close it (signal serious error)
1723  */
1724 int
1725 GMC_handle_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
1726                 const struct GNUNET_MessageHeader *message)
1727 {
1728   struct GNUNET_MESH_ACK *msg;
1729   struct MeshConnection *c;
1730   struct MeshFlowControl *fc;
1731   GNUNET_PEER_Id id;
1732   uint32_t ack;
1733   int fwd;
1734
1735   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1736   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
1737               GNUNET_i2s (peer));
1738   msg = (struct GNUNET_MESH_ACK *) message;
1739
1740   c = connection_get (&msg->cid);
1741
1742   if (NULL == c)
1743   {
1744     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
1745                               GNUNET_NO);
1746     return GNUNET_OK;
1747   }
1748
1749   /* Is this a forward or backward ACK? */
1750   id = GNUNET_PEER_search (peer);
1751   if (GMP_get_short_id (get_next_hop (c)) == id)
1752   {
1753     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
1754     fc = &c->fwd_fc;
1755     fwd = GNUNET_YES;
1756   }
1757   else if (GMP_get_short_id (get_prev_hop (c)) == id)
1758   {
1759     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
1760     fc = &c->bck_fc;
1761     fwd = GNUNET_NO;
1762   }
1763   else
1764   {
1765     GNUNET_break_op (0);
1766     return GNUNET_OK;
1767   }
1768
1769   ack = ntohl (msg->ack);
1770   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u (was %u)\n",
1771               ack, fc->last_ack_recv);
1772   if (GMC_is_pid_bigger (ack, fc->last_ack_recv))
1773     fc->last_ack_recv = ack;
1774
1775   /* Cancel polling if the ACK is big enough. */
1776   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
1777       GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
1778   {
1779     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
1780     GNUNET_SCHEDULER_cancel (fc->poll_task);
1781     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1782     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
1783   }
1784
1785   connection_unlock_queue (c, fwd);
1786
1787   return GNUNET_OK;
1788 }
1789
1790
1791 /**
1792  * Core handler for mesh network traffic point-to-point ack polls.
1793  *
1794  * @param cls closure
1795  * @param message message
1796  * @param peer peer identity this notification is about
1797  *
1798  * @return GNUNET_OK to keep the connection open,
1799  *         GNUNET_SYSERR to close it (signal serious error)
1800  */
1801 int
1802 GMC_handle_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
1803                  const struct GNUNET_MessageHeader *message)
1804 {
1805   struct GNUNET_MESH_Poll *msg;
1806   struct MeshConnection *c;
1807   struct MeshFlowControl *fc;
1808   GNUNET_PEER_Id id;
1809   uint32_t pid;
1810   int fwd;
1811
1812   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1813   LOG (GNUNET_ERROR_TYPE_DEBUG,
1814        "Got a POLL packet from %s!\n",
1815        GNUNET_i2s (peer));
1816
1817   msg = (struct GNUNET_MESH_Poll *) message;
1818
1819   c = connection_get (&msg->cid);
1820
1821   if (NULL == c)
1822   {
1823     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
1824                               GNUNET_NO);
1825     GNUNET_break_op (0);
1826     return GNUNET_OK;
1827   }
1828
1829   /* Is this a forward or backward ACK?
1830    * Note: a poll should never be needed in a loopback case,
1831    * since there is no possiblility of packet loss there, so
1832    * this way of discerining FWD/BCK should not be a problem.
1833    */
1834   id = GNUNET_PEER_search (peer);
1835   if (GMP_get_short_id (get_next_hop (c)) == id)
1836   {
1837     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
1838     fc = &c->fwd_fc;
1839   }
1840   else if (GMP_get_short_id (get_prev_hop (c)) == id)
1841   {
1842     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
1843     fc = &c->bck_fc;
1844   }
1845   else
1846   {
1847     GNUNET_break_op (0);
1848     return GNUNET_OK;
1849   }
1850
1851   pid = ntohl (msg->pid);
1852   LOG (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n", pid, fc->last_pid_recv);
1853   fc->last_pid_recv = pid;
1854   fwd = fc == &c->bck_fc;
1855   GMC_send_ack (c, fwd, GNUNET_YES);
1856
1857   return GNUNET_OK;
1858 }
1859
1860
1861 /**
1862  * Core handler for mesh keepalives.
1863  *
1864  * @param cls closure
1865  * @param message message
1866  * @param peer peer identity this notification is about
1867  * @return GNUNET_OK to keep the connection open,
1868  *         GNUNET_SYSERR to close it (signal serious error)
1869  *
1870  * TODO: Check who we got this from, to validate route.
1871  */
1872 int
1873 GMC_handle_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
1874                       const struct GNUNET_MessageHeader *message)
1875 {
1876   struct GNUNET_MESH_ConnectionKeepAlive *msg;
1877   struct MeshConnection *c;
1878   struct MeshPeer *neighbor;
1879   int fwd;
1880
1881   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
1882   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
1883               GNUNET_i2s (peer));
1884
1885   c = connection_get (&msg->cid);
1886   if (NULL == c)
1887   {
1888     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
1889                               GNUNET_NO);
1890     return GNUNET_OK;
1891   }
1892
1893   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
1894         GNUNET_YES : GNUNET_NO;
1895
1896   /* Check if origin is as expected */
1897   neighbor = get_hop (c, fwd);
1898   if (GNUNET_PEER_search (peer) != GMP_get_short_id (neighbor))
1899   {
1900     GNUNET_break_op (0);
1901     return GNUNET_OK;
1902   }
1903
1904   connection_change_state (c, MESH_CONNECTION_READY);
1905   connection_reset_timeout (c, fwd);
1906
1907   if (GMC_is_terminal (c, fwd))
1908     return GNUNET_OK;
1909
1910   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
1911   GMC_send_prebuilt_message (message, c, fwd, NULL, NULL);
1912
1913   return GNUNET_OK;
1914 }
1915
1916
1917 /**
1918  * Send an ACK on the appropriate connection/channel, depending on
1919  * the direction and the position of the peer.
1920  *
1921  * @param c Which connection to send the hop-by-hop ACK.
1922  * @param fwd Is this a fwd ACK? (will go dest->root).
1923  * @param force Send the ACK even if suboptimal (e.g. requested by POLL).
1924  */
1925 void
1926 GMC_send_ack (struct MeshConnection *c, int fwd, int force)
1927 {
1928   unsigned int buffer;
1929
1930   LOG (GNUNET_ERROR_TYPE_DEBUG,
1931        "GMC send %s ACK on %s\n",
1932        fwd ? "FWD" : "BCK", GMC_2s (c));
1933
1934   if (NULL == c)
1935   {
1936     GNUNET_break (0);
1937     return;
1938   }
1939
1940   /* Get available buffer space */
1941   if (GMC_is_terminal (c, fwd))
1942   {
1943     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from all channels\n");
1944     buffer = GMT_get_channels_buffer (c->t);
1945   }
1946   else
1947   {
1948     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
1949     buffer = GMC_get_buffer (c, fwd);
1950   }
1951   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
1952   if (0 == buffer && GNUNET_NO == force)
1953     return;
1954
1955   /* Send available buffer space */
1956   if (GMC_is_origin (c, fwd))
1957   {
1958     GNUNET_assert (NULL != c->t);
1959     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channels...\n");
1960     GMT_unchoke_channels (c->t);
1961   }
1962   else
1963   {
1964     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
1965     send_ack (c, buffer, fwd, force);
1966   }
1967 }
1968
1969
1970 /**
1971  * Initialize the connections subsystem
1972  *
1973  * @param c Configuration handle.
1974  */
1975 void
1976 GMC_init (const struct GNUNET_CONFIGURATION_Handle *c)
1977 {
1978   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1979   if (GNUNET_OK !=
1980       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
1981                                              &max_msgs_queue))
1982   {
1983     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
1984                                "MESH", "MAX_MSGS_QUEUE", "MISSING");
1985     GNUNET_SCHEDULER_shutdown ();
1986     return;
1987   }
1988
1989   if (GNUNET_OK !=
1990       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
1991                                              &max_connections))
1992   {
1993     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
1994                                "MESH", "MAX_CONNECTIONS", "MISSING");
1995     GNUNET_SCHEDULER_shutdown ();
1996     return;
1997   }
1998
1999   if (GNUNET_OK !=
2000       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
2001                                            &refresh_connection_time))
2002   {
2003     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2004                                "MESH", "REFRESH_CONNECTION_TIME", "MISSING");
2005     GNUNET_SCHEDULER_shutdown ();
2006     return;
2007   }
2008   connections = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
2009 }
2010
2011 /**
2012  * Shut down the connections subsystem.
2013  */
2014 void
2015 GMC_shutdown (void)
2016 {
2017   GNUNET_CONTAINER_multihashmap_destroy (connections);
2018 }
2019
2020
2021 struct MeshConnection *
2022 GMC_new (const struct GNUNET_HashCode *cid,
2023          struct MeshTunnel3 *t,
2024          struct MeshPeerPath *p,
2025          unsigned int own_pos)
2026 {
2027   struct MeshConnection *c;
2028
2029   c = GNUNET_new (struct MeshConnection);
2030   c->id = *cid;
2031   GNUNET_CONTAINER_multihashmap_put (connections, &c->id, c,
2032                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2033   fc_init (&c->fwd_fc);
2034   fc_init (&c->bck_fc);
2035   c->fwd_fc.c = c;
2036   c->bck_fc.c = c;
2037
2038   c->t = t;
2039   if (own_pos > p->length - 1)
2040   {
2041     GNUNET_break (0);
2042     GMC_destroy (c);
2043     return NULL;
2044   }
2045   c->own_pos = own_pos;
2046   c->path = p;
2047
2048   if (0 == own_pos)
2049   {
2050     c->fwd_maintenance_task =
2051             GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
2052                                           &connection_fwd_keepalive, c);
2053   }
2054   register_neighbors (c);
2055   return c;
2056 }
2057
2058
2059 void
2060 GMC_destroy (struct MeshConnection *c)
2061 {
2062   if (NULL == c)
2063     return;
2064
2065   if (2 == c->destroy) /* cancel queues -> GMP_queue_cancel -> q_destroy -> */
2066     return;            /* -> message_sent -> GMC_destroy. Don't loop. */
2067   c->destroy = 2;
2068
2069   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s\n", GMC_2s (c));
2070
2071   /* Cancel all traffic */
2072   connection_cancel_queues (c, GNUNET_YES);
2073   connection_cancel_queues (c, GNUNET_NO);
2074
2075   /* Cancel maintainance task (keepalive/timeout) */
2076   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
2077     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
2078   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
2079     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
2080
2081   /* Unregister from neighbors */
2082   unregister_neighbors (c);
2083
2084   /* Delete */
2085   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
2086   if (NULL != c->t)
2087     GMT_remove_connection (c->t, c);
2088
2089   if (GNUNET_NO == GMC_is_origin (c, GNUNET_YES))
2090     path_destroy (c->path);
2091
2092   GNUNET_free (c);
2093 }
2094
2095 /**
2096  * Get the connection ID.
2097  *
2098  * @param c Connection to get the ID from.
2099  *
2100  * @return ID of the connection.
2101  */
2102 const struct GNUNET_HashCode *
2103 GMC_get_id (const struct MeshConnection *c)
2104 {
2105   return &c->id;
2106 }
2107
2108
2109 /**
2110  * Get the connection path.
2111  *
2112  * @param c Connection to get the path from.
2113  *
2114  * @return path used by the connection.
2115  */
2116 const struct MeshPeerPath *
2117 GMC_get_path (const struct MeshConnection *c)
2118 {
2119   return c->path;
2120 }
2121
2122
2123 /**
2124  * Get the connection state.
2125  *
2126  * @param c Connection to get the state from.
2127  *
2128  * @return state of the connection.
2129  */
2130 enum MeshConnectionState
2131 GMC_get_state (const struct MeshConnection *c)
2132 {
2133   return c->state;
2134 }
2135
2136 /**
2137  * Get the connection tunnel.
2138  *
2139  * @param c Connection to get the tunnel from.
2140  *
2141  * @return tunnel of the connection.
2142  */
2143 struct MeshTunnel3 *
2144 GMC_get_tunnel (const struct MeshConnection *c)
2145 {
2146   return c->t;
2147 }
2148
2149
2150 /**
2151  * Get free buffer space in a connection.
2152  *
2153  * @param c Connection.
2154  * @param fwd Is query about FWD traffic?
2155  *
2156  * @return Free buffer space [0 - max_msgs_queue/max_connections]
2157  */
2158 unsigned int
2159 GMC_get_buffer (struct MeshConnection *c, int fwd)
2160 {
2161   struct MeshFlowControl *fc;
2162
2163   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2164
2165   return (fc->queue_max - fc->queue_n);
2166 }
2167
2168 /**
2169  * Get how many messages have we allowed to send to us from a direction.
2170  *
2171  * @param c Connection.
2172  * @param fwd Are we asking about traffic from FWD (BCK messages)?
2173  *
2174  * @return last_ack_sent - last_pid_recv
2175  */
2176 unsigned int
2177 GMC_get_allowed (struct MeshConnection *c, int fwd)
2178 {
2179   struct MeshFlowControl *fc;
2180
2181   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2182   if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
2183   {
2184     return 0;
2185   }
2186   return (fc->last_ack_sent - fc->last_pid_recv);
2187 }
2188
2189 /**
2190  * Get messages queued in a connection.
2191  *
2192  * @param c Connection.
2193  * @param fwd Is query about FWD traffic?
2194  *
2195  * @return Number of messages queued.
2196  */
2197 unsigned int
2198 GMC_get_qn (struct MeshConnection *c, int fwd)
2199 {
2200   struct MeshFlowControl *fc;
2201
2202   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2203
2204   return fc->queue_n;
2205 }
2206
2207
2208 /**
2209  * Allow the connection to advertise a buffer of the given size.
2210  *
2211  * The connection will send an @c fwd ACK message (so: in direction !fwd)
2212  * allowing up to last_pid_recv + buffer.
2213  *
2214  * @param c Connection.
2215  * @param buffer How many more messages the connection can accept.
2216  * @param fwd Is this about FWD traffic? (The ack will go dest->root).
2217  */
2218 void
2219 GMC_allow (struct MeshConnection *c, unsigned int buffer, int fwd)
2220 {
2221   send_ack (c, buffer, fwd, GNUNET_NO);
2222 }
2223
2224
2225 /**
2226  * Notify other peers on a connection of a broken link. Mark connections
2227  * to destroy after all traffic has been sent.
2228  *
2229  * @param c Connection on which there has been a disconnection.
2230  * @param peer Peer that disconnected.
2231  */
2232 void
2233 GMC_notify_broken (struct MeshConnection *c,
2234                    struct MeshPeer *peer)
2235 {
2236   int fwd;
2237
2238   fwd = peer == get_prev_hop (c);
2239
2240   if (GNUNET_YES == GMC_is_terminal (c, fwd))
2241   {
2242     /* Local shutdown, no one to notify about this. */
2243     GMC_destroy (c);
2244     return;
2245   }
2246   if (GNUNET_NO == c->destroy)
2247     send_broken (c, &my_full_id, GMP_get_id (peer), fwd);
2248
2249   /* Connection will have at least one pending message
2250    * (the one we just scheduled), so no point in checking whether to
2251    * destroy immediately. */
2252   c->destroy = GNUNET_YES;
2253
2254   /**
2255    * Cancel all queues, if no message is left, connection will be destroyed.
2256    */
2257   connection_cancel_queues (c, !fwd);
2258
2259   return;
2260 }
2261
2262
2263 /**
2264  * Is this peer the first one on the connection?
2265  *
2266  * @param c Connection.
2267  * @param fwd Is this about fwd traffic?
2268  *
2269  * @return #GNUNET_YES if origin, #GNUNET_NO if relay/terminal.
2270  */
2271 int
2272 GMC_is_origin (struct MeshConnection *c, int fwd)
2273 {
2274   if (!fwd && c->path->length - 1 == c->own_pos )
2275     return GNUNET_YES;
2276   if (fwd && 0 == c->own_pos)
2277     return GNUNET_YES;
2278   return GNUNET_NO;
2279 }
2280
2281
2282 /**
2283  * Is this peer the last one on the connection?
2284  *
2285  * @param c Connection.
2286  * @param fwd Is this about fwd traffic?
2287  *            Note that the ROOT is the terminal for BCK traffic!
2288  *
2289  * @return #GNUNET_YES if terminal, #GNUNET_NO if relay/origin.
2290  */
2291 int
2292 GMC_is_terminal (struct MeshConnection *c, int fwd)
2293 {
2294   return GMC_is_origin (c, !fwd);
2295 }
2296
2297
2298 /**
2299  * See if we are allowed to send by the next hop in the given direction.
2300  *
2301  * @param c Connection.
2302  * @param fwd Is this about fwd traffic?
2303  *
2304  * @return #GNUNET_YES in case it's OK to send.
2305  */
2306 int
2307 GMC_is_sendable (struct MeshConnection *c, int fwd)
2308 {
2309   struct MeshFlowControl *fc;
2310
2311   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2312   if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2313     return GNUNET_YES;
2314   return GNUNET_NO;
2315 }
2316
2317 /**
2318  * Sends an already built message on a connection, properly registering
2319  * all used resources.
2320  *
2321  * @param message Message to send. Function makes a copy of it.
2322  *                If message is not hop-by-hop, decrements TTL of copy.
2323  * @param c Connection on which this message is transmitted.
2324  * @param fwd Is this a fwd message?
2325  * @param cont Continuation called once message is sent. Can be NULL.
2326  * @param cont_cls Closure for @c cont.
2327  *
2328  * @return Handle to cancel the message before it's sent. NULL on error.
2329  *         Invalid on @c cont call.
2330  */
2331 struct MeshConnectionQueue *
2332 GMC_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2333                            struct MeshConnection *c, int fwd,
2334                            GMC_sent cont, void *cont_cls)
2335 {
2336   struct MeshFlowControl *fc;
2337   struct MeshConnectionQueue *q;
2338   void *data;
2339   size_t size;
2340   uint16_t type;
2341   int droppable;
2342
2343   size = ntohs (message->size);
2344   data = GNUNET_malloc (size);
2345   memcpy (data, message, size);
2346   type = ntohs (message->type);
2347   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send %s (%u bytes) on connection %s\n",
2348               GNUNET_MESH_DEBUG_M2S (type), size, GMC_2s (c));
2349
2350   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2351   droppable = GNUNET_YES;
2352   switch (type)
2353   {
2354     struct GNUNET_MESH_Encrypted *emsg;
2355     struct GNUNET_MESH_KX        *kmsg;
2356     struct GNUNET_MESH_ACK       *amsg;
2357     struct GNUNET_MESH_Poll      *pmsg;
2358     struct GNUNET_MESH_ConnectionDestroy *dmsg;
2359     struct GNUNET_MESH_ConnectionBroken  *bmsg;
2360     uint32_t ttl;
2361
2362     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
2363       emsg = (struct GNUNET_MESH_Encrypted *) data;
2364       ttl = ntohl (emsg->ttl);
2365       if (0 == ttl)
2366       {
2367         GNUNET_break_op (0);
2368         return NULL;
2369       }
2370       emsg->cid = c->id;
2371       emsg->ttl = htonl (ttl - 1);
2372       emsg->pid = htonl (fwd ? c->fwd_fc.next_pid++ : c->bck_fc.next_pid++);
2373       LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
2374       fc->queue_n++;
2375       LOG (GNUNET_ERROR_TYPE_DEBUG, "pid %u\n", ntohl (emsg->pid));
2376       LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid sent %u\n", fc->last_pid_sent);
2377       LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack recv %u\n", fc->last_ack_recv);
2378       if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
2379       {
2380         GMC_start_poll (c, fwd);
2381       }
2382       break;
2383
2384     case GNUNET_MESSAGE_TYPE_MESH_KX:
2385       kmsg = (struct GNUNET_MESH_KX *) data;
2386       kmsg->cid = c->id;
2387       break;
2388
2389     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2390       amsg = (struct GNUNET_MESH_ACK *) data;
2391       amsg->cid = c->id;
2392       LOG (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
2393       droppable = GNUNET_NO;
2394       break;
2395
2396     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2397       pmsg = (struct GNUNET_MESH_Poll *) data;
2398       pmsg->cid = c->id;
2399       LOG (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
2400       droppable = GNUNET_NO;
2401       break;
2402
2403     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
2404       dmsg = (struct GNUNET_MESH_ConnectionDestroy *) data;
2405       dmsg->cid = c->id;
2406       dmsg->reserved = 0;
2407       break;
2408
2409     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
2410       bmsg = (struct GNUNET_MESH_ConnectionBroken *) data;
2411       bmsg->cid = c->id;
2412       bmsg->reserved = 0;
2413       break;
2414
2415     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
2416     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
2417       break;
2418
2419     default:
2420       GNUNET_break (0);
2421   }
2422
2423   if (fc->queue_n > fc->queue_max && droppable)
2424   {
2425     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
2426                               1, GNUNET_NO);
2427     GNUNET_break (0);
2428     LOG (GNUNET_ERROR_TYPE_DEBUG,
2429                 "queue full: %u/%u\n",
2430                 fc->queue_n, fc->queue_max);
2431     if (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED == type)
2432       fc->queue_n--;
2433     return NULL; /* Drop this message */
2434   }
2435
2436   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u\n", c, c->pending_messages);
2437   c->pending_messages++;
2438
2439   q = GNUNET_new (struct MeshConnectionQueue);
2440   q->q = GMP_queue_add (get_hop (c, fwd), data, type, size, c, fwd,
2441                         &message_sent, q);
2442   q->cont = cont;
2443   q->cont_cls = cont_cls;
2444   return q;
2445 }
2446
2447
2448 /**
2449  * Cancel a previously sent message while it's in the queue.
2450  *
2451  * ONLY can be called before the continuation given to the send function
2452  * is called. Once the continuation is called, the message is no longer in the
2453  * queue.
2454  *
2455  * If the send function was given no continuation, GMC_cancel should
2456  * NOT be called, since it's not possible to determine if the message has
2457  * already been sent.
2458  *
2459  * @param q Handle to the queue.
2460  */
2461 void
2462 GMC_cancel (struct MeshConnectionQueue *q)
2463 {
2464   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  GMC cancel message\n");
2465   /* queue destroy calls message_sent, which calls q->cont */
2466   GMP_queue_destroy (q->q, GNUNET_YES);
2467
2468   GNUNET_free (q);
2469 }
2470
2471
2472 /**
2473  * Sends a CREATE CONNECTION message for a path to a peer.
2474  * Changes the connection and tunnel states if necessary.
2475  *
2476  * @param connection Connection to create.
2477  */
2478 void
2479 GMC_send_create (struct MeshConnection *connection)
2480 {
2481   enum MeshTunnel3State state;
2482   size_t size;
2483
2484   size = sizeof (struct GNUNET_MESH_ConnectionCreate);
2485   size += connection->path->length * sizeof (struct GNUNET_PeerIdentity);
2486   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
2487   GMP_queue_add (get_next_hop (connection), NULL,
2488                  GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
2489                  size, connection, GNUNET_YES, &message_sent, NULL);
2490   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u (create)\n",
2491        connection, connection->pending_messages);
2492   connection->pending_messages++;
2493   state = GMT_get_state (connection->t);
2494   if (MESH_TUNNEL3_SEARCHING == state || MESH_TUNNEL3_NEW == state)
2495     GMT_change_state (connection->t, MESH_TUNNEL3_WAITING);
2496   if (MESH_CONNECTION_NEW == connection->state)
2497     connection_change_state (connection, MESH_CONNECTION_SENT);
2498 }
2499
2500
2501 /**
2502  * Send a message to all peers in this connection that the connection
2503  * is no longer valid.
2504  *
2505  * If some peer should not receive the message, it should be zero'ed out
2506  * before calling this function.
2507  *
2508  * @param c The connection whose peers to notify.
2509  */
2510 void
2511 GMC_send_destroy (struct MeshConnection *c)
2512 {
2513   struct GNUNET_MESH_ConnectionDestroy msg;
2514
2515   if (GNUNET_YES == c->destroy)
2516     return;
2517
2518   msg.header.size = htons (sizeof (msg));
2519   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY);;
2520   msg.cid = c->id;
2521   LOG (GNUNET_ERROR_TYPE_DEBUG,
2522               "  sending connection destroy for connection %s\n",
2523               GMC_2s (c));
2524
2525   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_YES))
2526     GMC_send_prebuilt_message (&msg.header, c, GNUNET_YES, NULL, NULL);
2527   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_NO))
2528     GMC_send_prebuilt_message (&msg.header, c, GNUNET_NO, NULL, NULL);
2529   c->destroy = GNUNET_YES;
2530 }
2531
2532
2533 /**
2534  * @brief Start a polling timer for the connection.
2535  *
2536  * When a neighbor does not accept more traffic on the connection it could be
2537  * caused by a simple congestion or by a lost ACK. Polling enables to check
2538  * for the lastest ACK status for a connection.
2539  *
2540  * @param c Connection.
2541  * @param fwd Should we poll in the FWD direction?
2542  */
2543 void
2544 GMC_start_poll (struct MeshConnection *c, int fwd)
2545 {
2546   struct MeshFlowControl *fc;
2547
2548   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2549   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task && NULL != fc->poll_msg)
2550   {
2551     return;
2552   }
2553   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2554                                                 &connection_poll,
2555                                                 fc);
2556 }
2557
2558
2559 /**
2560  * @brief Stop polling a connection for ACKs.
2561  *
2562  * Once we have enough ACKs for future traffic, polls are no longer necessary.
2563  *
2564  * @param c Connection.
2565  * @param fwd Should we stop the poll in the FWD direction?
2566  */
2567 void
2568 GMC_stop_poll (struct MeshConnection *c, int fwd)
2569 {
2570   struct MeshFlowControl *fc;
2571
2572   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2573   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2574   {
2575     GNUNET_SCHEDULER_cancel (fc->poll_task);
2576     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2577   }
2578 }
2579
2580 /**
2581  * Get a (static) string for a connection.
2582  *
2583  * @param c Connection.
2584  */
2585 const char *
2586 GMC_2s (struct MeshConnection *c)
2587 {
2588   if (NULL != c->t)
2589   {
2590     static char buf[128];
2591
2592     sprintf (buf, "%s (->%s)", GNUNET_h2s (&c->id), GMT_2s (c->t));
2593     return buf;
2594   }
2595   return GNUNET_h2s (&c->id);
2596 }