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