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