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