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