- fix disconnect task scheduling
[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_MeshHash 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_MeshHash *cid)
417 {
418   return GNUNET_CONTAINER_multihashmap_get (connections, GM_h2hc (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_MeshHash *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, "=> BROKEN on unknown connection %s\n",
851        GNUNET_h2s (GM_h2hc (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_MeshHash *hash)
1484 {
1485   LOG (GNUNET_ERROR_TYPE_INFO, "<- %s on connection %s from %s\n",
1486        GM_m2s (ntohs (message->type)), GNUNET_h2s (GM_h2hc (hash)),
1487        GNUNET_i2s (peer));
1488 }
1489
1490 /******************************************************************************/
1491 /********************************    API    ***********************************/
1492 /******************************************************************************/
1493
1494 /**
1495  * Core handler for connection creation.
1496  *
1497  * @param cls Closure (unused).
1498  * @param peer Sender (neighbor).
1499  * @param message Message.
1500  *
1501  * @return GNUNET_OK to keep the connection open,
1502  *         GNUNET_SYSERR to close it (signal serious error)
1503  */
1504 int
1505 GMC_handle_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1506                    const struct GNUNET_MessageHeader *message)
1507 {
1508   struct GNUNET_MESH_ConnectionCreate *msg;
1509   struct GNUNET_PeerIdentity *id;
1510   struct GNUNET_MeshHash *cid;
1511   struct MeshPeerPath *path;
1512   struct MeshPeer *dest_peer;
1513   struct MeshPeer *orig_peer;
1514   struct MeshConnection *c;
1515   unsigned int own_pos;
1516   uint16_t size;
1517
1518   /* Check size */
1519   size = ntohs (message->size);
1520   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
1521   {
1522     GNUNET_break_op (0);
1523     return GNUNET_OK;
1524   }
1525
1526   /* Calculate hops */
1527   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
1528   if (size % sizeof (struct GNUNET_PeerIdentity))
1529   {
1530     GNUNET_break_op (0);
1531     return GNUNET_OK;
1532   }
1533   size /= sizeof (struct GNUNET_PeerIdentity);
1534   if (1 > size)
1535   {
1536     GNUNET_break_op (0);
1537     return GNUNET_OK;
1538   }
1539   LOG (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
1540
1541   /* Get parameters */
1542   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
1543   cid = &msg->cid;
1544   log_message (message, peer, cid);
1545   id = (struct GNUNET_PeerIdentity *) &msg[1];
1546   LOG (GNUNET_ERROR_TYPE_DEBUG, "    origin: %s\n", GNUNET_i2s (id));
1547
1548   /* Create connection */
1549   c = connection_get (cid);
1550   if (NULL == c)
1551   {
1552     path = build_path_from_peer_ids ((struct GNUNET_PeerIdentity *) &msg[1],
1553                                      size, &own_pos);
1554     if (NULL == path)
1555       return GNUNET_OK;
1556     if (0 == own_pos)
1557     {
1558       GNUNET_break_op (0);
1559       path_destroy (path);
1560       return GNUNET_OK;
1561     }
1562     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
1563     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
1564     c = GMC_new (cid, NULL, path_duplicate (path), own_pos);
1565     if (NULL == c)
1566     {
1567       if (path->length - 1 == own_pos)
1568       {
1569         /* If we are destination, why did the creation fail? */
1570         GNUNET_break (0);
1571         return GNUNET_OK;
1572       }
1573       send_broken2 (cid, &my_full_id,
1574                     GNUNET_PEER_resolve2 (path->peers[own_pos + 1]),
1575                     path->peers[own_pos - 1]);
1576       path_destroy (path);
1577       return GNUNET_OK;
1578     }
1579     GMP_add_path_to_all (path, GNUNET_NO);
1580     connection_reset_timeout (c, GNUNET_YES);
1581   }
1582   else
1583   {
1584     path = path_duplicate (c->path);
1585   }
1586   if (MESH_CONNECTION_NEW == c->state)
1587     connection_change_state (c, MESH_CONNECTION_SENT);
1588
1589   /* Remember peers */
1590   dest_peer = GMP_get (&id[size - 1]);
1591   orig_peer = GMP_get (&id[0]);
1592
1593   /* Is it a connection to us? */
1594   if (c->own_pos == size - 1)
1595   {
1596     LOG (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
1597     GMP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_YES);
1598
1599     add_to_peer (c, orig_peer);
1600     if (MESH_TUNNEL3_NEW == GMT_get_cstate (c->t))
1601       GMT_change_cstate (c->t,  MESH_TUNNEL3_WAITING);
1602
1603     send_connection_ack (c, GNUNET_NO);
1604     if (MESH_CONNECTION_SENT == c->state)
1605       connection_change_state (c, MESH_CONNECTION_ACK);
1606   }
1607   else
1608   {
1609     /* It's for somebody else! Retransmit. */
1610     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
1611     GMP_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
1612     GMP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_NO);
1613     GMC_send_prebuilt_message (message, c, GNUNET_YES, GNUNET_YES,
1614                                NULL, NULL);
1615   }
1616   path_destroy (path);
1617   return GNUNET_OK;
1618 }
1619
1620
1621 /**
1622  * Core handler for path confirmations.
1623  *
1624  * @param cls closure
1625  * @param message message
1626  * @param peer peer identity this notification is about
1627  *
1628  * @return GNUNET_OK to keep the connection open,
1629  *         GNUNET_SYSERR to close it (signal serious error)
1630  */
1631 int
1632 GMC_handle_confirm (void *cls, const struct GNUNET_PeerIdentity *peer,
1633                     const struct GNUNET_MessageHeader *message)
1634 {
1635   struct GNUNET_MESH_ConnectionACK *msg;
1636   struct MeshConnection *c;
1637   struct MeshPeerPath *p;
1638   struct MeshPeer *pi;
1639   enum MeshConnectionState oldstate;
1640   int fwd;
1641
1642   msg = (struct GNUNET_MESH_ConnectionACK *) message;
1643   log_message (message, peer, &msg->cid);
1644   c = connection_get (&msg->cid);
1645   if (NULL == c)
1646   {
1647     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1648                               1, GNUNET_NO);
1649     LOG (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
1650     return GNUNET_OK;
1651   }
1652
1653   if (GNUNET_NO != c->destroy)
1654   {
1655     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection being destroyed\n");
1656     return GNUNET_OK;
1657   }
1658
1659   oldstate = c->state;
1660   LOG (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n", GNUNET_i2s (peer));
1661   pi = GMP_get (peer);
1662   if (get_next_hop (c) == pi)
1663   {
1664     LOG (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
1665     fwd = GNUNET_NO;
1666     if (MESH_CONNECTION_SENT == oldstate)
1667       connection_change_state (c, MESH_CONNECTION_ACK);
1668   }
1669   else if (get_prev_hop (c) == pi)
1670   {
1671     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
1672     fwd = GNUNET_YES;
1673     connection_change_state (c, MESH_CONNECTION_READY);
1674   }
1675   else
1676   {
1677     GNUNET_break_op (0);
1678     return GNUNET_OK;
1679   }
1680
1681   connection_reset_timeout (c, fwd);
1682
1683   /* Add path to peers? */
1684   p = c->path;
1685   if (NULL != p)
1686   {
1687     GMP_add_path_to_all (p, GNUNET_YES);
1688   }
1689   else
1690   {
1691     GNUNET_break (0);
1692   }
1693
1694   /* Message for us as creator? */
1695   if (GMC_is_origin (c, GNUNET_YES))
1696   {
1697     if (GNUNET_NO != fwd)
1698     {
1699       GNUNET_break_op (0);
1700       return GNUNET_OK;
1701     }
1702     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
1703
1704     /* If just created, cancel the short timeout and start a long one */
1705     if (MESH_CONNECTION_SENT == oldstate)
1706       connection_reset_timeout (c, GNUNET_YES);
1707
1708     /* Change connection state */
1709     connection_change_state (c, MESH_CONNECTION_READY);
1710     send_connection_ack (c, GNUNET_YES);
1711
1712     /* Change tunnel state, trigger KX */
1713     if (MESH_TUNNEL3_WAITING == GMT_get_cstate (c->t))
1714       GMT_change_cstate (c->t, MESH_TUNNEL3_READY);
1715
1716     return GNUNET_OK;
1717   }
1718
1719   /* Message for us as destination? */
1720   if (GMC_is_terminal (c, GNUNET_YES))
1721   {
1722     if (GNUNET_YES != fwd)
1723     {
1724       GNUNET_break_op (0);
1725       return GNUNET_OK;
1726     }
1727     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
1728
1729     /* If just created, cancel the short timeout and start a long one */
1730     if (MESH_CONNECTION_ACK == oldstate)
1731       connection_reset_timeout (c, GNUNET_NO);
1732
1733     /* Change tunnel state */
1734     if (MESH_TUNNEL3_WAITING == GMT_get_cstate (c->t))
1735       GMT_change_cstate (c->t, MESH_TUNNEL3_READY);
1736
1737     return GNUNET_OK;
1738   }
1739
1740   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1741   GMC_send_prebuilt_message (message, c, fwd, GNUNET_YES, NULL, NULL);
1742   return GNUNET_OK;
1743 }
1744
1745
1746 /**
1747  * Core handler for notifications of broken paths
1748  *
1749  * @param cls Closure (unused).
1750  * @param id Peer identity of sending neighbor.
1751  * @param message Message.
1752  *
1753  * @return GNUNET_OK to keep the connection open,
1754  *         GNUNET_SYSERR to close it (signal serious error)
1755  */
1756 int
1757 GMC_handle_broken (void* cls,
1758                    const struct GNUNET_PeerIdentity* id,
1759                    const struct GNUNET_MessageHeader* message)
1760 {
1761   struct GNUNET_MESH_ConnectionBroken *msg;
1762   struct MeshConnection *c;
1763   int fwd;
1764
1765   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
1766   log_message (message, id, &msg->cid);
1767   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1768               GNUNET_i2s (&msg->peer1));
1769   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1770               GNUNET_i2s (&msg->peer2));
1771   c = connection_get (&msg->cid);
1772   if (NULL == c)
1773   {
1774     GNUNET_break_op (0);
1775     return GNUNET_OK;
1776   }
1777
1778   fwd = is_fwd (c, id);
1779   if (GMC_is_terminal (c, fwd))
1780   {
1781     path_invalidate (c->path);
1782     if (0 < c->pending_messages)
1783       c->destroy = GNUNET_YES;
1784     else
1785       GMC_destroy (c);
1786   }
1787   else
1788   {
1789     GMC_send_prebuilt_message (message, c, fwd, GNUNET_YES, NULL, NULL);
1790     c->destroy = GNUNET_YES;
1791     connection_cancel_queues (c, !fwd);
1792   }
1793
1794   return GNUNET_OK;
1795
1796 }
1797
1798
1799 /**
1800  * Core handler for tunnel destruction
1801  *
1802  * @param cls Closure (unused).
1803  * @param peer Peer identity of sending neighbor.
1804  * @param message Message.
1805  *
1806  * @return GNUNET_OK to keep the connection open,
1807  *         GNUNET_SYSERR to close it (signal serious error)
1808  */
1809 int
1810 GMC_handle_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
1811                     const struct GNUNET_MessageHeader *message)
1812 {
1813   struct GNUNET_MESH_ConnectionDestroy *msg;
1814   struct MeshConnection *c;
1815   int fwd;
1816
1817   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
1818   log_message (message, peer, &msg->cid);
1819   c = connection_get (&msg->cid);
1820   if (NULL == c)
1821   {
1822     /* Probably already got the message from another path,
1823      * destroyed the tunnel and retransmitted to children.
1824      * Safe to ignore.
1825      */
1826     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1827                               1, GNUNET_NO);
1828     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection unknown: already destroyed?\n");
1829     return GNUNET_OK;
1830   }
1831   fwd = is_fwd (c, peer);
1832   if (GNUNET_SYSERR == fwd)
1833   {
1834     GNUNET_break_op (0); /* FIXME */
1835     return GNUNET_OK;
1836   }
1837   if (GNUNET_NO == GMC_is_terminal (c, fwd))
1838     GMC_send_prebuilt_message (message, c, fwd, GNUNET_YES, NULL, NULL);
1839   else if (0 == c->pending_messages)
1840   {
1841     LOG (GNUNET_ERROR_TYPE_DEBUG, "!  directly destroying connection!\n");
1842     GMC_destroy (c);
1843     return GNUNET_OK;
1844   }
1845   c->destroy = GNUNET_YES;
1846   c->state = MESH_CONNECTION_DESTROYED;
1847   if (NULL != c->t)
1848   {
1849     GMT_remove_connection (c->t, c);
1850     c->t = NULL;
1851   }
1852
1853   return GNUNET_OK;
1854 }
1855
1856 /**
1857  * Generic handler for mesh network encrypted traffic.
1858  *
1859  * @param peer Peer identity this notification is about.
1860  * @param msg Encrypted message.
1861  *
1862  * @return GNUNET_OK to keep the connection open,
1863  *         GNUNET_SYSERR to close it (signal serious error)
1864  */
1865 static int
1866 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
1867                        const struct GNUNET_MESH_Encrypted *msg)
1868 {
1869   struct MeshConnection *c;
1870   struct MeshPeer *neighbor;
1871   struct MeshFlowControl *fc;
1872   GNUNET_PEER_Id peer_id;
1873   uint32_t pid;
1874   uint32_t ttl;
1875   size_t size;
1876   int fwd;
1877
1878   log_message (&msg->header, peer, &msg->cid);
1879
1880   /* Check size */
1881   size = ntohs (msg->header.size);
1882   if (size <
1883       sizeof (struct GNUNET_MESH_Encrypted) +
1884       sizeof (struct GNUNET_MessageHeader))
1885   {
1886     GNUNET_break_op (0);
1887     return GNUNET_OK;
1888   }
1889
1890   /* Check connection */
1891   c = connection_get (&msg->cid);
1892   if (NULL == c)
1893   {
1894     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
1895     LOG (GNUNET_ERROR_TYPE_DEBUG, "enc on unknown connection %s\n",
1896          GNUNET_h2s (GM_h2hc (&msg->cid)));
1897     return GNUNET_OK;
1898   }
1899
1900   LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s\n", GMC_2s (c));
1901
1902   /* Check if origin is as expected */
1903   neighbor = get_prev_hop (c);
1904   peer_id = GNUNET_PEER_search (peer);
1905   if (peer_id == GMP_get_short_id (neighbor))
1906   {
1907     fwd = GNUNET_YES;
1908   }
1909   else
1910   {
1911     neighbor = get_next_hop (c);
1912     if (peer_id == GMP_get_short_id (neighbor))
1913     {
1914       fwd = GNUNET_NO;
1915     }
1916     else
1917     {
1918       /* Unexpected peer sending traffic on a connection. */
1919       GNUNET_break_op (0);
1920       return GNUNET_OK;
1921     }
1922   }
1923
1924   /* Check PID */
1925   fc = fwd ? &c->bck_fc : &c->fwd_fc;
1926   pid = ntohl (msg->pid);
1927   if (GM_is_pid_bigger (pid, fc->last_ack_sent))
1928   {
1929     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
1930     LOG (GNUNET_ERROR_TYPE_DEBUG,
1931                 "WARNING Received PID %u, (prev %u), ACK %u\n",
1932                 pid, fc->last_pid_recv, fc->last_ack_sent);
1933     return GNUNET_OK;
1934   }
1935   if (GNUNET_NO == GM_is_pid_bigger (pid, fc->last_pid_recv))
1936   {
1937     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
1938     LOG (GNUNET_ERROR_TYPE_DEBUG,
1939                 " Pid %u not expected (%u+), dropping!\n",
1940                 pid, fc->last_pid_recv + 1);
1941     return GNUNET_OK;
1942   }
1943   if (MESH_CONNECTION_SENT == c->state || MESH_CONNECTION_ACK == c->state)
1944     connection_change_state (c, MESH_CONNECTION_READY);
1945   connection_reset_timeout (c, fwd);
1946   fc->last_pid_recv = pid;
1947
1948   /* Is this message for us? */
1949   if (GMC_is_terminal (c, fwd))
1950   {
1951     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
1952     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
1953
1954     if (NULL == c->t)
1955     {
1956       GNUNET_break (GNUNET_NO != c->destroy);
1957       return GNUNET_OK;
1958     }
1959     fc->last_pid_recv = pid;
1960     GMT_handle_encrypted (c->t, msg);
1961     GMC_send_ack (c, fwd, GNUNET_NO);
1962     return GNUNET_OK;
1963   }
1964
1965   /* Message not for us: forward to next hop */
1966   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1967   ttl = ntohl (msg->ttl);
1968   LOG (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
1969   if (ttl == 0)
1970   {
1971     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
1972     LOG (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
1973     GMC_send_ack (c, fwd, GNUNET_NO);
1974     return GNUNET_OK;
1975   }
1976
1977   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
1978   GMC_send_prebuilt_message (&msg->header, c, fwd, GNUNET_NO, NULL, NULL);
1979
1980   return GNUNET_OK;
1981 }
1982
1983 /**
1984  * Generic handler for mesh network encrypted traffic.
1985  *
1986  * @param peer Peer identity this notification is about.
1987  * @param msg Encrypted message.
1988  *
1989  * @return GNUNET_OK to keep the connection open,
1990  *         GNUNET_SYSERR to close it (signal serious error)
1991  */
1992 static int
1993 handle_mesh_kx (const struct GNUNET_PeerIdentity *peer,
1994                 const struct GNUNET_MESH_KX *msg)
1995 {
1996   struct MeshConnection *c;
1997   struct MeshPeer *neighbor;
1998   GNUNET_PEER_Id peer_id;
1999   size_t size;
2000   int fwd;
2001
2002   log_message (&msg->header, peer, &msg->cid);
2003
2004   /* Check size */
2005   size = ntohs (msg->header.size);
2006   if (size <
2007       sizeof (struct GNUNET_MESH_KX) +
2008       sizeof (struct GNUNET_MessageHeader))
2009   {
2010     GNUNET_break_op (0);
2011     return GNUNET_OK;
2012   }
2013
2014   /* Check connection */
2015   c = connection_get (&msg->cid);
2016   if (NULL == c)
2017   {
2018     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
2019     LOG (GNUNET_ERROR_TYPE_DEBUG, "kx on unknown connection %s\n",
2020          GNUNET_h2s (GM_h2hc (&msg->cid)));
2021     return GNUNET_OK;
2022   }
2023   LOG (GNUNET_ERROR_TYPE_DEBUG, " on connection %s\n", GMC_2s (c));
2024
2025   /* Check if origin is as expected */
2026   neighbor = get_prev_hop (c);
2027   peer_id = GNUNET_PEER_search (peer);
2028   if (peer_id == GMP_get_short_id (neighbor))
2029   {
2030     fwd = GNUNET_YES;
2031   }
2032   else
2033   {
2034     neighbor = get_next_hop (c);
2035     if (peer_id == GMP_get_short_id (neighbor))
2036     {
2037       fwd = GNUNET_NO;
2038     }
2039     else
2040     {
2041       /* Unexpected peer sending traffic on a connection. */
2042       GNUNET_break_op (0);
2043       return GNUNET_OK;
2044     }
2045   }
2046
2047   /* Count as connection confirmation. */
2048   if (MESH_CONNECTION_SENT == c->state || MESH_CONNECTION_ACK == c->state)
2049   {
2050     connection_change_state (c, MESH_CONNECTION_READY);
2051     if (NULL != c->t)
2052     {
2053       if (MESH_TUNNEL3_WAITING == GMT_get_cstate (c->t))
2054         GMT_change_cstate (c->t, MESH_TUNNEL3_READY);
2055     }
2056   }
2057   connection_reset_timeout (c, fwd);
2058
2059   /* Is this message for us? */
2060   if (GMC_is_terminal (c, fwd))
2061   {
2062     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
2063     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
2064     if (NULL == c->t)
2065     {
2066       GNUNET_break (0);
2067       return GNUNET_OK;
2068     }
2069     GMT_handle_kx (c->t, &msg[1].header);
2070     return GNUNET_OK;
2071   }
2072
2073   /* Message not for us: forward to next hop */
2074   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2075   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
2076   GMC_send_prebuilt_message (&msg->header, c, fwd, GNUNET_NO, NULL, NULL);
2077
2078   return GNUNET_OK;
2079 }
2080
2081
2082 /**
2083  * Core handler for encrypted mesh network traffic (channel mgmt, data).
2084  *
2085  * @param cls Closure (unused).
2086  * @param message Message received.
2087  * @param peer Peer who sent the message.
2088  *
2089  * @return GNUNET_OK to keep the connection open,
2090  *         GNUNET_SYSERR to close it (signal serious error)
2091  */
2092 int
2093 GMC_handle_encrypted (void *cls, const struct GNUNET_PeerIdentity *peer,
2094                       const struct GNUNET_MessageHeader *message)
2095 {
2096   return handle_mesh_encrypted (peer,
2097                                 (struct GNUNET_MESH_Encrypted *)message);
2098 }
2099
2100
2101 /**
2102  * Core handler for key exchange traffic (ephemeral key, ping, pong).
2103  *
2104  * @param cls Closure (unused).
2105  * @param message Message received.
2106  * @param peer Peer who sent the message.
2107  *
2108  * @return GNUNET_OK to keep the connection open,
2109  *         GNUNET_SYSERR to close it (signal serious error)
2110  */
2111 int
2112 GMC_handle_kx (void *cls, const struct GNUNET_PeerIdentity *peer,
2113                const struct GNUNET_MessageHeader *message)
2114 {
2115   return handle_mesh_kx (peer,
2116                          (struct GNUNET_MESH_KX *) message);
2117 }
2118
2119
2120 /**
2121  * Core handler for mesh network traffic point-to-point acks.
2122  *
2123  * @param cls closure
2124  * @param message message
2125  * @param peer peer identity this notification is about
2126  *
2127  * @return GNUNET_OK to keep the connection open,
2128  *         GNUNET_SYSERR to close it (signal serious error)
2129  */
2130 int
2131 GMC_handle_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2132                 const struct GNUNET_MessageHeader *message)
2133 {
2134   struct GNUNET_MESH_ACK *msg;
2135   struct MeshConnection *c;
2136   struct MeshFlowControl *fc;
2137   GNUNET_PEER_Id id;
2138   uint32_t ack;
2139   int fwd;
2140
2141   msg = (struct GNUNET_MESH_ACK *) message;
2142   log_message (message, peer, &msg->cid);
2143   c = connection_get (&msg->cid);
2144   if (NULL == c)
2145   {
2146     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
2147                               GNUNET_NO);
2148     return GNUNET_OK;
2149   }
2150
2151   /* Is this a forward or backward ACK? */
2152   id = GNUNET_PEER_search (peer);
2153   if (GMP_get_short_id (get_next_hop (c)) == id)
2154   {
2155     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
2156     fc = &c->fwd_fc;
2157     fwd = GNUNET_YES;
2158   }
2159   else if (GMP_get_short_id (get_prev_hop (c)) == id)
2160   {
2161     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
2162     fc = &c->bck_fc;
2163     fwd = GNUNET_NO;
2164   }
2165   else
2166   {
2167     GNUNET_break_op (0);
2168     return GNUNET_OK;
2169   }
2170
2171   ack = ntohl (msg->ack);
2172   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u (was %u)\n",
2173               ack, fc->last_ack_recv);
2174   if (GM_is_pid_bigger (ack, fc->last_ack_recv))
2175     fc->last_ack_recv = ack;
2176
2177   /* Cancel polling if the ACK is big enough. */
2178   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
2179       GM_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2180   {
2181     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
2182     GNUNET_SCHEDULER_cancel (fc->poll_task);
2183     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2184     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
2185   }
2186
2187   connection_unlock_queue (c, fwd);
2188
2189   return GNUNET_OK;
2190 }
2191
2192
2193 /**
2194  * Core handler for mesh network traffic point-to-point ack polls.
2195  *
2196  * @param cls closure
2197  * @param message message
2198  * @param peer peer identity this notification is about
2199  *
2200  * @return GNUNET_OK to keep the connection open,
2201  *         GNUNET_SYSERR to close it (signal serious error)
2202  */
2203 int
2204 GMC_handle_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
2205                  const struct GNUNET_MessageHeader *message)
2206 {
2207   struct GNUNET_MESH_Poll *msg;
2208   struct MeshConnection *c;
2209   struct MeshFlowControl *fc;
2210   GNUNET_PEER_Id id;
2211   uint32_t pid;
2212   int fwd;
2213
2214   msg = (struct GNUNET_MESH_Poll *) message;
2215   log_message (message, peer, &msg->cid);
2216   c = connection_get (&msg->cid);
2217   if (NULL == c)
2218   {
2219     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
2220                               GNUNET_NO);
2221     LOG (GNUNET_ERROR_TYPE_DEBUG,
2222          "WARNING POLL message on unknown connection %s!\n",
2223          GNUNET_h2s (GM_h2hc (&msg->cid)));
2224     return GNUNET_OK;
2225   }
2226
2227   /* Is this a forward or backward ACK?
2228    * Note: a poll should never be needed in a loopback case,
2229    * since there is no possiblility of packet loss there, so
2230    * this way of discerining FWD/BCK should not be a problem.
2231    */
2232   id = GNUNET_PEER_search (peer);
2233   if (GMP_get_short_id (get_next_hop (c)) == id)
2234   {
2235     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
2236     fc = &c->fwd_fc;
2237   }
2238   else if (GMP_get_short_id (get_prev_hop (c)) == id)
2239   {
2240     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
2241     fc = &c->bck_fc;
2242   }
2243   else
2244   {
2245     GNUNET_break_op (0);
2246     return GNUNET_OK;
2247   }
2248
2249   pid = ntohl (msg->pid);
2250   LOG (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n", pid, fc->last_pid_recv);
2251   fc->last_pid_recv = pid;
2252   fwd = fc == &c->bck_fc;
2253   GMC_send_ack (c, fwd, GNUNET_YES);
2254
2255   return GNUNET_OK;
2256 }
2257
2258
2259 /**
2260  * Send an ACK on the appropriate connection/channel, depending on
2261  * the direction and the position of the peer.
2262  *
2263  * @param c Which connection to send the hop-by-hop ACK.
2264  * @param fwd Is this a fwd ACK? (will go dest->root).
2265  * @param force Send the ACK even if suboptimal (e.g. requested by POLL).
2266  */
2267 void
2268 GMC_send_ack (struct MeshConnection *c, int fwd, int force)
2269 {
2270   unsigned int buffer;
2271
2272   LOG (GNUNET_ERROR_TYPE_DEBUG,
2273        "GMC send %s ACK on %s\n",
2274        GM_f2s (fwd), GMC_2s (c));
2275
2276   if (NULL == c)
2277   {
2278     GNUNET_break (0);
2279     return;
2280   }
2281
2282   if (GNUNET_NO != c->destroy)
2283   {
2284     LOG (GNUNET_ERROR_TYPE_DEBUG, "  being destroyed, why bother...\n");
2285     return;
2286   }
2287
2288   /* Get available buffer space */
2289   if (GMC_is_terminal (c, fwd))
2290   {
2291     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from all channels\n");
2292     buffer = GMT_get_channels_buffer (c->t);
2293   }
2294   else
2295   {
2296     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
2297     buffer = GMC_get_buffer (c, fwd);
2298   }
2299   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
2300   if (0 == buffer && GNUNET_NO == force)
2301     return;
2302
2303   /* Send available buffer space */
2304   if (GMC_is_origin (c, fwd))
2305   {
2306     GNUNET_assert (NULL != c->t);
2307     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channels...\n");
2308     GMT_unchoke_channels (c->t);
2309   }
2310   else
2311   {
2312     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
2313     send_ack (c, buffer, fwd, force);
2314   }
2315 }
2316
2317
2318 /**
2319  * Initialize the connections subsystem
2320  *
2321  * @param c Configuration handle.
2322  */
2323 void
2324 GMC_init (const struct GNUNET_CONFIGURATION_Handle *c)
2325 {
2326   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2327   if (GNUNET_OK !=
2328       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
2329                                              &max_msgs_queue))
2330   {
2331     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2332                                "MESH", "MAX_MSGS_QUEUE", "MISSING");
2333     GNUNET_SCHEDULER_shutdown ();
2334     return;
2335   }
2336
2337   if (GNUNET_OK !=
2338       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
2339                                              &max_connections))
2340   {
2341     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2342                                "MESH", "MAX_CONNECTIONS", "MISSING");
2343     GNUNET_SCHEDULER_shutdown ();
2344     return;
2345   }
2346
2347   if (GNUNET_OK !=
2348       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
2349                                            &refresh_connection_time))
2350   {
2351     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2352                                "MESH", "REFRESH_CONNECTION_TIME", "MISSING");
2353     GNUNET_SCHEDULER_shutdown ();
2354     return;
2355   }
2356   create_connection_time = GNUNET_TIME_UNIT_SECONDS;
2357   connections = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
2358 }
2359
2360
2361 /**
2362  * Destroy each connection on shutdown.
2363  *
2364  * @param cls Closure (unused).
2365  * @param key Current key code (CID, unused).
2366  * @param value Value in the hash map (connection)
2367  *
2368  * @return #GNUNET_YES, because we should continue to iterate,
2369  */
2370 static int
2371 shutdown_iterator (void *cls,
2372                    const struct GNUNET_HashCode *key,
2373                    void *value)
2374 {
2375   struct MeshConnection *c = value;
2376
2377   GMC_destroy (c);
2378   return GNUNET_YES;
2379 }
2380
2381
2382 /**
2383  * Shut down the connections subsystem.
2384  */
2385 void
2386 GMC_shutdown (void)
2387 {
2388   GNUNET_CONTAINER_multihashmap_iterate (connections, &shutdown_iterator, NULL);
2389   GNUNET_CONTAINER_multihashmap_destroy (connections);
2390   connections = NULL;
2391 }
2392
2393
2394 struct MeshConnection *
2395 GMC_new (const struct GNUNET_MeshHash *cid,
2396          struct MeshTunnel3 *t,
2397          struct MeshPeerPath *p,
2398          unsigned int own_pos)
2399 {
2400   struct MeshConnection *c;
2401
2402   c = GNUNET_new (struct MeshConnection);
2403   c->id = *cid;
2404   GNUNET_assert (GNUNET_OK ==
2405                  GNUNET_CONTAINER_multihashmap_put (connections,
2406                                                     GMC_get_h (c), c,
2407                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2408   fc_init (&c->fwd_fc);
2409   fc_init (&c->bck_fc);
2410   c->fwd_fc.c = c;
2411   c->bck_fc.c = c;
2412
2413   c->t = t;
2414   GNUNET_assert (own_pos <= p->length - 1);
2415   c->own_pos = own_pos;
2416   c->path = p;
2417
2418   if (GNUNET_OK != register_neighbors (c))
2419   {
2420     if (0 == own_pos)
2421     {
2422       path_invalidate (c->path);
2423       c->t = NULL;
2424       c->path = NULL;
2425     }
2426     GMC_destroy (c);
2427     return NULL;
2428   }
2429
2430   return c;
2431 }
2432
2433
2434 void
2435 GMC_destroy (struct MeshConnection *c)
2436 {
2437   if (NULL == c)
2438   {
2439     GNUNET_break (0);
2440     return;
2441   }
2442
2443   if (2 == c->destroy) /* cancel queues -> GMP_queue_cancel -> q_destroy -> */
2444     return;            /* -> message_sent -> GMC_destroy. Don't loop. */
2445   c->destroy = 2;
2446
2447   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s\n", GMC_2s (c));
2448   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc's f: %p, b: %p\n",
2449        &c->fwd_fc, &c->bck_fc);
2450   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc tasks f: %u, b: %u\n",
2451        c->fwd_fc.poll_task, c->bck_fc.poll_task);
2452
2453   /* Cancel all traffic */
2454   if (NULL != c->path)
2455   {
2456     connection_cancel_queues (c, GNUNET_YES);
2457     connection_cancel_queues (c, GNUNET_NO);
2458     unregister_neighbors (c);
2459   }
2460
2461   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc tasks f: %u, b: %u\n",
2462        c->fwd_fc.poll_task, c->bck_fc.poll_task);
2463
2464   /* Cancel maintainance task (keepalive/timeout) */
2465   if (NULL != c->fwd_fc.poll_msg)
2466   {
2467     GMC_cancel (c->fwd_fc.poll_msg);
2468     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL msg FWD canceled\n");
2469   }
2470   if (NULL != c->bck_fc.poll_msg)
2471   {
2472     GMC_cancel (c->bck_fc.poll_msg);
2473     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL msg BCK canceled\n");
2474   }
2475
2476   /* Delete from tunnel */
2477   if (NULL != c->t)
2478     GMT_remove_connection (c->t, c);
2479
2480   if (GNUNET_NO == GMC_is_origin (c, GNUNET_YES) && NULL != c->path)
2481     path_destroy (c->path);
2482   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
2483     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
2484   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
2485     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
2486   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_fc.poll_task)
2487   {
2488     GNUNET_SCHEDULER_cancel (c->fwd_fc.poll_task);
2489     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL FWD canceled\n");
2490   }
2491   if (GNUNET_SCHEDULER_NO_TASK != c->bck_fc.poll_task)
2492   {
2493     GNUNET_SCHEDULER_cancel (c->bck_fc.poll_task);
2494     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL BCK canceled\n");
2495   }
2496
2497   GNUNET_break (GNUNET_YES ==
2498                 GNUNET_CONTAINER_multihashmap_remove (connections,
2499                                                       GMC_get_h (c), c));
2500
2501   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
2502   GNUNET_free (c);
2503 }
2504
2505 /**
2506  * Get the connection ID.
2507  *
2508  * @param c Connection to get the ID from.
2509  *
2510  * @return ID of the connection.
2511  */
2512 const struct GNUNET_MeshHash *
2513 GMC_get_id (const struct MeshConnection *c)
2514 {
2515   return &c->id;
2516 }
2517
2518
2519 /**
2520  * Get the connection ID.
2521  *
2522  * @param c Connection to get the ID from.
2523  *
2524  * @return ID of the connection.
2525  */
2526 const struct GNUNET_HashCode *
2527 GMC_get_h (const struct MeshConnection *c)
2528 {
2529   return GM_h2hc (&c->id);
2530 }
2531
2532
2533 /**
2534  * Get the connection path.
2535  *
2536  * @param c Connection to get the path from.
2537  *
2538  * @return path used by the connection.
2539  */
2540 const struct MeshPeerPath *
2541 GMC_get_path (const struct MeshConnection *c)
2542 {
2543   if (GNUNET_NO == c->destroy)
2544     return c->path;
2545   return NULL;
2546 }
2547
2548
2549 /**
2550  * Get the connection state.
2551  *
2552  * @param c Connection to get the state from.
2553  *
2554  * @return state of the connection.
2555  */
2556 enum MeshConnectionState
2557 GMC_get_state (const struct MeshConnection *c)
2558 {
2559   return c->state;
2560 }
2561
2562 /**
2563  * Get the connection tunnel.
2564  *
2565  * @param c Connection to get the tunnel from.
2566  *
2567  * @return tunnel of the connection.
2568  */
2569 struct MeshTunnel3 *
2570 GMC_get_tunnel (const struct MeshConnection *c)
2571 {
2572   return c->t;
2573 }
2574
2575
2576 /**
2577  * Get free buffer space in a connection.
2578  *
2579  * @param c Connection.
2580  * @param fwd Is query about FWD traffic?
2581  *
2582  * @return Free buffer space [0 - max_msgs_queue/max_connections]
2583  */
2584 unsigned int
2585 GMC_get_buffer (struct MeshConnection *c, int fwd)
2586 {
2587   struct MeshFlowControl *fc;
2588
2589   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2590
2591   return (fc->queue_max - fc->queue_n);
2592 }
2593
2594 /**
2595  * Get how many messages have we allowed to send to us from a direction.
2596  *
2597  * @param c Connection.
2598  * @param fwd Are we asking about traffic from FWD (BCK messages)?
2599  *
2600  * @return last_ack_sent - last_pid_recv
2601  */
2602 unsigned int
2603 GMC_get_allowed (struct MeshConnection *c, int fwd)
2604 {
2605   struct MeshFlowControl *fc;
2606
2607   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2608   if (GM_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
2609   {
2610     return 0;
2611   }
2612   return (fc->last_ack_sent - fc->last_pid_recv);
2613 }
2614
2615 /**
2616  * Get messages queued in a connection.
2617  *
2618  * @param c Connection.
2619  * @param fwd Is query about FWD traffic?
2620  *
2621  * @return Number of messages queued.
2622  */
2623 unsigned int
2624 GMC_get_qn (struct MeshConnection *c, int fwd)
2625 {
2626   struct MeshFlowControl *fc;
2627
2628   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2629
2630   return fc->queue_n;
2631 }
2632
2633
2634 /**
2635  * Allow the connection to advertise a buffer of the given size.
2636  *
2637  * The connection will send an @c fwd ACK message (so: in direction !fwd)
2638  * allowing up to last_pid_recv + buffer.
2639  *
2640  * @param c Connection.
2641  * @param buffer How many more messages the connection can accept.
2642  * @param fwd Is this about FWD traffic? (The ack will go dest->root).
2643  */
2644 void
2645 GMC_allow (struct MeshConnection *c, unsigned int buffer, int fwd)
2646 {
2647   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowing %s %u messages %s\n",
2648        GMC_2s (c), buffer, GM_f2s (fwd));
2649   send_ack (c, buffer, fwd, GNUNET_NO);
2650 }
2651
2652
2653 /**
2654  * Notify other peers on a connection of a broken link. Mark connections
2655  * to destroy after all traffic has been sent.
2656  *
2657  * @param c Connection on which there has been a disconnection.
2658  * @param peer Peer that disconnected.
2659  */
2660 void
2661 GMC_notify_broken (struct MeshConnection *c,
2662                    struct MeshPeer *peer)
2663 {
2664   int fwd;
2665
2666   LOG (GNUNET_ERROR_TYPE_DEBUG,
2667        " notify broken on %s due to %s disconnect\n",
2668        GMC_2s (c), GMP_2s (peer));
2669
2670   fwd = peer == get_prev_hop (c);
2671
2672   if (GNUNET_YES == GMC_is_terminal (c, fwd))
2673   {
2674     /* Local shutdown, no one to notify about this. */
2675     GMC_destroy (c);
2676     return;
2677   }
2678   if (GNUNET_NO == c->destroy)
2679     send_broken (c, &my_full_id, GMP_get_id (peer), fwd);
2680
2681   /* Connection will have at least one pending message
2682    * (the one we just scheduled), so no point in checking whether to
2683    * destroy immediately. */
2684   c->destroy = GNUNET_YES;
2685   c->state = MESH_CONNECTION_DESTROYED;
2686
2687   /**
2688    * Cancel all queues, if no message is left, connection will be destroyed.
2689    */
2690   connection_cancel_queues (c, !fwd);
2691
2692   return;
2693 }
2694
2695
2696 /**
2697  * Is this peer the first one on the connection?
2698  *
2699  * @param c Connection.
2700  * @param fwd Is this about fwd traffic?
2701  *
2702  * @return #GNUNET_YES if origin, #GNUNET_NO if relay/terminal.
2703  */
2704 int
2705 GMC_is_origin (struct MeshConnection *c, int fwd)
2706 {
2707   if (!fwd && c->path->length - 1 == c->own_pos )
2708     return GNUNET_YES;
2709   if (fwd && 0 == c->own_pos)
2710     return GNUNET_YES;
2711   return GNUNET_NO;
2712 }
2713
2714
2715 /**
2716  * Is this peer the last one on the connection?
2717  *
2718  * @param c Connection.
2719  * @param fwd Is this about fwd traffic?
2720  *            Note that the ROOT is the terminal for BCK traffic!
2721  *
2722  * @return #GNUNET_YES if terminal, #GNUNET_NO if relay/origin.
2723  */
2724 int
2725 GMC_is_terminal (struct MeshConnection *c, int fwd)
2726 {
2727   return GMC_is_origin (c, !fwd);
2728 }
2729
2730
2731 /**
2732  * See if we are allowed to send by the next hop in the given direction.
2733  *
2734  * @param c Connection.
2735  * @param fwd Is this about fwd traffic?
2736  *
2737  * @return #GNUNET_YES in case it's OK to send.
2738  */
2739 int
2740 GMC_is_sendable (struct MeshConnection *c, int fwd)
2741 {
2742   struct MeshFlowControl *fc;
2743
2744   if (NULL == c)
2745   {
2746     GNUNET_break (0);
2747     return GNUNET_YES;
2748   }
2749   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2750   if (GM_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2751     return GNUNET_YES;
2752   return GNUNET_NO;
2753 }
2754
2755 /**
2756  * Sends an already built message on a connection, properly registering
2757  * all used resources.
2758  *
2759  * @param message Message to send. Function makes a copy of it.
2760  *                If message is not hop-by-hop, decrements TTL of copy.
2761  * @param c Connection on which this message is transmitted.
2762  * @param fwd Is this a fwd message?
2763  * @param force Force the connection to accept the message (buffer overfill).
2764  * @param cont Continuation called once message is sent. Can be NULL.
2765  * @param cont_cls Closure for @c cont.
2766  *
2767  * @return Handle to cancel the message before it's sent.
2768  *         NULL on error or if @c cont is NULL.
2769  *         Invalid on @c cont call.
2770  */
2771 struct MeshConnectionQueue *
2772 GMC_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2773                            struct MeshConnection *c, int fwd, int force,
2774                            GMC_sent cont, void *cont_cls)
2775 {
2776   struct MeshFlowControl *fc;
2777   struct MeshConnectionQueue *q;
2778   void *data;
2779   size_t size;
2780   uint16_t type;
2781   int droppable;
2782
2783   size = ntohs (message->size);
2784   data = GNUNET_malloc (size);
2785   memcpy (data, message, size);
2786   type = ntohs (message->type);
2787   LOG (GNUNET_ERROR_TYPE_INFO, "-> %s on connection %s (%u bytes)\n",
2788        GM_m2s (type), GMC_2s (c), size);
2789
2790   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2791   droppable = GNUNET_NO == force;
2792   switch (type)
2793   {
2794     struct GNUNET_MESH_Encrypted *emsg;
2795     struct GNUNET_MESH_KX        *kmsg;
2796     struct GNUNET_MESH_ACK       *amsg;
2797     struct GNUNET_MESH_Poll      *pmsg;
2798     struct GNUNET_MESH_ConnectionDestroy *dmsg;
2799     struct GNUNET_MESH_ConnectionBroken  *bmsg;
2800     uint32_t ttl;
2801
2802     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
2803       emsg = (struct GNUNET_MESH_Encrypted *) data;
2804       ttl = ntohl (emsg->ttl);
2805       if (0 == ttl)
2806       {
2807         GNUNET_break_op (0);
2808         GNUNET_free (data);
2809         return NULL;
2810       }
2811       emsg->cid = c->id;
2812       emsg->ttl = htonl (ttl - 1);
2813       emsg->pid = htonl (fc->next_pid++);
2814       LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
2815       if (GNUNET_YES == droppable)
2816       {
2817         fc->queue_n++;
2818         LOG (GNUNET_ERROR_TYPE_DEBUG, "pid %u\n", ntohl (emsg->pid));
2819         LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid sent %u\n", fc->last_pid_sent);
2820         LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack recv %u\n", fc->last_ack_recv);
2821       }
2822       else
2823       {
2824         LOG (GNUNET_ERROR_TYPE_DEBUG, "  not droppable, Q_N stays the same\n");
2825       }
2826       if (GM_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
2827       {
2828         GMC_start_poll (c, fwd);
2829       }
2830       break;
2831
2832     case GNUNET_MESSAGE_TYPE_MESH_KX:
2833       kmsg = (struct GNUNET_MESH_KX *) data;
2834       kmsg->cid = c->id;
2835       break;
2836
2837     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2838       amsg = (struct GNUNET_MESH_ACK *) data;
2839       amsg->cid = c->id;
2840       LOG (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
2841       droppable = GNUNET_NO;
2842       break;
2843
2844     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2845       pmsg = (struct GNUNET_MESH_Poll *) data;
2846       pmsg->cid = c->id;
2847       LOG (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
2848       droppable = GNUNET_NO;
2849       break;
2850
2851     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
2852       dmsg = (struct GNUNET_MESH_ConnectionDestroy *) data;
2853       dmsg->cid = c->id;
2854       break;
2855
2856     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
2857       bmsg = (struct GNUNET_MESH_ConnectionBroken *) data;
2858       bmsg->cid = c->id;
2859       break;
2860
2861     case GNUNET_MESSAGE_TYPE_MESH_KEEPALIVE:
2862       GNUNET_break (0);
2863       /* falltrough */
2864     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
2865     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
2866       break;
2867
2868     default:
2869       GNUNET_break (0);
2870       GNUNET_free (data);
2871       return NULL;
2872   }
2873
2874   if (fc->queue_n > fc->queue_max && droppable)
2875   {
2876     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
2877                               1, GNUNET_NO);
2878     GNUNET_break (0);
2879     LOG (GNUNET_ERROR_TYPE_DEBUG,
2880                 "queue full: %u/%u\n",
2881                 fc->queue_n, fc->queue_max);
2882     if (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED == type)
2883     {
2884       fc->queue_n--;
2885       fc->next_pid--;
2886     }
2887     GNUNET_free (data);
2888     return NULL; /* Drop this message */
2889   }
2890
2891   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u\n", c, c->pending_messages);
2892   c->pending_messages++;
2893
2894   q = GNUNET_new (struct MeshConnectionQueue);
2895   q->forced = !droppable;
2896   q->q = GMP_queue_add (get_hop (c, fwd), data, type, size, c, fwd,
2897                         &message_sent, q);
2898   if (NULL == q->q)
2899   {
2900     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING dropping msg on %s\n", GMC_2s (c));
2901     GNUNET_free (data);
2902     GNUNET_free (q);
2903     return NULL;
2904   }
2905   q->cont = cont;
2906   q->cont_cls = cont_cls;
2907   return q;
2908 }
2909
2910
2911 /**
2912  * Cancel a previously sent message while it's in the queue.
2913  *
2914  * ONLY can be called before the continuation given to the send function
2915  * is called. Once the continuation is called, the message is no longer in the
2916  * queue.
2917  *
2918  * @param q Handle to the queue.
2919  */
2920 void
2921 GMC_cancel (struct MeshConnectionQueue *q)
2922 {
2923   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  GMC cancel message\n");
2924
2925   /* queue destroy calls message_sent, which calls q->cont and frees q */
2926   GMP_queue_destroy (q->q, GNUNET_YES);
2927 }
2928
2929
2930 /**
2931  * Sends a CREATE CONNECTION message for a path to a peer.
2932  * Changes the connection and tunnel states if necessary.
2933  *
2934  * @param connection Connection to create.
2935  */
2936 void
2937 GMC_send_create (struct MeshConnection *connection)
2938 {
2939   enum MeshTunnel3CState state;
2940   size_t size;
2941
2942   size = sizeof (struct GNUNET_MESH_ConnectionCreate);
2943   size += connection->path->length * sizeof (struct GNUNET_PeerIdentity);
2944
2945   LOG (GNUNET_ERROR_TYPE_INFO, "=> %s on connection %s  (%u bytes)\n",
2946        GM_m2s (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE),
2947        GMC_2s (connection), size);
2948   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u (create)\n",
2949        connection, connection->pending_messages);
2950   connection->pending_messages++;
2951
2952   connection->maintenance_q =
2953     GMP_queue_add (get_next_hop (connection), NULL,
2954                    GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
2955                    size, connection, GNUNET_YES, &message_sent, NULL);
2956
2957   state = GMT_get_cstate (connection->t);
2958   if (MESH_TUNNEL3_SEARCHING == state || MESH_TUNNEL3_NEW == state)
2959     GMT_change_cstate (connection->t, MESH_TUNNEL3_WAITING);
2960   if (MESH_CONNECTION_NEW == connection->state)
2961     connection_change_state (connection, MESH_CONNECTION_SENT);
2962 }
2963
2964
2965 /**
2966  * Send a message to all peers in this connection that the connection
2967  * is no longer valid.
2968  *
2969  * If some peer should not receive the message, it should be zero'ed out
2970  * before calling this function.
2971  *
2972  * @param c The connection whose peers to notify.
2973  */
2974 void
2975 GMC_send_destroy (struct MeshConnection *c)
2976 {
2977   struct GNUNET_MESH_ConnectionDestroy msg;
2978
2979   if (GNUNET_YES == c->destroy)
2980     return;
2981
2982   msg.header.size = htons (sizeof (msg));
2983   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY);;
2984   msg.cid = c->id;
2985   LOG (GNUNET_ERROR_TYPE_DEBUG,
2986               "  sending connection destroy for connection %s\n",
2987               GMC_2s (c));
2988
2989   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_YES))
2990     GMC_send_prebuilt_message (&msg.header, c,
2991                                GNUNET_YES, GNUNET_YES, NULL, NULL);
2992   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_NO))
2993     GMC_send_prebuilt_message (&msg.header, c,
2994                                GNUNET_NO, GNUNET_YES, NULL, NULL);
2995   c->destroy = GNUNET_YES;
2996   c->state = MESH_CONNECTION_DESTROYED;
2997 }
2998
2999
3000 /**
3001  * @brief Start a polling timer for the connection.
3002  *
3003  * When a neighbor does not accept more traffic on the connection it could be
3004  * caused by a simple congestion or by a lost ACK. Polling enables to check
3005  * for the lastest ACK status for a connection.
3006  *
3007  * @param c Connection.
3008  * @param fwd Should we poll in the FWD direction?
3009  */
3010 void
3011 GMC_start_poll (struct MeshConnection *c, int fwd)
3012 {
3013   struct MeshFlowControl *fc;
3014
3015   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3016   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL %s requested\n",
3017        GM_f2s (fwd));
3018   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task || NULL != fc->poll_msg)
3019   {
3020     LOG (GNUNET_ERROR_TYPE_DEBUG, " ***   not needed (%u, %p)\n",
3021          fc->poll_task, fc->poll_msg);
3022     return;
3023   }
3024   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL started on request\n");
3025   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3026                                                 &connection_poll,
3027                                                 fc);
3028 }
3029
3030
3031 /**
3032  * @brief Stop polling a connection for ACKs.
3033  *
3034  * Once we have enough ACKs for future traffic, polls are no longer necessary.
3035  *
3036  * @param c Connection.
3037  * @param fwd Should we stop the poll in the FWD direction?
3038  */
3039 void
3040 GMC_stop_poll (struct MeshConnection *c, int fwd)
3041 {
3042   struct MeshFlowControl *fc;
3043
3044   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3045   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
3046   {
3047     GNUNET_SCHEDULER_cancel (fc->poll_task);
3048     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3049   }
3050 }
3051
3052 /**
3053  * Get a (static) string for a connection.
3054  *
3055  * @param c Connection.
3056  */
3057 const char *
3058 GMC_2s (const struct MeshConnection *c)
3059 {
3060   if (NULL == c)
3061     return "NULL";
3062
3063   if (NULL != c->t)
3064   {
3065     static char buf[128];
3066
3067     sprintf (buf, "%s (->%s)", GNUNET_h2s (GM_h2hc (GMC_get_id(c))), GMT_2s (c->t));
3068     return buf;
3069   }
3070   return GNUNET_h2s (GM_h2hc (&c->id));
3071 }