- refactor logging to allow for shorter log files
[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.h"
34 #include "mesh.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    * Queued poll message, to cancel if not necessary anymore (got ACK).
110    */
111   struct MeshConnectionQueue *poll_msg;
112
113   /**
114    * Queued poll message, to cancel if not necessary anymore (got ACK).
115    */
116   struct MeshConnectionQueue *ack_msg;
117 };
118
119 /**
120  * Keep a record of the last messages sent on this connection.
121  */
122 struct MeshConnectionPerformance
123 {
124   /**
125    * Circular buffer for storing measurements.
126    */
127   double usecsperbyte[AVG_MSGS];
128
129   /**
130    * Running average of @c usecsperbyte.
131    */
132   double avg;
133
134   /**
135    * How many values of @c usecsperbyte are valid.
136    */
137   uint16_t size;
138
139   /**
140    * Index of the next "free" position in @c usecsperbyte.
141    */
142   uint16_t idx;
143 };
144
145
146 /**
147  * Struct containing all information regarding a connection to a peer.
148  */
149 struct MeshConnection
150 {
151   /**
152    * Tunnel this connection is part of.
153    */
154   struct MeshTunnel3 *t;
155
156   /**
157    * Flow control information for traffic fwd.
158    */
159   struct MeshFlowControl fwd_fc;
160
161   /**
162    * Flow control information for traffic bck.
163    */
164   struct MeshFlowControl bck_fc;
165
166   /**
167    * Measure connection performance on the endpoint.
168    */
169   struct MeshConnectionPerformance *perf;
170
171   /**
172    * ID of the connection.
173    */
174   struct GNUNET_HashCode id;
175
176   /**
177    * State of the connection.
178    */
179   enum MeshConnectionState state;
180
181   /**
182    * Path being used for the tunnel. At the origin of the connection
183    * it's a pointer to the destination's path pool, otherwise just a copy.
184    */
185   struct MeshPeerPath *path;
186
187   /**
188    * Position of the local peer in the path.
189    */
190   unsigned int own_pos;
191
192   /**
193    * Task to keep the used paths alive at the owner,
194    * time tunnel out on all the other peers.
195    */
196   GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
197
198   /**
199    * Task to keep the used paths alive at the destination,
200    * time tunnel out on all the other peers.
201    */
202   GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
203
204   /**
205    * Queue handle for maintainance traffic. One handle for FWD and BCK since
206    * one peer never needs to maintain both directions (no loopback connections).
207    */
208   struct MeshPeerQueue *maintenance_q;
209
210   /**
211    * Counter to do exponential backoff when creating a connection (max 64).
212    */
213   unsigned short create_retry;
214
215   /**
216    * Pending message count.
217    */
218   int pending_messages;
219
220   /**
221    * Destroy flag: if true, destroy on last message.
222    */
223   int destroy;
224 };
225
226 /**
227  * Handle for messages queued but not yet sent.
228  */
229 struct MeshConnectionQueue
230 {
231   /**
232    * Peer queue handle, to cancel if necessary.
233    */
234   struct MeshPeerQueue *q;
235
236   /**
237    * Was this a forced message? (Do not account for it)
238    */
239   int forced;
240
241   /**
242    * Continuation to call once sent.
243    */
244   GMC_sent cont;
245
246   /**
247    * Closure for @c cont.
248    */
249   void *cont_cls;
250 };
251
252 /******************************************************************************/
253 /*******************************   GLOBALS  ***********************************/
254 /******************************************************************************/
255
256 /**
257  * Global handle to the statistics service.
258  */
259 extern struct GNUNET_STATISTICS_Handle *stats;
260
261 /**
262  * Local peer own ID (memory efficient handle).
263  */
264 extern GNUNET_PEER_Id myid;
265
266 /**
267  * Local peer own ID (full value).
268  */
269 extern struct GNUNET_PeerIdentity my_full_id;
270
271 /**
272  * Connections known, indexed by cid (MeshConnection).
273  */
274 static struct GNUNET_CONTAINER_MultiHashMap *connections;
275
276 /**
277  * How many connections are we willing to maintain.
278  * Local connections are always allowed, even if there are more connections than max.
279  */
280 static unsigned long long max_connections;
281
282 /**
283  * How many messages *in total* are we willing to queue, divide by number of
284  * connections to get connection queue size.
285  */
286 static unsigned long long max_msgs_queue;
287
288 /**
289  * How often to send path keepalives. Paths timeout after 4 missed.
290  */
291 static struct GNUNET_TIME_Relative refresh_connection_time;
292
293 /**
294  * How often to send path create / ACKs.
295  */
296 static struct GNUNET_TIME_Relative create_connection_time;
297
298
299 /******************************************************************************/
300 /********************************   STATIC  ***********************************/
301 /******************************************************************************/
302
303 #if 0 // avoid compiler warning for unused static function
304 static void
305 fc_debug (struct MeshFlowControl *fc)
306 {
307   LOG (GNUNET_ERROR_TYPE_DEBUG, "    IN: %u/%u\n",
308               fc->last_pid_recv, fc->last_ack_sent);
309   LOG (GNUNET_ERROR_TYPE_DEBUG, "    OUT: %u/%u\n",
310               fc->last_pid_sent, fc->last_ack_recv);
311   LOG (GNUNET_ERROR_TYPE_DEBUG, "    QUEUE: %u/%u\n",
312               fc->queue_n, fc->queue_max);
313 }
314
315 static void
316 connection_debug (struct MeshConnection *c)
317 {
318   if (NULL == c)
319   {
320     LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CONNECTION ***\n");
321     return;
322   }
323   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
324               peer2s (c->t->peer), GMC_2s (c));
325   LOG (GNUNET_ERROR_TYPE_DEBUG, "  state: %u, pending msgs: %u\n",
326               c->state, c->pending_messages);
327   LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
328   fc_debug (&c->fwd_fc);
329   LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
330   fc_debug (&c->bck_fc);
331 }
332 #endif
333
334
335 /**
336  * Schedule next keepalive task, taking in consideration
337  * the connection state and number of retries.
338  *
339  * @param c Connection for which to schedule the next keepalive.
340  * @param fwd Direction for the next keepalive.
341  */
342 static void
343 schedule_next_keepalive (struct MeshConnection *c, int fwd);
344
345
346 /**
347  * Get string description for tunnel state.
348  *
349  * @param s Tunnel state.
350  *
351  * @return String representation.
352  */
353 static const char *
354 GMC_state2s (enum MeshConnectionState s)
355 {
356   switch (s)
357   {
358     case MESH_CONNECTION_NEW:
359       return "MESH_CONNECTION_NEW";
360     case MESH_CONNECTION_SENT:
361       return "MESH_CONNECTION_SENT";
362     case MESH_CONNECTION_ACK:
363       return "MESH_CONNECTION_ACK";
364     case MESH_CONNECTION_READY:
365       return "MESH_CONNECTION_READY";
366     case MESH_CONNECTION_DESTROYED:
367       return "MESH_CONNECTION_DESTROYED";
368     default:
369       return "MESH_CONNECTION_STATE_ERROR";
370   }
371 }
372
373
374 /**
375  * Initialize a Flow Control structure to the initial state.
376  *
377  * @param fc Flow Control structure to initialize.
378  */
379 static void
380 fc_init (struct MeshFlowControl *fc)
381 {
382   fc->next_pid = 0;
383   fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
384   fc->last_pid_recv = (uint32_t) -1;
385   fc->last_ack_sent = (uint32_t) 0;
386   fc->last_ack_recv = (uint32_t) 0;
387   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
388   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
389   fc->queue_n = 0;
390   fc->queue_max = (max_msgs_queue / max_connections) + 1;
391 }
392
393
394 /**
395  * Find a connection.
396  *
397  * @param cid Connection ID.
398  */
399 static struct MeshConnection *
400 connection_get (const struct GNUNET_HashCode *cid)
401 {
402   return GNUNET_CONTAINER_multihashmap_get (connections, cid);
403 }
404
405
406 static void
407 connection_change_state (struct MeshConnection* c,
408                          enum MeshConnectionState state)
409 {
410   LOG (GNUNET_ERROR_TYPE_DEBUG,
411               "Connection %s state was %s\n",
412               GMC_2s (c), GMC_state2s (c->state));
413   if (MESH_CONNECTION_DESTROYED == c->state)
414   {
415     LOG (GNUNET_ERROR_TYPE_DEBUG, "state not changing anymore\n");
416     return;
417   }
418   LOG (GNUNET_ERROR_TYPE_DEBUG,
419               "Connection %s state is now %s\n",
420               GMC_2s (c), GMC_state2s (state));
421   c->state = state;
422   if (MESH_CONNECTION_READY == state)
423     c->create_retry = 1;
424 }
425
426
427 /**
428  * Callback called when a queued ACK message is sent.
429  *
430  * @param cls Closure (FC).
431  * @param c Connection this message was on.
432  * @param q Queue handler this call invalidates.
433  * @param type Type of message sent.
434  * @param fwd Was this a FWD going message?
435  * @param size Size of the message.
436  */
437 static void
438 ack_sent (void *cls,
439           struct MeshConnection *c,
440           struct MeshConnectionQueue *q,
441           uint16_t type, int fwd, size_t size)
442 {
443   struct MeshFlowControl *fc = cls;
444
445   fc->ack_msg = NULL;
446 }
447
448
449 /**
450  * Send an ACK on the connection, informing the predecessor about
451  * the available buffer space. Should not be called in case the peer
452  * is origin (no predecessor) in the @c fwd direction.
453  *
454  * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
455  * the ACK itself goes "back" (dest->root).
456  *
457  * @param c Connection on which to send the ACK.
458  * @param buffer How much space free to advertise?
459  * @param fwd Is this FWD ACK? (Going dest -> root)
460  * @param force Don't optimize out.
461  */
462 static void
463 send_ack (struct MeshConnection *c, unsigned int buffer, int fwd, int force)
464 {
465   struct MeshFlowControl *next_fc;
466   struct MeshFlowControl *prev_fc;
467   struct GNUNET_MESH_ACK msg;
468   uint32_t ack;
469   int delta;
470
471   /* If origin, there is no connection to send ACKs. Wrong function! */
472   if (GMC_is_origin (c, fwd))
473   {
474     LOG (GNUNET_ERROR_TYPE_DEBUG, "connection %s is origin in %s\n",
475          GMC_2s (c), GM_f2s (fwd));
476     GNUNET_break (0);
477     return;
478   }
479
480   next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
481   prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
482
483   LOG (GNUNET_ERROR_TYPE_DEBUG, "connection send %s ack on %s\n",
484        GM_f2s (fwd), GMC_2s (c));
485
486   /* Check if we need to transmit the ACK. */
487   delta = prev_fc->last_ack_sent - prev_fc->last_pid_recv;
488   if (3 < delta && buffer < delta && GNUNET_NO == force)
489   {
490     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
491     LOG (GNUNET_ERROR_TYPE_DEBUG,
492          "  last pid recv: %u, last ack sent: %u\n",
493          prev_fc->last_pid_recv, prev_fc->last_ack_sent);
494     return;
495   }
496
497   /* Ok, ACK might be necessary, what PID to ACK? */
498   ack = prev_fc->last_pid_recv + buffer;
499   LOG (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
500   LOG (GNUNET_ERROR_TYPE_DEBUG,
501        " last pid %u, last ack %u, qmax %u, q %u\n",
502        prev_fc->last_pid_recv, prev_fc->last_ack_sent,
503        next_fc->queue_max, next_fc->queue_n);
504   if (ack == prev_fc->last_ack_sent && GNUNET_NO == force)
505   {
506     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
507     return;
508   }
509
510   /* Check if message is already in queue */
511   if (NULL != prev_fc->ack_msg)
512   {
513     if (GM_is_pid_bigger (ack, prev_fc->last_ack_sent))
514     {
515       LOG (GNUNET_ERROR_TYPE_DEBUG, " canceling old ACK\n");
516       GMC_cancel (prev_fc->ack_msg);
517       /* GMC_cancel triggers ack_sent(), which clears fc->ack_msg */
518     }
519     else
520     {
521       LOG (GNUNET_ERROR_TYPE_DEBUG, " same ACK already in queue\n");
522       return;
523     }
524   }
525
526   prev_fc->last_ack_sent = ack;
527
528   /* Build ACK message and send on connection */
529   msg.header.size = htons (sizeof (msg));
530   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
531   msg.ack = htonl (ack);
532   msg.cid = c->id;
533
534   prev_fc->ack_msg = GMC_send_prebuilt_message (&msg.header, c,
535                                                 !fwd, GNUNET_YES,
536                                                 &ack_sent, prev_fc);
537 }
538
539
540 /**
541  * Callback called when a queued message is sent.
542  *
543  * Calculates the average time and connection packet tracking.
544  *
545  * @param cls Closure (ConnectionQueue Handle).
546  * @param c Connection this message was on.
547  * @param type Type of message sent.
548  * @param fwd Was this a FWD going message?
549  * @param size Size of the message.
550  * @param wait Time spent waiting for core (only the time for THIS message)
551  */
552 static void
553 message_sent (void *cls,
554               struct MeshConnection *c, uint16_t type,
555               int fwd, size_t size,
556               struct GNUNET_TIME_Relative wait)
557 {
558   struct MeshConnectionPerformance *p;
559   struct MeshFlowControl *fc;
560   struct MeshConnectionQueue *q = cls;
561   double usecsperbyte;
562   int forced;
563
564   fc = fwd ? &c->fwd_fc : &c->bck_fc;
565   LOG (GNUNET_ERROR_TYPE_DEBUG,
566        "!  sent %s %s\n",
567        GM_f2s (fwd),
568        GM_m2s (type));
569   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  C_P- %p %u\n", c, c->pending_messages);
570   if (NULL != q)
571   {
572     forced = q->forced;
573     if (NULL != q->cont)
574     {
575       LOG (GNUNET_ERROR_TYPE_DEBUG, "!  calling cont\n");
576       q->cont (q->cont_cls, c, q, type, fwd, size);
577     }
578     GNUNET_free (q);
579   }
580   else if (type == GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED)
581   {
582     /* If NULL == q and ENCRYPTED == type, message must have been ch_mngmnt */
583     forced = GNUNET_YES;
584   }
585   else
586   {
587     forced = GNUNET_NO;
588   }
589   c->pending_messages--;
590   if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
591   {
592     LOG (GNUNET_ERROR_TYPE_DEBUG, "!  destroying connection!\n");
593     GMC_destroy (c);
594     return;
595   }
596   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
597   switch (type)
598   {
599     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
600     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
601       c->maintenance_q = NULL;
602       /* Don't trigger a keepalive for sent ACKs, only SYN and SYNACKs */
603       if (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE == type || !fwd)
604         schedule_next_keepalive (c, fwd);
605       break;
606
607     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
608       fc->last_pid_sent++;
609       LOG (GNUNET_ERROR_TYPE_DEBUG, "!  Q_N- %p %u\n", fc, fc->queue_n);
610       if (GNUNET_NO == forced)
611       {
612         fc->queue_n--;
613         LOG (GNUNET_ERROR_TYPE_DEBUG,
614             "!   accounting pid %u\n",
615             fc->last_pid_sent);
616       }
617       else
618       {
619         LOG (GNUNET_ERROR_TYPE_DEBUG,
620              "!   forced, Q_N not accounting pid %u\n",
621              fc->last_pid_sent);
622       }
623       GMC_send_ack (c, fwd, GNUNET_NO);
624       break;
625
626     case GNUNET_MESSAGE_TYPE_MESH_POLL:
627       fc->poll_msg = NULL;
628       break;
629
630     case GNUNET_MESSAGE_TYPE_MESH_ACK:
631       fc->ack_msg = NULL;
632       break;
633
634     default:
635       break;
636   }
637   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  message sent!\n");
638
639   if (NULL == c->perf)
640     return; /* Only endpoints are interested in timing. */
641
642   p = c->perf;
643   usecsperbyte = ((double) wait.rel_value_us) / size;
644   if (p->size == AVG_MSGS)
645   {
646     /* Array is full. Substract oldest value, add new one and store. */
647     p->avg -= (p->usecsperbyte[p->idx] / AVG_MSGS);
648     p->usecsperbyte[p->idx] = usecsperbyte;
649     p->avg += (p->usecsperbyte[p->idx] / AVG_MSGS);
650   }
651   else
652   {
653     /* Array not yet full. Add current value to avg and store. */
654     p->usecsperbyte[p->idx] = usecsperbyte;
655     p->avg *= p->size;
656     p->avg += p->usecsperbyte[p->idx];
657     p->size++;
658     p->avg /= p->size;
659   }
660   p->idx = (p->idx + 1) % AVG_MSGS;
661 }
662
663
664 /**
665  * Get the previous hop in a connection
666  *
667  * @param c Connection.
668  *
669  * @return Previous peer in the connection.
670  */
671 static struct MeshPeer *
672 get_prev_hop (const struct MeshConnection *c)
673 {
674   GNUNET_PEER_Id id;
675
676   LOG (GNUNET_ERROR_TYPE_DEBUG, "  get prev hop %s [%u/%u]\n",
677        GMC_2s (c), c->own_pos, c->path->length);
678   if (0 == c->own_pos || c->path->length < 2)
679   {
680     LOG (GNUNET_ERROR_TYPE_DEBUG, "  own pos is zero\n");
681     id = c->path->peers[0];
682   }
683   else
684   {
685     LOG (GNUNET_ERROR_TYPE_DEBUG, "  own pos is NOT zero\n");
686     id = c->path->peers[c->own_pos - 1];
687   }
688
689   LOG (GNUNET_ERROR_TYPE_DEBUG, "  id: %u\n", id);
690   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ID: %s\n", GNUNET_i2s (GNUNET_PEER_resolve2 (id)));
691   return GMP_get_short (id);
692 }
693
694
695 /**
696  * Get the next hop in a connection
697  *
698  * @param c Connection.
699  *
700  * @return Next peer in the connection.
701  */
702 static struct MeshPeer *
703 get_next_hop (const struct MeshConnection *c)
704 {
705   GNUNET_PEER_Id id;
706
707   LOG (GNUNET_ERROR_TYPE_DEBUG, "  get next hop %s [%u/%u]\n",
708        GMC_2s (c), c->own_pos, c->path->length);
709   if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
710   {
711     LOG (GNUNET_ERROR_TYPE_DEBUG, "  own pos is end\n");
712     id = c->path->peers[c->path->length - 1];
713   }
714   else
715   {
716     LOG (GNUNET_ERROR_TYPE_DEBUG, "  own pos is NOT end\n");
717     id = c->path->peers[c->own_pos + 1];
718   }
719
720   LOG (GNUNET_ERROR_TYPE_DEBUG, "  id: %u\n", id);
721   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ID: %s\n", GNUNET_i2s (GNUNET_PEER_resolve2 (id)));
722
723   return GMP_get_short (id);
724 }
725
726
727 /**
728  * Get the hop in a connection.
729  *
730  * @param c Connection.
731  * @param fwd Next hop?
732  *
733  * @return Next peer in the connection.
734  */
735 static struct MeshPeer *
736 get_hop (struct MeshConnection *c, int fwd)
737 {
738   if (fwd)
739     return get_next_hop (c);
740   return get_prev_hop (c);
741 }
742
743
744 /**
745  * Is traffic coming from this sender 'FWD' traffic?
746  *
747  * @param c Connection to check.
748  * @param sender Peer identity of neighbor.
749  *
750  * @return #GNUNET_YES in case the sender is the 'prev' hop and therefore
751  *         the traffic is 'FWD'.
752  *         #GNUNET_NO for BCK.
753  *         #GNUNET_SYSERR for errors.
754  */
755 static int
756 is_fwd (const struct MeshConnection *c,
757         const struct GNUNET_PeerIdentity *sender)
758 {
759   GNUNET_PEER_Id id;
760
761   id = GNUNET_PEER_search (sender);
762   if (GMP_get_short_id (get_prev_hop (c)) == id)
763     return GNUNET_YES;
764
765   if (GMP_get_short_id (get_next_hop (c)) == id)
766     return GNUNET_NO;
767
768   GNUNET_break (0);
769   return GNUNET_SYSERR;
770 }
771
772
773 /**
774  * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
775  * or a first CONNECTION_ACK directed to us.
776  *
777  * @param connection Connection to confirm.
778  * @param fwd Should we send it FWD? (root->dest)
779  *            (First (~SYNACK) goes BCK, second (~ACK) goes FWD)
780  */
781 static void
782 send_connection_ack (struct MeshConnection *connection, int fwd)
783 {
784   struct MeshTunnel3 *t;
785
786   t = connection->t;
787   LOG (GNUNET_ERROR_TYPE_INFO, "Send %s ACK on connection %s\n",
788        GM_f2s (!fwd), GMC_2s (connection));
789   GMP_queue_add (get_hop (connection, fwd), NULL,
790                  GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
791                  sizeof (struct GNUNET_MESH_ConnectionACK),
792                  connection, fwd, &message_sent, NULL);
793   connection->pending_messages++;
794   if (MESH_TUNNEL3_NEW == GMT_get_cstate (t))
795     GMT_change_cstate (t, MESH_TUNNEL3_WAITING);
796   if (MESH_CONNECTION_READY != connection->state)
797     connection_change_state (connection, MESH_CONNECTION_SENT);
798 }
799
800
801 /**
802  * Send a notification that a connection is broken.
803  *
804  * @param c Connection that is broken.
805  * @param id1 Peer that has disconnected.
806  * @param id2 Peer that has disconnected.
807  * @param fwd Direction towards which to send it.
808  */
809 static void
810 send_broken (struct MeshConnection *c,
811              const struct GNUNET_PeerIdentity *id1,
812              const struct GNUNET_PeerIdentity *id2,
813              int fwd)
814 {
815   struct GNUNET_MESH_ConnectionBroken msg;
816
817   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
818   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
819   msg.cid = c->id;
820   msg.peer1 = *id1;
821   msg.peer2 = *id2;
822   GMC_send_prebuilt_message (&msg.header, c, fwd, GNUNET_YES, NULL, NULL);
823 }
824
825
826 /**
827  * Send a notification that a connection is broken, when a connection
828  * isn't even created.
829  *
830  * @param connection_id Connection ID.
831  * @param id1 Peer that has disconnected.
832  * @param id2 Peer that has disconnected.
833  * @param peer Peer to notify (neighbor who sent the connection).
834  */
835 static void
836 send_broken2 (struct GNUNET_HashCode *connection_id,
837              const struct GNUNET_PeerIdentity *id1,
838              const struct GNUNET_PeerIdentity *id2,
839              GNUNET_PEER_Id peer_id)
840 {
841   struct GNUNET_MESH_ConnectionBroken *msg;
842   struct MeshPeer *neighbor;
843
844   LOG (GNUNET_ERROR_TYPE_INFO, "Send BROKEN on connection %s\n", GMC_2s (c));
845
846   msg = GNUNET_new (struct GNUNET_MESH_ConnectionBroken);
847   msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
848   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
849   msg->cid = *connection_id;
850   msg->peer1 = *id1;
851   msg->peer2 = *id2;
852   neighbor = GMP_get_short (peer_id);
853   GMP_queue_add (neighbor, msg,
854                  GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED,
855                  sizeof (struct GNUNET_MESH_ConnectionBroken),
856                  NULL, GNUNET_SYSERR, /* connection, fwd */
857                  NULL, NULL); /* continuation */
858 }
859
860
861 /**
862  * Send keepalive packets for a connection.
863  *
864  * @param c Connection to keep alive..
865  * @param fwd Is this a FWD keepalive? (owner -> dest).
866  */
867 static void
868 connection_keepalive (struct MeshConnection *c, int fwd)
869 {
870   struct GNUNET_MESH_ConnectionKeepAlive *msg;
871   size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
872   char cbuf[size];
873
874   LOG (GNUNET_ERROR_TYPE_DEBUG,
875        "sending %s keepalive for connection %s]\n",
876        GM_f2s (fwd), GMC_2s (c));
877
878   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
879   msg->header.size = htons (size);
880   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KEEPALIVE);
881   msg->cid = c->id;
882   msg->reserved = htonl (0);
883
884   GMC_send_prebuilt_message (&msg->header, c, fwd, GNUNET_YES, NULL, NULL);
885 }
886
887
888 /**
889  * Send CONNECTION_{CREATE/ACK} packets for a connection.
890  *
891  * @param c Connection for which to send the message.
892  * @param fwd If #GNUNET_YES, send CREATE, otherwise send ACK.
893  */
894 static void
895 connection_recreate (struct MeshConnection *c, int fwd)
896 {
897   LOG (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
898   if (fwd)
899     GMC_send_create (c);
900   else
901     send_connection_ack (c, GNUNET_NO);
902 }
903
904
905 /**
906  * Generic connection timer management.
907  * Depending on the role of the peer in the connection will send the
908  * appropriate message (build or keepalive)
909  *
910  * @param c Conncetion to maintain.
911  * @param fwd Is FWD?
912  */
913 static void
914 connection_maintain (struct MeshConnection *c, int fwd)
915 {
916   if (GNUNET_NO != c->destroy)
917     return;
918
919   if (MESH_TUNNEL3_SEARCHING == GMT_get_cstate (c->t))
920   {
921     /* TODO DHT GET with RO_BART */
922     return;
923   }
924   switch (c->state)
925   {
926     case MESH_CONNECTION_NEW:
927       GNUNET_break (0);
928       /* fall-through */
929     case MESH_CONNECTION_SENT:
930       connection_recreate (c, fwd);
931       break;
932     case MESH_CONNECTION_READY:
933       connection_keepalive (c, fwd);
934       break;
935     default:
936       break;
937   }
938 }
939
940
941 /**
942  * Keep the connection alive in the FWD direction.
943  *
944  * @param cls Closure (connection to keepalive).
945  * @param tc TaskContext.
946  */
947 static void
948 connection_fwd_keepalive (void *cls,
949                           const struct GNUNET_SCHEDULER_TaskContext *tc)
950 {
951   struct MeshConnection *c = cls;
952
953   LOG (GNUNET_ERROR_TYPE_DEBUG, "FWD keepalive for %s\n", GMC_2s (c));
954   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
955   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
956     return;
957
958   connection_maintain (c, GNUNET_YES);
959
960   /* Next execution will be scheduled by message_sent */
961 }
962
963
964 /**
965  * Keep the connection alive in the BCK direction.
966  *
967  * TODO refactor and merge with connection_fwd_keepalive.
968  *
969  * @param cls Closure (connection to keepalive).
970  * @param tc TaskContext.
971  */
972 static void
973 connection_bck_keepalive (void *cls,
974                           const struct GNUNET_SCHEDULER_TaskContext *tc)
975 {
976   struct MeshConnection *c = cls;
977
978   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
979   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
980     return;
981
982   connection_maintain (c, GNUNET_NO);
983
984   /* Next execution will be scheduled by message_sent */
985 }
986
987
988 /**
989  * Schedule next keepalive task, taking in consideration
990  * the connection state and number of retries.
991  *
992  * If the peer is not the origin, do nothing.
993  *
994  * @param c Connection for which to schedule the next keepalive.
995  * @param fwd Direction for the next keepalive.
996  */
997 static void
998 schedule_next_keepalive (struct MeshConnection *c, int fwd)
999 {
1000   struct GNUNET_TIME_Relative delay;
1001   GNUNET_SCHEDULER_TaskIdentifier *task_id;
1002   GNUNET_SCHEDULER_Task keepalive_task;
1003
1004   if (GNUNET_NO == GMC_is_origin (c, fwd))
1005     return;
1006
1007   /* Calculate delay to use, depending on the state of the connection */
1008   if (MESH_CONNECTION_READY == c->state)
1009   {
1010     delay = refresh_connection_time;
1011   }
1012   else
1013   {
1014     if (1 > c->create_retry)
1015       c->create_retry = 1;
1016     delay = GNUNET_TIME_relative_multiply (create_connection_time,
1017                                            c->create_retry);
1018     if (c->create_retry < 64)
1019       c->create_retry *= 2;
1020   }
1021
1022   /* Select direction-dependent parameters */
1023   if (GNUNET_YES == fwd)
1024   {
1025     task_id = &c->fwd_maintenance_task;
1026     keepalive_task = &connection_fwd_keepalive;
1027   }
1028   else
1029   {
1030     task_id = &c->bck_maintenance_task;
1031     keepalive_task = &connection_bck_keepalive;
1032   }
1033
1034   /* Check that no one scheduled it before us (and alert in that case) */
1035   if (GNUNET_SCHEDULER_NO_TASK != *task_id)
1036   {
1037     GNUNET_break (0);
1038     GNUNET_SCHEDULER_cancel (*task_id);
1039   }
1040
1041   /* Schedule the task */
1042   *task_id = GNUNET_SCHEDULER_add_delayed (delay, keepalive_task, c);
1043 }
1044
1045
1046 /**
1047  * @brief Re-initiate traffic on this connection if necessary.
1048  *
1049  * Check if there is traffic queued towards this peer
1050  * and the core transmit handle is NULL (traffic was stalled).
1051  * If so, call core tmt rdy.
1052  *
1053  * @param c Connection on which initiate traffic.
1054  * @param fwd Is this about fwd traffic?
1055  */
1056 static void
1057 connection_unlock_queue (struct MeshConnection *c, int fwd)
1058 {
1059   struct MeshPeer *peer;
1060
1061   LOG (GNUNET_ERROR_TYPE_DEBUG,
1062               "connection_unlock_queue %s on %s\n",
1063               GM_f2s (fwd), GMC_2s (c));
1064
1065   if (GMC_is_terminal (c, fwd))
1066   {
1067     LOG (GNUNET_ERROR_TYPE_DEBUG, " is terminal!\n");
1068     return;
1069   }
1070
1071   peer = get_hop (c, fwd);
1072   GMP_queue_unlock (peer, c);
1073 }
1074
1075
1076 /**
1077  * Cancel all transmissions that belong to a certain connection.
1078  *
1079  * If the connection is scheduled for destruction and no more messages are left,
1080  * the connection will be destroyed by the continuation call.
1081  *
1082  * @param c Connection which to cancel. Might be destroyed during this call.
1083  * @param fwd Cancel fwd traffic?
1084  */
1085 static void
1086 connection_cancel_queues (struct MeshConnection *c, int fwd)
1087 {
1088   struct MeshFlowControl *fc;
1089   struct MeshPeer *peer;
1090
1091   LOG (GNUNET_ERROR_TYPE_DEBUG,
1092        " *** Cancel %s queues for connection %s\n",
1093        GM_f2s (fwd), GMC_2s (c));
1094   if (NULL == c)
1095   {
1096     GNUNET_break (0);
1097     return;
1098   }
1099
1100   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1101   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
1102   {
1103     GNUNET_SCHEDULER_cancel (fc->poll_task);
1104     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1105     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** Cancel POLL in ccq for fc %p\n", fc);
1106   }
1107   peer = get_hop (c, fwd);
1108   GMP_queue_cancel (peer, c);
1109 }
1110
1111
1112 /**
1113  * Function called if a connection has been stalled for a while,
1114  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
1115  *
1116  * @param cls Closure (poll ctx).
1117  * @param tc TaskContext.
1118  */
1119 static void
1120 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1121
1122
1123 /**
1124  * Callback called when a queued POLL message is sent.
1125  *
1126  * @param cls Closure (FC).
1127  * @param c Connection this message was on.
1128  * @param q Queue handler this call invalidates.
1129  * @param type Type of message sent.
1130  * @param fwd Was this a FWD going message?
1131  * @param size Size of the message.
1132  */
1133 static void
1134 poll_sent (void *cls,
1135            struct MeshConnection *c,
1136            struct MeshConnectionQueue *q,
1137            uint16_t type, int fwd, size_t size)
1138 {
1139   struct MeshFlowControl *fc = cls;
1140
1141   if (2 == c->destroy)
1142   {
1143     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL canceled on shutdown\n");
1144     return;
1145   }
1146   LOG (GNUNET_ERROR_TYPE_DEBUG,
1147        " *** POLL sent for , scheduling new one!\n");
1148   fc->poll_msg = NULL;
1149   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
1150   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
1151                                                 &connection_poll, fc);
1152   LOG (GNUNET_ERROR_TYPE_DEBUG, " task %u\n", fc->poll_task);
1153
1154 }
1155
1156 /**
1157  * Function called if a connection has been stalled for a while,
1158  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
1159  *
1160  * @param cls Closure (poll ctx).
1161  * @param tc TaskContext.
1162  */
1163 static void
1164 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1165 {
1166   struct MeshFlowControl *fc = cls;
1167   struct GNUNET_MESH_Poll msg;
1168   struct MeshConnection *c;
1169
1170   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1171   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1172   {
1173     return;
1174   }
1175
1176   c = fc->c;
1177   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
1178   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** connection [%s]\n", GMC_2s (c));
1179   LOG (GNUNET_ERROR_TYPE_DEBUG, " ***   %s\n",
1180        fc == &c->fwd_fc ? "FWD" : "BCK");
1181
1182   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
1183   msg.header.size = htons (sizeof (msg));
1184   msg.pid = htonl (fc->last_pid_sent);
1185   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** last pid sent: %u!\n", fc->last_pid_sent);
1186   fc->poll_msg = GMC_send_prebuilt_message (&msg.header, c,
1187                                             fc == &c->fwd_fc, GNUNET_YES,
1188                                             &poll_sent, fc);
1189 }
1190
1191
1192 /**
1193  * Timeout function due to lack of keepalive/traffic from the owner.
1194  * Destroys connection if called.
1195  *
1196  * @param cls Closure (connection to destroy).
1197  * @param tc TaskContext.
1198  */
1199 static void
1200 connection_fwd_timeout (void *cls,
1201                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1202 {
1203   struct MeshConnection *c = cls;
1204
1205   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
1206   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1207     return;
1208
1209   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s FWD timed out. Destroying.\n",
1210        GMC_2s (c));
1211   if (GMC_is_origin (c, GNUNET_YES)) /* If local, leave. */
1212   {
1213     GNUNET_break (0);
1214     return;
1215   }
1216
1217   GMC_destroy (c);
1218 }
1219
1220
1221 /**
1222  * Timeout function due to lack of keepalive/traffic from the destination.
1223  * Destroys connection if called.
1224  *
1225  * @param cls Closure (connection to destroy).
1226  * @param tc TaskContext
1227  */
1228 static void
1229 connection_bck_timeout (void *cls,
1230                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1231 {
1232   struct MeshConnection *c = cls;
1233
1234   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
1235   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1236     return;
1237
1238   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s BCK timed out. Destroying.\n",
1239        GMC_2s (c));
1240
1241   if (GMC_is_origin (c, GNUNET_NO)) /* If local, leave. */
1242   {
1243     GNUNET_break (0);
1244     return;
1245   }
1246
1247   GMC_destroy (c);
1248 }
1249
1250
1251 /**
1252  * Resets the connection timeout task, some other message has done the
1253  * task's job.
1254  * - For the first peer on the direction this means to send
1255  *   a keepalive or a path confirmation message (either create or ACK).
1256  * - For all other peers, this means to destroy the connection,
1257  *   due to lack of activity.
1258  * Starts the timeout if no timeout was running (connection just created).
1259  *
1260  * @param c Connection whose timeout to reset.
1261  * @param fwd Is this forward?
1262  *
1263  * TODO use heap to improve efficiency of scheduler.
1264  */
1265 static void
1266 connection_reset_timeout (struct MeshConnection *c, int fwd)
1267 {
1268   GNUNET_SCHEDULER_TaskIdentifier *ti;
1269   GNUNET_SCHEDULER_Task f;
1270
1271   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
1272
1273   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s reset timeout\n", GM_f2s (fwd));
1274
1275   if (GNUNET_SCHEDULER_NO_TASK != *ti)
1276     GNUNET_SCHEDULER_cancel (*ti);
1277
1278   if (GMC_is_origin (c, fwd)) /* Startpoint */
1279   {
1280     f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
1281     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
1282   }
1283   else /* Relay, endpoint. */
1284   {
1285     struct GNUNET_TIME_Relative delay;
1286
1287     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
1288     f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
1289     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
1290   }
1291 }
1292
1293
1294 /**
1295  * Add the connection to the list of both neighbors.
1296  *
1297  * @param c Connection.
1298  *
1299  * @return #GNUNET_OK if everything went fine
1300  *         #GNUNET_SYSERR if the was an error and @c c is malformed.
1301  */
1302 static int
1303 register_neighbors (struct MeshConnection *c)
1304 {
1305   struct MeshPeer *next_peer;
1306   struct MeshPeer *prev_peer;
1307
1308   next_peer = get_next_hop (c);
1309   prev_peer = get_prev_hop (c);
1310
1311   LOG (GNUNET_ERROR_TYPE_DEBUG, "register neighbors for connection %s\n",
1312        GMC_2s (c));
1313   path_debug (c->path);
1314   LOG (GNUNET_ERROR_TYPE_DEBUG, "own pos %u\n", c->own_pos);
1315   LOG (GNUNET_ERROR_TYPE_DEBUG, "putting connection %s to next peer %p\n",
1316        GMC_2s (c), next_peer);
1317   LOG (GNUNET_ERROR_TYPE_DEBUG, "next peer %p %s\n", next_peer, GMP_2s (next_peer));
1318   LOG (GNUNET_ERROR_TYPE_DEBUG, "putting connection %s to prev peer %p\n",
1319        GMC_2s (c), prev_peer);
1320   LOG (GNUNET_ERROR_TYPE_DEBUG, "prev peer %p %s\n", prev_peer, GMP_2s (prev_peer));
1321
1322   if (GNUNET_NO == GMP_is_neighbor (next_peer)
1323       || GNUNET_NO == GMP_is_neighbor (prev_peer))
1324   {
1325     if (GMC_is_origin (c, GNUNET_YES))
1326       GNUNET_STATISTICS_update (stats, "# local bad paths", 1, GNUNET_NO);
1327     GNUNET_STATISTICS_update (stats, "# bad paths", 1, GNUNET_NO);
1328
1329     LOG (GNUNET_ERROR_TYPE_DEBUG, "  register neighbors failed\n");
1330     LOG (GNUNET_ERROR_TYPE_DEBUG, "  prev: %s, neighbor?: %d\n",
1331          GMP_2s (prev_peer), GMP_is_neighbor (prev_peer));
1332     LOG (GNUNET_ERROR_TYPE_DEBUG, "  next: %s, neighbor?: %d\n",
1333          GMP_2s (next_peer), GMP_is_neighbor (next_peer));
1334     return GNUNET_SYSERR;
1335   }
1336
1337   GMP_add_connection (next_peer, c);
1338   GMP_add_connection (prev_peer, c);
1339
1340   return GNUNET_OK;
1341 }
1342
1343
1344 /**
1345  * Remove the connection from the list of both neighbors.
1346  *
1347  * @param c Connection.
1348  */
1349 static void
1350 unregister_neighbors (struct MeshConnection *c)
1351 {
1352   struct MeshPeer *peer;
1353
1354   peer = get_next_hop (c);
1355   if (GNUNET_OK != GMP_remove_connection (peer, c))
1356   {
1357     GNUNET_assert (MESH_CONNECTION_NEW == c->state
1358                   || MESH_CONNECTION_DESTROYED == c->state);
1359     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate: %u\n", c->state);
1360     if (NULL != c->t) GMT_debug (c->t);
1361   }
1362
1363   peer = get_prev_hop (c);
1364   if (GNUNET_OK != GMP_remove_connection (peer, c))
1365   {
1366     GNUNET_assert (MESH_CONNECTION_NEW == c->state
1367                   || MESH_CONNECTION_DESTROYED == c->state);
1368     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate: %u\n", c->state);
1369     if (NULL != c->t) GMT_debug (c->t);
1370   }
1371 }
1372
1373
1374 /**
1375  * Bind the connection to the peer and the tunnel to that peer.
1376  *
1377  * If the peer has no tunnel, create one. Update tunnel and connection
1378  * data structres to reflect new status.
1379  *
1380  * @param c Connection.
1381  * @param peer Peer.
1382  */
1383 static void
1384 add_to_peer (struct MeshConnection *c, struct MeshPeer *peer)
1385 {
1386   GMP_add_tunnel (peer);
1387   c->t = GMP_get_tunnel (peer);
1388   GMT_add_connection (c->t, c);
1389 }
1390
1391
1392 /**
1393  * Builds a path from a PeerIdentity array.
1394  *
1395  * @param peers PeerIdentity array.
1396  * @param size Size of the @c peers array.
1397  * @param own_pos Output parameter: own position in the path.
1398  *
1399  * @return Fixed and shortened path.
1400  */
1401 static struct MeshPeerPath *
1402 build_path_from_peer_ids (struct GNUNET_PeerIdentity *peers,
1403                           unsigned int size,
1404                           unsigned int *own_pos)
1405 {
1406   struct MeshPeerPath *path;
1407   GNUNET_PEER_Id shortid;
1408   unsigned int i;
1409   unsigned int j;
1410   unsigned int offset;
1411
1412   /* Create path */
1413   LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
1414   path = path_new (size);
1415   *own_pos = 0;
1416   offset = 0;
1417   for (i = 0; i < size; i++)
1418   {
1419     LOG (GNUNET_ERROR_TYPE_DEBUG, "  - %u: taking %s\n",
1420          i, GNUNET_i2s (&peers[i]));
1421     shortid = GNUNET_PEER_intern (&peers[i]);
1422
1423     /* Check for loops / duplicates */
1424     for (j = 0; j < i - offset; j++)
1425     {
1426       if (path->peers[j] == shortid)
1427       {
1428         LOG (GNUNET_ERROR_TYPE_DEBUG, "    already exists at pos %u\n", j);
1429         offset += i - j;
1430         LOG (GNUNET_ERROR_TYPE_DEBUG, "    offset now\n", offset);
1431         GNUNET_PEER_change_rc (shortid, -1);
1432       }
1433     }
1434     LOG (GNUNET_ERROR_TYPE_DEBUG, "    storing at %u\n", i - offset);
1435     path->peers[i - offset] = shortid;
1436     if (path->peers[i] == myid)
1437       *own_pos = i;
1438   }
1439   path->length -= offset;
1440
1441   if (path->peers[*own_pos] != myid)
1442   {
1443     /* create path: self not found in path through self */
1444     GNUNET_break_op (0);
1445     path_destroy (path);
1446     return NULL;
1447   }
1448
1449   return path;
1450 }
1451
1452
1453 /**
1454  * Log receipt of message on stderr (INFO level).
1455  *
1456  * @param message Message received.
1457  * @param peer Peer who sent the message.
1458  */
1459 static void
1460 log_message (const struct GNUNET_MessageHeader *message,
1461              const struct GNUNET_PeerIdentity *peer)
1462 {
1463   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
1464   LOG (GNUNET_ERROR_TYPE_INFO, "Got a %s message from %s\n",
1465        GM_m2s (ntohs (message->type)), GNUNET_i2s (peer));
1466 }
1467
1468 /******************************************************************************/
1469 /********************************    API    ***********************************/
1470 /******************************************************************************/
1471
1472 /**
1473  * Core handler for connection creation.
1474  *
1475  * @param cls Closure (unused).
1476  * @param peer Sender (neighbor).
1477  * @param message Message.
1478  *
1479  * @return GNUNET_OK to keep the connection open,
1480  *         GNUNET_SYSERR to close it (signal serious error)
1481  */
1482 int
1483 GMC_handle_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1484                    const struct GNUNET_MessageHeader *message)
1485 {
1486   struct GNUNET_MESH_ConnectionCreate *msg;
1487   struct GNUNET_PeerIdentity *id;
1488   struct GNUNET_HashCode *cid;
1489   struct MeshPeerPath *path;
1490   struct MeshPeer *dest_peer;
1491   struct MeshPeer *orig_peer;
1492   struct MeshConnection *c;
1493   unsigned int own_pos;
1494   uint16_t size;
1495
1496   log_message (message, peer);
1497
1498   /* Check size */
1499   size = ntohs (message->size);
1500   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
1501   {
1502     GNUNET_break_op (0);
1503     return GNUNET_OK;
1504   }
1505
1506   /* Calculate hops */
1507   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
1508   if (size % sizeof (struct GNUNET_PeerIdentity))
1509   {
1510     GNUNET_break_op (0);
1511     return GNUNET_OK;
1512   }
1513   size /= sizeof (struct GNUNET_PeerIdentity);
1514   if (1 > size)
1515   {
1516     GNUNET_break_op (0);
1517     return GNUNET_OK;
1518   }
1519   LOG (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
1520
1521   /* Get parameters */
1522   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
1523   cid = &msg->cid;
1524   id = (struct GNUNET_PeerIdentity *) &msg[1];
1525   LOG (GNUNET_ERROR_TYPE_DEBUG, "    connection %s (%s->).\n",
1526        GNUNET_h2s (cid), GNUNET_i2s (id));
1527
1528   /* Create connection */
1529   c = connection_get (cid);
1530   if (NULL == c)
1531   {
1532     path = build_path_from_peer_ids ((struct GNUNET_PeerIdentity *) &msg[1],
1533                                      size, &own_pos);
1534     if (NULL == path)
1535       return GNUNET_OK;
1536     if (0 == own_pos)
1537     {
1538       GNUNET_break_op (0);
1539       path_destroy (path);
1540       return GNUNET_OK;
1541     }
1542     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
1543     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
1544     c = GMC_new (cid, NULL, path_duplicate (path), own_pos);
1545     if (NULL == c)
1546     {
1547       if (path->length - 1 == own_pos)
1548       {
1549         /* If we are destination, why did the creation fail? */
1550         GNUNET_break (0);
1551         return GNUNET_OK;
1552       }
1553       send_broken2 (cid, &my_full_id,
1554                     GNUNET_PEER_resolve2 (path->peers[own_pos + 1]),
1555                     path->peers[own_pos - 1]);
1556       path_destroy (path);
1557       return GNUNET_OK;
1558     }
1559     GMP_add_path_to_all (path, GNUNET_NO);
1560     connection_reset_timeout (c, GNUNET_YES);
1561   }
1562   else
1563   {
1564     path = path_duplicate (c->path);
1565   }
1566   if (MESH_CONNECTION_NEW == c->state)
1567     connection_change_state (c, MESH_CONNECTION_SENT);
1568
1569   /* Remember peers */
1570   dest_peer = GMP_get (&id[size - 1]);
1571   orig_peer = GMP_get (&id[0]);
1572
1573   /* Is it a connection to us? */
1574   if (c->own_pos == size - 1)
1575   {
1576     LOG (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
1577     GMP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_YES);
1578
1579     add_to_peer (c, orig_peer);
1580     if (MESH_TUNNEL3_NEW == GMT_get_cstate (c->t))
1581       GMT_change_cstate (c->t,  MESH_TUNNEL3_WAITING);
1582
1583     send_connection_ack (c, GNUNET_NO);
1584     if (MESH_CONNECTION_SENT == c->state)
1585       connection_change_state (c, MESH_CONNECTION_ACK);
1586   }
1587   else
1588   {
1589     /* It's for somebody else! Retransmit. */
1590     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
1591     GMP_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
1592     GMP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_NO);
1593     GMC_send_prebuilt_message (message, c, GNUNET_YES, GNUNET_YES,
1594                                NULL, NULL);
1595   }
1596   path_destroy (path);
1597   return GNUNET_OK;
1598 }
1599
1600
1601 /**
1602  * Core handler for path confirmations.
1603  *
1604  * @param cls closure
1605  * @param message message
1606  * @param peer peer identity this notification is about
1607  *
1608  * @return GNUNET_OK to keep the connection open,
1609  *         GNUNET_SYSERR to close it (signal serious error)
1610  */
1611 int
1612 GMC_handle_confirm (void *cls, const struct GNUNET_PeerIdentity *peer,
1613                     const struct GNUNET_MessageHeader *message)
1614 {
1615   struct GNUNET_MESH_ConnectionACK *msg;
1616   struct MeshConnection *c;
1617   struct MeshPeerPath *p;
1618   struct MeshPeer *pi;
1619   enum MeshConnectionState oldstate;
1620   int fwd;
1621
1622   log_message (message, peer);
1623
1624   msg = (struct GNUNET_MESH_ConnectionACK *) message;
1625   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
1626               GNUNET_h2s (&msg->cid));
1627   c = connection_get (&msg->cid);
1628   if (NULL == c)
1629   {
1630     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1631                               1, GNUNET_NO);
1632     LOG (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
1633     return GNUNET_OK;
1634   }
1635
1636   if (GNUNET_NO != c->destroy)
1637   {
1638     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection being destroyed\n");
1639     return GNUNET_OK;
1640   }
1641
1642   oldstate = c->state;
1643   LOG (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n", GNUNET_i2s (peer));
1644   pi = GMP_get (peer);
1645   if (get_next_hop (c) == pi)
1646   {
1647     LOG (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
1648     fwd = GNUNET_NO;
1649     if (MESH_CONNECTION_SENT == oldstate)
1650       connection_change_state (c, MESH_CONNECTION_ACK);
1651   }
1652   else if (get_prev_hop (c) == pi)
1653   {
1654     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
1655     fwd = GNUNET_YES;
1656     connection_change_state (c, MESH_CONNECTION_READY);
1657   }
1658   else
1659   {
1660     GNUNET_break_op (0);
1661     return GNUNET_OK;
1662   }
1663
1664   connection_reset_timeout (c, fwd);
1665
1666   /* Add path to peers? */
1667   p = c->path;
1668   if (NULL != p)
1669   {
1670     GMP_add_path_to_all (p, GNUNET_YES);
1671   }
1672   else
1673   {
1674     GNUNET_break (0);
1675   }
1676
1677   /* Message for us as creator? */
1678   if (GMC_is_origin (c, GNUNET_YES))
1679   {
1680     if (GNUNET_NO != fwd)
1681     {
1682       GNUNET_break_op (0);
1683       return GNUNET_OK;
1684     }
1685     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
1686
1687     /* If just created, cancel the short timeout and start a long one */
1688     if (MESH_CONNECTION_SENT == oldstate)
1689       connection_reset_timeout (c, GNUNET_YES);
1690
1691     /* Change connection state */
1692     connection_change_state (c, MESH_CONNECTION_READY);
1693     send_connection_ack (c, GNUNET_YES);
1694
1695     /* Change tunnel state, trigger KX */
1696     if (MESH_TUNNEL3_WAITING == GMT_get_cstate (c->t))
1697       GMT_change_cstate (c->t, MESH_TUNNEL3_READY);
1698
1699     return GNUNET_OK;
1700   }
1701
1702   /* Message for us as destination? */
1703   if (GMC_is_terminal (c, GNUNET_YES))
1704   {
1705     if (GNUNET_YES != fwd)
1706     {
1707       GNUNET_break_op (0);
1708       return GNUNET_OK;
1709     }
1710     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
1711
1712     /* If just created, cancel the short timeout and start a long one */
1713     if (MESH_CONNECTION_ACK == oldstate)
1714       connection_reset_timeout (c, GNUNET_NO);
1715
1716     /* Change tunnel state */
1717     if (MESH_TUNNEL3_WAITING == GMT_get_cstate (c->t))
1718       GMT_change_cstate (c->t, MESH_TUNNEL3_READY);
1719
1720     return GNUNET_OK;
1721   }
1722
1723   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1724   GMC_send_prebuilt_message (message, c, fwd, GNUNET_YES, NULL, NULL);
1725   return GNUNET_OK;
1726 }
1727
1728
1729 /**
1730  * Core handler for notifications of broken paths
1731  *
1732  * @param cls Closure (unused).
1733  * @param id Peer identity of sending neighbor.
1734  * @param message Message.
1735  *
1736  * @return GNUNET_OK to keep the connection open,
1737  *         GNUNET_SYSERR to close it (signal serious error)
1738  */
1739 int
1740 GMC_handle_broken (void* cls,
1741                    const struct GNUNET_PeerIdentity* id,
1742                    const struct GNUNET_MessageHeader* message)
1743 {
1744   struct GNUNET_MESH_ConnectionBroken *msg;
1745   struct MeshConnection *c;
1746   int fwd;
1747
1748   log_message (message, id);
1749
1750   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
1751   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1752               GNUNET_i2s (&msg->peer1));
1753   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1754               GNUNET_i2s (&msg->peer2));
1755   c = connection_get (&msg->cid);
1756   if (NULL == c)
1757   {
1758     GNUNET_break_op (0);
1759     return GNUNET_OK;
1760   }
1761
1762   fwd = is_fwd (c, id);
1763   if (GMC_is_terminal (c, fwd))
1764   {
1765     path_invalidate (c->path);
1766     if (0 < c->pending_messages)
1767       c->destroy = GNUNET_YES;
1768     else
1769       GMC_destroy (c);
1770   }
1771   else
1772   {
1773     GMC_send_prebuilt_message (message, c, fwd, GNUNET_YES, NULL, NULL);
1774     c->destroy = GNUNET_YES;
1775     connection_cancel_queues (c, !fwd);
1776   }
1777
1778   return GNUNET_OK;
1779
1780 }
1781
1782
1783 /**
1784  * Core handler for tunnel destruction
1785  *
1786  * @param cls Closure (unused).
1787  * @param peer Peer identity of sending neighbor.
1788  * @param message Message.
1789  *
1790  * @return GNUNET_OK to keep the connection open,
1791  *         GNUNET_SYSERR to close it (signal serious error)
1792  */
1793 int
1794 GMC_handle_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
1795                     const struct GNUNET_MessageHeader *message)
1796 {
1797   struct GNUNET_MESH_ConnectionDestroy *msg;
1798   struct MeshConnection *c;
1799   int fwd;
1800
1801   log_message (message, peer);
1802
1803   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
1804   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n", GNUNET_h2s (&msg->cid));
1805   c = connection_get (&msg->cid);
1806   if (NULL == c)
1807   {
1808     /* Probably already got the message from another path,
1809      * destroyed the tunnel and retransmitted to children.
1810      * Safe to ignore.
1811      */
1812     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1813                               1, GNUNET_NO);
1814     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection unknown: already destroyed?\n");
1815     return GNUNET_OK;
1816   }
1817   fwd = is_fwd (c, peer);
1818   if (GNUNET_SYSERR == fwd)
1819   {
1820     GNUNET_break_op (0); /* FIXME */
1821     return GNUNET_OK;
1822   }
1823   if (GNUNET_NO == GMC_is_terminal (c, fwd))
1824     GMC_send_prebuilt_message (message, c, fwd, GNUNET_YES, NULL, NULL);
1825   else if (0 == c->pending_messages)
1826   {
1827     LOG (GNUNET_ERROR_TYPE_DEBUG, "!  directly destroying connection!\n");
1828     GMC_destroy (c);
1829     return GNUNET_OK;
1830   }
1831   c->destroy = GNUNET_YES;
1832   c->state = MESH_CONNECTION_DESTROYED;
1833   if (NULL != c->t)
1834   {
1835     GMT_remove_connection (c->t, c);
1836     c->t = NULL;
1837   }
1838
1839   return GNUNET_OK;
1840 }
1841
1842 /**
1843  * Generic handler for mesh network encrypted traffic.
1844  *
1845  * @param peer Peer identity this notification is about.
1846  * @param msg Encrypted message.
1847  *
1848  * @return GNUNET_OK to keep the connection open,
1849  *         GNUNET_SYSERR to close it (signal serious error)
1850  */
1851 static int
1852 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
1853                        const struct GNUNET_MESH_Encrypted *msg)
1854 {
1855   struct MeshConnection *c;
1856   struct MeshPeer *neighbor;
1857   struct MeshFlowControl *fc;
1858   GNUNET_PEER_Id peer_id;
1859   uint32_t pid;
1860   uint32_t ttl;
1861   size_t size;
1862   int fwd;
1863
1864   /* Check size */
1865   size = ntohs (msg->header.size);
1866   if (size <
1867       sizeof (struct GNUNET_MESH_Encrypted) +
1868       sizeof (struct GNUNET_MessageHeader))
1869   {
1870     GNUNET_break_op (0);
1871     return GNUNET_OK;
1872   }
1873
1874   /* Check connection */
1875   c = connection_get (&msg->cid);
1876   if (NULL == c)
1877   {
1878     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
1879     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING enc on unknown connection %s\n",
1880          GNUNET_h2s (&msg->cid));
1881     return GNUNET_OK;
1882   }
1883
1884   LOG (GNUNET_ERROR_TYPE_INFO, "  on connection %s\n", GMC_2s (c));
1885
1886   /* Check if origin is as expected */
1887   neighbor = get_prev_hop (c);
1888   peer_id = GNUNET_PEER_search (peer);
1889   if (peer_id == GMP_get_short_id (neighbor))
1890   {
1891     fwd = GNUNET_YES;
1892   }
1893   else
1894   {
1895     neighbor = get_next_hop (c);
1896     if (peer_id == GMP_get_short_id (neighbor))
1897     {
1898       fwd = GNUNET_NO;
1899     }
1900     else
1901     {
1902       /* Unexpected peer sending traffic on a connection. */
1903       GNUNET_break_op (0);
1904       return GNUNET_OK;
1905     }
1906   }
1907
1908   /* Check PID */
1909   fc = fwd ? &c->bck_fc : &c->fwd_fc;
1910   pid = ntohl (msg->pid);
1911   if (GM_is_pid_bigger (pid, fc->last_ack_sent))
1912   {
1913     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
1914     LOG (GNUNET_ERROR_TYPE_DEBUG,
1915                 "WARNING Received PID %u, (prev %u), ACK %u\n",
1916                 pid, fc->last_pid_recv, fc->last_ack_sent);
1917     return GNUNET_OK;
1918   }
1919   if (GNUNET_NO == GM_is_pid_bigger (pid, fc->last_pid_recv))
1920   {
1921     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
1922     LOG (GNUNET_ERROR_TYPE_DEBUG,
1923                 " Pid %u not expected (%u+), dropping!\n",
1924                 pid, fc->last_pid_recv + 1);
1925     return GNUNET_OK;
1926   }
1927   if (MESH_CONNECTION_SENT == c->state || MESH_CONNECTION_ACK == c->state)
1928     connection_change_state (c, MESH_CONNECTION_READY);
1929   connection_reset_timeout (c, fwd);
1930   fc->last_pid_recv = pid;
1931
1932   /* Is this message for us? */
1933   if (GMC_is_terminal (c, fwd))
1934   {
1935     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
1936     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
1937
1938     if (NULL == c->t)
1939     {
1940       GNUNET_break (GNUNET_NO != c->destroy);
1941       return GNUNET_OK;
1942     }
1943     fc->last_pid_recv = pid;
1944     GMT_handle_encrypted (c->t, msg);
1945     GMC_send_ack (c, fwd, GNUNET_NO);
1946     return GNUNET_OK;
1947   }
1948
1949   /* Message not for us: forward to next hop */
1950   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1951   ttl = ntohl (msg->ttl);
1952   LOG (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
1953   if (ttl == 0)
1954   {
1955     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
1956     LOG (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
1957     GMC_send_ack (c, fwd, GNUNET_NO);
1958     return GNUNET_OK;
1959   }
1960
1961   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
1962   GMC_send_prebuilt_message (&msg->header, c, fwd, GNUNET_NO, NULL, NULL);
1963
1964   return GNUNET_OK;
1965 }
1966
1967 /**
1968  * Generic handler for mesh network encrypted traffic.
1969  *
1970  * @param peer Peer identity this notification is about.
1971  * @param msg Encrypted message.
1972  *
1973  * @return GNUNET_OK to keep the connection open,
1974  *         GNUNET_SYSERR to close it (signal serious error)
1975  */
1976 static int
1977 handle_mesh_kx (const struct GNUNET_PeerIdentity *peer,
1978                 const struct GNUNET_MESH_KX *msg)
1979 {
1980   struct MeshConnection *c;
1981   struct MeshPeer *neighbor;
1982   GNUNET_PEER_Id peer_id;
1983   size_t size;
1984   int fwd;
1985
1986   /* Check size */
1987   size = ntohs (msg->header.size);
1988   if (size <
1989       sizeof (struct GNUNET_MESH_Encrypted) +
1990       sizeof (struct GNUNET_MessageHeader))
1991   {
1992     GNUNET_break_op (0);
1993     return GNUNET_OK;
1994   }
1995
1996   /* Check connection */
1997   c = connection_get (&msg->cid);
1998   if (NULL == c)
1999   {
2000     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
2001     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING kx on unknown connection %s\n",
2002          GNUNET_h2s (&msg->cid));
2003     return GNUNET_OK;
2004   }
2005   LOG (GNUNET_ERROR_TYPE_DEBUG, " on connection %s\n", GMC_2s (c));
2006
2007   /* Check if origin is as expected */
2008   neighbor = get_prev_hop (c);
2009   peer_id = GNUNET_PEER_search (peer);
2010   if (peer_id == GMP_get_short_id (neighbor))
2011   {
2012     fwd = GNUNET_YES;
2013   }
2014   else
2015   {
2016     neighbor = get_next_hop (c);
2017     if (peer_id == GMP_get_short_id (neighbor))
2018     {
2019       fwd = GNUNET_NO;
2020     }
2021     else
2022     {
2023       /* Unexpected peer sending traffic on a connection. */
2024       GNUNET_break_op (0);
2025       return GNUNET_OK;
2026     }
2027   }
2028
2029   /* Count as connection confirmation. */
2030   if (MESH_CONNECTION_SENT == c->state || MESH_CONNECTION_ACK == c->state)
2031   {
2032     connection_change_state (c, MESH_CONNECTION_READY);
2033     if (NULL != c->t)
2034     {
2035       if (MESH_TUNNEL3_WAITING == GMT_get_cstate (c->t))
2036         GMT_change_cstate (c->t, MESH_TUNNEL3_READY);
2037     }
2038   }
2039   connection_reset_timeout (c, fwd);
2040
2041   /* Is this message for us? */
2042   if (GMC_is_terminal (c, fwd))
2043   {
2044     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
2045     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
2046     if (NULL == c->t)
2047     {
2048       GNUNET_break (0);
2049       return GNUNET_OK;
2050     }
2051     GMT_handle_kx (c->t, &msg[1].header);
2052     return GNUNET_OK;
2053   }
2054
2055   /* Message not for us: forward to next hop */
2056   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2057   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
2058   GMC_send_prebuilt_message (&msg->header, c, fwd, GNUNET_NO, NULL, NULL);
2059
2060   return GNUNET_OK;
2061 }
2062
2063
2064 /**
2065  * Core handler for encrypted mesh network traffic (channel mgmt, data).
2066  *
2067  * @param cls Closure (unused).
2068  * @param message Message received.
2069  * @param peer Peer who sent the message.
2070  *
2071  * @return GNUNET_OK to keep the connection open,
2072  *         GNUNET_SYSERR to close it (signal serious error)
2073  */
2074 int
2075 GMC_handle_encrypted (void *cls, const struct GNUNET_PeerIdentity *peer,
2076                       const struct GNUNET_MessageHeader *message)
2077 {
2078   log_message (message, peer);
2079
2080   return handle_mesh_encrypted (peer,
2081                                 (struct GNUNET_MESH_Encrypted *)message);
2082 }
2083
2084
2085 /**
2086  * Core handler for key exchange traffic (ephemeral key, ping, pong).
2087  *
2088  * @param cls Closure (unused).
2089  * @param message Message received.
2090  * @param peer Peer who sent the message.
2091  *
2092  * @return GNUNET_OK to keep the connection open,
2093  *         GNUNET_SYSERR to close it (signal serious error)
2094  */
2095 int
2096 GMC_handle_kx (void *cls, const struct GNUNET_PeerIdentity *peer,
2097                const struct GNUNET_MessageHeader *message)
2098 {
2099   log_message (message, peer);
2100
2101   return handle_mesh_kx (peer,
2102                          (struct GNUNET_MESH_KX *) message);
2103 }
2104
2105
2106 /**
2107  * Core handler for mesh network traffic point-to-point acks.
2108  *
2109  * @param cls closure
2110  * @param message message
2111  * @param peer peer identity this notification is about
2112  *
2113  * @return GNUNET_OK to keep the connection open,
2114  *         GNUNET_SYSERR to close it (signal serious error)
2115  */
2116 int
2117 GMC_handle_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2118                 const struct GNUNET_MessageHeader *message)
2119 {
2120   struct GNUNET_MESH_ACK *msg;
2121   struct MeshConnection *c;
2122   struct MeshFlowControl *fc;
2123   GNUNET_PEER_Id id;
2124   uint32_t ack;
2125   int fwd;
2126
2127   log_message (message, peer);
2128
2129   msg = (struct GNUNET_MESH_ACK *) message;
2130   c = connection_get (&msg->cid);
2131   if (NULL == c)
2132   {
2133     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
2134                               GNUNET_NO);
2135     return GNUNET_OK;
2136   }
2137
2138   /* Is this a forward or backward ACK? */
2139   id = GNUNET_PEER_search (peer);
2140   if (GMP_get_short_id (get_next_hop (c)) == id)
2141   {
2142     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
2143     fc = &c->fwd_fc;
2144     fwd = GNUNET_YES;
2145   }
2146   else if (GMP_get_short_id (get_prev_hop (c)) == id)
2147   {
2148     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
2149     fc = &c->bck_fc;
2150     fwd = GNUNET_NO;
2151   }
2152   else
2153   {
2154     GNUNET_break_op (0);
2155     return GNUNET_OK;
2156   }
2157
2158   ack = ntohl (msg->ack);
2159   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u (was %u)\n",
2160               ack, fc->last_ack_recv);
2161   if (GM_is_pid_bigger (ack, fc->last_ack_recv))
2162     fc->last_ack_recv = ack;
2163
2164   /* Cancel polling if the ACK is big enough. */
2165   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
2166       GM_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2167   {
2168     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
2169     GNUNET_SCHEDULER_cancel (fc->poll_task);
2170     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2171     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
2172   }
2173
2174   connection_unlock_queue (c, fwd);
2175
2176   return GNUNET_OK;
2177 }
2178
2179
2180 /**
2181  * Core handler for mesh network traffic point-to-point ack polls.
2182  *
2183  * @param cls closure
2184  * @param message message
2185  * @param peer peer identity this notification is about
2186  *
2187  * @return GNUNET_OK to keep the connection open,
2188  *         GNUNET_SYSERR to close it (signal serious error)
2189  */
2190 int
2191 GMC_handle_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
2192                  const struct GNUNET_MessageHeader *message)
2193 {
2194   struct GNUNET_MESH_Poll *msg;
2195   struct MeshConnection *c;
2196   struct MeshFlowControl *fc;
2197   GNUNET_PEER_Id id;
2198   uint32_t pid;
2199   int fwd;
2200
2201   log_message (message, peer);
2202
2203   msg = (struct GNUNET_MESH_Poll *) message;
2204   c = connection_get (&msg->cid);
2205   if (NULL == c)
2206   {
2207     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
2208                               GNUNET_NO);
2209     LOG (GNUNET_ERROR_TYPE_DEBUG,
2210          "WARNING POLL message on unknown connection %s!\n",
2211          GNUNET_h2s (&msg->cid));
2212     return GNUNET_OK;
2213   }
2214
2215   /* Is this a forward or backward ACK?
2216    * Note: a poll should never be needed in a loopback case,
2217    * since there is no possiblility of packet loss there, so
2218    * this way of discerining FWD/BCK should not be a problem.
2219    */
2220   id = GNUNET_PEER_search (peer);
2221   if (GMP_get_short_id (get_next_hop (c)) == id)
2222   {
2223     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
2224     fc = &c->fwd_fc;
2225   }
2226   else if (GMP_get_short_id (get_prev_hop (c)) == id)
2227   {
2228     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
2229     fc = &c->bck_fc;
2230   }
2231   else
2232   {
2233     GNUNET_break_op (0);
2234     return GNUNET_OK;
2235   }
2236
2237   pid = ntohl (msg->pid);
2238   LOG (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n", pid, fc->last_pid_recv);
2239   fc->last_pid_recv = pid;
2240   fwd = fc == &c->bck_fc;
2241   GMC_send_ack (c, fwd, GNUNET_YES);
2242
2243   return GNUNET_OK;
2244 }
2245
2246
2247 /**
2248  * Core handler for mesh keepalives.
2249  *
2250  * @param cls closure
2251  * @param message message
2252  * @param peer peer identity this notification is about
2253  * @return GNUNET_OK to keep the connection open,
2254  *         GNUNET_SYSERR to close it (signal serious error)
2255  *
2256  * TODO: Check who we got this from, to validate route.
2257  */
2258 int
2259 GMC_handle_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
2260                       const struct GNUNET_MessageHeader *message)
2261 {
2262   struct GNUNET_MESH_ConnectionKeepAlive *msg;
2263   struct MeshConnection *c;
2264   struct MeshPeer *neighbor;
2265   GNUNET_PEER_Id peer_id;
2266   int fwd;
2267
2268   log_message (message, peer);
2269
2270   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
2271   c = connection_get (&msg->cid);
2272   if (NULL == c)
2273   {
2274     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
2275                               GNUNET_NO);
2276     return GNUNET_OK;
2277   }
2278
2279   /* Check if origin is as expected TODO refactor and reuse */
2280   peer_id = GNUNET_PEER_search (peer);
2281   neighbor = get_prev_hop (c);
2282   if (peer_id == GMP_get_short_id (neighbor))
2283   {
2284     fwd = GNUNET_YES;
2285   }
2286   else
2287   {
2288     neighbor = get_next_hop (c);
2289     if (peer_id == GMP_get_short_id (neighbor))
2290     {
2291       fwd = GNUNET_NO;
2292     }
2293     else
2294     {
2295       GNUNET_break_op (0);
2296       return GNUNET_OK;
2297     }
2298   }
2299
2300   connection_change_state (c, MESH_CONNECTION_READY);
2301   connection_reset_timeout (c, fwd);
2302
2303   if (GMC_is_terminal (c, fwd))
2304     return GNUNET_OK;
2305
2306   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
2307   GMC_send_prebuilt_message (message, c, fwd, GNUNET_YES, NULL, NULL);
2308
2309   return GNUNET_OK;
2310 }
2311
2312
2313 /**
2314  * Send an ACK on the appropriate connection/channel, depending on
2315  * the direction and the position of the peer.
2316  *
2317  * @param c Which connection to send the hop-by-hop ACK.
2318  * @param fwd Is this a fwd ACK? (will go dest->root).
2319  * @param force Send the ACK even if suboptimal (e.g. requested by POLL).
2320  */
2321 void
2322 GMC_send_ack (struct MeshConnection *c, int fwd, int force)
2323 {
2324   unsigned int buffer;
2325
2326   LOG (GNUNET_ERROR_TYPE_DEBUG,
2327        "GMC send %s ACK on %s\n",
2328        GM_f2s (fwd), GMC_2s (c));
2329
2330   if (NULL == c)
2331   {
2332     GNUNET_break (0);
2333     return;
2334   }
2335
2336   if (GNUNET_NO != c->destroy)
2337   {
2338     LOG (GNUNET_ERROR_TYPE_DEBUG, "  being destroyed, why bother...\n");
2339     return;
2340   }
2341
2342   /* Get available buffer space */
2343   if (GMC_is_terminal (c, fwd))
2344   {
2345     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from all channels\n");
2346     buffer = GMT_get_channels_buffer (c->t);
2347   }
2348   else
2349   {
2350     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
2351     buffer = GMC_get_buffer (c, fwd);
2352   }
2353   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
2354   if (0 == buffer && GNUNET_NO == force)
2355     return;
2356
2357   /* Send available buffer space */
2358   if (GMC_is_origin (c, fwd))
2359   {
2360     GNUNET_assert (NULL != c->t);
2361     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channels...\n");
2362     GMT_unchoke_channels (c->t);
2363   }
2364   else
2365   {
2366     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
2367     send_ack (c, buffer, fwd, force);
2368   }
2369 }
2370
2371
2372 /**
2373  * Initialize the connections subsystem
2374  *
2375  * @param c Configuration handle.
2376  */
2377 void
2378 GMC_init (const struct GNUNET_CONFIGURATION_Handle *c)
2379 {
2380   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2381   if (GNUNET_OK !=
2382       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
2383                                              &max_msgs_queue))
2384   {
2385     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2386                                "MESH", "MAX_MSGS_QUEUE", "MISSING");
2387     GNUNET_SCHEDULER_shutdown ();
2388     return;
2389   }
2390
2391   if (GNUNET_OK !=
2392       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
2393                                              &max_connections))
2394   {
2395     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2396                                "MESH", "MAX_CONNECTIONS", "MISSING");
2397     GNUNET_SCHEDULER_shutdown ();
2398     return;
2399   }
2400
2401   if (GNUNET_OK !=
2402       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
2403                                            &refresh_connection_time))
2404   {
2405     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2406                                "MESH", "REFRESH_CONNECTION_TIME", "MISSING");
2407     GNUNET_SCHEDULER_shutdown ();
2408     return;
2409   }
2410   create_connection_time = GNUNET_TIME_UNIT_SECONDS;
2411   connections = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
2412 }
2413
2414
2415 /**
2416  * Destroy each connection on shutdown.
2417  *
2418  * @param cls Closure (unused).
2419  * @param key Current key code (CID, unused).
2420  * @param value Value in the hash map (connection)
2421  *
2422  * @return #GNUNET_YES, because we should continue to iterate,
2423  */
2424 static int
2425 shutdown_iterator (void *cls,
2426                    const struct GNUNET_HashCode *key,
2427                    void *value)
2428 {
2429   struct MeshConnection *c = value;
2430
2431   GMC_destroy (c);
2432   return GNUNET_YES;
2433 }
2434
2435
2436 /**
2437  * Shut down the connections subsystem.
2438  */
2439 void
2440 GMC_shutdown (void)
2441 {
2442   GNUNET_CONTAINER_multihashmap_iterate (connections, &shutdown_iterator, NULL);
2443   GNUNET_CONTAINER_multihashmap_destroy (connections);
2444   connections = NULL;
2445 }
2446
2447
2448 struct MeshConnection *
2449 GMC_new (const struct GNUNET_HashCode *cid,
2450          struct MeshTunnel3 *t,
2451          struct MeshPeerPath *p,
2452          unsigned int own_pos)
2453 {
2454   struct MeshConnection *c;
2455
2456   c = GNUNET_new (struct MeshConnection);
2457   c->id = *cid;
2458   GNUNET_assert (GNUNET_OK ==
2459                  GNUNET_CONTAINER_multihashmap_put (connections,
2460                                                     &c->id, c,
2461                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2462   fc_init (&c->fwd_fc);
2463   fc_init (&c->bck_fc);
2464   c->fwd_fc.c = c;
2465   c->bck_fc.c = c;
2466
2467   c->t = t;
2468   GNUNET_assert (own_pos <= p->length - 1);
2469   c->own_pos = own_pos;
2470   c->path = p;
2471
2472   if (GNUNET_OK != register_neighbors (c))
2473   {
2474     if (0 == own_pos)
2475     {
2476       path_invalidate (c->path);
2477       c->t = NULL;
2478       c->path = NULL;
2479     }
2480     GMC_destroy (c);
2481     return NULL;
2482   }
2483
2484   return c;
2485 }
2486
2487
2488 void
2489 GMC_destroy (struct MeshConnection *c)
2490 {
2491   if (NULL == c)
2492   {
2493     GNUNET_break (0);
2494     return;
2495   }
2496
2497   if (2 == c->destroy) /* cancel queues -> GMP_queue_cancel -> q_destroy -> */
2498     return;            /* -> message_sent -> GMC_destroy. Don't loop. */
2499   c->destroy = 2;
2500
2501   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s\n", GMC_2s (c));
2502   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc's f: %p, b: %p\n",
2503        &c->fwd_fc, &c->bck_fc);
2504   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc tasks f: %u, b: %u\n",
2505        c->fwd_fc.poll_task, c->bck_fc.poll_task);
2506
2507   /* Cancel all traffic */
2508   if (NULL != c->path)
2509   {
2510     connection_cancel_queues (c, GNUNET_YES);
2511     connection_cancel_queues (c, GNUNET_NO);
2512     unregister_neighbors (c);
2513   }
2514
2515   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc tasks f: %u, b: %u\n",
2516        c->fwd_fc.poll_task, c->bck_fc.poll_task);
2517
2518   /* Cancel maintainance task (keepalive/timeout) */
2519   if (NULL != c->fwd_fc.poll_msg)
2520   {
2521     GMC_cancel (c->fwd_fc.poll_msg);
2522     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL msg FWD canceled\n");
2523   }
2524   if (NULL != c->bck_fc.poll_msg)
2525   {
2526     GMC_cancel (c->bck_fc.poll_msg);
2527     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL msg BCK canceled\n");
2528   }
2529
2530   /* Delete from tunnel */
2531   if (NULL != c->t)
2532     GMT_remove_connection (c->t, c);
2533
2534   if (GNUNET_NO == GMC_is_origin (c, GNUNET_YES) && NULL != c->path)
2535     path_destroy (c->path);
2536   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
2537     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
2538   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
2539     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
2540   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_fc.poll_task)
2541   {
2542     GNUNET_SCHEDULER_cancel (c->fwd_fc.poll_task);
2543     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL FWD canceled\n");
2544   }
2545   if (GNUNET_SCHEDULER_NO_TASK != c->bck_fc.poll_task)
2546   {
2547     GNUNET_SCHEDULER_cancel (c->bck_fc.poll_task);
2548     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL BCK canceled\n");
2549   }
2550
2551   GNUNET_break (GNUNET_YES ==
2552                 GNUNET_CONTAINER_multihashmap_remove (connections, &c->id, c));
2553
2554   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
2555   GNUNET_free (c);
2556 }
2557
2558 /**
2559  * Get the connection ID.
2560  *
2561  * @param c Connection to get the ID from.
2562  *
2563  * @return ID of the connection.
2564  */
2565 const struct GNUNET_HashCode *
2566 GMC_get_id (const struct MeshConnection *c)
2567 {
2568   return &c->id;
2569 }
2570
2571
2572 /**
2573  * Get the connection path.
2574  *
2575  * @param c Connection to get the path from.
2576  *
2577  * @return path used by the connection.
2578  */
2579 const struct MeshPeerPath *
2580 GMC_get_path (const struct MeshConnection *c)
2581 {
2582   if (GNUNET_NO == c->destroy)
2583     return c->path;
2584   return NULL;
2585 }
2586
2587
2588 /**
2589  * Get the connection state.
2590  *
2591  * @param c Connection to get the state from.
2592  *
2593  * @return state of the connection.
2594  */
2595 enum MeshConnectionState
2596 GMC_get_state (const struct MeshConnection *c)
2597 {
2598   return c->state;
2599 }
2600
2601 /**
2602  * Get the connection tunnel.
2603  *
2604  * @param c Connection to get the tunnel from.
2605  *
2606  * @return tunnel of the connection.
2607  */
2608 struct MeshTunnel3 *
2609 GMC_get_tunnel (const struct MeshConnection *c)
2610 {
2611   return c->t;
2612 }
2613
2614
2615 /**
2616  * Get free buffer space in a connection.
2617  *
2618  * @param c Connection.
2619  * @param fwd Is query about FWD traffic?
2620  *
2621  * @return Free buffer space [0 - max_msgs_queue/max_connections]
2622  */
2623 unsigned int
2624 GMC_get_buffer (struct MeshConnection *c, int fwd)
2625 {
2626   struct MeshFlowControl *fc;
2627
2628   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2629
2630   return (fc->queue_max - fc->queue_n);
2631 }
2632
2633 /**
2634  * Get how many messages have we allowed to send to us from a direction.
2635  *
2636  * @param c Connection.
2637  * @param fwd Are we asking about traffic from FWD (BCK messages)?
2638  *
2639  * @return last_ack_sent - last_pid_recv
2640  */
2641 unsigned int
2642 GMC_get_allowed (struct MeshConnection *c, int fwd)
2643 {
2644   struct MeshFlowControl *fc;
2645
2646   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2647   if (GM_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
2648   {
2649     return 0;
2650   }
2651   return (fc->last_ack_sent - fc->last_pid_recv);
2652 }
2653
2654 /**
2655  * Get messages queued in a connection.
2656  *
2657  * @param c Connection.
2658  * @param fwd Is query about FWD traffic?
2659  *
2660  * @return Number of messages queued.
2661  */
2662 unsigned int
2663 GMC_get_qn (struct MeshConnection *c, int fwd)
2664 {
2665   struct MeshFlowControl *fc;
2666
2667   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2668
2669   return fc->queue_n;
2670 }
2671
2672
2673 /**
2674  * Allow the connection to advertise a buffer of the given size.
2675  *
2676  * The connection will send an @c fwd ACK message (so: in direction !fwd)
2677  * allowing up to last_pid_recv + buffer.
2678  *
2679  * @param c Connection.
2680  * @param buffer How many more messages the connection can accept.
2681  * @param fwd Is this about FWD traffic? (The ack will go dest->root).
2682  */
2683 void
2684 GMC_allow (struct MeshConnection *c, unsigned int buffer, int fwd)
2685 {
2686   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowing %s %u messages %s\n",
2687        GMC_2s (c), buffer, GM_f2s (fwd));
2688   send_ack (c, buffer, fwd, GNUNET_NO);
2689 }
2690
2691
2692 /**
2693  * Notify other peers on a connection of a broken link. Mark connections
2694  * to destroy after all traffic has been sent.
2695  *
2696  * @param c Connection on which there has been a disconnection.
2697  * @param peer Peer that disconnected.
2698  */
2699 void
2700 GMC_notify_broken (struct MeshConnection *c,
2701                    struct MeshPeer *peer)
2702 {
2703   int fwd;
2704
2705   LOG (GNUNET_ERROR_TYPE_DEBUG,
2706        " notify broken on %s due to %s disconnect\n",
2707        GMC_2s (c), GMP_2s (peer));
2708
2709   fwd = peer == get_prev_hop (c);
2710
2711   if (GNUNET_YES == GMC_is_terminal (c, fwd))
2712   {
2713     /* Local shutdown, no one to notify about this. */
2714     GMC_destroy (c);
2715     return;
2716   }
2717   if (GNUNET_NO == c->destroy)
2718     send_broken (c, &my_full_id, GMP_get_id (peer), fwd);
2719
2720   /* Connection will have at least one pending message
2721    * (the one we just scheduled), so no point in checking whether to
2722    * destroy immediately. */
2723   c->destroy = GNUNET_YES;
2724   c->state = MESH_CONNECTION_DESTROYED;
2725
2726   /**
2727    * Cancel all queues, if no message is left, connection will be destroyed.
2728    */
2729   connection_cancel_queues (c, !fwd);
2730
2731   return;
2732 }
2733
2734
2735 /**
2736  * Is this peer the first one on the connection?
2737  *
2738  * @param c Connection.
2739  * @param fwd Is this about fwd traffic?
2740  *
2741  * @return #GNUNET_YES if origin, #GNUNET_NO if relay/terminal.
2742  */
2743 int
2744 GMC_is_origin (struct MeshConnection *c, int fwd)
2745 {
2746   if (!fwd && c->path->length - 1 == c->own_pos )
2747     return GNUNET_YES;
2748   if (fwd && 0 == c->own_pos)
2749     return GNUNET_YES;
2750   return GNUNET_NO;
2751 }
2752
2753
2754 /**
2755  * Is this peer the last one on the connection?
2756  *
2757  * @param c Connection.
2758  * @param fwd Is this about fwd traffic?
2759  *            Note that the ROOT is the terminal for BCK traffic!
2760  *
2761  * @return #GNUNET_YES if terminal, #GNUNET_NO if relay/origin.
2762  */
2763 int
2764 GMC_is_terminal (struct MeshConnection *c, int fwd)
2765 {
2766   return GMC_is_origin (c, !fwd);
2767 }
2768
2769
2770 /**
2771  * See if we are allowed to send by the next hop in the given direction.
2772  *
2773  * @param c Connection.
2774  * @param fwd Is this about fwd traffic?
2775  *
2776  * @return #GNUNET_YES in case it's OK to send.
2777  */
2778 int
2779 GMC_is_sendable (struct MeshConnection *c, int fwd)
2780 {
2781   struct MeshFlowControl *fc;
2782
2783   if (NULL == c)
2784   {
2785     GNUNET_break (0);
2786     return GNUNET_YES;
2787   }
2788   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2789   if (GM_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2790     return GNUNET_YES;
2791   return GNUNET_NO;
2792 }
2793
2794 /**
2795  * Sends an already built message on a connection, properly registering
2796  * all used resources.
2797  *
2798  * @param message Message to send. Function makes a copy of it.
2799  *                If message is not hop-by-hop, decrements TTL of copy.
2800  * @param c Connection on which this message is transmitted.
2801  * @param fwd Is this a fwd message?
2802  * @param force Force the connection to accept the message (buffer overfill).
2803  * @param cont Continuation called once message is sent. Can be NULL.
2804  * @param cont_cls Closure for @c cont.
2805  *
2806  * @return Handle to cancel the message before it's sent.
2807  *         NULL on error or if @c cont is NULL.
2808  *         Invalid on @c cont call.
2809  */
2810 struct MeshConnectionQueue *
2811 GMC_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2812                            struct MeshConnection *c, int fwd, int force,
2813                            GMC_sent cont, void *cont_cls)
2814 {
2815   struct MeshFlowControl *fc;
2816   struct MeshConnectionQueue *q;
2817   void *data;
2818   size_t size;
2819   uint16_t type;
2820   int droppable;
2821
2822   size = ntohs (message->size);
2823   data = GNUNET_malloc (size);
2824   memcpy (data, message, size);
2825   type = ntohs (message->type);
2826   LOG (GNUNET_ERROR_TYPE_INFO, "Send %s (%u bytes) on connection %s\n",
2827        GM_m2s (type), size, GMC_2s (c));
2828
2829   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2830   droppable = GNUNET_NO == force;
2831   switch (type)
2832   {
2833     struct GNUNET_MESH_Encrypted *emsg;
2834     struct GNUNET_MESH_KX        *kmsg;
2835     struct GNUNET_MESH_ACK       *amsg;
2836     struct GNUNET_MESH_Poll      *pmsg;
2837     struct GNUNET_MESH_ConnectionDestroy *dmsg;
2838     struct GNUNET_MESH_ConnectionBroken  *bmsg;
2839     uint32_t ttl;
2840
2841     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
2842       emsg = (struct GNUNET_MESH_Encrypted *) data;
2843       ttl = ntohl (emsg->ttl);
2844       if (0 == ttl)
2845       {
2846         GNUNET_break_op (0);
2847         GNUNET_free (data);
2848         return NULL;
2849       }
2850       emsg->cid = c->id;
2851       emsg->ttl = htonl (ttl - 1);
2852       emsg->pid = htonl (fc->next_pid++);
2853       LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
2854       if (GNUNET_YES == droppable)
2855       {
2856         fc->queue_n++;
2857         LOG (GNUNET_ERROR_TYPE_DEBUG, "pid %u\n", ntohl (emsg->pid));
2858         LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid sent %u\n", fc->last_pid_sent);
2859         LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack recv %u\n", fc->last_ack_recv);
2860       }
2861       else
2862       {
2863         LOG (GNUNET_ERROR_TYPE_DEBUG, "  not droppable, Q_N stays the same\n");
2864       }
2865       if (GM_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
2866       {
2867         GMC_start_poll (c, fwd);
2868       }
2869       break;
2870
2871     case GNUNET_MESSAGE_TYPE_MESH_KX:
2872       kmsg = (struct GNUNET_MESH_KX *) data;
2873       kmsg->cid = c->id;
2874       break;
2875
2876     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2877       amsg = (struct GNUNET_MESH_ACK *) data;
2878       amsg->cid = c->id;
2879       LOG (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
2880       droppable = GNUNET_NO;
2881       break;
2882
2883     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2884       pmsg = (struct GNUNET_MESH_Poll *) data;
2885       pmsg->cid = c->id;
2886       LOG (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
2887       droppable = GNUNET_NO;
2888       break;
2889
2890     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
2891       dmsg = (struct GNUNET_MESH_ConnectionDestroy *) data;
2892       dmsg->cid = c->id;
2893       dmsg->reserved = 0;
2894       break;
2895
2896     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
2897       bmsg = (struct GNUNET_MESH_ConnectionBroken *) data;
2898       bmsg->cid = c->id;
2899       bmsg->reserved = 0;
2900       break;
2901
2902     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
2903     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
2904     case GNUNET_MESSAGE_TYPE_MESH_KEEPALIVE:
2905       break;
2906
2907     default:
2908       GNUNET_break (0);
2909       GNUNET_free (data);
2910       return NULL;
2911   }
2912
2913   if (fc->queue_n > fc->queue_max && droppable)
2914   {
2915     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
2916                               1, GNUNET_NO);
2917     GNUNET_break (0);
2918     LOG (GNUNET_ERROR_TYPE_DEBUG,
2919                 "queue full: %u/%u\n",
2920                 fc->queue_n, fc->queue_max);
2921     if (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED == type)
2922     {
2923       fc->queue_n--;
2924       fc->next_pid--;
2925     }
2926     GNUNET_free (data);
2927     return NULL; /* Drop this message */
2928   }
2929
2930   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u\n", c, c->pending_messages);
2931   c->pending_messages++;
2932
2933   q = GNUNET_new (struct MeshConnectionQueue);
2934   q->forced = !droppable;
2935   q->q = GMP_queue_add (get_hop (c, fwd), data, type, size, c, fwd,
2936                         &message_sent, q);
2937   if (NULL == q->q)
2938   {
2939     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING dropping msg on %s\n", GMC_2s (c));
2940     GNUNET_free (data);
2941     GNUNET_free (q);
2942     return NULL;
2943   }
2944   q->cont = cont;
2945   q->cont_cls = cont_cls;
2946   return q;
2947 }
2948
2949
2950 /**
2951  * Cancel a previously sent message while it's in the queue.
2952  *
2953  * ONLY can be called before the continuation given to the send function
2954  * is called. Once the continuation is called, the message is no longer in the
2955  * queue.
2956  *
2957  * @param q Handle to the queue.
2958  */
2959 void
2960 GMC_cancel (struct MeshConnectionQueue *q)
2961 {
2962   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  GMC cancel message\n");
2963
2964   /* queue destroy calls message_sent, which calls q->cont and frees q */
2965   GMP_queue_destroy (q->q, GNUNET_YES);
2966 }
2967
2968
2969 /**
2970  * Sends a CREATE CONNECTION message for a path to a peer.
2971  * Changes the connection and tunnel states if necessary.
2972  *
2973  * @param connection Connection to create.
2974  */
2975 void
2976 GMC_send_create (struct MeshConnection *connection)
2977 {
2978   enum MeshTunnel3CState state;
2979   size_t size;
2980
2981   size = sizeof (struct GNUNET_MESH_ConnectionCreate);
2982   size += connection->path->length * sizeof (struct GNUNET_PeerIdentity);
2983
2984   LOG (GNUNET_ERROR_TYPE_INFO, "Send %s (%u bytes) on connection %s\n",
2985        GM_m2s (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE),
2986        size, GMC_2s (connection));
2987   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u (create)\n",
2988        connection, connection->pending_messages);
2989   connection->pending_messages++;
2990
2991   connection->maintenance_q =
2992     GMP_queue_add (get_next_hop (connection), NULL,
2993                    GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
2994                    size, connection, GNUNET_YES, &message_sent, NULL);
2995
2996   state = GMT_get_cstate (connection->t);
2997   if (MESH_TUNNEL3_SEARCHING == state || MESH_TUNNEL3_NEW == state)
2998     GMT_change_cstate (connection->t, MESH_TUNNEL3_WAITING);
2999   if (MESH_CONNECTION_NEW == connection->state)
3000     connection_change_state (connection, MESH_CONNECTION_SENT);
3001 }
3002
3003
3004 /**
3005  * Send a message to all peers in this connection that the connection
3006  * is no longer valid.
3007  *
3008  * If some peer should not receive the message, it should be zero'ed out
3009  * before calling this function.
3010  *
3011  * @param c The connection whose peers to notify.
3012  */
3013 void
3014 GMC_send_destroy (struct MeshConnection *c)
3015 {
3016   struct GNUNET_MESH_ConnectionDestroy msg;
3017
3018   if (GNUNET_YES == c->destroy)
3019     return;
3020
3021   msg.header.size = htons (sizeof (msg));
3022   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY);;
3023   msg.cid = c->id;
3024   LOG (GNUNET_ERROR_TYPE_DEBUG,
3025               "  sending connection destroy for connection %s\n",
3026               GMC_2s (c));
3027
3028   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_YES))
3029     GMC_send_prebuilt_message (&msg.header, c,
3030                                GNUNET_YES, GNUNET_YES, NULL, NULL);
3031   if (GNUNET_NO == GMC_is_terminal (c, GNUNET_NO))
3032     GMC_send_prebuilt_message (&msg.header, c,
3033                                GNUNET_NO, GNUNET_YES, NULL, NULL);
3034   c->destroy = GNUNET_YES;
3035   c->state = MESH_CONNECTION_DESTROYED;
3036 }
3037
3038
3039 /**
3040  * @brief Start a polling timer for the connection.
3041  *
3042  * When a neighbor does not accept more traffic on the connection it could be
3043  * caused by a simple congestion or by a lost ACK. Polling enables to check
3044  * for the lastest ACK status for a connection.
3045  *
3046  * @param c Connection.
3047  * @param fwd Should we poll in the FWD direction?
3048  */
3049 void
3050 GMC_start_poll (struct MeshConnection *c, int fwd)
3051 {
3052   struct MeshFlowControl *fc;
3053
3054   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3055   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL %s requested\n",
3056        GM_f2s (fwd));
3057   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task || NULL != fc->poll_msg)
3058   {
3059     LOG (GNUNET_ERROR_TYPE_DEBUG, " ***   not needed (%u, %p)\n",
3060          fc->poll_task, fc->poll_msg);
3061     return;
3062   }
3063   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL started on request\n");
3064   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3065                                                 &connection_poll,
3066                                                 fc);
3067 }
3068
3069
3070 /**
3071  * @brief Stop polling a connection for ACKs.
3072  *
3073  * Once we have enough ACKs for future traffic, polls are no longer necessary.
3074  *
3075  * @param c Connection.
3076  * @param fwd Should we stop the poll in the FWD direction?
3077  */
3078 void
3079 GMC_stop_poll (struct MeshConnection *c, int fwd)
3080 {
3081   struct MeshFlowControl *fc;
3082
3083   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3084   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
3085   {
3086     GNUNET_SCHEDULER_cancel (fc->poll_task);
3087     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3088   }
3089 }
3090
3091 /**
3092  * Get a (static) string for a connection.
3093  *
3094  * @param c Connection.
3095  */
3096 const char *
3097 GMC_2s (const struct MeshConnection *c)
3098 {
3099   if (NULL == c)
3100     return "NULL";
3101
3102   if (NULL != c->t)
3103   {
3104     static char buf[128];
3105
3106     sprintf (buf, "%s (->%s)", GNUNET_h2s (&c->id), GMT_2s (c->t));
3107     return buf;
3108   }
3109   return GNUNET_h2s (&c->id);
3110 }