- fix use after free
[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     return;
456   }
457   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
458   switch (type)
459   {
460     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
461       fc->last_pid_sent++;
462       fc->queue_n--;
463       LOG (GNUNET_ERROR_TYPE_DEBUG,
464            "!   accounting pid %u\n",
465            fc->last_pid_sent);
466       GMC_send_ack (c, fwd);
467       break;
468     default:
469       break;
470   }
471   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  message sent!\n");
472
473   if (NULL == c->perf)
474     return; /* Only endpoints are interested in timing. */
475
476   p = c->perf;
477   usecsperbyte = ((double) wait.rel_value_us) / size;
478   if (p->size == AVG_MSGS)
479   {
480     /* Array is full. Substract oldest value, add new one and store. */
481     p->avg -= (p->usecsperbyte[p->idx] / AVG_MSGS);
482     p->usecsperbyte[p->idx] = usecsperbyte;
483     p->avg += (p->usecsperbyte[p->idx] / AVG_MSGS);
484   }
485   else
486   {
487     /* Array not yet full. Add current value to avg and store. */
488     p->usecsperbyte[p->idx] = usecsperbyte;
489     p->avg *= p->size;
490     p->avg += p->usecsperbyte[p->idx];
491     p->size++;
492     p->avg /= p->size;
493   }
494   p->idx = (p->idx + 1) % AVG_MSGS;
495
496 //   if (NULL != c->t)
497 //   {
498 //     c->t->pending_messages--;
499 //     if (GNUNET_YES == c->t->destroy && 0 == t->pending_messages)
500 //     {
501 //       LOG (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
502 //       GMT_destroy (c->t);
503 //     }
504 //   }
505 }
506
507
508 /**
509  * Get the previous hop in a connection
510  *
511  * @param c Connection.
512  *
513  * @return Previous peer in the connection.
514  */
515 static struct MeshPeer *
516 get_prev_hop (const struct MeshConnection *c)
517 {
518   GNUNET_PEER_Id id;
519
520   if (0 == c->own_pos || c->path->length < 2)
521     id = c->path->peers[0];
522   else
523     id = c->path->peers[c->own_pos - 1];
524
525   return GMP_get_short (id);
526 }
527
528
529 /**
530  * Get the next hop in a connection
531  *
532  * @param c Connection.
533  *
534  * @return Next peer in the connection.
535  */
536 static struct MeshPeer *
537 get_next_hop (const struct MeshConnection *c)
538 {
539   GNUNET_PEER_Id id;
540
541   if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
542     id = c->path->peers[c->path->length - 1];
543   else
544     id = c->path->peers[c->own_pos + 1];
545
546   return GMP_get_short (id);
547 }
548
549
550 /**
551  * Get the hop in a connection.
552  *
553  * @param c Connection.
554  * @param fwd Next hop?
555  *
556  * @return Next peer in the connection.
557  */
558 static struct MeshPeer *
559 get_hop (struct MeshConnection *c, int fwd)
560 {
561   if (fwd)
562     return get_next_hop (c);
563   return get_prev_hop (c);
564 }
565
566
567 /**
568  * Is traffic coming from this sender 'FWD' traffic?
569  *
570  * @param c Connection to check.
571  * @param sender Peer identity of neighbor.
572  *
573  * @return GNUNET_YES in case the sender is the 'prev' hop and therefore
574  *         the traffic is 'FWD'. GNUNET_NO for BCK. GNUNET_SYSERR for errors.
575  */
576 static int 
577 is_fwd (const struct MeshConnection *c,
578         const struct GNUNET_PeerIdentity *sender)
579 {
580   GNUNET_PEER_Id id;
581
582   id = GNUNET_PEER_search (sender);
583   if (GMP_get_short_id (get_prev_hop (c)) == id)
584     return GNUNET_YES;
585
586   if (GMP_get_short_id (get_next_hop (c)) == id)
587     return GNUNET_NO;
588
589   GNUNET_break (0);
590   return GNUNET_SYSERR;
591 }
592
593
594 /**
595  * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
596  * or a first CONNECTION_ACK directed to us.
597  *
598  * @param connection Connection to confirm.
599  * @param fwd Should we send it FWD?
600  *            (First (~SYNACK) goes BCK, second (~ACK) goes FWD)
601  */
602 static void
603 send_connection_ack (struct MeshConnection *connection, int fwd)
604 {
605   struct MeshTunnel3 *t;
606
607   t = connection->t;
608   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
609   GMP_queue_add (get_hop (connection, fwd), NULL,
610                  GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
611                  sizeof (struct GNUNET_MESH_ConnectionACK),
612                  connection, NULL, fwd,
613                  &message_sent, NULL);
614   if (MESH_TUNNEL3_NEW == GMT_get_state (t))
615     GMT_change_state (t, MESH_TUNNEL3_WAITING);
616   if (MESH_CONNECTION_READY != connection->state)
617     connection_change_state (connection, MESH_CONNECTION_SENT);
618 }
619
620
621 /**
622  * Send a notification that a connection is broken.
623  *
624  * @param c Connection that is broken.
625  * @param id1 Peer that has disconnected.
626  * @param id2 Peer that has disconnected.
627  * @param fwd Direction towards which to send it.
628  */
629 static void
630 send_broken (struct MeshConnection *c,
631              const struct GNUNET_PeerIdentity *id1,
632              const struct GNUNET_PeerIdentity *id2,
633              int fwd)
634 {
635   struct GNUNET_MESH_ConnectionBroken msg;
636
637   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
638   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
639   msg.cid = c->id;
640   msg.peer1 = *id1;
641   msg.peer2 = *id2;
642   GMC_send_prebuilt_message (&msg.header, c, NULL, fwd);
643 }
644
645
646
647 /**
648  * Send keepalive packets for a connection.
649  *
650  * @param c Connection to keep alive..
651  * @param fwd Is this a FWD keepalive? (owner -> dest).
652  */
653 static void
654 connection_keepalive (struct MeshConnection *c, int fwd)
655 {
656   struct GNUNET_MESH_ConnectionKeepAlive *msg;
657   size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
658   char cbuf[size];
659   uint16_t type;
660
661   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
662                GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
663
664   LOG (GNUNET_ERROR_TYPE_DEBUG,
665        "sending %s keepalive for connection %s]\n",
666        fwd ? "FWD" : "BCK", GMC_2s (c));
667
668   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
669   msg->header.size = htons (size);
670   msg->header.type = htons (type);
671   msg->cid = c->id;
672
673   GMC_send_prebuilt_message (&msg->header, c, NULL, fwd);
674 }
675
676
677 /**
678  * Send CONNECTION_{CREATE/ACK} packets for a connection.
679  *
680  * @param c Connection for which to send the message.
681  * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
682  */
683 static void
684 connection_recreate (struct MeshConnection *c, int fwd)
685 {
686   LOG (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
687   if (fwd)
688     GMC_send_create (c);
689   else
690     send_connection_ack (c, GNUNET_NO);
691 }
692
693
694 /**
695  * Generic connection timer management.
696  * Depending on the role of the peer in the connection will send the
697  * appropriate message (build or keepalive)
698  *
699  * @param c Conncetion to maintain.
700  * @param fwd Is FWD?
701  */
702 static void
703 connection_maintain (struct MeshConnection *c, int fwd)
704 {
705   if (MESH_TUNNEL3_SEARCHING == GMT_get_state (c->t))
706   {
707     /* TODO DHT GET with RO_BART */
708     return;
709   }
710   switch (c->state)
711   {
712     case MESH_CONNECTION_NEW:
713       GNUNET_break (0);
714     case MESH_CONNECTION_SENT:
715       connection_recreate (c, fwd);
716       break;
717     case MESH_CONNECTION_READY:
718       connection_keepalive (c, fwd);
719       break;
720     default:
721       break;
722   }
723 }
724
725
726 static void
727 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
728 {
729   struct MeshConnection *c = cls;
730
731   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
732   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
733     return;
734
735   connection_maintain (c, GNUNET_YES);
736   c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
737                                                           &connection_fwd_keepalive,
738                                                           c);
739 }
740
741
742 static void
743 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
744 {
745   struct MeshConnection *c = cls;
746
747   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
748   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
749     return;
750
751   connection_maintain (c, GNUNET_NO);
752   c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
753                                                           &connection_bck_keepalive,
754                                                           c);
755 }
756
757
758 /**
759  * @brief Re-initiate traffic on this connection if necessary.
760  *
761  * Check if there is traffic queued towards this peer
762  * and the core transmit handle is NULL (traffic was stalled).
763  * If so, call core tmt rdy.
764  *
765  * @param c Connection on which initiate traffic.
766  * @param fwd Is this about fwd traffic?
767  */
768 static void
769 connection_unlock_queue (struct MeshConnection *c, int fwd)
770 {
771   struct MeshPeer *peer;
772
773   LOG (GNUNET_ERROR_TYPE_DEBUG,
774               "connection_unlock_queue %s on %s\n",
775               fwd ? "FWD" : "BCK", GMC_2s (c));
776
777   if (GMC_is_terminal (c, fwd))
778   {
779     LOG (GNUNET_ERROR_TYPE_DEBUG, " is terminal!\n");
780     return;
781   }
782
783   peer = get_hop (c, fwd);
784   GMP_queue_unlock (peer, c);
785 }
786
787
788 /**
789  * Cancel all transmissions that belong to a certain connection.
790  *
791  * @param c Connection which to cancel.
792  * @param fwd Cancel fwd traffic?
793  */
794 static void
795 connection_cancel_queues (struct MeshConnection *c, int fwd)
796 {
797   struct MeshFlowControl *fc;
798   struct MeshPeer *peer;
799
800   if (NULL == c)
801   {
802     GNUNET_break (0);
803     return;
804   }
805
806   fc = fwd ? &c->fwd_fc : &c->bck_fc;
807   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
808   {
809     GNUNET_SCHEDULER_cancel (fc->poll_task);
810     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
811   }
812   peer = get_hop (c, fwd);
813   GMP_queue_cancel (peer, c);
814 }
815
816
817 /**
818  * Function called if a connection has been stalled for a while,
819  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
820  *
821  * @param cls Closure (poll ctx).
822  * @param tc TaskContext.
823  */
824 static void
825 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
826 {
827   struct MeshFlowControl *fc = cls;
828   struct GNUNET_MESH_Poll msg;
829   struct MeshConnection *c;
830
831   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
832   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
833   {
834     return;
835   }
836
837   c = fc->c;
838   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
839   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** connection [%s]\n", GMC_2s (c));
840   LOG (GNUNET_ERROR_TYPE_DEBUG, " ***   %s\n",
841               fc == &c->fwd_fc ? "FWD" : "BCK");
842
843   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
844   msg.header.size = htons (sizeof (msg));
845   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
846   GMC_send_prebuilt_message (&msg.header, c, NULL, fc == &c->fwd_fc);
847   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
848   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
849                                                 &connection_poll, fc);
850 }
851
852
853 /**
854  * Timeout function due to lack of keepalive/traffic from the owner.
855  * Destroys connection if called.
856  *
857  * @param cls Closure (connection to destroy).
858  * @param tc TaskContext.
859  */
860 static void
861 connection_fwd_timeout (void *cls,
862                         const struct GNUNET_SCHEDULER_TaskContext *tc)
863 {
864   struct MeshConnection *c = cls;
865
866   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
867   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
868     return;
869   LOG (GNUNET_ERROR_TYPE_DEBUG,
870               "Connection %s[%X] FWD timed out. Destroying.\n",
871               GMT_2s (c->t),
872               c->id);
873
874   if (GMC_is_origin (c, GNUNET_YES)) /* If local, leave. */
875     return;
876
877   GMC_destroy (c);
878 }
879
880
881 /**
882  * Timeout function due to lack of keepalive/traffic from the destination.
883  * Destroys connection if called.
884  *
885  * @param cls Closure (connection to destroy).
886  * @param tc TaskContext
887  */
888 static void
889 connection_bck_timeout (void *cls,
890                         const struct GNUNET_SCHEDULER_TaskContext *tc)
891 {
892   struct MeshConnection *c = cls;
893
894   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
895   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
896     return;
897
898   LOG (GNUNET_ERROR_TYPE_DEBUG,
899               "Connection %s[%X] FWD timed out. Destroying.\n",
900               GMT_2s (c->t), c->id);
901
902   if (GMC_is_origin (c, GNUNET_NO)) /* If local, leave. */
903     return;
904
905   GMC_destroy (c);
906 }
907
908
909 /**
910  * Resets the connection timeout task, some other message has done the
911  * task's job.
912  * - For the first peer on the direction this means to send
913  *   a keepalive or a path confirmation message (either create or ACK).
914  * - For all other peers, this means to destroy the connection,
915  *   due to lack of activity.
916  * Starts the tiemout if no timeout was running (connection just created).
917  *
918  * @param c Connection whose timeout to reset.
919  * @param fwd Is this forward?
920  *
921  * TODO use heap to improve efficiency of scheduler.
922  */
923 static void
924 connection_reset_timeout (struct MeshConnection *c, int fwd)
925 {
926   GNUNET_SCHEDULER_TaskIdentifier *ti;
927   GNUNET_SCHEDULER_Task f;
928
929   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
930
931   if (GNUNET_SCHEDULER_NO_TASK != *ti)
932     GNUNET_SCHEDULER_cancel (*ti);
933
934   if (GMC_is_origin (c, fwd)) /* Endpoint */
935   {
936     f  = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
937     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
938   }
939   else /* Relay */
940   {
941     struct GNUNET_TIME_Relative delay;
942
943     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
944     f  = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
945     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
946   }
947 }
948
949
950 /**
951  * Add the connection to the list of both neighbors.
952  *
953  * @param c Connection.
954  */
955 static void
956 register_neighbors (struct MeshConnection *c)
957 {
958   struct MeshPeer *peer;
959
960   peer = get_next_hop (c);
961   if (GNUNET_NO == GMP_is_neighbor (peer))
962   {
963     GMC_destroy (c);
964     return;
965   }
966   GMP_add_connection (peer, c);
967   peer = get_prev_hop (c);
968   if (GNUNET_NO == GMP_is_neighbor (peer))
969   {
970     GMC_destroy (c);
971     return;
972   }
973   GMP_add_connection (peer, c);
974 }
975
976
977 /**
978  * Remove the connection from the list of both neighbors.
979  *
980  * @param c Connection.
981  */
982 static void
983 unregister_neighbors (struct MeshConnection *c)
984 {
985   struct MeshPeer *peer;
986
987   peer = get_next_hop (c);
988   GMP_remove_connection (peer, c);
989
990   peer = get_prev_hop (c);
991   GMP_remove_connection (peer, c);
992
993 }
994
995
996 /**
997  * Bind the connection to the peer and the tunnel to that peer.
998  *
999  * If the peer has no tunnel, create one. Update tunnel and connection
1000  * data structres to reflect new status.
1001  *
1002  * @param c Connection.
1003  * @param peer Peer.
1004  */
1005 static void
1006 add_to_peer (struct MeshConnection *c, struct MeshPeer *peer)
1007 {
1008   GMP_add_tunnel (peer);
1009   c->t = GMP_get_tunnel (peer);
1010   GMT_add_connection (c->t, c);
1011 }
1012
1013 /******************************************************************************/
1014 /********************************    API    ***********************************/
1015 /******************************************************************************/
1016
1017 /**
1018  * Core handler for connection creation.
1019  *
1020  * @param cls Closure (unused).
1021  * @param peer Sender (neighbor).
1022  * @param message Message.
1023  *
1024  * @return GNUNET_OK to keep the connection open,
1025  *         GNUNET_SYSERR to close it (signal serious error)
1026  */
1027 int
1028 GMC_handle_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1029                    const struct GNUNET_MessageHeader *message)
1030 {
1031   struct GNUNET_MESH_ConnectionCreate *msg;
1032   struct GNUNET_PeerIdentity *id;
1033   struct GNUNET_HashCode *cid;
1034   struct MeshPeerPath *path;
1035   struct MeshPeer *dest_peer;
1036   struct MeshPeer *orig_peer;
1037   struct MeshConnection *c;
1038   unsigned int own_pos;
1039   uint16_t size;
1040   uint16_t i;
1041
1042   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1043   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
1044
1045   /* Check size */
1046   size = ntohs (message->size);
1047   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
1048   {
1049     GNUNET_break_op (0);
1050     return GNUNET_OK;
1051   }
1052
1053   /* Calculate hops */
1054   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
1055   if (size % sizeof (struct GNUNET_PeerIdentity))
1056   {
1057     GNUNET_break_op (0);
1058     return GNUNET_OK;
1059   }
1060   size /= sizeof (struct GNUNET_PeerIdentity);
1061   if (1 > size)
1062   {
1063     GNUNET_break_op (0);
1064     return GNUNET_OK;
1065   }
1066   LOG (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
1067
1068   /* Get parameters */
1069   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
1070   cid = &msg->cid;
1071   id = (struct GNUNET_PeerIdentity *) &msg[1];
1072   LOG (GNUNET_ERROR_TYPE_DEBUG,
1073               "    connection %s (%s).\n",
1074               GNUNET_h2s (cid), GNUNET_i2s (id));
1075
1076   /* Create connection */
1077   c = connection_get (cid);
1078   if (NULL == c)
1079   {
1080     /* Create path */
1081     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
1082     path = path_new (size);
1083     own_pos = 0;
1084     for (i = 0; i < size; i++)
1085     {
1086       LOG (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
1087                   GNUNET_i2s (&id[i]));
1088       path->peers[i] = GNUNET_PEER_intern (&id[i]);
1089       if (path->peers[i] == myid)
1090         own_pos = i;
1091     }
1092     if (own_pos == 0 && path->peers[own_pos] != myid)
1093     {
1094       /* create path: self not found in path through self */
1095       GNUNET_break_op (0);
1096       path_destroy (path);
1097       return GNUNET_OK;
1098     }
1099     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
1100     GMP_add_path_to_all (path, GNUNET_NO);
1101         LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
1102     c = GMC_new (cid, NULL, path_duplicate (path), own_pos);
1103     if (NULL == c)
1104       return GNUNET_OK;
1105     connection_reset_timeout (c, GNUNET_YES);
1106   }
1107   else
1108   {
1109     path = NULL;
1110   }
1111   if (MESH_CONNECTION_NEW == c->state)
1112     connection_change_state (c, MESH_CONNECTION_SENT);
1113
1114   /* Remember peers */
1115   dest_peer = GMP_get (&id[size - 1]);
1116   orig_peer = GMP_get (&id[0]);
1117
1118   /* Is it a connection to us? */
1119   if (c->own_pos == size - 1)
1120   {
1121     LOG (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
1122     GMP_add_path_to_origin (orig_peer, path, GNUNET_YES);
1123
1124     add_to_peer (c, orig_peer);
1125     if (MESH_TUNNEL3_NEW == GMT_get_state (c->t))
1126       GMT_change_state (c->t,  MESH_TUNNEL3_WAITING);
1127
1128     send_connection_ack (c, GNUNET_NO);
1129     if (MESH_CONNECTION_SENT == c->state)
1130       connection_change_state (c, MESH_CONNECTION_ACK);
1131
1132     /* Keep tunnel alive in direction dest->owner*/
1133     connection_reset_timeout (c, GNUNET_NO);
1134   }
1135   else
1136   {
1137     /* It's for somebody else! Retransmit. */
1138     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
1139     GMP_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
1140     GMP_add_path_to_origin (orig_peer, path, GNUNET_NO);
1141     GMC_send_prebuilt_message (message, c, NULL, GNUNET_YES);
1142   }
1143   return GNUNET_OK;
1144 }
1145
1146
1147 /**
1148  * Core handler for path confirmations.
1149  *
1150  * @param cls closure
1151  * @param message message
1152  * @param peer peer identity this notification is about
1153  *
1154  * @return GNUNET_OK to keep the connection open,
1155  *         GNUNET_SYSERR to close it (signal serious error)
1156  */
1157 int
1158 GMC_handle_confirm (void *cls, const struct GNUNET_PeerIdentity *peer,
1159                     const struct GNUNET_MessageHeader *message)
1160 {
1161   struct GNUNET_MESH_ConnectionACK *msg;
1162   struct MeshConnection *c;
1163   struct MeshPeerPath *p;
1164   struct MeshPeer *pi;
1165   int fwd;
1166
1167   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1168   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
1169   msg = (struct GNUNET_MESH_ConnectionACK *) message;
1170   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
1171               GNUNET_h2s (&msg->cid));
1172   c = connection_get (&msg->cid);
1173   if (NULL == c)
1174   {
1175     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1176                               1, GNUNET_NO);
1177     LOG (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
1178     return GNUNET_OK;
1179   }
1180
1181
1182   LOG (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
1183               GNUNET_i2s (peer));
1184   pi = GMP_get (peer);
1185   if (get_next_hop (c) == pi)
1186   {
1187     LOG (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
1188     fwd = GNUNET_NO;
1189     if (MESH_CONNECTION_SENT == c->state)
1190       connection_change_state (c, MESH_CONNECTION_ACK);
1191   }
1192   else if (get_prev_hop (c) == pi)
1193   {
1194     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
1195     fwd = GNUNET_YES;
1196     connection_change_state (c, MESH_CONNECTION_READY);
1197   }
1198   else
1199   {
1200     GNUNET_break_op (0);
1201     return GNUNET_OK;
1202   }
1203   connection_reset_timeout (c, fwd);
1204
1205   /* Add path to peers? */
1206   p = c->path;
1207   if (NULL != p)
1208   {
1209     GMP_add_path_to_all (p, GNUNET_YES);
1210   }
1211   else
1212   {
1213     GNUNET_break (0);
1214   }
1215
1216   /* Message for us as creator? */
1217   if (GMC_is_origin (c, GNUNET_YES))
1218   {
1219     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
1220     connection_change_state (c, MESH_CONNECTION_READY);
1221     GMT_change_state (c->t, MESH_TUNNEL3_READY);
1222     send_connection_ack (c, GNUNET_YES);
1223     GMT_send_queued_data (c->t, GNUNET_YES);
1224     return GNUNET_OK;
1225   }
1226
1227   /* Message for us as destination? */
1228   if (GMC_is_terminal (c, GNUNET_YES))
1229   {
1230     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
1231     connection_change_state (c, MESH_CONNECTION_READY);
1232     GMT_change_state (c->t, MESH_TUNNEL3_READY);
1233     GMT_send_queued_data (c->t, GNUNET_NO);
1234     return GNUNET_OK;
1235   }
1236
1237   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1238   GMC_send_prebuilt_message (message, c, NULL, fwd);
1239   return GNUNET_OK;
1240 }
1241
1242
1243 /**
1244  * Core handler for notifications of broken paths
1245  *
1246  * @param cls Closure (unused).
1247  * @param id Peer identity of sending neighbor.
1248  * @param message Message.
1249  *
1250  * @return GNUNET_OK to keep the connection open,
1251  *         GNUNET_SYSERR to close it (signal serious error)
1252  */
1253 int
1254 GMC_handle_broken (void* cls,
1255                    const struct GNUNET_PeerIdentity* id,
1256                    const struct GNUNET_MessageHeader* message)
1257 {
1258   struct GNUNET_MESH_ConnectionBroken *msg;
1259   struct MeshConnection *c;
1260   int fwd;
1261
1262   LOG (GNUNET_ERROR_TYPE_DEBUG,
1263               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (id));
1264   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
1265   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1266               GNUNET_i2s (&msg->peer1));
1267   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1268               GNUNET_i2s (&msg->peer2));
1269   c = connection_get (&msg->cid);
1270   if (NULL == c)
1271   {
1272     GNUNET_break_op (0);
1273     return GNUNET_OK;
1274   }
1275
1276   fwd = is_fwd (c, id);
1277   connection_cancel_queues (c, !fwd);
1278   if (GMC_is_terminal (c, fwd))
1279   {
1280     if (0 < c->pending_messages)
1281       c->destroy = GNUNET_YES;
1282     else
1283       GMC_destroy (c);
1284   }
1285   else
1286   {
1287     GMC_send_prebuilt_message (message, c, NULL, fwd);
1288     c->destroy = GNUNET_YES;
1289   }
1290
1291   return GNUNET_OK;
1292
1293 }
1294
1295
1296 /**
1297  * Core handler for tunnel destruction
1298  *
1299  * @param cls Closure (unused).
1300  * @param peer Peer identity of sending neighbor.
1301  * @param message Message.
1302  *
1303  * @return GNUNET_OK to keep the connection open,
1304  *         GNUNET_SYSERR to close it (signal serious error)
1305  */
1306 int
1307 GMC_handle_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
1308                     const struct GNUNET_MessageHeader *message)
1309 {
1310   struct GNUNET_MESH_ConnectionDestroy *msg;
1311   struct MeshConnection *c;
1312   int fwd;
1313
1314   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
1315   LOG (GNUNET_ERROR_TYPE_DEBUG,
1316               "Got a CONNECTION DESTROY message from %s\n",
1317               GNUNET_i2s (peer));
1318   LOG (GNUNET_ERROR_TYPE_DEBUG,
1319               "  for connection %s\n",
1320               GNUNET_h2s (&msg->cid));
1321   c = connection_get (&msg->cid);
1322   if (NULL == c)
1323   {
1324     /* Probably already got the message from another path,
1325      * destroyed the tunnel and retransmitted to children.
1326      * Safe to ignore.
1327      */
1328     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
1329                               1, GNUNET_NO);
1330     return GNUNET_OK;
1331   }
1332   fwd = is_fwd (c, peer);
1333   if (GNUNET_SYSERR == fwd)
1334   {
1335     GNUNET_break_op (0);
1336     return GNUNET_OK;
1337   }
1338   GMC_send_prebuilt_message (message, c, NULL, fwd);
1339   c->destroy = GNUNET_YES;
1340
1341   return GNUNET_OK;
1342 }
1343
1344 /**
1345  * Generic handler for mesh network encrypted traffic.
1346  *
1347  * @param peer Peer identity this notification is about.
1348  * @param msg Encrypted message.
1349  *
1350  * @return GNUNET_OK to keep the connection open,
1351  *         GNUNET_SYSERR to close it (signal serious error)
1352  */
1353 static int
1354 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
1355                        const struct GNUNET_MESH_Encrypted *msg)
1356 {
1357   struct MeshConnection *c;
1358   struct MeshPeer *neighbor;
1359   struct MeshFlowControl *fc;
1360   GNUNET_PEER_Id peer_id;
1361   uint32_t pid;
1362   uint32_t ttl;
1363   uint16_t type;
1364   size_t size;
1365   int fwd;
1366
1367   /* Check size */
1368   size = ntohs (msg->header.size);
1369   if (size <
1370       sizeof (struct GNUNET_MESH_Encrypted) +
1371       sizeof (struct GNUNET_MessageHeader))
1372   {
1373     GNUNET_break_op (0);
1374     return GNUNET_OK;
1375   }
1376   type = ntohs (msg->header.type);
1377   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1378   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
1379               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
1380
1381   /* Check connection */
1382   c = connection_get (&msg->cid);
1383   if (NULL == c)
1384   {
1385     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
1386     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
1387     return GNUNET_OK;
1388   }
1389
1390   /* Check if origin is as expected */
1391   neighbor = get_prev_hop (c);
1392   peer_id = GNUNET_PEER_search (peer);
1393   if (peer_id == GMP_get_short_id (neighbor))
1394   {
1395     fwd = GNUNET_YES;
1396   }
1397   else
1398   {
1399     neighbor = get_next_hop (c);
1400     if (peer_id == GMP_get_short_id (neighbor))
1401     {
1402       fwd = GNUNET_NO;
1403     }
1404     else
1405     {
1406       /* Unexpected peer sending traffic on a connection. */
1407       GNUNET_break_op (0);
1408       return GNUNET_OK;
1409     }
1410   }
1411
1412   /* Check PID */
1413   fc = fwd ? &c->bck_fc : &c->fwd_fc;
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 || MESH_CONNECTION_ACK == 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   if (2 == c->destroy) /* cancel queues -> GMP_queue_cancel -> q_destroy -> */
1845     return;            /* -> message_sent -> GMC_destroy. Don't loop. */
1846   c->destroy = 2;
1847
1848   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s\n", GMC_2s (c));
1849
1850   /* Cancel all traffic */
1851   connection_cancel_queues (c, GNUNET_YES);
1852   connection_cancel_queues (c, GNUNET_NO);
1853
1854   /* Cancel maintainance task (keepalive/timeout) */
1855   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
1856     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
1857   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
1858     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
1859
1860   /* Unregister from neighbors */
1861   unregister_neighbors (c);
1862
1863   /* Delete */
1864   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
1865   if (NULL != c->t)
1866     GMT_remove_connection (c->t, c);
1867   GNUNET_free (c);
1868 }
1869
1870 /**
1871  * Get the connection ID.
1872  *
1873  * @param c Connection to get the ID from.
1874  *
1875  * @return ID of the connection.
1876  */
1877 const struct GNUNET_HashCode *
1878 GMC_get_id (const struct MeshConnection *c)
1879 {
1880   return &c->id;
1881 }
1882
1883
1884 /**
1885  * Get the connection path.
1886  *
1887  * @param c Connection to get the path from.
1888  *
1889  * @return path used by the connection.
1890  */
1891 const struct MeshPeerPath *
1892 GMC_get_path (const struct MeshConnection *c)
1893 {
1894   return c->path;
1895 }
1896
1897
1898 /**
1899  * Get the connection state.
1900  *
1901  * @param c Connection to get the state from.
1902  *
1903  * @return state of the connection.
1904  */
1905 enum MeshConnectionState
1906 GMC_get_state (const struct MeshConnection *c)
1907 {
1908   return c->state;
1909 }
1910
1911 /**
1912  * Get the connection tunnel.
1913  *
1914  * @param c Connection to get the tunnel from.
1915  *
1916  * @return tunnel of the connection.
1917  */
1918 struct MeshTunnel3 *
1919 GMC_get_tunnel (const struct MeshConnection *c)
1920 {
1921   return c->t;
1922 }
1923
1924
1925 /**
1926  * Get free buffer space in a connection.
1927  *
1928  * @param c Connection.
1929  * @param fwd Is query about FWD traffic?
1930  *
1931  * @return Free buffer space [0 - max_msgs_queue/max_connections]
1932  */
1933 unsigned int
1934 GMC_get_buffer (struct MeshConnection *c, int fwd)
1935 {
1936   struct MeshFlowControl *fc;
1937
1938   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1939
1940   return (fc->queue_max - fc->queue_n);
1941 }
1942
1943 /**
1944  * Get how many messages have we allowed to send to us from a direction.
1945  *
1946  * @param c Connection.
1947  * @param fwd Are we asking about traffic from FWD (BCK messages)?
1948  *
1949  * @return last_ack_sent - last_pid_recv
1950  */
1951 unsigned int
1952 GMC_get_allowed (struct MeshConnection *c, int fwd)
1953 {
1954   struct MeshFlowControl *fc;
1955
1956   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1957   if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
1958   {
1959     return 0;
1960   }
1961   return (fc->last_ack_sent - fc->last_pid_recv);
1962 }
1963
1964 /**
1965  * Get messages queued in a connection.
1966  *
1967  * @param c Connection.
1968  * @param fwd Is query about FWD traffic?
1969  *
1970  * @return Number of messages queued.
1971  */
1972 unsigned int
1973 GMC_get_qn (struct MeshConnection *c, int fwd)
1974 {
1975   struct MeshFlowControl *fc;
1976
1977   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1978
1979   return fc->queue_n;
1980 }
1981
1982
1983 /**
1984  * Allow the connection to advertise a buffer of the given size.
1985  *
1986  * The connection will send an @c fwd ACK message (so: in direction !fwd)
1987  * allowing up to last_pid_recv + buffer.
1988  *
1989  * @param c Connection.
1990  * @param buffer How many more messages the connection can accept.
1991  * @param fwd Is this about FWD traffic? (The ack will go dest->root).
1992  */
1993 void
1994 GMC_allow (struct MeshConnection *c, unsigned int buffer, int fwd)
1995 {
1996   send_ack (c, buffer, fwd);
1997 }
1998
1999
2000 /**
2001  * Notify other peers on a connection of a broken link. Mark connections
2002  * to destroy after all traffic has been sent.
2003  *
2004  * @param c Connection on which there has been a disconnection.
2005  * @param peer Peer that disconnected.
2006  */
2007 void
2008 GMC_notify_broken (struct MeshConnection *c,
2009                    struct MeshPeer *peer)
2010 {
2011   int fwd;
2012
2013   fwd = peer == get_prev_hop (c);
2014
2015   if (GNUNET_YES == GMC_is_terminal (c, fwd))
2016   {
2017     /* Local shutdown, no one to notify about this. */
2018     GMC_destroy (c);
2019     return;
2020   }
2021   send_broken (c, &my_full_id, GMP_get_id (peer), fwd);
2022   connection_cancel_queues (c, !fwd);
2023
2024   /* Connection will have at least one pending message
2025    * (the one we just scheduled), so no point in checking whether to
2026    * destroy immediately. */
2027   c->destroy = GNUNET_YES;
2028
2029   return;
2030 }
2031
2032
2033 /**
2034  * Is this peer the first one on the connection?
2035  *
2036  * @param c Connection.
2037  * @param fwd Is this about fwd traffic?
2038  *
2039  * @return GNUNET_YES if origin, GNUNET_NO if relay/terminal.
2040  */
2041 int
2042 GMC_is_origin (struct MeshConnection *c, int fwd)
2043 {
2044   if (!fwd && c->path->length - 1 == c->own_pos )
2045     return GNUNET_YES;
2046   if (fwd && 0 == c->own_pos)
2047     return GNUNET_YES;
2048   return GNUNET_NO;
2049 }
2050
2051
2052 /**
2053  * Is this peer the last one on the connection?
2054  *
2055  * @param c Connection.
2056  * @param fwd Is this about fwd traffic?
2057  *            Note that the ROOT is the terminal for BCK traffic!
2058  *
2059  * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
2060  */
2061 int
2062 GMC_is_terminal (struct MeshConnection *c, int fwd)
2063 {
2064   return GMC_is_origin (c, !fwd);
2065 }
2066
2067
2068 /**
2069  * See if we are allowed to send by the next hop in the given direction.
2070  *
2071  * @param c Connection.
2072  * @param fwd Is this about fwd traffic?
2073  *
2074  * @return GNUNET_YES in case it's OK.
2075  */
2076 int
2077 GMC_is_sendable (struct MeshConnection *c, int fwd)
2078 {
2079   struct MeshFlowControl *fc;
2080
2081   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2082   if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2083     return GNUNET_YES;
2084   return GNUNET_NO;
2085 }
2086
2087 /**
2088  * Sends an already built message on a connection, properly registering
2089  * all used resources.
2090  *
2091  * @param message Message to send. Function makes a copy of it.
2092  *                If message is not hop-by-hop, decrements TTL of copy.
2093  * @param c Connection on which this message is transmitted.
2094  * @param ch Channel on which this message is transmitted, or NULL.
2095  * @param fwd Is this a fwd message?
2096  */
2097 void
2098 GMC_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2099                            struct MeshConnection *c,
2100                            struct MeshChannel *ch,
2101                            int fwd)
2102 {
2103   struct MeshFlowControl *fc;
2104   void *data;
2105   size_t size;
2106   uint16_t type;
2107   int droppable;
2108
2109   size = ntohs (message->size);
2110   data = GNUNET_malloc (size);
2111   memcpy (data, message, size);
2112   type = ntohs (message->type);
2113   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send %s (%u) on connection %s\n",
2114               GNUNET_MESH_DEBUG_M2S (type), size, GMC_2s (c));
2115
2116   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2117   droppable = GNUNET_YES;
2118   switch (type)
2119   {
2120     struct GNUNET_MESH_Encrypted *emsg;
2121     struct GNUNET_MESH_ACK       *amsg;
2122     struct GNUNET_MESH_Poll      *pmsg;
2123     struct GNUNET_MESH_ConnectionDestroy *dmsg;
2124     struct GNUNET_MESH_ConnectionBroken  *bmsg;
2125     uint32_t ttl;
2126
2127     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
2128       emsg = (struct GNUNET_MESH_Encrypted *) data;
2129       ttl = ntohl (emsg->ttl);
2130       if (0 == ttl)
2131       {
2132         GNUNET_break_op (0);
2133         return;
2134       }
2135       emsg->cid = c->id;
2136       emsg->ttl = htonl (ttl - 1);
2137       emsg->pid = htonl (fwd ? c->fwd_fc.next_pid++ : c->bck_fc.next_pid++);
2138       LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
2139       fc->queue_n++;
2140       LOG (GNUNET_ERROR_TYPE_DEBUG, "pid %u\n", ntohl (emsg->pid));
2141       LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid %u\n", fc->last_pid_sent);
2142       LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack %u\n", fc->last_ack_recv);
2143       if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
2144       {
2145         GMC_start_poll (c, fwd);
2146       }
2147       break;
2148
2149     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2150       amsg = (struct GNUNET_MESH_ACK *) data;
2151       amsg->cid = c->id;
2152       LOG (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
2153       droppable = GNUNET_NO;
2154       break;
2155
2156     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2157       pmsg = (struct GNUNET_MESH_Poll *) data;
2158       pmsg->cid = c->id;
2159       pmsg->pid = htonl (fwd ? c->fwd_fc.last_pid_sent : c->bck_fc.last_pid_sent);
2160       LOG (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
2161       droppable = GNUNET_NO;
2162       break;
2163
2164     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
2165       dmsg = (struct GNUNET_MESH_ConnectionDestroy *) data;
2166       dmsg->cid = c->id;
2167       dmsg->reserved = 0;
2168       break;
2169
2170     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
2171       bmsg = (struct GNUNET_MESH_ConnectionBroken *) data;
2172       bmsg->cid = c->id;
2173       bmsg->reserved = 0;
2174       break;
2175
2176     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
2177     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
2178       break;
2179
2180     default:
2181       GNUNET_break (0);
2182   }
2183
2184   if (fc->queue_n > fc->queue_max && droppable)
2185   {
2186     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
2187                               1, GNUNET_NO);
2188     GNUNET_break (0);
2189     LOG (GNUNET_ERROR_TYPE_DEBUG,
2190                 "queue full: %u/%u\n",
2191                 fc->queue_n, fc->queue_max);
2192     if (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED == type)
2193       fc->queue_n--;
2194     return; /* Drop this message */
2195   }
2196
2197   c->pending_messages++;
2198
2199   GMP_queue_add (get_hop (c, fwd), data, type, size, c, ch, fwd,
2200                  &message_sent, NULL);
2201 }
2202
2203
2204 /**
2205  * Sends a CREATE CONNECTION message for a path to a peer.
2206  * Changes the connection and tunnel states if necessary.
2207  *
2208  * @param connection Connection to create.
2209  */
2210 void
2211 GMC_send_create (struct MeshConnection *connection)
2212 {
2213   enum MeshTunnel3State state;
2214   size_t size;
2215
2216   size = sizeof (struct GNUNET_MESH_ConnectionCreate);
2217   size += connection->path->length * sizeof (struct GNUNET_PeerIdentity);
2218   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
2219   GMP_queue_add (get_next_hop (connection), NULL,
2220                  GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
2221                  size, connection, NULL,
2222                  GNUNET_YES, &message_sent, NULL);
2223   state = GMT_get_state (connection->t);
2224   if (MESH_TUNNEL3_SEARCHING == state || MESH_TUNNEL3_NEW == state)
2225     GMT_change_state (connection->t, MESH_TUNNEL3_WAITING);
2226   if (MESH_CONNECTION_NEW == connection->state)
2227     connection_change_state (connection, MESH_CONNECTION_SENT);
2228 }
2229
2230
2231 /**
2232  * Send a message to all peers in this connection that the connection
2233  * is no longer valid.
2234  *
2235  * If some peer should not receive the message, it should be zero'ed out
2236  * before calling this function.
2237  *
2238  * @param c The connection whose peers to notify.
2239  */
2240 void
2241 GMC_send_destroy (struct MeshConnection *c)
2242 {
2243   struct GNUNET_MESH_ConnectionDestroy msg;
2244
2245   if (GNUNET_YES == c->destroy)
2246     return;
2247
2248   msg.header.size = htons (sizeof (msg));
2249   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY);;
2250   msg.cid = c->id;
2251   LOG (GNUNET_ERROR_TYPE_DEBUG,
2252               "  sending connection destroy for connection %s\n",
2253               GMC_2s (c));
2254
2255   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_YES))
2256     GMC_send_prebuilt_message (&msg.header, c, NULL, GNUNET_YES);
2257   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_NO))
2258     GMC_send_prebuilt_message (&msg.header, c, NULL, GNUNET_NO);
2259   c->destroy = GNUNET_YES;
2260 }
2261
2262
2263 /**
2264  * @brief Start a polling timer for the connection.
2265  *
2266  * When a neighbor does not accept more traffic on the connection it could be
2267  * caused by a simple congestion or by a lost ACK. Polling enables to check
2268  * for the lastest ACK status for a connection.
2269  *
2270  * @param c Connection.
2271  * @param fwd Should we poll in the FWD direction?
2272  */
2273 void
2274 GMC_start_poll (struct MeshConnection *c, int fwd)
2275 {
2276   struct MeshFlowControl *fc;
2277
2278   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2279   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2280   {
2281     return;
2282   }
2283   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2284                                                 &connection_poll,
2285                                                 fc);
2286 }
2287
2288
2289 /**
2290  * @brief Stop polling a connection for ACKs.
2291  *
2292  * Once we have enough ACKs for future traffic, polls are no longer necessary.
2293  *
2294  * @param c Connection.
2295  * @param fwd Should we stop the poll in the FWD direction?
2296  */
2297 void
2298 GMC_stop_poll (struct MeshConnection *c, int fwd)
2299 {
2300   struct MeshFlowControl *fc;
2301
2302   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2303   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2304   {
2305     GNUNET_SCHEDULER_cancel (fc->poll_task);
2306     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2307   }
2308 }
2309
2310 /**
2311  * Get a (static) string for a connection.
2312  *
2313  * @param c Connection.
2314  */
2315 const char *
2316 GMC_2s (struct MeshConnection *c)
2317 {
2318   if (NULL != c->t)
2319   {
2320     static char buf[128];
2321
2322     sprintf (buf, "%s (->%s)", GNUNET_h2s (&c->id), GMT_2s (c->t));
2323     return buf;
2324   }
2325   return GNUNET_h2s (&c->id);
2326 }