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