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