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