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