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