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