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