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