- fix polling
[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, "!  C_P- %p %u\n", c, c->pending_messages);
449   c->pending_messages--;
450   if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
451   {
452     LOG (GNUNET_ERROR_TYPE_DEBUG, "!  destroying connection!\n");
453     GMC_destroy (c);
454     return;
455   }
456   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
457   switch (type)
458   {
459     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
460       fc->last_pid_sent++;
461       LOG (GNUNET_ERROR_TYPE_DEBUG, "!  Q_N- %p %u\n", fc, fc->queue_n);
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   connection->pending_messages++;
608   if (MESH_TUNNEL3_NEW == GMT_get_state (t))
609     GMT_change_state (t, MESH_TUNNEL3_WAITING);
610   if (MESH_CONNECTION_READY != connection->state)
611     connection_change_state (connection, MESH_CONNECTION_SENT);
612 }
613
614
615 /**
616  * Send a notification that a connection is broken.
617  *
618  * @param c Connection that is broken.
619  * @param id1 Peer that has disconnected.
620  * @param id2 Peer that has disconnected.
621  * @param fwd Direction towards which to send it.
622  */
623 static void
624 send_broken (struct MeshConnection *c,
625              const struct GNUNET_PeerIdentity *id1,
626              const struct GNUNET_PeerIdentity *id2,
627              int fwd)
628 {
629   struct GNUNET_MESH_ConnectionBroken msg;
630
631   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
632   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
633   msg.cid = c->id;
634   msg.peer1 = *id1;
635   msg.peer2 = *id2;
636   GMC_send_prebuilt_message (&msg.header, c, fwd);
637 }
638
639
640
641 /**
642  * Send keepalive packets for a connection.
643  *
644  * @param c Connection to keep alive..
645  * @param fwd Is this a FWD keepalive? (owner -> dest).
646  */
647 static void
648 connection_keepalive (struct MeshConnection *c, int fwd)
649 {
650   struct GNUNET_MESH_ConnectionKeepAlive *msg;
651   size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
652   char cbuf[size];
653   uint16_t type;
654
655   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
656                GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
657
658   LOG (GNUNET_ERROR_TYPE_DEBUG,
659        "sending %s keepalive for connection %s]\n",
660        fwd ? "FWD" : "BCK", GMC_2s (c));
661
662   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
663   msg->header.size = htons (size);
664   msg->header.type = htons (type);
665   msg->cid = c->id;
666
667   GMC_send_prebuilt_message (&msg->header, c, fwd);
668 }
669
670
671 /**
672  * Send CONNECTION_{CREATE/ACK} packets for a connection.
673  *
674  * @param c Connection for which to send the message.
675  * @param fwd If #GNUNET_YES, send CREATE, otherwise send ACK.
676  */
677 static void
678 connection_recreate (struct MeshConnection *c, int fwd)
679 {
680   LOG (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
681   if (fwd)
682     GMC_send_create (c);
683   else
684     send_connection_ack (c, GNUNET_NO);
685 }
686
687
688 /**
689  * Generic connection timer management.
690  * Depending on the role of the peer in the connection will send the
691  * appropriate message (build or keepalive)
692  *
693  * @param c Conncetion to maintain.
694  * @param fwd Is FWD?
695  */
696 static void
697 connection_maintain (struct MeshConnection *c, int fwd)
698 {
699   if (MESH_TUNNEL3_SEARCHING == GMT_get_state (c->t))
700   {
701     /* TODO DHT GET with RO_BART */
702     return;
703   }
704   switch (c->state)
705   {
706     case MESH_CONNECTION_NEW:
707       GNUNET_break (0);
708     case MESH_CONNECTION_SENT:
709       connection_recreate (c, fwd);
710       break;
711     case MESH_CONNECTION_READY:
712       connection_keepalive (c, fwd);
713       break;
714     default:
715       break;
716   }
717 }
718
719
720 static void
721 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
722 {
723   struct MeshConnection *c = cls;
724
725   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
726   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
727     return;
728
729   connection_maintain (c, GNUNET_YES);
730   c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
731                                                           &connection_fwd_keepalive,
732                                                           c);
733 }
734
735
736 static void
737 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
738 {
739   struct MeshConnection *c = cls;
740
741   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
742   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
743     return;
744
745   connection_maintain (c, GNUNET_NO);
746   c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
747                                                           &connection_bck_keepalive,
748                                                           c);
749 }
750
751
752 /**
753  * @brief Re-initiate traffic on this connection if necessary.
754  *
755  * Check if there is traffic queued towards this peer
756  * and the core transmit handle is NULL (traffic was stalled).
757  * If so, call core tmt rdy.
758  *
759  * @param c Connection on which initiate traffic.
760  * @param fwd Is this about fwd traffic?
761  */
762 static void
763 connection_unlock_queue (struct MeshConnection *c, int fwd)
764 {
765   struct MeshPeer *peer;
766
767   LOG (GNUNET_ERROR_TYPE_DEBUG,
768               "connection_unlock_queue %s on %s\n",
769               fwd ? "FWD" : "BCK", GMC_2s (c));
770
771   if (GMC_is_terminal (c, fwd))
772   {
773     LOG (GNUNET_ERROR_TYPE_DEBUG, " is terminal!\n");
774     return;
775   }
776
777   peer = get_hop (c, fwd);
778   GMP_queue_unlock (peer, c);
779 }
780
781
782 /**
783  * Cancel all transmissions that belong to a certain connection.
784  * 
785  * If the connection is scheduled for destruction and no more messages are left,
786  * the connection will be destroyed by the continuation call.
787  *
788  * @param c Connection which to cancel. Might be destroyed during this call.
789  * @param fwd Cancel fwd traffic?
790  */
791 static void
792 connection_cancel_queues (struct MeshConnection *c, int fwd)
793 {
794   struct MeshFlowControl *fc;
795   struct MeshPeer *peer;
796
797   if (NULL == c)
798   {
799     GNUNET_break (0);
800     return;
801   }
802
803   fc = fwd ? &c->fwd_fc : &c->bck_fc;
804   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
805   {
806     GNUNET_SCHEDULER_cancel (fc->poll_task);
807     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
808   }
809   peer = get_hop (c, fwd);
810   GMP_queue_cancel (peer, c);
811 }
812
813
814 /**
815  * Function called if a connection has been stalled for a while,
816  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
817  *
818  * @param cls Closure (poll ctx).
819  * @param tc TaskContext.
820  */
821 static void
822 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
823 {
824   struct MeshFlowControl *fc = cls;
825   struct GNUNET_MESH_Poll msg;
826   struct MeshConnection *c;
827
828   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
829   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
830   {
831     return;
832   }
833
834   c = fc->c;
835   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
836   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** connection [%s]\n", GMC_2s (c));
837   LOG (GNUNET_ERROR_TYPE_DEBUG, " ***   %s\n",
838               fc == &c->fwd_fc ? "FWD" : "BCK");
839
840   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
841   msg.header.size = htons (sizeof (msg));
842   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
843   GMC_send_prebuilt_message (&msg.header, c, fc == &c->fwd_fc);
844   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
845   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
846                                                 &connection_poll, fc);
847 }
848
849
850 /**
851  * Timeout function due to lack of keepalive/traffic from the owner.
852  * Destroys connection if called.
853  *
854  * @param cls Closure (connection to destroy).
855  * @param tc TaskContext.
856  */
857 static void
858 connection_fwd_timeout (void *cls,
859                         const struct GNUNET_SCHEDULER_TaskContext *tc)
860 {
861   struct MeshConnection *c = cls;
862
863   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
864   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
865     return;
866   LOG (GNUNET_ERROR_TYPE_DEBUG,
867               "Connection %s[%X] FWD timed out. Destroying.\n",
868               GMT_2s (c->t),
869               c->id);
870
871   if (GMC_is_origin (c, GNUNET_YES)) /* If local, leave. */
872     return;
873
874   GMC_destroy (c);
875 }
876
877
878 /**
879  * Timeout function due to lack of keepalive/traffic from the destination.
880  * Destroys connection if called.
881  *
882  * @param cls Closure (connection to destroy).
883  * @param tc TaskContext
884  */
885 static void
886 connection_bck_timeout (void *cls,
887                         const struct GNUNET_SCHEDULER_TaskContext *tc)
888 {
889   struct MeshConnection *c = cls;
890
891   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
892   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
893     return;
894
895   LOG (GNUNET_ERROR_TYPE_DEBUG,
896               "Connection %s[%X] FWD timed out. Destroying.\n",
897               GMT_2s (c->t), c->id);
898
899   if (GMC_is_origin (c, GNUNET_NO)) /* If local, leave. */
900     return;
901
902   GMC_destroy (c);
903 }
904
905
906 /**
907  * Resets the connection timeout task, some other message has done the
908  * task's job.
909  * - For the first peer on the direction this means to send
910  *   a keepalive or a path confirmation message (either create or ACK).
911  * - For all other peers, this means to destroy the connection,
912  *   due to lack of activity.
913  * Starts the tiemout if no timeout was running (connection just created).
914  *
915  * @param c Connection whose timeout to reset.
916  * @param fwd Is this forward?
917  *
918  * TODO use heap to improve efficiency of scheduler.
919  */
920 static void
921 connection_reset_timeout (struct MeshConnection *c, int fwd)
922 {
923   GNUNET_SCHEDULER_TaskIdentifier *ti;
924   GNUNET_SCHEDULER_Task f;
925
926   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
927
928   if (GNUNET_SCHEDULER_NO_TASK != *ti)
929     GNUNET_SCHEDULER_cancel (*ti);
930
931   if (GMC_is_origin (c, fwd)) /* Endpoint */
932   {
933     f  = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
934     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
935   }
936   else /* Relay */
937   {
938     struct GNUNET_TIME_Relative delay;
939
940     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
941     f  = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
942     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
943   }
944 }
945
946
947 /**
948  * Add the connection to the list of both neighbors.
949  *
950  * @param c Connection.
951  */
952 static void
953 register_neighbors (struct MeshConnection *c)
954 {
955   struct MeshPeer *peer;
956
957   peer = get_next_hop (c);
958   if (GNUNET_NO == GMP_is_neighbor (peer))
959   {
960     GMC_destroy (c);
961     return;
962   }
963   GMP_add_connection (peer, c);
964   peer = get_prev_hop (c);
965   if (GNUNET_NO == GMP_is_neighbor (peer))
966   {
967     GMC_destroy (c);
968     return;
969   }
970   GMP_add_connection (peer, c);
971 }
972
973
974 /**
975  * Remove the connection from the list of both neighbors.
976  *
977  * @param c Connection.
978  */
979 static void
980 unregister_neighbors (struct MeshConnection *c)
981 {
982   struct MeshPeer *peer;
983
984   peer = get_next_hop (c);
985   GMP_remove_connection (peer, c);
986
987   peer = get_prev_hop (c);
988   GMP_remove_connection (peer, c);
989
990 }
991
992
993 /**
994  * Bind the connection to the peer and the tunnel to that peer.
995  *
996  * If the peer has no tunnel, create one. Update tunnel and connection
997  * data structres to reflect new status.
998  *
999  * @param c Connection.
1000  * @param peer Peer.
1001  */
1002 static void
1003 add_to_peer (struct MeshConnection *c, struct MeshPeer *peer)
1004 {
1005   GMP_add_tunnel (peer);
1006   c->t = GMP_get_tunnel (peer);
1007   GMT_add_connection (c->t, c);
1008 }
1009
1010 /******************************************************************************/
1011 /********************************    API    ***********************************/
1012 /******************************************************************************/
1013
1014 /**
1015  * Core handler for connection creation.
1016  *
1017  * @param cls Closure (unused).
1018  * @param peer Sender (neighbor).
1019  * @param message Message.
1020  *
1021  * @return GNUNET_OK to keep the connection open,
1022  *         GNUNET_SYSERR to close it (signal serious error)
1023  */
1024 int
1025 GMC_handle_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1026                    const struct GNUNET_MessageHeader *message)
1027 {
1028   struct GNUNET_MESH_ConnectionCreate *msg;
1029   struct GNUNET_PeerIdentity *id;
1030   struct GNUNET_HashCode *cid;
1031   struct MeshPeerPath *path;
1032   struct MeshPeer *dest_peer;
1033   struct MeshPeer *orig_peer;
1034   struct MeshConnection *c;
1035   unsigned int own_pos;
1036   uint16_t size;
1037   uint16_t i;
1038
1039   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1040   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
1041
1042   /* Check size */
1043   size = ntohs (message->size);
1044   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
1045   {
1046     GNUNET_break_op (0);
1047     return GNUNET_OK;
1048   }
1049
1050   /* Calculate hops */
1051   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
1052   if (size % sizeof (struct GNUNET_PeerIdentity))
1053   {
1054     GNUNET_break_op (0);
1055     return GNUNET_OK;
1056   }
1057   size /= sizeof (struct GNUNET_PeerIdentity);
1058   if (1 > size)
1059   {
1060     GNUNET_break_op (0);
1061     return GNUNET_OK;
1062   }
1063   LOG (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
1064
1065   /* Get parameters */
1066   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
1067   cid = &msg->cid;
1068   id = (struct GNUNET_PeerIdentity *) &msg[1];
1069   LOG (GNUNET_ERROR_TYPE_DEBUG,
1070               "    connection %s (%s).\n",
1071               GNUNET_h2s (cid), GNUNET_i2s (id));
1072
1073   /* Create connection */
1074   c = connection_get (cid);
1075   if (NULL == c)
1076   {
1077     /* Create path */
1078     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
1079     path = path_new (size);
1080     own_pos = 0;
1081     for (i = 0; i < size; i++)
1082     {
1083       LOG (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
1084                   GNUNET_i2s (&id[i]));
1085       path->peers[i] = GNUNET_PEER_intern (&id[i]);
1086       if (path->peers[i] == myid)
1087         own_pos = i;
1088     }
1089     if (own_pos == 0 && path->peers[own_pos] != myid)
1090     {
1091       /* create path: self not found in path through self */
1092       GNUNET_break_op (0);
1093       path_destroy (path);
1094       return GNUNET_OK;
1095     }
1096     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
1097     GMP_add_path_to_all (path, GNUNET_NO);
1098         LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
1099     c = GMC_new (cid, NULL, path_duplicate (path), own_pos);
1100     if (NULL == c)
1101       return GNUNET_OK;
1102     connection_reset_timeout (c, GNUNET_YES);
1103   }
1104   else
1105   {
1106     path = NULL;
1107   }
1108   if (MESH_CONNECTION_NEW == c->state)
1109     connection_change_state (c, MESH_CONNECTION_SENT);
1110
1111   /* Remember peers */
1112   dest_peer = GMP_get (&id[size - 1]);
1113   orig_peer = GMP_get (&id[0]);
1114
1115   /* Is it a connection to us? */
1116   if (c->own_pos == size - 1)
1117   {
1118     LOG (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
1119     GMP_add_path_to_origin (orig_peer, path, GNUNET_YES);
1120
1121     add_to_peer (c, orig_peer);
1122     if (MESH_TUNNEL3_NEW == GMT_get_state (c->t))
1123       GMT_change_state (c->t,  MESH_TUNNEL3_WAITING);
1124
1125     send_connection_ack (c, GNUNET_NO);
1126     if (MESH_CONNECTION_SENT == c->state)
1127       connection_change_state (c, MESH_CONNECTION_ACK);
1128
1129     /* Keep tunnel alive in direction dest->owner*/
1130     connection_reset_timeout (c, GNUNET_NO);
1131   }
1132   else
1133   {
1134     /* It's for somebody else! Retransmit. */
1135     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
1136     GMP_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
1137     GMP_add_path_to_origin (orig_peer, path, GNUNET_NO);
1138     GMC_send_prebuilt_message (message, c, GNUNET_YES);
1139   }
1140   return GNUNET_OK;
1141 }
1142
1143
1144 /**
1145  * Core handler for path confirmations.
1146  *
1147  * @param cls closure
1148  * @param message message
1149  * @param peer peer identity this notification is about
1150  *
1151  * @return GNUNET_OK to keep the connection open,
1152  *         GNUNET_SYSERR to close it (signal serious error)
1153  */
1154 int
1155 GMC_handle_confirm (void *cls, const struct GNUNET_PeerIdentity *peer,
1156                     const struct GNUNET_MessageHeader *message)
1157 {
1158   struct GNUNET_MESH_ConnectionACK *msg;
1159   struct MeshConnection *c;
1160   struct MeshPeerPath *p;
1161   struct MeshPeer *pi;
1162   int fwd;
1163
1164   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1165   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
1166   msg = (struct GNUNET_MESH_ConnectionACK *) message;
1167   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
1168               GNUNET_h2s (&msg->cid));
1169   c = connection_get (&msg->cid);
1170   if (NULL == c)
1171   {
1172     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1173                               1, GNUNET_NO);
1174     LOG (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
1175     return GNUNET_OK;
1176   }
1177
1178
1179   LOG (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
1180               GNUNET_i2s (peer));
1181   pi = GMP_get (peer);
1182   if (get_next_hop (c) == pi)
1183   {
1184     LOG (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
1185     fwd = GNUNET_NO;
1186     if (MESH_CONNECTION_SENT == c->state)
1187       connection_change_state (c, MESH_CONNECTION_ACK);
1188   }
1189   else if (get_prev_hop (c) == pi)
1190   {
1191     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
1192     fwd = GNUNET_YES;
1193     connection_change_state (c, MESH_CONNECTION_READY);
1194   }
1195   else
1196   {
1197     GNUNET_break_op (0);
1198     return GNUNET_OK;
1199   }
1200   connection_reset_timeout (c, fwd);
1201
1202   /* Add path to peers? */
1203   p = c->path;
1204   if (NULL != p)
1205   {
1206     GMP_add_path_to_all (p, GNUNET_YES);
1207   }
1208   else
1209   {
1210     GNUNET_break (0);
1211   }
1212
1213   /* Message for us as creator? */
1214   if (GMC_is_origin (c, GNUNET_YES))
1215   {
1216     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
1217     connection_change_state (c, MESH_CONNECTION_READY);
1218     if (MESH_TUNNEL3_WAITING == GMT_get_state (c->t))
1219       GMT_change_state (c->t, MESH_TUNNEL3_READY);
1220     send_connection_ack (c, GNUNET_YES);
1221     return GNUNET_OK;
1222   }
1223
1224   /* Message for us as destination? */
1225   if (GMC_is_terminal (c, GNUNET_YES))
1226   {
1227     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
1228     connection_change_state (c, MESH_CONNECTION_READY);
1229     if (MESH_TUNNEL3_WAITING == GMT_get_state (c->t))
1230       GMT_change_state (c->t, MESH_TUNNEL3_READY);
1231     return GNUNET_OK;
1232   }
1233
1234   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1235   GMC_send_prebuilt_message (message, c, fwd);
1236   return GNUNET_OK;
1237 }
1238
1239
1240 /**
1241  * Core handler for notifications of broken paths
1242  *
1243  * @param cls Closure (unused).
1244  * @param id Peer identity of sending neighbor.
1245  * @param message Message.
1246  *
1247  * @return GNUNET_OK to keep the connection open,
1248  *         GNUNET_SYSERR to close it (signal serious error)
1249  */
1250 int
1251 GMC_handle_broken (void* cls,
1252                    const struct GNUNET_PeerIdentity* id,
1253                    const struct GNUNET_MessageHeader* message)
1254 {
1255   struct GNUNET_MESH_ConnectionBroken *msg;
1256   struct MeshConnection *c;
1257   int fwd;
1258
1259   LOG (GNUNET_ERROR_TYPE_DEBUG,
1260               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (id));
1261   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
1262   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1263               GNUNET_i2s (&msg->peer1));
1264   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1265               GNUNET_i2s (&msg->peer2));
1266   c = connection_get (&msg->cid);
1267   if (NULL == c)
1268   {
1269     GNUNET_break_op (0);
1270     return GNUNET_OK;
1271   }
1272
1273   fwd = is_fwd (c, id);
1274   connection_cancel_queues (c, !fwd);
1275   if (GMC_is_terminal (c, fwd))
1276   {
1277     if (0 < c->pending_messages)
1278       c->destroy = GNUNET_YES;
1279     else
1280       GMC_destroy (c);
1281   }
1282   else
1283   {
1284     GMC_send_prebuilt_message (message, c, fwd);
1285     c->destroy = GNUNET_YES;
1286   }
1287
1288   return GNUNET_OK;
1289
1290 }
1291
1292
1293 /**
1294  * Core handler for tunnel destruction
1295  *
1296  * @param cls Closure (unused).
1297  * @param peer Peer identity of sending neighbor.
1298  * @param message Message.
1299  *
1300  * @return GNUNET_OK to keep the connection open,
1301  *         GNUNET_SYSERR to close it (signal serious error)
1302  */
1303 int
1304 GMC_handle_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
1305                     const struct GNUNET_MessageHeader *message)
1306 {
1307   struct GNUNET_MESH_ConnectionDestroy *msg;
1308   struct MeshConnection *c;
1309   int fwd;
1310
1311   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
1312   LOG (GNUNET_ERROR_TYPE_DEBUG,
1313               "Got a CONNECTION DESTROY message from %s\n",
1314               GNUNET_i2s (peer));
1315   LOG (GNUNET_ERROR_TYPE_DEBUG,
1316               "  for connection %s\n",
1317               GNUNET_h2s (&msg->cid));
1318   c = connection_get (&msg->cid);
1319   if (NULL == c)
1320   {
1321     /* Probably already got the message from another path,
1322      * destroyed the tunnel and retransmitted to children.
1323      * Safe to ignore.
1324      */
1325     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
1326                               1, GNUNET_NO);
1327     return GNUNET_OK;
1328   }
1329   fwd = is_fwd (c, peer);
1330   if (GNUNET_SYSERR == fwd)
1331   {
1332     GNUNET_break_op (0);
1333     return GNUNET_OK;
1334   }
1335   GMC_send_prebuilt_message (message, c, fwd);
1336   c->destroy = GNUNET_YES;
1337
1338   return GNUNET_OK;
1339 }
1340
1341 /**
1342  * Generic handler for mesh network encrypted traffic.
1343  *
1344  * @param peer Peer identity this notification is about.
1345  * @param msg Encrypted message.
1346  *
1347  * @return GNUNET_OK to keep the connection open,
1348  *         GNUNET_SYSERR to close it (signal serious error)
1349  */
1350 static int
1351 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
1352                        const struct GNUNET_MESH_Encrypted *msg)
1353 {
1354   struct MeshConnection *c;
1355   struct MeshPeer *neighbor;
1356   struct MeshFlowControl *fc;
1357   GNUNET_PEER_Id peer_id;
1358   uint32_t pid;
1359   uint32_t ttl;
1360   uint16_t type;
1361   size_t size;
1362   int fwd;
1363
1364   /* Check size */
1365   size = ntohs (msg->header.size);
1366   if (size <
1367       sizeof (struct GNUNET_MESH_Encrypted) +
1368       sizeof (struct GNUNET_MessageHeader))
1369   {
1370     GNUNET_break_op (0);
1371     return GNUNET_OK;
1372   }
1373   type = ntohs (msg->header.type);
1374   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1375   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
1376               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
1377
1378   /* Check connection */
1379   c = connection_get (&msg->cid);
1380   if (NULL == c)
1381   {
1382     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
1383     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
1384     return GNUNET_OK;
1385   }
1386
1387   /* Check if origin is as expected */
1388   neighbor = get_prev_hop (c);
1389   peer_id = GNUNET_PEER_search (peer);
1390   if (peer_id == GMP_get_short_id (neighbor))
1391   {
1392     fwd = GNUNET_YES;
1393   }
1394   else
1395   {
1396     neighbor = get_next_hop (c);
1397     if (peer_id == GMP_get_short_id (neighbor))
1398     {
1399       fwd = GNUNET_NO;
1400     }
1401     else
1402     {
1403       /* Unexpected peer sending traffic on a connection. */
1404       GNUNET_break_op (0);
1405       return GNUNET_OK;
1406     }
1407   }
1408
1409   /* Check PID */
1410   fc = fwd ? &c->bck_fc : &c->fwd_fc;
1411   pid = ntohl (msg->pid);
1412   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
1413   {
1414     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
1415     LOG (GNUNET_ERROR_TYPE_DEBUG,
1416                 "WARNING Received PID %u, (prev %u), ACK %u\n",
1417                 pid, fc->last_pid_recv, fc->last_ack_sent);
1418     return GNUNET_OK;
1419   }
1420   if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
1421   {
1422     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
1423     LOG (GNUNET_ERROR_TYPE_DEBUG,
1424                 " Pid %u not expected (%u+), dropping!\n",
1425                 pid, fc->last_pid_recv + 1);
1426     return GNUNET_OK;
1427   }
1428   if (MESH_CONNECTION_SENT == c->state || MESH_CONNECTION_ACK == c->state)
1429     connection_change_state (c, MESH_CONNECTION_READY);
1430   connection_reset_timeout (c, fwd);
1431   fc->last_pid_recv = pid;
1432
1433   /* Is this message for us? */
1434   if (GMC_is_terminal (c, fwd))
1435   {
1436     /* TODO signature verification */
1437     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
1438     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
1439
1440     if (NULL == c->t)
1441     {
1442       GNUNET_break (0);
1443       return GNUNET_OK;
1444     }
1445     fc->last_pid_recv = pid;
1446     GMT_handle_encrypted (c->t, msg);
1447     GMC_send_ack (c, fwd);
1448     return GNUNET_OK;
1449   }
1450
1451   /* Message not for us: forward to next hop */
1452   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1453   ttl = ntohl (msg->ttl);
1454   LOG (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
1455   if (ttl == 0)
1456   {
1457     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
1458     LOG (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
1459     GMC_send_ack (c, fwd);
1460     return GNUNET_OK;
1461   }
1462   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
1463
1464   GMC_send_prebuilt_message (&msg->header, c, fwd);
1465
1466   return GNUNET_OK;
1467 }
1468
1469 /**
1470  * Generic handler for mesh network encrypted traffic.
1471  *
1472  * @param peer Peer identity this notification is about.
1473  * @param msg Encrypted message.
1474  *
1475  * @return GNUNET_OK to keep the connection open,
1476  *         GNUNET_SYSERR to close it (signal serious error)
1477  */
1478 static int
1479 handle_mesh_kx (const struct GNUNET_PeerIdentity *peer,
1480                 const struct GNUNET_MESH_KX *msg)
1481 {
1482   struct MeshConnection *c;
1483   struct MeshPeer *neighbor;
1484   GNUNET_PEER_Id peer_id;
1485   size_t size;
1486   uint16_t type;
1487   int fwd;
1488
1489   /* Check size */
1490   size = ntohs (msg->header.size);
1491   if (size <
1492       sizeof (struct GNUNET_MESH_Encrypted) +
1493       sizeof (struct GNUNET_MessageHeader))
1494   {
1495     GNUNET_break_op (0);
1496     return GNUNET_OK;
1497   }
1498   type = ntohs (msg->header.type);
1499   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1500   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
1501               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
1502
1503   /* Check connection */
1504   c = connection_get (&msg->cid);
1505   if (NULL == c)
1506   {
1507     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
1508     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
1509     return GNUNET_OK;
1510   }
1511
1512   /* Check if origin is as expected */
1513   neighbor = get_prev_hop (c);
1514   peer_id = GNUNET_PEER_search (peer);
1515   if (peer_id == GMP_get_short_id (neighbor))
1516   {
1517     fwd = GNUNET_YES;
1518   }
1519   else
1520   {
1521     neighbor = get_next_hop (c);
1522     if (peer_id == GMP_get_short_id (neighbor))
1523     {
1524       fwd = GNUNET_NO;
1525     }
1526     else
1527     {
1528       /* Unexpected peer sending traffic on a connection. */
1529       GNUNET_break_op (0);
1530       return GNUNET_OK;
1531     }
1532   }
1533
1534   /* Count as connection confirmation. */
1535   if (MESH_CONNECTION_SENT == c->state || MESH_CONNECTION_ACK == c->state)
1536     connection_change_state (c, MESH_CONNECTION_READY);
1537   connection_reset_timeout (c, fwd);
1538   if (NULL != c->t)
1539   {
1540     if (MESH_TUNNEL3_WAITING == GMT_get_state (c->t))
1541       GMT_change_state (c->t, MESH_TUNNEL3_READY);
1542   }
1543
1544   /* Is this message for us? */
1545   if (GMC_is_terminal (c, fwd))
1546   {
1547     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
1548     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
1549     if (NULL == c->t)
1550     {
1551       GNUNET_break (0);
1552       return GNUNET_OK;
1553     }
1554     GMT_handle_kx (c->t, &msg[1].header);
1555     return GNUNET_OK;
1556   }
1557
1558   /* Message not for us: forward to next hop */
1559   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1560   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
1561
1562   GMC_send_prebuilt_message (&msg->header, c, fwd);
1563
1564   return GNUNET_OK;
1565 }
1566
1567
1568 /**
1569  * Core handler for encrypted mesh network traffic (channel mgmt, data).
1570  *
1571  * @param cls Closure (unused).
1572  * @param message Message received.
1573  * @param peer Peer who sent the message.
1574  *
1575  * @return GNUNET_OK to keep the connection open,
1576  *         GNUNET_SYSERR to close it (signal serious error)
1577  */
1578 int
1579 GMC_handle_encrypted (void *cls, const struct GNUNET_PeerIdentity *peer,
1580                       const struct GNUNET_MessageHeader *message)
1581 {
1582   return handle_mesh_encrypted (peer,
1583                                 (struct GNUNET_MESH_Encrypted *)message);
1584 }
1585
1586
1587 /**
1588  * Core handler for key exchange traffic (ephemeral key, ping, pong).
1589  *
1590  * @param cls Closure (unused).
1591  * @param message Message received.
1592  * @param peer Peer who sent the message.
1593  *
1594  * @return GNUNET_OK to keep the connection open,
1595  *         GNUNET_SYSERR to close it (signal serious error)
1596  */
1597 int
1598 GMC_handle_kx (void *cls, const struct GNUNET_PeerIdentity *peer,
1599                const struct GNUNET_MessageHeader *message)
1600 {
1601   return handle_mesh_kx (peer,
1602                          (struct GNUNET_MESH_KX *) message);
1603 }
1604
1605
1606 /**
1607  * Core handler for mesh network traffic point-to-point acks.
1608  *
1609  * @param cls closure
1610  * @param message message
1611  * @param peer peer identity this notification is about
1612  *
1613  * @return GNUNET_OK to keep the connection open,
1614  *         GNUNET_SYSERR to close it (signal serious error)
1615  */
1616 int
1617 GMC_handle_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
1618                 const struct GNUNET_MessageHeader *message)
1619 {
1620   struct GNUNET_MESH_ACK *msg;
1621   struct MeshConnection *c;
1622   struct MeshFlowControl *fc;
1623   GNUNET_PEER_Id id;
1624   uint32_t ack;
1625   int fwd;
1626
1627   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1628   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
1629               GNUNET_i2s (peer));
1630   msg = (struct GNUNET_MESH_ACK *) message;
1631
1632   c = connection_get (&msg->cid);
1633
1634   if (NULL == c)
1635   {
1636     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
1637                               GNUNET_NO);
1638     return GNUNET_OK;
1639   }
1640
1641   /* Is this a forward or backward ACK? */
1642   id = GNUNET_PEER_search (peer);
1643   if (GMP_get_short_id (get_next_hop (c)) == id)
1644   {
1645     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
1646     fc = &c->fwd_fc;
1647     fwd = GNUNET_YES;
1648   }
1649   else if (GMP_get_short_id (get_prev_hop (c)) == id)
1650   {
1651     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
1652     fc = &c->bck_fc;
1653     fwd = GNUNET_NO;
1654   }
1655   else
1656   {
1657     GNUNET_break_op (0);
1658     return GNUNET_OK;
1659   }
1660
1661   ack = ntohl (msg->ack);
1662   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u (was %u)\n",
1663               ack, fc->last_ack_recv);
1664   if (GMC_is_pid_bigger (ack, fc->last_ack_recv))
1665     fc->last_ack_recv = ack;
1666
1667   /* Cancel polling if the ACK is big enough. */
1668   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
1669       GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
1670   {
1671     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
1672     GNUNET_SCHEDULER_cancel (fc->poll_task);
1673     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1674     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
1675   }
1676
1677   connection_unlock_queue (c, fwd);
1678
1679   return GNUNET_OK;
1680 }
1681
1682
1683 /**
1684  * Core handler for mesh network traffic point-to-point ack polls.
1685  *
1686  * @param cls closure
1687  * @param message message
1688  * @param peer peer identity this notification is about
1689  *
1690  * @return GNUNET_OK to keep the connection open,
1691  *         GNUNET_SYSERR to close it (signal serious error)
1692  */
1693 int
1694 GMC_handle_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
1695                  const struct GNUNET_MessageHeader *message)
1696 {
1697   struct GNUNET_MESH_Poll *msg;
1698   struct MeshConnection *c;
1699   struct MeshFlowControl *fc;
1700   GNUNET_PEER_Id id;
1701   uint32_t pid;
1702   int fwd;
1703
1704   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1705   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
1706               GNUNET_i2s (peer));
1707
1708   msg = (struct GNUNET_MESH_Poll *) message;
1709
1710   c = connection_get (&msg->cid);
1711
1712   if (NULL == c)
1713   {
1714     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
1715                               GNUNET_NO);
1716     GNUNET_break_op (0);
1717     return GNUNET_OK;
1718   }
1719
1720   /* Is this a forward or backward ACK?
1721    * Note: a poll should never be needed in a loopback case,
1722    * since there is no possiblility of packet loss there, so
1723    * this way of discerining FWD/BCK should not be a problem.
1724    */
1725   id = GNUNET_PEER_search (peer);
1726   if (GMP_get_short_id (get_next_hop (c)) == id)
1727   {
1728     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
1729     fc = &c->fwd_fc;
1730   }
1731   else if (GMP_get_short_id (get_prev_hop (c)) == id)
1732   {
1733     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
1734     fc = &c->bck_fc;
1735   }
1736   else
1737   {
1738     GNUNET_break_op (0);
1739     return GNUNET_OK;
1740   }
1741
1742   pid = ntohl (msg->pid);
1743   LOG (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n", pid, fc->last_pid_recv);
1744   fc->last_pid_recv = pid;
1745   fwd = fc == &c->bck_fc;
1746   GMC_send_ack (c, fwd);
1747
1748   return GNUNET_OK;
1749 }
1750
1751
1752 /**
1753  * Core handler for mesh keepalives.
1754  *
1755  * @param cls closure
1756  * @param message message
1757  * @param peer peer identity this notification is about
1758  * @return GNUNET_OK to keep the connection open,
1759  *         GNUNET_SYSERR to close it (signal serious error)
1760  *
1761  * TODO: Check who we got this from, to validate route.
1762  */
1763 int
1764 GMC_handle_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
1765                       const struct GNUNET_MessageHeader *message)
1766 {
1767   struct GNUNET_MESH_ConnectionKeepAlive *msg;
1768   struct MeshConnection *c;
1769   struct MeshPeer *neighbor;
1770   int fwd;
1771
1772   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
1773   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
1774               GNUNET_i2s (peer));
1775
1776   c = connection_get (&msg->cid);
1777   if (NULL == c)
1778   {
1779     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
1780                               GNUNET_NO);
1781     return GNUNET_OK;
1782   }
1783
1784   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
1785         GNUNET_YES : GNUNET_NO;
1786
1787   /* Check if origin is as expected */
1788   neighbor = get_hop (c, fwd);
1789   if (GNUNET_PEER_search (peer) != GMP_get_short_id (neighbor))
1790   {
1791     GNUNET_break_op (0);
1792     return GNUNET_OK;
1793   }
1794
1795   connection_change_state (c, MESH_CONNECTION_READY);
1796   connection_reset_timeout (c, fwd);
1797
1798   if (GMC_is_terminal (c, fwd))
1799     return GNUNET_OK;
1800
1801   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
1802   GMC_send_prebuilt_message (message, c, fwd);
1803
1804   return GNUNET_OK;
1805 }
1806
1807
1808 /**
1809  * Send an ACK on the appropriate connection/channel, depending on
1810  * the direction and the position of the peer.
1811  *
1812  * @param c Which connection to send the hop-by-hop ACK.
1813  * @param fwd Is this a fwd ACK? (will go dest->root)
1814  */
1815 void
1816 GMC_send_ack (struct MeshConnection *c, int fwd)
1817 {
1818   unsigned int buffer;
1819
1820   LOG (GNUNET_ERROR_TYPE_DEBUG,
1821        "GMC send %s ACK on %s\n",
1822        fwd ? "FWD" : "BCK", GMC_2s (c));
1823
1824   if (NULL == c)
1825   {
1826     GNUNET_break (0);
1827     return;
1828   }
1829
1830   /* Get available buffer space */
1831   if (GMC_is_terminal (c, fwd))
1832   {
1833     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from all channels\n");
1834     buffer = GMT_get_channels_buffer (c->t);
1835   }
1836   else
1837   {
1838     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
1839     buffer = GMC_get_buffer (c, fwd);
1840   }
1841   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
1842
1843   /* Send available buffer space */
1844   if (GMC_is_origin (c, fwd))
1845   {
1846     GNUNET_assert (NULL != c->t);
1847     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channels...\n");
1848     if (0 < buffer)
1849     {
1850       LOG (GNUNET_ERROR_TYPE_DEBUG, "  really sending!\n");
1851       GMT_unchoke_channels (c->t);
1852     }
1853   }
1854   else
1855   {
1856     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
1857     send_ack (c, buffer, fwd);
1858   }
1859 }
1860
1861
1862 /**
1863  * Initialize the connections subsystem
1864  *
1865  * @param c Configuration handle.
1866  */
1867 void
1868 GMC_init (const struct GNUNET_CONFIGURATION_Handle *c)
1869 {
1870   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1871   if (GNUNET_OK !=
1872       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
1873                                              &max_msgs_queue))
1874   {
1875     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
1876                                "MESH", "MAX_MSGS_QUEUE", "MISSING");
1877     GNUNET_SCHEDULER_shutdown ();
1878     return;
1879   }
1880
1881   if (GNUNET_OK !=
1882       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
1883                                              &max_connections))
1884   {
1885     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
1886                                "MESH", "MAX_CONNECTIONS", "MISSING");
1887     GNUNET_SCHEDULER_shutdown ();
1888     return;
1889   }
1890
1891   if (GNUNET_OK !=
1892       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
1893                                            &refresh_connection_time))
1894   {
1895     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
1896                                "MESH", "REFRESH_CONNECTION_TIME", "MISSING");
1897     GNUNET_SCHEDULER_shutdown ();
1898     return;
1899   }
1900   connections = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
1901 }
1902
1903 /**
1904  * Shut down the connections subsystem.
1905  */
1906 void
1907 GMC_shutdown (void)
1908 {
1909   GNUNET_CONTAINER_multihashmap_destroy (connections);
1910 }
1911
1912
1913 struct MeshConnection *
1914 GMC_new (const struct GNUNET_HashCode *cid,
1915          struct MeshTunnel3 *t,
1916          struct MeshPeerPath *p,
1917          unsigned int own_pos)
1918 {
1919   struct MeshConnection *c;
1920
1921   c = GNUNET_new (struct MeshConnection);
1922   c->id = *cid;
1923   GNUNET_CONTAINER_multihashmap_put (connections, &c->id, c,
1924                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1925   fc_init (&c->fwd_fc);
1926   fc_init (&c->bck_fc);
1927   c->fwd_fc.c = c;
1928   c->bck_fc.c = c;
1929
1930   c->t = t;
1931   if (own_pos > p->length - 1)
1932   {
1933     GNUNET_break (0);
1934     GMC_destroy (c);
1935     return NULL;
1936   }
1937   c->own_pos = own_pos;
1938   c->path = p;
1939
1940   if (0 == own_pos)
1941   {
1942     c->fwd_maintenance_task =
1943             GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
1944                                           &connection_fwd_keepalive, c);
1945   }
1946   register_neighbors (c);
1947   return c;
1948 }
1949
1950
1951 void
1952 GMC_destroy (struct MeshConnection *c)
1953 {
1954   if (NULL == c)
1955     return;
1956
1957   if (2 == c->destroy) /* cancel queues -> GMP_queue_cancel -> q_destroy -> */
1958     return;            /* -> message_sent -> GMC_destroy. Don't loop. */
1959   c->destroy = 2;
1960
1961   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s\n", GMC_2s (c));
1962
1963   /* Cancel all traffic */
1964   connection_cancel_queues (c, GNUNET_YES);
1965   connection_cancel_queues (c, GNUNET_NO);
1966
1967   /* Cancel maintainance task (keepalive/timeout) */
1968   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
1969     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
1970   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
1971     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
1972
1973   /* Unregister from neighbors */
1974   unregister_neighbors (c);
1975
1976   /* Delete */
1977   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
1978   if (NULL != c->t)
1979     GMT_remove_connection (c->t, c);
1980
1981   if (GNUNET_NO == GMC_is_origin (c, GNUNET_YES))
1982     path_destroy (c->path);
1983
1984   GNUNET_free (c);
1985 }
1986
1987 /**
1988  * Get the connection ID.
1989  *
1990  * @param c Connection to get the ID from.
1991  *
1992  * @return ID of the connection.
1993  */
1994 const struct GNUNET_HashCode *
1995 GMC_get_id (const struct MeshConnection *c)
1996 {
1997   return &c->id;
1998 }
1999
2000
2001 /**
2002  * Get the connection path.
2003  *
2004  * @param c Connection to get the path from.
2005  *
2006  * @return path used by the connection.
2007  */
2008 const struct MeshPeerPath *
2009 GMC_get_path (const struct MeshConnection *c)
2010 {
2011   return c->path;
2012 }
2013
2014
2015 /**
2016  * Get the connection state.
2017  *
2018  * @param c Connection to get the state from.
2019  *
2020  * @return state of the connection.
2021  */
2022 enum MeshConnectionState
2023 GMC_get_state (const struct MeshConnection *c)
2024 {
2025   return c->state;
2026 }
2027
2028 /**
2029  * Get the connection tunnel.
2030  *
2031  * @param c Connection to get the tunnel from.
2032  *
2033  * @return tunnel of the connection.
2034  */
2035 struct MeshTunnel3 *
2036 GMC_get_tunnel (const struct MeshConnection *c)
2037 {
2038   return c->t;
2039 }
2040
2041
2042 /**
2043  * Get free buffer space in a connection.
2044  *
2045  * @param c Connection.
2046  * @param fwd Is query about FWD traffic?
2047  *
2048  * @return Free buffer space [0 - max_msgs_queue/max_connections]
2049  */
2050 unsigned int
2051 GMC_get_buffer (struct MeshConnection *c, int fwd)
2052 {
2053   struct MeshFlowControl *fc;
2054
2055   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2056
2057   return (fc->queue_max - fc->queue_n);
2058 }
2059
2060 /**
2061  * Get how many messages have we allowed to send to us from a direction.
2062  *
2063  * @param c Connection.
2064  * @param fwd Are we asking about traffic from FWD (BCK messages)?
2065  *
2066  * @return last_ack_sent - last_pid_recv
2067  */
2068 unsigned int
2069 GMC_get_allowed (struct MeshConnection *c, int fwd)
2070 {
2071   struct MeshFlowControl *fc;
2072
2073   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2074   if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
2075   {
2076     return 0;
2077   }
2078   return (fc->last_ack_sent - fc->last_pid_recv);
2079 }
2080
2081 /**
2082  * Get messages queued in a connection.
2083  *
2084  * @param c Connection.
2085  * @param fwd Is query about FWD traffic?
2086  *
2087  * @return Number of messages queued.
2088  */
2089 unsigned int
2090 GMC_get_qn (struct MeshConnection *c, int fwd)
2091 {
2092   struct MeshFlowControl *fc;
2093
2094   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2095
2096   return fc->queue_n;
2097 }
2098
2099
2100 /**
2101  * Allow the connection to advertise a buffer of the given size.
2102  *
2103  * The connection will send an @c fwd ACK message (so: in direction !fwd)
2104  * allowing up to last_pid_recv + buffer.
2105  *
2106  * @param c Connection.
2107  * @param buffer How many more messages the connection can accept.
2108  * @param fwd Is this about FWD traffic? (The ack will go dest->root).
2109  */
2110 void
2111 GMC_allow (struct MeshConnection *c, unsigned int buffer, int fwd)
2112 {
2113   send_ack (c, buffer, fwd);
2114 }
2115
2116
2117 /**
2118  * Notify other peers on a connection of a broken link. Mark connections
2119  * to destroy after all traffic has been sent.
2120  *
2121  * @param c Connection on which there has been a disconnection.
2122  * @param peer Peer that disconnected.
2123  */
2124 void
2125 GMC_notify_broken (struct MeshConnection *c,
2126                    struct MeshPeer *peer)
2127 {
2128   int fwd;
2129
2130   fwd = peer == get_prev_hop (c);
2131
2132   if (GNUNET_YES == GMC_is_terminal (c, fwd))
2133   {
2134     /* Local shutdown, no one to notify about this. */
2135     GMC_destroy (c);
2136     return;
2137   }
2138   if (GNUNET_NO == c->destroy)
2139     send_broken (c, &my_full_id, GMP_get_id (peer), fwd);
2140
2141   /* Connection will have at least one pending message
2142    * (the one we just scheduled), so no point in checking whether to
2143    * destroy immediately. */
2144   c->destroy = GNUNET_YES;
2145
2146   /**
2147    * Cancel all queues, if no message is left, connection will be destroyed.
2148    */
2149   connection_cancel_queues (c, !fwd);
2150
2151   return;
2152 }
2153
2154
2155 /**
2156  * Is this peer the first one on the connection?
2157  *
2158  * @param c Connection.
2159  * @param fwd Is this about fwd traffic?
2160  *
2161  * @return #GNUNET_YES if origin, #GNUNET_NO if relay/terminal.
2162  */
2163 int
2164 GMC_is_origin (struct MeshConnection *c, int fwd)
2165 {
2166   if (!fwd && c->path->length - 1 == c->own_pos )
2167     return GNUNET_YES;
2168   if (fwd && 0 == c->own_pos)
2169     return GNUNET_YES;
2170   return GNUNET_NO;
2171 }
2172
2173
2174 /**
2175  * Is this peer the last one on the connection?
2176  *
2177  * @param c Connection.
2178  * @param fwd Is this about fwd traffic?
2179  *            Note that the ROOT is the terminal for BCK traffic!
2180  *
2181  * @return #GNUNET_YES if terminal, #GNUNET_NO if relay/origin.
2182  */
2183 int
2184 GMC_is_terminal (struct MeshConnection *c, int fwd)
2185 {
2186   return GMC_is_origin (c, !fwd);
2187 }
2188
2189
2190 /**
2191  * See if we are allowed to send by the next hop in the given direction.
2192  *
2193  * @param c Connection.
2194  * @param fwd Is this about fwd traffic?
2195  *
2196  * @return #GNUNET_YES in case it's OK to send.
2197  */
2198 int
2199 GMC_is_sendable (struct MeshConnection *c, int fwd)
2200 {
2201   struct MeshFlowControl *fc;
2202
2203   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2204   if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2205     return GNUNET_YES;
2206   return GNUNET_NO;
2207 }
2208
2209 /**
2210  * Sends an already built message on a connection, properly registering
2211  * all used resources.
2212  *
2213  * @param message Message to send. Function makes a copy of it.
2214  *                If message is not hop-by-hop, decrements TTL of copy.
2215  * @param c Connection on which this message is transmitted.
2216  * @param fwd Is this a fwd message?
2217  */
2218 void
2219 GMC_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2220                            struct MeshConnection *c,
2221                            int fwd)
2222 {
2223   struct MeshFlowControl *fc;
2224   void *data;
2225   size_t size;
2226   uint16_t type;
2227   int droppable;
2228
2229   size = ntohs (message->size);
2230   data = GNUNET_malloc (size);
2231   memcpy (data, message, size);
2232   type = ntohs (message->type);
2233   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send %s (%u bytes) on connection %s\n",
2234               GNUNET_MESH_DEBUG_M2S (type), size, GMC_2s (c));
2235
2236   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2237   droppable = GNUNET_YES;
2238   switch (type)
2239   {
2240     struct GNUNET_MESH_Encrypted *emsg;
2241     struct GNUNET_MESH_KX        *kmsg;
2242     struct GNUNET_MESH_ACK       *amsg;
2243     struct GNUNET_MESH_Poll      *pmsg;
2244     struct GNUNET_MESH_ConnectionDestroy *dmsg;
2245     struct GNUNET_MESH_ConnectionBroken  *bmsg;
2246     uint32_t ttl;
2247
2248     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
2249       emsg = (struct GNUNET_MESH_Encrypted *) data;
2250       ttl = ntohl (emsg->ttl);
2251       if (0 == ttl)
2252       {
2253         GNUNET_break_op (0);
2254         return;
2255       }
2256       emsg->cid = c->id;
2257       emsg->ttl = htonl (ttl - 1);
2258       emsg->pid = htonl (fwd ? c->fwd_fc.next_pid++ : c->bck_fc.next_pid++);
2259       LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
2260       fc->queue_n++;
2261       LOG (GNUNET_ERROR_TYPE_DEBUG, "pid %u\n", ntohl (emsg->pid));
2262       LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid %u\n", fc->last_pid_sent);
2263       LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack %u\n", fc->last_ack_recv);
2264       if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
2265       {
2266         GMC_start_poll (c, fwd);
2267       }
2268       break;
2269
2270     case GNUNET_MESSAGE_TYPE_MESH_KX:
2271       kmsg = (struct GNUNET_MESH_KX *) data;
2272       kmsg->cid = c->id;
2273       break;
2274
2275     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2276       amsg = (struct GNUNET_MESH_ACK *) data;
2277       amsg->cid = c->id;
2278       LOG (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
2279       droppable = GNUNET_NO;
2280       break;
2281
2282     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2283       pmsg = (struct GNUNET_MESH_Poll *) data;
2284       pmsg->cid = c->id;
2285       pmsg->pid = htonl (fwd ? c->fwd_fc.last_pid_sent : c->bck_fc.last_pid_sent);
2286       LOG (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
2287       droppable = GNUNET_NO;
2288       break;
2289
2290     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
2291       dmsg = (struct GNUNET_MESH_ConnectionDestroy *) data;
2292       dmsg->cid = c->id;
2293       dmsg->reserved = 0;
2294       break;
2295
2296     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
2297       bmsg = (struct GNUNET_MESH_ConnectionBroken *) data;
2298       bmsg->cid = c->id;
2299       bmsg->reserved = 0;
2300       break;
2301
2302     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
2303     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
2304       break;
2305
2306     default:
2307       GNUNET_break (0);
2308   }
2309
2310   if (fc->queue_n > fc->queue_max && droppable)
2311   {
2312     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
2313                               1, GNUNET_NO);
2314     GNUNET_break (0);
2315     LOG (GNUNET_ERROR_TYPE_DEBUG,
2316                 "queue full: %u/%u\n",
2317                 fc->queue_n, fc->queue_max);
2318     if (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED == type)
2319       fc->queue_n--;
2320     return; /* Drop this message */
2321   }
2322
2323   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u\n", c, c->pending_messages);
2324   c->pending_messages++;
2325
2326   GMP_queue_add (get_hop (c, fwd), data, type, size, c, fwd,
2327                  &message_sent, NULL);
2328 }
2329
2330
2331 /**
2332  * Sends a CREATE CONNECTION message for a path to a peer.
2333  * Changes the connection and tunnel states if necessary.
2334  *
2335  * @param connection Connection to create.
2336  */
2337 void
2338 GMC_send_create (struct MeshConnection *connection)
2339 {
2340   enum MeshTunnel3State state;
2341   size_t size;
2342
2343   size = sizeof (struct GNUNET_MESH_ConnectionCreate);
2344   size += connection->path->length * sizeof (struct GNUNET_PeerIdentity);
2345   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
2346   GMP_queue_add (get_next_hop (connection), NULL,
2347                  GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
2348                  size, connection, GNUNET_YES, &message_sent, NULL);
2349   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u (create)\n",
2350        connection, connection->pending_messages);
2351   connection->pending_messages++;
2352   state = GMT_get_state (connection->t);
2353   if (MESH_TUNNEL3_SEARCHING == state || MESH_TUNNEL3_NEW == state)
2354     GMT_change_state (connection->t, MESH_TUNNEL3_WAITING);
2355   if (MESH_CONNECTION_NEW == connection->state)
2356     connection_change_state (connection, MESH_CONNECTION_SENT);
2357 }
2358
2359
2360 /**
2361  * Send a message to all peers in this connection that the connection
2362  * is no longer valid.
2363  *
2364  * If some peer should not receive the message, it should be zero'ed out
2365  * before calling this function.
2366  *
2367  * @param c The connection whose peers to notify.
2368  */
2369 void
2370 GMC_send_destroy (struct MeshConnection *c)
2371 {
2372   struct GNUNET_MESH_ConnectionDestroy msg;
2373
2374   if (GNUNET_YES == c->destroy)
2375     return;
2376
2377   msg.header.size = htons (sizeof (msg));
2378   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY);;
2379   msg.cid = c->id;
2380   LOG (GNUNET_ERROR_TYPE_DEBUG,
2381               "  sending connection destroy for connection %s\n",
2382               GMC_2s (c));
2383
2384   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_YES))
2385     GMC_send_prebuilt_message (&msg.header, c, GNUNET_YES);
2386   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_NO))
2387     GMC_send_prebuilt_message (&msg.header, c, GNUNET_NO);
2388   c->destroy = GNUNET_YES;
2389 }
2390
2391
2392 /**
2393  * @brief Start a polling timer for the connection.
2394  *
2395  * When a neighbor does not accept more traffic on the connection it could be
2396  * caused by a simple congestion or by a lost ACK. Polling enables to check
2397  * for the lastest ACK status for a connection.
2398  *
2399  * @param c Connection.
2400  * @param fwd Should we poll in the FWD direction?
2401  */
2402 void
2403 GMC_start_poll (struct MeshConnection *c, int fwd)
2404 {
2405   struct MeshFlowControl *fc;
2406
2407   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2408   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2409   {
2410     return;
2411   }
2412   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2413                                                 &connection_poll,
2414                                                 fc);
2415 }
2416
2417
2418 /**
2419  * @brief Stop polling a connection for ACKs.
2420  *
2421  * Once we have enough ACKs for future traffic, polls are no longer necessary.
2422  *
2423  * @param c Connection.
2424  * @param fwd Should we stop the poll in the FWD direction?
2425  */
2426 void
2427 GMC_stop_poll (struct MeshConnection *c, int fwd)
2428 {
2429   struct MeshFlowControl *fc;
2430
2431   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2432   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2433   {
2434     GNUNET_SCHEDULER_cancel (fc->poll_task);
2435     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2436   }
2437 }
2438
2439 /**
2440  * Get a (static) string for a connection.
2441  *
2442  * @param c Connection.
2443  */
2444 const char *
2445 GMC_2s (struct MeshConnection *c)
2446 {
2447   if (NULL != c->t)
2448   {
2449     static char buf[128];
2450
2451     sprintf (buf, "%s (->%s)", GNUNET_h2s (&c->id), GMT_2s (c->t));
2452     return buf;
2453   }
2454   return GNUNET_h2s (&c->id);
2455 }