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