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