- flow control changes and fixes
[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_enc.h"
34 #include "mesh_enc.h"
35 #include "gnunet-service-mesh_connection.h"
36 #include "gnunet-service-mesh_peer.h"
37 #include "gnunet-service-mesh_tunnel.h"
38 #include "gnunet-service-mesh_channel.h"
39
40
41 #define LOG(level, ...) GNUNET_log_from (level,"mesh-con",__VA_ARGS__)
42
43 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
44                                   GNUNET_TIME_UNIT_MINUTES,\
45                                   10)
46 #define AVG_MSGS                32
47
48
49 /******************************************************************************/
50 /********************************   STRUCTS  **********************************/
51 /******************************************************************************/
52
53 /**
54  * Struct to encapsulate all the Flow Control information to a peer to which
55  * we are directly connected (on a core level).
56  */
57 struct MeshFlowControl
58 {
59   /**
60    * Connection this controls.
61    */
62   struct MeshConnection *c;
63
64   /**
65    * How many messages are in the queue on this connection.
66    */
67   unsigned int queue_n;
68
69   /**
70    * How many messages do we accept in the queue.
71    */
72   unsigned int queue_max;
73
74   /**
75    * Next ID to use.
76    */
77   uint32_t next_pid;
78
79   /**
80    * ID of the last packet sent towards the peer.
81    */
82   uint32_t last_pid_sent;
83
84   /**
85    * ID of the last packet received from the peer.
86    */
87   uint32_t last_pid_recv;
88
89   /**
90    * Last ACK sent to the peer (peer can't send more than this PID).
91    */
92   uint32_t last_ack_sent;
93
94   /**
95    * Last ACK sent towards the origin (for traffic towards leaf node).
96    */
97   uint32_t last_ack_recv;
98
99   /**
100    * Task to poll the peer in case of a lost ACK causes stall.
101    */
102   GNUNET_SCHEDULER_TaskIdentifier poll_task;
103
104   /**
105    * How frequently to poll for ACKs.
106    */
107   struct GNUNET_TIME_Relative poll_time;
108 };
109
110 /**
111  * Keep a record of the last messages sent on this connection.
112  */
113 struct MeshConnectionPerformance
114 {
115   /**
116    * Circular buffer for storing measurements.
117    */
118   double usecsperbyte[AVG_MSGS];
119
120   /**
121    * Running average of @c usecsperbyte.
122    */
123   double avg;
124
125   /**
126    * How many values of @c usecsperbyte are valid.
127    */
128   uint16_t size;
129
130   /**
131    * Index of the next "free" position in @c usecsperbyte.
132    */
133   uint16_t idx;
134 };
135
136
137 /**
138  * Struct containing all information regarding a connection to a peer.
139  */
140 struct MeshConnection
141 {
142   /**
143    * Tunnel this connection is part of.
144    */
145   struct MeshTunnel3 *t;
146
147   /**
148    * Flow control information for traffic fwd.
149    */
150   struct MeshFlowControl fwd_fc;
151
152   /**
153    * Flow control information for traffic bck.
154    */
155   struct MeshFlowControl bck_fc;
156
157   /**
158    * Measure connection performance on the endpoint.
159    */
160   struct MeshConnectionPerformance *perf;
161
162   /**
163    * ID of the connection.
164    */
165   struct GNUNET_HashCode id;
166
167   /**
168    * State of the connection.
169    */
170   enum MeshConnectionState state;
171
172   /**
173    * Path being used for the tunnel.
174    */
175   struct MeshPeerPath *path;
176
177   /**
178    * Position of the local peer in the path.
179    */
180   unsigned int own_pos;
181
182   /**
183    * Task to keep the used paths alive at the owner,
184    * time tunnel out on all the other peers.
185    */
186   GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
187
188   /**
189    * Task to keep the used paths alive at the destination,
190    * time tunnel out on all the other peers.
191    */
192   GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
193
194   /**
195    * Pending message count.
196    */
197   int pending_messages;
198
199   /**
200    * Destroy flag: if true, destroy on last message.
201    */
202   int destroy;
203 };
204
205 /******************************************************************************/
206 /*******************************   GLOBALS  ***********************************/
207 /******************************************************************************/
208
209 /**
210  * Global handle to the statistics service.
211  */
212 extern struct GNUNET_STATISTICS_Handle *stats;
213
214 /**
215  * Local peer own ID (memory efficient handle).
216  */
217 extern GNUNET_PEER_Id myid;
218
219 /**
220  * Local peer own ID (full value).
221  */
222 extern struct GNUNET_PeerIdentity my_full_id;
223
224 /**
225  * Connections known, indexed by cid (MeshConnection).
226  */
227 static struct GNUNET_CONTAINER_MultiHashMap *connections;
228
229 /**
230  * How many connections are we willing to maintain.
231  * Local connections are always allowed, even if there are more connections than max.
232  */
233 static unsigned long long max_connections;
234
235 /**
236  * How many messages *in total* are we willing to queue, divide by number of
237  * connections to get connection queue size.
238  */
239 static unsigned long long max_msgs_queue;
240
241 /**
242  * How often to send path keepalives. Paths timeout after 4 missed.
243  */
244 static struct GNUNET_TIME_Relative refresh_connection_time;
245
246
247 /******************************************************************************/
248 /********************************   STATIC  ***********************************/
249 /******************************************************************************/
250
251 #if 0 // avoid compiler warning for unused static function
252 static void
253 fc_debug (struct MeshFlowControl *fc)
254 {
255   LOG (GNUNET_ERROR_TYPE_DEBUG, "    IN: %u/%u\n",
256               fc->last_pid_recv, fc->last_ack_sent);
257   LOG (GNUNET_ERROR_TYPE_DEBUG, "    OUT: %u/%u\n",
258               fc->last_pid_sent, fc->last_ack_recv);
259   LOG (GNUNET_ERROR_TYPE_DEBUG, "    QUEUE: %u/%u\n",
260               fc->queue_n, fc->queue_max);
261 }
262
263 static void
264 connection_debug (struct MeshConnection *c)
265 {
266   if (NULL == c)
267   {
268     LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CONNECTION ***\n");
269     return;
270   }
271   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
272               peer2s (c->t->peer), GMC_2s (c));
273   LOG (GNUNET_ERROR_TYPE_DEBUG, "  state: %u, pending msgs: %u\n",
274               c->state, c->pending_messages);
275   LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
276   fc_debug (&c->fwd_fc);
277   LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
278   fc_debug (&c->bck_fc);
279 }
280 #endif
281
282 /**
283  * Get string description for tunnel state.
284  *
285  * @param s Tunnel state.
286  *
287  * @return String representation.
288  */
289 static const char *
290 GMC_state2s (enum MeshConnectionState s)
291 {
292   switch (s)
293   {
294     case MESH_CONNECTION_NEW:
295       return "MESH_CONNECTION_NEW";
296     case MESH_CONNECTION_SENT:
297       return "MESH_CONNECTION_SENT";
298     case MESH_CONNECTION_ACK:
299       return "MESH_CONNECTION_ACK";
300     case MESH_CONNECTION_READY:
301       return "MESH_CONNECTION_READY";
302     default:
303       return "MESH_CONNECTION_STATE_ERROR";
304   }
305 }
306
307
308 /**
309  * Initialize a Flow Control structure to the initial state.
310  *
311  * @param fc Flow Control structure to initialize.
312  */
313 static void
314 fc_init (struct MeshFlowControl *fc)
315 {
316   fc->next_pid = 0;
317   fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
318   fc->last_pid_recv = (uint32_t) -1;
319   fc->last_ack_sent = (uint32_t) 0;
320   fc->last_ack_recv = (uint32_t) 0;
321   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
322   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
323   fc->queue_n = 0;
324   fc->queue_max = (max_msgs_queue / max_connections) + 1;
325 }
326
327
328 /**
329  * Find a connection.
330  *
331  * @param cid Connection ID.
332  */
333 static struct MeshConnection *
334 connection_get (const struct GNUNET_HashCode *cid)
335 {
336   return GNUNET_CONTAINER_multihashmap_get (connections, cid);
337 }
338
339
340 static void
341 connection_change_state (struct MeshConnection* c,
342                          enum MeshConnectionState state)
343 {
344   LOG (GNUNET_ERROR_TYPE_DEBUG,
345               "Connection %s state was %s\n",
346               GMC_2s (c), GMC_state2s (c->state));
347   LOG (GNUNET_ERROR_TYPE_DEBUG,
348               "Connection %s state is now %s\n",
349               GMC_2s (c), GMC_state2s (state));
350   c->state = state;
351 }
352
353
354 /**
355  * Send an ACK on the connection, informing the predecessor about
356  * the available buffer space. Should not be called in case the peer
357  * is origin (no predecessor).
358  *
359  * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
360  * the ACK itself goes "back" (dest->root).
361  *
362  * @param c Connection on which to send the ACK.
363  * @param buffer How much space free to advertise?
364  * @param fwd Is this FWD ACK? (Going dest->owner)
365  */
366 static void
367 send_ack (struct MeshConnection *c, unsigned int buffer, int fwd)
368 {
369   struct MeshFlowControl *next_fc;
370   struct MeshFlowControl *prev_fc;
371   struct GNUNET_MESH_ACK msg;
372   uint32_t ack;
373   int delta;
374
375   /* If origin, there is no connection to send ACKs. Wrong function! */
376   if (GMC_is_origin (c, fwd))
377   {
378     GNUNET_break (0);
379     return;
380   }
381
382   next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
383   prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
384
385   LOG (GNUNET_ERROR_TYPE_DEBUG,
386               "connection send %s ack on %s\n",
387               fwd ? "FWD" : "BCK", GMC_2s (c));
388
389   /* Check if we need to transmit the ACK */
390   delta = prev_fc->last_ack_sent - prev_fc->last_pid_recv;
391   if (3 < delta && buffer < delta)
392   {
393     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
394     LOG (GNUNET_ERROR_TYPE_DEBUG,
395          "  last pid recv: %u, last ack sent: %u\n",
396          prev_fc->last_pid_recv, prev_fc->last_ack_sent);
397     return;
398   }
399
400   /* Ok, ACK might be necessary, what PID to ACK? */
401   ack = prev_fc->last_pid_recv + buffer;
402   LOG (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
403   LOG (GNUNET_ERROR_TYPE_DEBUG,
404        " last pid %u, last ack %u, qmax %u, q %u\n",
405        prev_fc->last_pid_recv, prev_fc->last_ack_sent,
406        next_fc->queue_max, next_fc->queue_n);
407   if (ack == prev_fc->last_ack_sent)
408   {
409     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
410     return;
411   }
412
413   prev_fc->last_ack_sent = ack;
414
415   /* Build ACK message and send on connection */
416   msg.header.size = htons (sizeof (msg));
417   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
418   msg.ack = htonl (ack);
419   msg.cid = c->id;
420
421   GMC_send_prebuilt_message (&msg.header, c, NULL, !fwd);
422 }
423
424
425 /**
426  * Callback called when a queued message is sent.
427  *
428  * Calculates the average time and connection packet tracking.
429  *
430  * @param cls Closure.
431  * @param c Connection this message was on.
432  * @param type Type of message sent.
433  * @param fwd Was this a FWD going message?
434  * @param size Size of the message.
435  * @param wait Time spent waiting for core (only the time for THIS message)
436  */
437 static void 
438 message_sent (void *cls,
439               struct MeshConnection *c, uint16_t type,
440               int fwd, size_t size,
441               struct GNUNET_TIME_Relative wait)
442 {
443   struct MeshConnectionPerformance *p;
444   struct MeshFlowControl *fc;
445   double usecsperbyte;
446
447   fc = fwd ? &c->fwd_fc : &c->bck_fc;
448   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  sent %s\n", GNUNET_MESH_DEBUG_M2S (type));
449   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  Q_N- %p %u\n", fc, fc->queue_n);
450   c->pending_messages--;
451   if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
452   {
453     LOG (GNUNET_ERROR_TYPE_DEBUG, "!  destroying connection!\n");
454     GMC_destroy (c);
455   }
456   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
457   switch (type)
458   {
459     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
460       fc->last_pid_sent++;
461       fc->queue_n--;
462       LOG (GNUNET_ERROR_TYPE_DEBUG,
463            "!   accounting pid %u\n",
464            fc->last_pid_sent);
465       GMC_send_ack (c, fwd);
466       break;
467     default:
468       break;
469   }
470   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  message sent!\n");
471
472   if (NULL == c->perf)
473     return; /* Only endpoints are interested in timing. */
474
475   p = c->perf;
476   usecsperbyte = ((double) wait.rel_value_us) / size;
477   if (p->size == AVG_MSGS)
478   {
479     /* Array is full. Substract oldest value, add new one and store. */
480     p->avg -= (p->usecsperbyte[p->idx] / AVG_MSGS);
481     p->usecsperbyte[p->idx] = usecsperbyte;
482     p->avg += (p->usecsperbyte[p->idx] / AVG_MSGS);
483   }
484   else
485   {
486     /* Array not yet full. Add current value to avg and store. */
487     p->usecsperbyte[p->idx] = usecsperbyte;
488     p->avg *= p->size;
489     p->avg += p->usecsperbyte[p->idx];
490     p->size++;
491     p->avg /= p->size;
492   }
493   p->idx = (p->idx + 1) % AVG_MSGS;
494
495 //   if (NULL != c->t)
496 //   {
497 //     c->t->pending_messages--;
498 //     if (GNUNET_YES == c->t->destroy && 0 == t->pending_messages)
499 //     {
500 //       LOG (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
501 //       GMT_destroy (c->t);
502 //     }
503 //   }
504 }
505
506
507 /**
508  * Get the previous hop in a connection
509  *
510  * @param c Connection.
511  *
512  * @return Previous peer in the connection.
513  */
514 static struct MeshPeer *
515 get_prev_hop (const struct MeshConnection *c)
516 {
517   GNUNET_PEER_Id id;
518
519   if (0 == c->own_pos || c->path->length < 2)
520     id = c->path->peers[0];
521   else
522     id = c->path->peers[c->own_pos - 1];
523
524   return GMP_get_short (id);
525 }
526
527
528 /**
529  * Get the next hop in a connection
530  *
531  * @param c Connection.
532  *
533  * @return Next peer in the connection.
534  */
535 static struct MeshPeer *
536 get_next_hop (const struct MeshConnection *c)
537 {
538   GNUNET_PEER_Id id;
539
540   if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
541     id = c->path->peers[c->path->length - 1];
542   else
543     id = c->path->peers[c->own_pos + 1];
544
545   return GMP_get_short (id);
546 }
547
548
549 /**
550  * Get the hop in a connection.
551  *
552  * @param c Connection.
553  * @param fwd Next hop?
554  *
555  * @return Next peer in the connection.
556  */
557 static struct MeshPeer *
558 get_hop (struct MeshConnection *c, int fwd)
559 {
560   if (fwd)
561     return get_next_hop (c);
562   return get_prev_hop (c);
563 }
564
565
566 /**
567  * Is traffic coming from this sender 'FWD' traffic?
568  *
569  * @param c Connection to check.
570  * @param sender Peer identity of neighbor.
571  *
572  * @return GNUNET_YES in case the sender is the 'prev' hop and therefore
573  *         the traffic is 'FWD'. GNUNET_NO for BCK. GNUNET_SYSERR for errors.
574  */
575 static int 
576 is_fwd (const struct MeshConnection *c,
577         const struct GNUNET_PeerIdentity *sender)
578 {
579   GNUNET_PEER_Id id;
580
581   id = GNUNET_PEER_search (sender);
582   if (GMP_get_short_id (get_prev_hop (c)) == id)
583     return GNUNET_YES;
584
585   if (GMP_get_short_id (get_next_hop (c)) == id)
586     return GNUNET_NO;
587
588   GNUNET_break (0);
589   return GNUNET_SYSERR;
590 }
591
592
593 /**
594  * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
595  * or a first CONNECTION_ACK directed to us.
596  *
597  * @param connection Connection to confirm.
598  * @param fwd Should we send it FWD?
599  *            (First (~SYNACK) goes BCK, second (~ACK) goes FWD)
600  */
601 static void
602 send_connection_ack (struct MeshConnection *connection, int fwd)
603 {
604   struct MeshTunnel3 *t;
605
606   t = connection->t;
607   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
608   GMP_queue_add (get_hop (connection, fwd), NULL,
609                  GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
610                  sizeof (struct GNUNET_MESH_ConnectionACK),
611                  connection, NULL, fwd,
612                  &message_sent, NULL);
613   if (MESH_TUNNEL3_NEW == GMT_get_state (t))
614     GMT_change_state (t, MESH_TUNNEL3_WAITING);
615   if (MESH_CONNECTION_READY != connection->state)
616     connection_change_state (connection, MESH_CONNECTION_SENT);
617 }
618
619
620 /**
621  * Send a notification that a connection is broken.
622  *
623  * @param c Connection that is broken.
624  * @param id1 Peer that has disconnected.
625  * @param id2 Peer that has disconnected.
626  * @param fwd Direction towards which to send it.
627  */
628 static void
629 send_broken (struct MeshConnection *c,
630              const struct GNUNET_PeerIdentity *id1,
631              const struct GNUNET_PeerIdentity *id2,
632              int fwd)
633 {
634   struct GNUNET_MESH_ConnectionBroken msg;
635
636   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
637   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
638   msg.cid = c->id;
639   msg.peer1 = *id1;
640   msg.peer2 = *id2;
641   GMC_send_prebuilt_message (&msg.header, c, NULL, fwd);
642 }
643
644
645
646 /**
647  * Send keepalive packets for a connection.
648  *
649  * @param c Connection to keep alive..
650  * @param fwd Is this a FWD keepalive? (owner -> dest).
651  */
652 static void
653 connection_keepalive (struct MeshConnection *c, int fwd)
654 {
655   struct GNUNET_MESH_ConnectionKeepAlive *msg;
656   size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
657   char cbuf[size];
658   uint16_t type;
659
660   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
661                GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
662
663   LOG (GNUNET_ERROR_TYPE_DEBUG,
664        "sending %s keepalive for connection %s]\n",
665        fwd ? "FWD" : "BCK", GMC_2s (c));
666
667   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
668   msg->header.size = htons (size);
669   msg->header.type = htons (type);
670   msg->cid = c->id;
671
672   GMC_send_prebuilt_message (&msg->header, c, NULL, fwd);
673 }
674
675
676 /**
677  * Send CONNECTION_{CREATE/ACK} packets for a connection.
678  *
679  * @param c Connection for which to send the message.
680  * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
681  */
682 static void
683 connection_recreate (struct MeshConnection *c, int fwd)
684 {
685   LOG (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
686   if (fwd)
687     GMC_send_create (c);
688   else
689     send_connection_ack (c, GNUNET_NO);
690 }
691
692
693 /**
694  * Generic connection timer management.
695  * Depending on the role of the peer in the connection will send the
696  * appropriate message (build or keepalive)
697  *
698  * @param c Conncetion to maintain.
699  * @param fwd Is FWD?
700  */
701 static void
702 connection_maintain (struct MeshConnection *c, int fwd)
703 {
704   if (MESH_TUNNEL3_SEARCHING == GMT_get_state (c->t))
705   {
706     /* TODO DHT GET with RO_BART */
707     return;
708   }
709   switch (c->state)
710   {
711     case MESH_CONNECTION_NEW:
712       GNUNET_break (0);
713     case MESH_CONNECTION_SENT:
714       connection_recreate (c, fwd);
715       break;
716     case MESH_CONNECTION_READY:
717       connection_keepalive (c, fwd);
718       break;
719     default:
720       break;
721   }
722 }
723
724
725 static void
726 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
727 {
728   struct MeshConnection *c = cls;
729
730   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
731   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
732     return;
733
734   connection_maintain (c, GNUNET_YES);
735   c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
736                                                           &connection_fwd_keepalive,
737                                                           c);
738 }
739
740
741 static void
742 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
743 {
744   struct MeshConnection *c = cls;
745
746   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
747   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
748     return;
749
750   connection_maintain (c, GNUNET_NO);
751   c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
752                                                           &connection_bck_keepalive,
753                                                           c);
754 }
755
756
757 /**
758  * @brief Re-initiate traffic on this connection if necessary.
759  *
760  * Check if there is traffic queued towards this peer
761  * and the core transmit handle is NULL (traffic was stalled).
762  * If so, call core tmt rdy.
763  *
764  * @param c Connection on which initiate traffic.
765  * @param fwd Is this about fwd traffic?
766  */
767 static void
768 connection_unlock_queue (struct MeshConnection *c, int fwd)
769 {
770   struct MeshPeer *peer;
771
772   LOG (GNUNET_ERROR_TYPE_DEBUG,
773               "connection_unlock_queue %s on %s\n",
774               fwd ? "FWD" : "BCK", GMC_2s (c));
775
776   if (GMC_is_terminal (c, fwd))
777   {
778     LOG (GNUNET_ERROR_TYPE_DEBUG, " is terminal!\n");
779     return;
780   }
781
782   peer = get_hop (c, fwd);
783   GMP_queue_unlock (peer, c);
784 }
785
786
787 /**
788  * Cancel all transmissions that belong to a certain connection.
789  *
790  * @param c Connection which to cancel.
791  * @param fwd Cancel fwd traffic?
792  */
793 static void
794 connection_cancel_queues (struct MeshConnection *c, int fwd)
795 {
796
797   struct MeshFlowControl *fc;
798   struct MeshPeer *peer;
799
800   if (NULL == c)
801   {
802     GNUNET_break (0);
803     return;
804   }
805
806   peer = get_hop (c, fwd);
807   GMP_queue_cancel (peer, c);
808
809   fc = fwd ? &c->fwd_fc : &c->bck_fc;
810   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
811   {
812     GNUNET_SCHEDULER_cancel (fc->poll_task);
813     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
814   }
815 }
816
817
818 /**
819  * Function called if a connection has been stalled for a while,
820  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
821  *
822  * @param cls Closure (poll ctx).
823  * @param tc TaskContext.
824  */
825 static void
826 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
827 {
828   struct MeshFlowControl *fc = cls;
829   struct GNUNET_MESH_Poll msg;
830   struct MeshConnection *c;
831
832   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
833   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
834   {
835     return;
836   }
837
838   c = fc->c;
839   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
840   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** connection [%s]\n", GMC_2s (c));
841   LOG (GNUNET_ERROR_TYPE_DEBUG, " ***   %s\n",
842               fc == &c->fwd_fc ? "FWD" : "BCK");
843
844   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
845   msg.header.size = htons (sizeof (msg));
846   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
847   GMC_send_prebuilt_message (&msg.header, c, NULL, fc == &c->fwd_fc);
848   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
849   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
850                                                 &connection_poll, fc);
851 }
852
853
854 /**
855  * Timeout function due to lack of keepalive/traffic from the owner.
856  * Destroys connection if called.
857  *
858  * @param cls Closure (connection to destroy).
859  * @param tc TaskContext.
860  */
861 static void
862 connection_fwd_timeout (void *cls,
863                         const struct GNUNET_SCHEDULER_TaskContext *tc)
864 {
865   struct MeshConnection *c = cls;
866
867   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
868   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
869     return;
870   LOG (GNUNET_ERROR_TYPE_DEBUG,
871               "Connection %s[%X] FWD timed out. Destroying.\n",
872               GMT_2s (c->t),
873               c->id);
874
875   if (GMC_is_origin (c, GNUNET_YES)) /* If local, leave. */
876     return;
877
878   GMC_destroy (c);
879 }
880
881
882 /**
883  * Timeout function due to lack of keepalive/traffic from the destination.
884  * Destroys connection if called.
885  *
886  * @param cls Closure (connection to destroy).
887  * @param tc TaskContext
888  */
889 static void
890 connection_bck_timeout (void *cls,
891                         const struct GNUNET_SCHEDULER_TaskContext *tc)
892 {
893   struct MeshConnection *c = cls;
894
895   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
896   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
897     return;
898
899   LOG (GNUNET_ERROR_TYPE_DEBUG,
900               "Connection %s[%X] FWD timed out. Destroying.\n",
901               GMT_2s (c->t), c->id);
902
903   if (GMC_is_origin (c, GNUNET_NO)) /* If local, leave. */
904     return;
905
906   GMC_destroy (c);
907 }
908
909
910 /**
911  * Resets the connection timeout task, some other message has done the
912  * task's job.
913  * - For the first peer on the direction this means to send
914  *   a keepalive or a path confirmation message (either create or ACK).
915  * - For all other peers, this means to destroy the connection,
916  *   due to lack of activity.
917  * Starts the tiemout if no timeout was running (connection just created).
918  *
919  * @param c Connection whose timeout to reset.
920  * @param fwd Is this forward?
921  *
922  * TODO use heap to improve efficiency of scheduler.
923  */
924 static void
925 connection_reset_timeout (struct MeshConnection *c, int fwd)
926 {
927   GNUNET_SCHEDULER_TaskIdentifier *ti;
928   GNUNET_SCHEDULER_Task f;
929
930   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
931
932   if (GNUNET_SCHEDULER_NO_TASK != *ti)
933     GNUNET_SCHEDULER_cancel (*ti);
934
935   if (GMC_is_origin (c, fwd)) /* Endpoint */
936   {
937     f  = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
938     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
939   }
940   else /* Relay */
941   {
942     struct GNUNET_TIME_Relative delay;
943
944     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
945     f  = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
946     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
947   }
948 }
949
950
951 /**
952  * Add the connection to the list of both neighbors.
953  *
954  * @param c Connection.
955  */
956 static void
957 register_neighbors (struct MeshConnection *c)
958 {
959   struct MeshPeer *peer;
960
961   peer = get_next_hop (c);
962   if (GNUNET_NO == GMP_is_neighbor (peer))
963   {
964     GMC_destroy (c);
965     return;
966   }
967   GMP_add_connection (peer, c);
968   peer = get_prev_hop (c);
969   if (GNUNET_NO == GMP_is_neighbor (peer))
970   {
971     GMC_destroy (c);
972     return;
973   }
974   GMP_add_connection (peer, c);
975 }
976
977
978 /**
979  * Remove the connection from the list of both neighbors.
980  *
981  * @param c Connection.
982  */
983 static void
984 unregister_neighbors (struct MeshConnection *c)
985 {
986   struct MeshPeer *peer;
987
988   peer = get_next_hop (c);
989   GMP_remove_connection (peer, c);
990
991   peer = get_prev_hop (c);
992   GMP_remove_connection (peer, c);
993
994 }
995
996
997 /**
998  * Bind the connection to the peer and the tunnel to that peer.
999  *
1000  * If the peer has no tunnel, create one. Update tunnel and connection
1001  * data structres to reflect new status.
1002  *
1003  * @param c Connection.
1004  * @param peer Peer.
1005  */
1006 static void
1007 add_to_peer (struct MeshConnection *c, struct MeshPeer *peer)
1008 {
1009   GMP_add_tunnel (peer);
1010   c->t = GMP_get_tunnel (peer);
1011   GMT_add_connection (c->t, c);
1012 }
1013
1014 /******************************************************************************/
1015 /********************************    API    ***********************************/
1016 /******************************************************************************/
1017
1018 /**
1019  * Core handler for connection creation.
1020  *
1021  * @param cls Closure (unused).
1022  * @param peer Sender (neighbor).
1023  * @param message Message.
1024  *
1025  * @return GNUNET_OK to keep the connection open,
1026  *         GNUNET_SYSERR to close it (signal serious error)
1027  */
1028 int
1029 GMC_handle_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1030                    const struct GNUNET_MessageHeader *message)
1031 {
1032   struct GNUNET_MESH_ConnectionCreate *msg;
1033   struct GNUNET_PeerIdentity *id;
1034   struct GNUNET_HashCode *cid;
1035   struct MeshPeerPath *path;
1036   struct MeshPeer *dest_peer;
1037   struct MeshPeer *orig_peer;
1038   struct MeshConnection *c;
1039   unsigned int own_pos;
1040   uint16_t size;
1041   uint16_t i;
1042
1043   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1044   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
1045
1046   /* Check size */
1047   size = ntohs (message->size);
1048   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
1049   {
1050     GNUNET_break_op (0);
1051     return GNUNET_OK;
1052   }
1053
1054   /* Calculate hops */
1055   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
1056   if (size % sizeof (struct GNUNET_PeerIdentity))
1057   {
1058     GNUNET_break_op (0);
1059     return GNUNET_OK;
1060   }
1061   size /= sizeof (struct GNUNET_PeerIdentity);
1062   if (1 > size)
1063   {
1064     GNUNET_break_op (0);
1065     return GNUNET_OK;
1066   }
1067   LOG (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
1068
1069   /* Get parameters */
1070   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
1071   cid = &msg->cid;
1072   id = (struct GNUNET_PeerIdentity *) &msg[1];
1073   LOG (GNUNET_ERROR_TYPE_DEBUG,
1074               "    connection %s (%s).\n",
1075               GNUNET_h2s (cid), GNUNET_i2s (id));
1076
1077   /* Create connection */
1078   c = connection_get (cid);
1079   if (NULL == c)
1080   {
1081     /* Create path */
1082     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
1083     path = path_new (size);
1084     own_pos = 0;
1085     for (i = 0; i < size; i++)
1086     {
1087       LOG (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
1088                   GNUNET_i2s (&id[i]));
1089       path->peers[i] = GNUNET_PEER_intern (&id[i]);
1090       if (path->peers[i] == myid)
1091         own_pos = i;
1092     }
1093     if (own_pos == 0 && path->peers[own_pos] != myid)
1094     {
1095       /* create path: self not found in path through self */
1096       GNUNET_break_op (0);
1097       path_destroy (path);
1098       return GNUNET_OK;
1099     }
1100     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
1101     GMP_add_path_to_all (path, GNUNET_NO);
1102         LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
1103     c = GMC_new (cid, NULL, path_duplicate (path), own_pos);
1104     if (NULL == c)
1105       return GNUNET_OK;
1106     connection_reset_timeout (c, GNUNET_YES);
1107   }
1108   else
1109   {
1110     path = NULL;
1111   }
1112   if (MESH_CONNECTION_NEW == c->state)
1113     connection_change_state (c, MESH_CONNECTION_SENT);
1114
1115   /* Remember peers */
1116   dest_peer = GMP_get (&id[size - 1]);
1117   orig_peer = GMP_get (&id[0]);
1118
1119   /* Is it a connection to us? */
1120   if (c->own_pos == size - 1)
1121   {
1122     LOG (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
1123     GMP_add_path_to_origin (orig_peer, path, GNUNET_YES);
1124
1125     add_to_peer (c, orig_peer);
1126     if (MESH_TUNNEL3_NEW == GMT_get_state (c->t))
1127       GMT_change_state (c->t,  MESH_TUNNEL3_WAITING);
1128
1129     send_connection_ack (c, GNUNET_NO);
1130     if (MESH_CONNECTION_SENT == c->state)
1131       connection_change_state (c, MESH_CONNECTION_ACK);
1132
1133     /* Keep tunnel alive in direction dest->owner*/
1134     connection_reset_timeout (c, GNUNET_NO);
1135   }
1136   else
1137   {
1138     /* It's for somebody else! Retransmit. */
1139     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
1140     GMP_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
1141     GMP_add_path_to_origin (orig_peer, path, GNUNET_NO);
1142     GMC_send_prebuilt_message (message, c, NULL, GNUNET_YES);
1143   }
1144   return GNUNET_OK;
1145 }
1146
1147
1148 /**
1149  * Core handler for path confirmations.
1150  *
1151  * @param cls closure
1152  * @param message message
1153  * @param peer peer identity this notification is about
1154  *
1155  * @return GNUNET_OK to keep the connection open,
1156  *         GNUNET_SYSERR to close it (signal serious error)
1157  */
1158 int
1159 GMC_handle_confirm (void *cls, const struct GNUNET_PeerIdentity *peer,
1160                     const struct GNUNET_MessageHeader *message)
1161 {
1162   struct GNUNET_MESH_ConnectionACK *msg;
1163   struct MeshConnection *c;
1164   struct MeshPeerPath *p;
1165   struct MeshPeer *pi;
1166   int fwd;
1167
1168   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1169   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
1170   msg = (struct GNUNET_MESH_ConnectionACK *) message;
1171   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
1172               GNUNET_h2s (&msg->cid));
1173   c = connection_get (&msg->cid);
1174   if (NULL == c)
1175   {
1176     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1177                               1, GNUNET_NO);
1178     LOG (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
1179     return GNUNET_OK;
1180   }
1181
1182
1183   LOG (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
1184               GNUNET_i2s (peer));
1185   pi = GMP_get (peer);
1186   if (get_next_hop (c) == pi)
1187   {
1188     LOG (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
1189     fwd = GNUNET_NO;
1190     if (MESH_CONNECTION_SENT == c->state)
1191       connection_change_state (c, MESH_CONNECTION_ACK);
1192   }
1193   else if (get_prev_hop (c) == pi)
1194   {
1195     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
1196     fwd = GNUNET_YES;
1197     connection_change_state (c, MESH_CONNECTION_READY);
1198   }
1199   else
1200   {
1201     GNUNET_break_op (0);
1202     return GNUNET_OK;
1203   }
1204   connection_reset_timeout (c, fwd);
1205
1206   /* Add path to peers? */
1207   p = c->path;
1208   if (NULL != p)
1209   {
1210     GMP_add_path_to_all (p, GNUNET_YES);
1211   }
1212   else
1213   {
1214     GNUNET_break (0);
1215   }
1216
1217   /* Message for us as creator? */
1218   if (GMC_is_origin (c, GNUNET_YES))
1219   {
1220     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
1221     connection_change_state (c, MESH_CONNECTION_READY);
1222     GMT_change_state (c->t, MESH_TUNNEL3_READY);
1223     send_connection_ack (c, GNUNET_YES);
1224     GMT_send_queued_data (c->t, GNUNET_YES);
1225     return GNUNET_OK;
1226   }
1227
1228   /* Message for us as destination? */
1229   if (GMC_is_terminal (c, GNUNET_YES))
1230   {
1231     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
1232     connection_change_state (c, MESH_CONNECTION_READY);
1233     GMT_change_state (c->t, MESH_TUNNEL3_READY);
1234     GMT_send_queued_data (c->t, GNUNET_NO);
1235     return GNUNET_OK;
1236   }
1237
1238   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1239   GMC_send_prebuilt_message (message, c, NULL, fwd);
1240   return GNUNET_OK;
1241 }
1242
1243
1244 /**
1245  * Core handler for notifications of broken paths
1246  *
1247  * @param cls Closure (unused).
1248  * @param id Peer identity of sending neighbor.
1249  * @param message Message.
1250  *
1251  * @return GNUNET_OK to keep the connection open,
1252  *         GNUNET_SYSERR to close it (signal serious error)
1253  */
1254 int
1255 GMC_handle_broken (void* cls,
1256                    const struct GNUNET_PeerIdentity* id,
1257                    const struct GNUNET_MessageHeader* message)
1258 {
1259   struct GNUNET_MESH_ConnectionBroken *msg;
1260   struct MeshConnection *c;
1261   int fwd;
1262
1263   LOG (GNUNET_ERROR_TYPE_DEBUG,
1264               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (id));
1265   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
1266   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1267               GNUNET_i2s (&msg->peer1));
1268   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1269               GNUNET_i2s (&msg->peer2));
1270   c = connection_get (&msg->cid);
1271   if (NULL == c)
1272   {
1273     GNUNET_break_op (0);
1274     return GNUNET_OK;
1275   }
1276
1277   fwd = is_fwd (c, id);
1278   connection_cancel_queues (c, !fwd);
1279   if (GMC_is_terminal (c, fwd))
1280   {
1281     if (0 < c->pending_messages)
1282       c->destroy = GNUNET_YES;
1283     else
1284       GMC_destroy (c);
1285   }
1286   else
1287   {
1288     GMC_send_prebuilt_message (message, c, NULL, fwd);
1289     c->destroy = GNUNET_YES;
1290   }
1291
1292   return GNUNET_OK;
1293
1294 }
1295
1296
1297 /**
1298  * Core handler for tunnel destruction
1299  *
1300  * @param cls Closure (unused).
1301  * @param peer Peer identity of sending neighbor.
1302  * @param message Message.
1303  *
1304  * @return GNUNET_OK to keep the connection open,
1305  *         GNUNET_SYSERR to close it (signal serious error)
1306  */
1307 int
1308 GMC_handle_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
1309                     const struct GNUNET_MessageHeader *message)
1310 {
1311   struct GNUNET_MESH_ConnectionDestroy *msg;
1312   struct MeshConnection *c;
1313   int fwd;
1314
1315   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
1316   LOG (GNUNET_ERROR_TYPE_DEBUG,
1317               "Got a CONNECTION DESTROY message from %s\n",
1318               GNUNET_i2s (peer));
1319   LOG (GNUNET_ERROR_TYPE_DEBUG,
1320               "  for connection %s\n",
1321               GNUNET_h2s (&msg->cid));
1322   c = connection_get (&msg->cid);
1323   if (NULL == c)
1324   {
1325     /* Probably already got the message from another path,
1326      * destroyed the tunnel and retransmitted to children.
1327      * Safe to ignore.
1328      */
1329     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
1330                               1, GNUNET_NO);
1331     return GNUNET_OK;
1332   }
1333   fwd = is_fwd (c, peer);
1334   if (GNUNET_SYSERR == fwd)
1335   {
1336     GNUNET_break_op (0);
1337     return GNUNET_OK;
1338   }
1339   GMC_send_prebuilt_message (message, c, NULL, fwd);
1340   c->destroy = GNUNET_YES;
1341
1342   return GNUNET_OK;
1343 }
1344
1345 /**
1346  * Generic handler for mesh network encrypted traffic.
1347  *
1348  * @param peer Peer identity this notification is about.
1349  * @param message Encrypted message.
1350  *
1351  * @return GNUNET_OK to keep the connection open,
1352  *         GNUNET_SYSERR to close it (signal serious error)
1353  */
1354 static int
1355 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
1356                        const struct GNUNET_MESH_Encrypted *msg)
1357 {
1358   struct MeshConnection *c;
1359   struct MeshPeer *neighbor;
1360   struct MeshFlowControl *fc;
1361   GNUNET_PEER_Id peer_id;
1362   uint32_t pid;
1363   uint32_t ttl;
1364   uint16_t type;
1365   size_t size;
1366   int fwd;
1367
1368   /* Check size */
1369   size = ntohs (msg->header.size);
1370   if (size <
1371       sizeof (struct GNUNET_MESH_Encrypted) +
1372       sizeof (struct GNUNET_MessageHeader))
1373   {
1374     GNUNET_break_op (0);
1375     return GNUNET_OK;
1376   }
1377   type = ntohs (msg->header.type);
1378   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1379   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
1380               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
1381
1382   /* Check connection */
1383   c = connection_get (&msg->cid);
1384   if (NULL == c)
1385   {
1386     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
1387     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
1388     return GNUNET_OK;
1389   }
1390
1391   /* Check if origin is as expected */
1392   neighbor = get_prev_hop (c);
1393   peer_id = GNUNET_PEER_search (peer);
1394   if (peer_id == GMP_get_short_id (neighbor))
1395   {
1396     fwd = GNUNET_YES;
1397   }
1398   else
1399   {
1400     neighbor = get_next_hop (c);
1401     if (peer_id == GMP_get_short_id (neighbor))
1402     {
1403       fwd = GNUNET_NO;
1404     }
1405     else
1406     {
1407       GNUNET_break_op (0);
1408       return GNUNET_OK;
1409     }
1410   }
1411   fc = fwd ? &c->bck_fc : &c->fwd_fc;
1412
1413   /* Check PID */
1414   pid = ntohl (msg->pid);
1415   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
1416   {
1417     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
1418     LOG (GNUNET_ERROR_TYPE_DEBUG,
1419                 "WARNING Received PID %u, (prev %u), ACK %u\n",
1420                 pid, fc->last_pid_recv, fc->last_ack_sent);
1421     return GNUNET_OK;
1422   }
1423   if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
1424   {
1425     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
1426     LOG (GNUNET_ERROR_TYPE_DEBUG,
1427                 " Pid %u not expected (%u+), dropping!\n",
1428                 pid, fc->last_pid_recv + 1);
1429     return GNUNET_OK;
1430   }
1431   if (MESH_CONNECTION_SENT == c->state)
1432     connection_change_state (c, MESH_CONNECTION_READY);
1433   connection_reset_timeout (c, fwd);
1434   fc->last_pid_recv = pid;
1435
1436   /* Is this message for us? */
1437   if (GMC_is_terminal (c, fwd))
1438   {
1439     /* TODO signature verification */
1440     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
1441     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
1442
1443     if (NULL == c->t)
1444     {
1445       GNUNET_break (0);
1446       return GNUNET_OK;
1447     }
1448     fc->last_pid_recv = pid;
1449     GMT_handle_encrypted (c->t, msg, fwd);
1450     GMC_send_ack (c, fwd);
1451     return GNUNET_OK;
1452   }
1453
1454   /* Message not for us: forward to next hop */
1455   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1456   ttl = ntohl (msg->ttl);
1457   LOG (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
1458   if (ttl == 0)
1459   {
1460     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
1461     LOG (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
1462     GMC_send_ack (c, fwd);
1463     return GNUNET_OK;
1464   }
1465   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
1466
1467   GMC_send_prebuilt_message (&msg->header, c, NULL, fwd);
1468
1469   return GNUNET_OK;
1470 }
1471
1472
1473 /**
1474  * Core handler for encrypted mesh network traffic (channel mgmt, data).
1475  *
1476  * @param cls Closure (unused).
1477  * @param message Message received.
1478  * @param peer Peer who sent the message.
1479  *
1480  * @return GNUNET_OK to keep the connection open,
1481  *         GNUNET_SYSERR to close it (signal serious error)
1482  */
1483 int
1484 GMC_handle_encrypted (void *cls, const struct GNUNET_PeerIdentity *peer,
1485                       const struct GNUNET_MessageHeader *message)
1486 {
1487   return handle_mesh_encrypted (peer,
1488                                 (struct GNUNET_MESH_Encrypted *)message);
1489 }
1490
1491
1492 /**
1493  * Core handler for mesh network traffic point-to-point acks.
1494  *
1495  * @param cls closure
1496  * @param message message
1497  * @param peer peer identity this notification is about
1498  *
1499  * @return GNUNET_OK to keep the connection open,
1500  *         GNUNET_SYSERR to close it (signal serious error)
1501  */
1502 int
1503 GMC_handle_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
1504                 const struct GNUNET_MessageHeader *message)
1505 {
1506   struct GNUNET_MESH_ACK *msg;
1507   struct MeshConnection *c;
1508   struct MeshFlowControl *fc;
1509   GNUNET_PEER_Id id;
1510   uint32_t ack;
1511   int fwd;
1512
1513   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1514   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
1515               GNUNET_i2s (peer));
1516   msg = (struct GNUNET_MESH_ACK *) message;
1517
1518   c = connection_get (&msg->cid);
1519
1520   if (NULL == c)
1521   {
1522     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
1523                               GNUNET_NO);
1524     return GNUNET_OK;
1525   }
1526
1527   /* Is this a forward or backward ACK? */
1528   id = GNUNET_PEER_search (peer);
1529   if (GMP_get_short_id (get_next_hop (c)) == id)
1530   {
1531     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
1532     fc = &c->fwd_fc;
1533     fwd = GNUNET_YES;
1534   }
1535   else if (GMP_get_short_id (get_prev_hop (c)) == id)
1536   {
1537     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
1538     fc = &c->bck_fc;
1539     fwd = GNUNET_NO;
1540   }
1541   else
1542   {
1543     GNUNET_break_op (0);
1544     return GNUNET_OK;
1545   }
1546
1547   ack = ntohl (msg->ack);
1548   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u (was %u)\n",
1549               ack, fc->last_ack_recv);
1550   if (GMC_is_pid_bigger (ack, fc->last_ack_recv))
1551     fc->last_ack_recv = ack;
1552
1553   /* Cancel polling if the ACK is big enough. */
1554   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
1555       GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
1556   {
1557     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
1558     GNUNET_SCHEDULER_cancel (fc->poll_task);
1559     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1560     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
1561   }
1562
1563   connection_unlock_queue (c, fwd);
1564
1565   return GNUNET_OK;
1566 }
1567
1568
1569 /**
1570  * Core handler for mesh network traffic point-to-point ack polls.
1571  *
1572  * @param cls closure
1573  * @param message message
1574  * @param peer peer identity this notification is about
1575  *
1576  * @return GNUNET_OK to keep the connection open,
1577  *         GNUNET_SYSERR to close it (signal serious error)
1578  */
1579 int
1580 GMC_handle_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
1581                  const struct GNUNET_MessageHeader *message)
1582 {
1583   struct GNUNET_MESH_Poll *msg;
1584   struct MeshConnection *c;
1585   struct MeshFlowControl *fc;
1586   GNUNET_PEER_Id id;
1587   uint32_t pid;
1588   int fwd;
1589
1590   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1591   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
1592               GNUNET_i2s (peer));
1593
1594   msg = (struct GNUNET_MESH_Poll *) message;
1595
1596   c = connection_get (&msg->cid);
1597
1598   if (NULL == c)
1599   {
1600     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
1601                               GNUNET_NO);
1602     GNUNET_break_op (0);
1603     return GNUNET_OK;
1604   }
1605
1606   /* Is this a forward or backward ACK?
1607    * Note: a poll should never be needed in a loopback case,
1608    * since there is no possiblility of packet loss there, so
1609    * this way of discerining FWD/BCK should not be a problem.
1610    */
1611   id = GNUNET_PEER_search (peer);
1612   if (GMP_get_short_id (get_next_hop (c)) == id)
1613   {
1614     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
1615     fc = &c->fwd_fc;
1616   }
1617   else if (GMP_get_short_id (get_prev_hop (c)) == id)
1618   {
1619     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
1620     fc = &c->bck_fc;
1621   }
1622   else
1623   {
1624     GNUNET_break_op (0);
1625     return GNUNET_OK;
1626   }
1627
1628   pid = ntohl (msg->pid);
1629   LOG (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n",
1630               pid, fc->last_pid_recv);
1631   fc->last_pid_recv = pid;
1632   fwd = fc == &c->fwd_fc;
1633   GMC_send_ack (c, fwd);
1634
1635   return GNUNET_OK;
1636 }
1637
1638
1639 /**
1640  * Core handler for mesh keepalives.
1641  *
1642  * @param cls closure
1643  * @param message message
1644  * @param peer peer identity this notification is about
1645  * @return GNUNET_OK to keep the connection open,
1646  *         GNUNET_SYSERR to close it (signal serious error)
1647  *
1648  * TODO: Check who we got this from, to validate route.
1649  */
1650 int
1651 GMC_handle_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
1652                       const struct GNUNET_MessageHeader *message)
1653 {
1654   struct GNUNET_MESH_ConnectionKeepAlive *msg;
1655   struct MeshConnection *c;
1656   struct MeshPeer *neighbor;
1657   int fwd;
1658
1659   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
1660   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
1661               GNUNET_i2s (peer));
1662
1663   c = connection_get (&msg->cid);
1664   if (NULL == c)
1665   {
1666     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
1667                               GNUNET_NO);
1668     return GNUNET_OK;
1669   }
1670
1671   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
1672         GNUNET_YES : GNUNET_NO;
1673
1674   /* Check if origin is as expected */
1675   neighbor = get_hop (c, fwd);
1676   if (GNUNET_PEER_search (peer) != GMP_get_short_id (neighbor))
1677   {
1678     GNUNET_break_op (0);
1679     return GNUNET_OK;
1680   }
1681
1682   connection_change_state (c, MESH_CONNECTION_READY);
1683   connection_reset_timeout (c, fwd);
1684
1685   if (GMC_is_terminal (c, fwd))
1686     return GNUNET_OK;
1687
1688   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
1689   GMC_send_prebuilt_message (message, c, NULL, fwd);
1690
1691   return GNUNET_OK;
1692 }
1693
1694
1695 /**
1696  * Send an ACK on the appropriate connection/channel, depending on
1697  * the direction and the position of the peer.
1698  *
1699  * @param c Which connection to send the hop-by-hop ACK.
1700  * @param fwd Is this a fwd ACK? (will go dest->root)
1701  */
1702 void
1703 GMC_send_ack (struct MeshConnection *c, int fwd)
1704 {
1705   unsigned int buffer;
1706
1707   LOG (GNUNET_ERROR_TYPE_DEBUG,
1708        "GMC send %s ACK on %s\n",
1709        fwd ? "FWD" : "BCK", GMC_2s (c));
1710
1711   if (NULL == c)
1712   {
1713     GNUNET_break (0);
1714     return;
1715   }
1716
1717   /* Get available buffer space */
1718   if (GMC_is_terminal (c, fwd))
1719   {
1720     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from all channels\n");
1721     buffer = GMT_get_buffer (c->t, fwd);
1722   }
1723   else
1724   {
1725     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
1726     buffer = GMC_get_buffer (c, fwd);
1727   }
1728   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
1729
1730   /* Send available buffer space */
1731   if (GMC_is_origin (c, fwd))
1732   {
1733     GNUNET_assert (NULL != c->t);
1734     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channels...\n");
1735     if (0 < buffer)
1736     {
1737       LOG (GNUNET_ERROR_TYPE_DEBUG, "  really sending!\n");
1738       GMT_unchoke_channels (c->t, fwd);
1739     }
1740   }
1741   else
1742   {
1743     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
1744     send_ack (c, buffer, fwd);
1745   }
1746 }
1747
1748
1749 /**
1750  * Initialize the connections subsystem
1751  *
1752  * @param c Configuration handle.
1753  */
1754 void
1755 GMC_init (const struct GNUNET_CONFIGURATION_Handle *c)
1756 {
1757   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1758   if (GNUNET_OK !=
1759       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
1760                                              &max_msgs_queue))
1761   {
1762     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
1763                                "MESH", "MAX_MSGS_QUEUE", "MISSING");
1764     GNUNET_SCHEDULER_shutdown ();
1765     return;
1766   }
1767
1768   if (GNUNET_OK !=
1769       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
1770                                              &max_connections))
1771   {
1772     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
1773                                "MESH", "MAX_CONNECTIONS", "MISSING");
1774     GNUNET_SCHEDULER_shutdown ();
1775     return;
1776   }
1777
1778   if (GNUNET_OK !=
1779       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
1780                                            &refresh_connection_time))
1781   {
1782     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
1783                                "MESH", "REFRESH_CONNECTION_TIME", "MISSING");
1784     GNUNET_SCHEDULER_shutdown ();
1785     return;
1786   }
1787   connections = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
1788 }
1789
1790 /**
1791  * Shut down the connections subsystem.
1792  */
1793 void
1794 GMC_shutdown (void)
1795 {
1796   GNUNET_CONTAINER_multihashmap_destroy (connections);
1797 }
1798
1799
1800 struct MeshConnection *
1801 GMC_new (const struct GNUNET_HashCode *cid,
1802          struct MeshTunnel3 *t,
1803          struct MeshPeerPath *p,
1804          unsigned int own_pos)
1805 {
1806   struct MeshConnection *c;
1807
1808   c = GNUNET_new (struct MeshConnection);
1809   c->id = *cid;
1810   GNUNET_CONTAINER_multihashmap_put (connections, &c->id, c,
1811                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1812   fc_init (&c->fwd_fc);
1813   fc_init (&c->bck_fc);
1814   c->fwd_fc.c = c;
1815   c->bck_fc.c = c;
1816
1817   c->t = t;
1818   if (own_pos > p->length - 1)
1819   {
1820     GNUNET_break (0);
1821     GMC_destroy (c);
1822     return NULL;
1823   }
1824   c->own_pos = own_pos;
1825   c->path = p;
1826
1827   if (0 == own_pos)
1828   {
1829     c->fwd_maintenance_task =
1830             GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
1831                                           &connection_fwd_keepalive, c);
1832   }
1833   register_neighbors (c);
1834   return c;
1835 }
1836
1837
1838 void
1839 GMC_destroy (struct MeshConnection *c)
1840 {
1841   if (NULL == c)
1842     return;
1843
1844   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s\n", GMC_2s (c));
1845
1846   /* Cancel all traffic */
1847   connection_cancel_queues (c, GNUNET_YES);
1848   connection_cancel_queues (c, GNUNET_NO);
1849
1850   /* Cancel maintainance task (keepalive/timeout) */
1851   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
1852     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
1853   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
1854     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
1855
1856   /* Unregister from neighbors */
1857   unregister_neighbors (c);
1858
1859   /* Delete */
1860   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
1861   if (NULL != c->t)
1862     GMT_remove_connection (c->t, c);
1863   GNUNET_free (c);
1864 }
1865
1866 /**
1867  * Get the connection ID.
1868  *
1869  * @param c Connection to get the ID from.
1870  *
1871  * @return ID of the connection.
1872  */
1873 const struct GNUNET_HashCode *
1874 GMC_get_id (const struct MeshConnection *c)
1875 {
1876   return &c->id;
1877 }
1878
1879
1880 /**
1881  * Get the connection path.
1882  *
1883  * @param c Connection to get the path from.
1884  *
1885  * @return path used by the connection.
1886  */
1887 const struct MeshPeerPath *
1888 GMC_get_path (const struct MeshConnection *c)
1889 {
1890   return c->path;
1891 }
1892
1893
1894 /**
1895  * Get the connection state.
1896  *
1897  * @param c Connection to get the state from.
1898  *
1899  * @return state of the connection.
1900  */
1901 enum MeshConnectionState
1902 GMC_get_state (const struct MeshConnection *c)
1903 {
1904   return c->state;
1905 }
1906
1907 /**
1908  * Get the connection tunnel.
1909  *
1910  * @param c Connection to get the tunnel from.
1911  *
1912  * @return tunnel of the connection.
1913  */
1914 struct MeshTunnel3 *
1915 GMC_get_tunnel (const struct MeshConnection *c)
1916 {
1917   return c->t;
1918 }
1919
1920
1921 /**
1922  * Get free buffer space in a connection.
1923  *
1924  * @param c Connection.
1925  * @param fwd Is query about FWD traffic?
1926  *
1927  * @return Free buffer space [0 - max_msgs_queue/max_connections]
1928  */
1929 unsigned int
1930 GMC_get_buffer (struct MeshConnection *c, int fwd)
1931 {
1932   struct MeshFlowControl *fc;
1933
1934   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1935
1936   return (fc->queue_max - fc->queue_n);
1937 }
1938
1939 /**
1940  * Get how many messages have we allowed to send to us from a direction..
1941  *
1942  * @param c Connection.
1943  * @param fwd Are we asking about traffic from FWD (BCK messages)?
1944  *
1945  * @return last_ack_sent - last_pid_recv
1946  */
1947 unsigned int
1948 GMC_get_allowed (struct MeshConnection *c, int fwd)
1949 {
1950   struct MeshFlowControl *fc;
1951
1952   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1953   if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
1954   {
1955     return 0;
1956   }
1957   return (fc->last_ack_sent - fc->last_pid_recv);
1958 }
1959
1960 /**
1961  * Get messages queued in a connection.
1962  *
1963  * @param c Connection.
1964  * @param fwd Is query about FWD traffic?
1965  *
1966  * @return Number of messages queued.
1967  */
1968 unsigned int
1969 GMC_get_qn (struct MeshConnection *c, int fwd)
1970 {
1971   struct MeshFlowControl *fc;
1972
1973   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1974
1975   return fc->queue_n;
1976 }
1977
1978
1979 /**
1980  * Allow the connection to advertise a buffer of the given size.
1981  *
1982  * The connection will send an @c fwd ACK message (so: in direction !fwd)
1983  * allowing up to last_pid_recv + buffer.
1984  *
1985  * @param c Connection.
1986  * @param buffer How many more messages the connection can accept.
1987  * @param fwd Is this about FWD traffic? (The ack will go dest->root).
1988  */
1989 void
1990 GMC_allow (struct MeshConnection *c, unsigned int buffer, int fwd)
1991 {
1992   send_ack (c, buffer, fwd);
1993 }
1994
1995
1996 /**
1997  * Notify other peers on a connection of a broken link. Mark connections
1998  * to destroy after all traffic has been sent.
1999  *
2000  * @param c Connection on which there has been a disconnection.
2001  * @param peer Peer that disconnected.
2002  */
2003 void
2004 GMC_notify_broken (struct MeshConnection *c,
2005                    struct MeshPeer *peer)
2006 {
2007   int fwd;
2008
2009   fwd = peer == get_prev_hop (c);
2010
2011   connection_cancel_queues (c, !fwd);
2012   if (GMC_is_terminal (c, fwd))
2013   {
2014     /* Local shutdown, no one to notify about this. */
2015     GMC_destroy (c);
2016     return;
2017   }
2018
2019   send_broken (c, &my_full_id, GMP_get_id (peer), fwd);
2020
2021   /* Connection will have at least one pending message
2022    * (the one we just scheduled), so no point in checking whether to
2023    * destroy immediately. */
2024   c->destroy = GNUNET_YES;
2025
2026   return;
2027 }
2028
2029
2030 /**
2031  * Is this peer the first one on the connection?
2032  *
2033  * @param c Connection.
2034  * @param fwd Is this about fwd traffic?
2035  *
2036  * @return GNUNET_YES if origin, GNUNET_NO if relay/terminal.
2037  */
2038 int
2039 GMC_is_origin (struct MeshConnection *c, int fwd)
2040 {
2041   if (!fwd && c->path->length - 1 == c->own_pos )
2042     return GNUNET_YES;
2043   if (fwd && 0 == c->own_pos)
2044     return GNUNET_YES;
2045   return GNUNET_NO;
2046 }
2047
2048
2049 /**
2050  * Is this peer the last one on the connection?
2051  *
2052  * @param c Connection.
2053  * @param fwd Is this about fwd traffic?
2054  *            Note that the ROOT is the terminal for BCK traffic!
2055  *
2056  * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
2057  */
2058 int
2059 GMC_is_terminal (struct MeshConnection *c, int fwd)
2060 {
2061   return GMC_is_origin (c, !fwd);
2062 }
2063
2064
2065 /**
2066  * See if we are allowed to send by the next hop in the given direction.
2067  *
2068  * @param c Connection.
2069  * @param fwd Is this about fwd traffic?
2070  *
2071  * @return GNUNET_YES in case it's OK.
2072  */
2073 int
2074 GMC_is_sendable (struct MeshConnection *c, int fwd)
2075 {
2076   struct MeshFlowControl *fc;
2077
2078   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2079   if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2080     return GNUNET_YES;
2081   return GNUNET_NO;
2082 }
2083
2084 /**
2085  * Sends an already built message on a connection, properly registering
2086  * all used resources.
2087  *
2088  * @param message Message to send. Function makes a copy of it.
2089  *                If message is not hop-by-hop, decrements TTL of copy.
2090  * @param c Connection on which this message is transmitted.
2091  * @param ch Channel on which this message is transmitted, or NULL.
2092  * @param fwd Is this a fwd message?
2093  */
2094 void
2095 GMC_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2096                            struct MeshConnection *c,
2097                            struct MeshChannel *ch,
2098                            int fwd)
2099 {
2100   struct MeshFlowControl *fc;
2101   void *data;
2102   size_t size;
2103   uint16_t type;
2104   int droppable;
2105
2106   size = ntohs (message->size);
2107   data = GNUNET_malloc (size);
2108   memcpy (data, message, size);
2109   type = ntohs (message->type);
2110   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send %s (%u) on connection %s\n",
2111               GNUNET_MESH_DEBUG_M2S (type), size, GMC_2s (c));
2112
2113   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2114   droppable = GNUNET_YES;
2115   switch (type)
2116   {
2117     struct GNUNET_MESH_Encrypted *emsg;
2118     struct GNUNET_MESH_ACK       *amsg;
2119     struct GNUNET_MESH_Poll      *pmsg;
2120     struct GNUNET_MESH_ConnectionDestroy *dmsg;
2121     struct GNUNET_MESH_ConnectionBroken  *bmsg;
2122     uint32_t ttl;
2123
2124     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
2125       emsg = (struct GNUNET_MESH_Encrypted *) data;
2126       ttl = ntohl (emsg->ttl);
2127       if (0 == ttl)
2128       {
2129         GNUNET_break_op (0);
2130         return;
2131       }
2132       emsg->cid = c->id;
2133       emsg->ttl = htonl (ttl - 1);
2134       emsg->pid = htonl (fwd ? c->fwd_fc.next_pid++ : c->bck_fc.next_pid++);
2135       LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
2136       fc->queue_n++;
2137       LOG (GNUNET_ERROR_TYPE_DEBUG, "pid %u\n", ntohl (emsg->pid));
2138       LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid %u\n", fc->last_pid_sent);
2139       LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack %u\n", fc->last_ack_recv);
2140       if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
2141       {
2142         GMC_start_poll (c, fwd);
2143       }
2144       break;
2145
2146     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2147       amsg = (struct GNUNET_MESH_ACK *) data;
2148       amsg->cid = c->id;
2149       LOG (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
2150       droppable = GNUNET_NO;
2151       break;
2152
2153     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2154       pmsg = (struct GNUNET_MESH_Poll *) data;
2155       pmsg->cid = c->id;
2156       pmsg->pid = htonl (fwd ? c->fwd_fc.last_pid_sent : c->bck_fc.last_pid_sent);
2157       LOG (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
2158       droppable = GNUNET_NO;
2159       break;
2160
2161     case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
2162       dmsg = (struct GNUNET_MESH_ConnectionDestroy *) data;
2163       dmsg->cid = c->id;
2164       dmsg->reserved = 0;
2165       break;
2166
2167     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
2168       bmsg = (struct GNUNET_MESH_ConnectionBroken *) data;
2169       bmsg->cid = c->id;
2170       bmsg->reserved = 0;
2171       break;
2172
2173     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
2174     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
2175       break;
2176
2177     default:
2178       GNUNET_break (0);
2179   }
2180
2181   if (fc->queue_n >= fc->queue_max && droppable)
2182   {
2183     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
2184                               1, GNUNET_NO);
2185     GNUNET_break (0);
2186     LOG (GNUNET_ERROR_TYPE_DEBUG,
2187                 "queue full: %u/%u\n",
2188                 fc->queue_n, fc->queue_max);
2189     return; /* Drop this message */
2190   }
2191
2192   c->pending_messages++;
2193
2194   GMP_queue_add (get_hop (c, fwd), data, type, size, c, ch, fwd,
2195                  &message_sent, NULL);
2196 }
2197
2198
2199 /**
2200  * Sends a CREATE CONNECTION message for a path to a peer.
2201  * Changes the connection and tunnel states if necessary.
2202  *
2203  * @param connection Connection to create.
2204  */
2205 void
2206 GMC_send_create (struct MeshConnection *connection)
2207 {
2208   enum MeshTunnel3State state;
2209   size_t size;
2210
2211   size = sizeof (struct GNUNET_MESH_ConnectionCreate);
2212   size += connection->path->length * sizeof (struct GNUNET_PeerIdentity);
2213   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
2214   GMP_queue_add (get_next_hop (connection), NULL,
2215                  GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
2216                  size, connection, NULL,
2217                  GNUNET_YES, &message_sent, NULL);
2218   state = GMT_get_state (connection->t);
2219   if (MESH_TUNNEL3_SEARCHING == state || MESH_TUNNEL3_NEW == state)
2220     GMT_change_state (connection->t, MESH_TUNNEL3_WAITING);
2221   if (MESH_CONNECTION_NEW == connection->state)
2222     connection_change_state (connection, MESH_CONNECTION_SENT);
2223 }
2224
2225
2226 /**
2227  * Send a message to all peers in this connection that the connection
2228  * is no longer valid.
2229  *
2230  * If some peer should not receive the message, it should be zero'ed out
2231  * before calling this function.
2232  *
2233  * @param c The connection whose peers to notify.
2234  */
2235 void
2236 GMC_send_destroy (struct MeshConnection *c)
2237 {
2238   struct GNUNET_MESH_ConnectionDestroy msg;
2239
2240   if (GNUNET_YES == c->destroy)
2241     return;
2242
2243   msg.header.size = htons (sizeof (msg));
2244   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
2245   msg.cid = c->id;
2246   LOG (GNUNET_ERROR_TYPE_DEBUG,
2247               "  sending connection destroy for connection %s\n",
2248               GMC_2s (c));
2249
2250   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_YES))
2251     GMC_send_prebuilt_message (&msg.header, c, NULL, GNUNET_YES);
2252   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_NO))
2253     GMC_send_prebuilt_message (&msg.header, c, NULL, GNUNET_NO);
2254   c->destroy = GNUNET_YES;
2255 }
2256
2257
2258 /**
2259  * @brief Start a polling timer for the connection.
2260  *
2261  * When a neighbor does not accept more traffic on the connection it could be
2262  * caused by a simple congestion or by a lost ACK. Polling enables to check
2263  * for the lastest ACK status for a connection.
2264  *
2265  * @param c Connection.
2266  * @param fwd Should we poll in the FWD direction?
2267  */
2268 void
2269 GMC_start_poll (struct MeshConnection *c, int fwd)
2270 {
2271   struct MeshFlowControl *fc;
2272
2273   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2274   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2275   {
2276     return;
2277   }
2278   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2279                                                 &connection_poll,
2280                                                 fc);
2281 }
2282
2283
2284 /**
2285  * @brief Stop polling a connection for ACKs.
2286  *
2287  * Once we have enough ACKs for future traffic, polls are no longer necessary.
2288  *
2289  * @param c Connection.
2290  * @param fwd Should we stop the poll in the FWD direction?
2291  */
2292 void
2293 GMC_stop_poll (struct MeshConnection *c, int fwd)
2294 {
2295   struct MeshFlowControl *fc;
2296
2297   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2298   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2299   {
2300     GNUNET_SCHEDULER_cancel (fc->poll_task);
2301     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2302   }
2303 }
2304
2305 /**
2306  * Get a (static) string for a connection.
2307  *
2308  * @param c Connection.
2309  */
2310 const char *
2311 GMC_2s (struct MeshConnection *c)
2312 {
2313   if (NULL != c->t)
2314   {
2315     static char buf[128];
2316
2317     sprintf (buf, "%s (->%s)", GNUNET_h2s (&c->id), GMT_2s (c->t));
2318     return buf;
2319   }
2320   return GNUNET_h2s (&c->id);
2321 }