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