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