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