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