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