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