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