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