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