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