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