Eliminated mesh API buffering
[oweals/gnunet.git] / src / mesh / mesh_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
4      GNUnet is free software; you can redistribute it and/or modify
5      it under the terms of the GNU General Public License as published
6      by the Free Software Foundation; either version 3, or (at your
7      option) any later version.
8      GNUnet is distributed in the hope that it will be useful, but
9      WITHOUT ANY WARRANTY; without even the implied warranty of
10      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11      General Public License for more details.
12      You should have received a copy of the GNU General Public License
13      along with GNUnet; see the file COPYING.  If not, write to the
14      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
15      Boston, MA 02111-1307, USA.
16 */
17
18 /**
19  * @file mesh/mesh_api.c
20  * @brief mesh api: client implementation of mesh service
21  * @author Bartlomiej Polot
22  *
23  * STRUCTURE:
24  * - CONSTANTS
25  * - DATA STRUCTURES
26  * - AUXILIARY FUNCTIONS
27  * - RECEIVE HANDLERS
28  * - SEND FUNCTIONS
29  * - API CALL DEFINITIONS
30  *
31  * TODO: add regex to reconnect
32  */
33 #include "platform.h"
34 #include "gnunet_common.h"
35 #include "gnunet_client_lib.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_peer_lib.h"
38 #include "gnunet_mesh_service.h"
39 #include "mesh.h"
40 #include "mesh_protocol.h"
41
42 #define LOG(kind,...) GNUNET_log_from (kind, "mesh-api",__VA_ARGS__)
43
44
45 /******************************************************************************/
46 /************************        CONSTANTS         ****************************/
47 /******************************************************************************/
48
49 #define HIGH_PID 0xFFFF0000
50 #define LOW_PID 0x0000FFFF
51
52 #define PID_OVERFLOW(pid, max) (pid > HIGH_PID && max < LOW_PID)
53
54 /******************************************************************************/
55 /************************      DATA STRUCTURES     ****************************/
56 /******************************************************************************/
57
58 /**
59  * Transmission queue to the service
60  */
61 struct GNUNET_MESH_TransmitHandle
62 {
63
64     /**
65      * Double Linked list
66      */
67   struct GNUNET_MESH_TransmitHandle *next;
68
69     /**
70      * Double Linked list
71      */
72   struct GNUNET_MESH_TransmitHandle *prev;
73
74     /**
75      * Tunnel this message is sent on / for (may be NULL for control messages).
76      */
77   struct GNUNET_MESH_Tunnel *tunnel;
78
79     /**
80      * Callback to obtain the message to transmit, or NULL if we
81      * got the message in 'data'.  Notice that messages built
82      * by 'notify' need to be encapsulated with information about
83      * the 'target'.
84      */
85   GNUNET_CONNECTION_TransmitReadyNotify notify;
86
87     /**
88      * Closure for 'notify'
89      */
90   void *notify_cls;
91
92     /**
93      * How long is this message valid.  Once the timeout has been
94      * reached, the message must no longer be sent.  If this
95      * is a message with a 'notify' callback set, the 'notify'
96      * function should be called with 'buf' NULL and size 0.
97      */
98   struct GNUNET_TIME_Absolute timeout;
99
100     /**
101      * Task triggering a timeout, can be NO_TASK if the timeout is FOREVER.
102      */
103   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
104
105     /**
106      * Priority of the message.  The queue is sorted by priority,
107      * control messages have the maximum priority (UINT32_MAX).
108      */
109   uint32_t priority;
110
111     /**
112      * Target of the message, 0 for multicast.  This field
113      * is only valid if 'notify' is non-NULL.
114      */
115   GNUNET_PEER_Id target;
116
117     /**
118      * Size of 'data' -- or the desired size of 'notify' if 'data' is NULL.
119      */
120   size_t size;
121 };
122
123
124 /**
125  * Opaque handle to the service.
126  */
127 struct GNUNET_MESH_Handle
128 {
129
130     /**
131      * Handle to the server connection, to send messages later
132      */
133   struct GNUNET_CLIENT_Connection *client;
134
135     /**
136      * Set of handlers used for processing incoming messages in the tunnels
137      */
138   const struct GNUNET_MESH_MessageHandler *message_handlers;
139
140     /**
141      * Set of applications that should be claimed to be offered at this node.
142      * Note that this is just informative, the appropiate handlers must be
143      * registered independently and the mapping is up to the developer of the
144      * client application.
145      */
146   const GNUNET_MESH_ApplicationType *applications;
147
148     /**
149      * Double linked list of the tunnels this client is connected to.
150      */
151   struct GNUNET_MESH_Tunnel *tunnels_head;
152   struct GNUNET_MESH_Tunnel *tunnels_tail;
153
154     /**
155      * Callback for inbound tunnel creation
156      */
157   GNUNET_MESH_InboundTunnelNotificationHandler *new_tunnel;
158
159     /**
160      * Callback for inbound tunnel disconnection
161      */
162   GNUNET_MESH_TunnelEndHandler *cleaner;
163
164     /**
165      * Handle to cancel pending transmissions in case of disconnection
166      */
167   struct GNUNET_CLIENT_TransmitHandle *th;
168
169     /**
170      * Closure for all the handlers given by the client
171      */
172   void *cls;
173
174     /**
175      * Messages to send to the service
176      */
177   struct GNUNET_MESH_TransmitHandle *th_head;
178   struct GNUNET_MESH_TransmitHandle *th_tail;
179
180     /**
181      * tid of the next tunnel to create (to avoid reusing IDs often)
182      */
183   MESH_TunnelNumber next_tid;
184   unsigned int n_handlers;
185   unsigned int n_applications;
186   unsigned int max_queue_size;
187
188     /**
189      * Have we started the task to receive messages from the service
190      * yet? We do this after we send the 'MESH_LOCAL_CONNECT' message.
191      */
192   int in_receive;
193
194     /**
195      * Number of packets queued
196      */
197   unsigned int npackets;
198
199   /**
200    * Configuration given by the client, in case of reconnection
201    */
202   const struct GNUNET_CONFIGURATION_Handle *cfg;
203
204   /**
205    * Time to the next reconnect in case one reconnect fails
206    */
207   struct GNUNET_TIME_Relative reconnect_time;
208   
209   /**
210    * Task for trying to reconnect.
211    */
212   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
213 };
214
215
216 /**
217  * Description of a peer
218  */
219 struct GNUNET_MESH_Peer
220 {
221     /**
222      * ID of the peer in short form
223      */
224   GNUNET_PEER_Id id;
225
226   /**
227    * Tunnel this peer belongs to
228    */
229   struct GNUNET_MESH_Tunnel *t;
230
231   /**
232    * Flag indicating whether service has informed about its connection
233    */
234   int connected;
235
236 };
237
238
239 /**
240  * Opaque handle to a tunnel.
241  */
242 struct GNUNET_MESH_Tunnel
243 {
244
245     /**
246      * DLL next
247      */
248   struct GNUNET_MESH_Tunnel *next;
249
250     /**
251      * DLL prev
252      */
253   struct GNUNET_MESH_Tunnel *prev;
254
255     /**
256      * Callback to execute when peers connect to the tunnel
257      */
258   GNUNET_MESH_PeerConnectHandler connect_handler;
259
260     /**
261      * Callback to execute when peers disconnect from the tunnel
262      */
263   GNUNET_MESH_PeerDisconnectHandler disconnect_handler;
264
265     /**
266      * Closure for the connect/disconnect handlers
267      */
268   void *cls;
269
270     /**
271      * Handle to the mesh this tunnel belongs to
272      */
273   struct GNUNET_MESH_Handle *mesh;
274
275     /**
276      * Local ID of the tunnel
277      */
278   MESH_TunnelNumber tid;
279
280     /**
281      * Owner of the tunnel. 0 if the tunnel is the local client.
282      */
283   GNUNET_PEER_Id owner;
284
285     /**
286      * All peers added to the tunnel
287      */
288   struct GNUNET_MESH_Peer **peers;
289
290   /**
291    * List of application types that have been requested for this tunnel
292    */
293   GNUNET_MESH_ApplicationType *apps;
294
295   /**
296    * Any data the caller wants to put in here
297    */
298   void *ctx;
299
300   /**
301      * Number of peers added to the tunnel
302      */
303   unsigned int npeers;
304
305     /**
306      * Number of packets queued in this tunnel
307      */
308   unsigned int npackets;
309
310     /**
311      * Number of applications requested this tunnel
312      */
313   unsigned int napps;
314
315     /**
316      * Is the tunnel throttled to the slowest peer?
317      */
318   int speed_min;
319
320     /**
321      * Is the tunnel allowed to buffer?
322      */
323   int buffering;
324
325     /**
326      * Next packet PID.
327      */
328   uint32_t pid;
329
330     /**
331      * Maximum allowed PID.
332      */
333   uint32_t max_pid;
334
335
336 };
337
338
339 /******************************************************************************/
340 /***********************     AUXILIARY FUNCTIONS      *************************/
341 /******************************************************************************/
342
343 /**
344  * Get the tunnel handler for the tunnel specified by id from the given handle
345  * @param h Mesh handle
346  * @param tid ID of the wanted tunnel
347  * @return handle to the required tunnel or NULL if not found
348  */
349 static struct GNUNET_MESH_Tunnel *
350 retrieve_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
351 {
352   struct GNUNET_MESH_Tunnel *t;
353
354   t = h->tunnels_head;
355   while (t != NULL)
356   {
357     if (t->tid == tid)
358       return t;
359     t = t->next;
360   }
361   return NULL;
362 }
363
364
365 /**
366  * Create a new tunnel and insert it in the tunnel list of the mesh handle
367  * @param h Mesh handle
368  * @param tid desired tid of the tunnel, 0 to assign one automatically
369  * @return handle to the created tunnel
370  */
371 static struct GNUNET_MESH_Tunnel *
372 create_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
373 {
374   struct GNUNET_MESH_Tunnel *t;
375
376   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
377   GNUNET_CONTAINER_DLL_insert (h->tunnels_head, h->tunnels_tail, t);
378   t->mesh = h;
379   if (0 == tid)
380   {
381     t->tid = h->next_tid;
382     while (NULL != retrieve_tunnel (h, h->next_tid))
383     {
384       h->next_tid++;
385       h->next_tid &= ~GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
386       h->next_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
387     }
388   }
389   else
390   {
391     t->tid = tid;
392   }
393   return t;
394 }
395
396
397 /**
398  * Destroy the specified tunnel.
399  * - Destroys all peers, calling the disconnect callback on each if needed
400  * - Cancels all outgoing traffic for that tunnel, calling respective notifys
401  * - Calls cleaner if tunnel was inbound
402  * - Frees all memory used
403  *
404  * @param t Pointer to the tunnel.
405  * @param call_cleaner Whether to call the cleaner handler.
406  *
407  * @return Handle to the required tunnel or NULL if not found.
408  */
409 static void
410 destroy_tunnel (struct GNUNET_MESH_Tunnel *t, int call_cleaner)
411 {
412   struct GNUNET_MESH_Handle *h;
413   struct GNUNET_PeerIdentity pi;
414   struct GNUNET_MESH_TransmitHandle *th;
415   struct GNUNET_MESH_TransmitHandle *next;
416   unsigned int i;
417
418   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroy_tunnel %X\n", t->tid);
419
420   if (NULL == t)
421   {
422     GNUNET_break (0);
423     return;
424   }
425   h = t->mesh;
426
427   /* disconnect all peers */
428   GNUNET_CONTAINER_DLL_remove (h->tunnels_head, h->tunnels_tail, t);
429   for (i = 0; i < t->npeers; i++)
430   {
431     if ( (NULL != t->disconnect_handler) && t->peers[i]->connected)
432     {
433       GNUNET_PEER_resolve (t->peers[i]->id, &pi);
434       t->disconnect_handler (t->cls, &pi);
435     }
436     GNUNET_PEER_change_rc (t->peers[i]->id, -1);
437     GNUNET_free (t->peers[i]);
438   }
439
440   /* signal tunnel destruction */
441   if ( (NULL != h->cleaner) && (0 != t->owner) && (GNUNET_YES == call_cleaner) )
442     h->cleaner (h->cls, t, t->ctx);
443
444   /* check that clients did not leave messages behind in the queue */
445   for (th = h->th_head; NULL != th; th = next)
446   {
447     next = th->next;
448     if (th->tunnel != t)
449       continue;
450     /* Clients should have aborted their requests already.
451      * Management traffic should be ok, as clients can't cancel that */
452     GNUNET_break (NULL == th->notify);
453     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
454
455     /* clean up request */
456     if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
457       GNUNET_SCHEDULER_cancel (th->timeout_task);
458     GNUNET_free (th);    
459   }
460
461   /* if there are no more pending requests with mesh service, cancel active request */
462   /* Note: this should be unnecessary... */
463   if ( (NULL == h->th_head) && (NULL != h->th))
464   {
465     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
466     h->th = NULL;
467   }
468
469
470   if (t->npeers > 0)
471     GNUNET_free (t->peers);
472   if (0 != t->owner)
473     GNUNET_PEER_change_rc (t->owner, -1);
474   if (0 != t->napps && t->apps)
475     GNUNET_free (t->apps);
476   GNUNET_free (t);
477   return;
478 }
479
480
481 /**
482  * Get the peer descriptor for the peer with id from the given tunnel
483  * @param t Tunnel handle
484  * @param id Short form ID of the wanted peer
485  * @return handle to the requested peer or NULL if not found
486  */
487 static struct GNUNET_MESH_Peer *
488 retrieve_peer (struct GNUNET_MESH_Tunnel *t, GNUNET_PEER_Id id)
489 {
490   unsigned int i;
491
492   for (i = 0; i < t->npeers; i++)
493     if (t->peers[i]->id == id)
494       return t->peers[i];
495   return NULL;
496 }
497
498
499 /**
500  * Add a peer into a tunnel
501  * @param t Tunnel handle
502  * @param pi Full ID of the new peer
503  * @return handle to the newly created peer
504  */
505 static struct GNUNET_MESH_Peer *
506 add_peer_to_tunnel (struct GNUNET_MESH_Tunnel *t,
507                     const struct GNUNET_PeerIdentity *pi)
508 {
509   struct GNUNET_MESH_Peer *p;
510   GNUNET_PEER_Id id;
511
512   if (0 != t->owner)
513   {
514     GNUNET_break (0);
515     return NULL;
516   }
517   id = GNUNET_PEER_intern (pi);
518
519   p = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer));
520   p->id = id;
521   p->t = t;
522   GNUNET_array_append (t->peers, t->npeers, p);
523   return p;
524 }
525
526
527 /**
528  * Remove a peer from a tunnel
529  * @param p Peer handle
530  */
531 static void
532 remove_peer_from_tunnel (struct GNUNET_MESH_Peer *p)
533 {
534   unsigned int i;
535
536   for (i = 0; i < p->t->npeers; i++)
537   {
538     if (p->t->peers[i] == p)
539       break;
540   }
541   if (i == p->t->npeers)
542   {
543     GNUNET_break (0);
544     return;
545   }
546   p->t->peers[i] = p->t->peers[p->t->npeers - 1];
547   GNUNET_array_grow (p->t->peers, p->t->npeers, p->t->npeers - 1);
548 }
549
550
551 /**
552  * Notify client that the transmission has timed out
553  * @param cls closure
554  * @param tc task context
555  */
556 static void
557 timeout_transmission (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
558 {
559   struct GNUNET_MESH_TransmitHandle *th = cls;
560   struct GNUNET_MESH_Handle *mesh;
561
562   mesh = th->tunnel->mesh;
563   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
564   if (th->notify != NULL)
565     th->notify (th->notify_cls, 0, NULL);
566   GNUNET_free (th);
567   if ((NULL == mesh->th_head) && (NULL != mesh->th))
568   {
569     /* queue empty, no point in asking for transmission */
570     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
571     mesh->th = NULL;
572   }
573 }
574
575
576 /**
577  * Add a transmit handle to the transmission queue by priority and set the
578  * timeout if needed.
579  *
580  * @param h mesh handle with the queue head and tail
581  * @param th handle to the packet to be transmitted
582  */
583 static void
584 add_to_queue (struct GNUNET_MESH_Handle *h,
585               struct GNUNET_MESH_TransmitHandle *th)
586 {
587   struct GNUNET_MESH_TransmitHandle *p;
588
589   p = h->th_head;
590   while ((NULL != p) && (th->priority <= p->priority))
591     p = p->next;
592   if (NULL == p)
593     p = h->th_tail;
594   else
595     p = p->prev;
596   GNUNET_CONTAINER_DLL_insert_after (h->th_head, h->th_tail, p, th);
597   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value == th->timeout.abs_value)
598     return;
599   th->timeout_task =
600       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
601                                     (th->timeout), &timeout_transmission, th);
602 }
603
604
605 /**
606  * Auxiliary function to send an already constructed packet to the service.
607  * Takes care of creating a new queue element, copying the message and
608  * calling the tmt_rdy function if necessary.
609  *
610  * @param h mesh handle
611  * @param msg message to transmit
612  * @param tunnel tunnel this send is related to (NULL if N/A)
613  */
614 static void
615 send_packet (struct GNUNET_MESH_Handle *h,
616              const struct GNUNET_MessageHeader *msg,
617              struct GNUNET_MESH_Tunnel *tunnel);
618
619
620 /**
621  * Reconnect callback: tries to reconnect again after a failer previous
622  * reconnecttion
623  * @param cls closure (mesh handle)
624  * @param tc task context
625  */
626 static void
627 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
628
629
630 /**
631  * Send a connect packet to the service with the applications and types
632  * requested by the user.
633  *
634  * @param h The mesh handle.
635  *
636  */
637 static void
638 send_connect (struct GNUNET_MESH_Handle *h)
639 {
640   size_t size;
641
642   size = sizeof (struct GNUNET_MESH_ClientConnect);
643   size += h->n_applications * sizeof (GNUNET_MESH_ApplicationType);
644   size += h->n_handlers * sizeof (uint16_t);
645   {
646     char buf[size] GNUNET_ALIGN;
647     struct GNUNET_MESH_ClientConnect *msg;
648     GNUNET_MESH_ApplicationType *apps;
649     uint16_t napps;
650     uint16_t *types;
651     uint16_t ntypes;
652
653     /* build connection packet */
654     msg = (struct GNUNET_MESH_ClientConnect *) buf;
655     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT);
656     msg->header.size = htons (size);
657     apps = (GNUNET_MESH_ApplicationType *) &msg[1];
658     for (napps = 0; napps < h->n_applications; napps++)
659     {
660       apps[napps] = htonl (h->applications[napps]);
661       LOG (GNUNET_ERROR_TYPE_DEBUG, " app %u\n", h->applications[napps]);
662     }
663     types = (uint16_t *) & apps[napps];
664     for (ntypes = 0; ntypes < h->n_handlers; ntypes++)
665       types[ntypes] = htons (h->message_handlers[ntypes].type);
666     msg->applications = htons (napps);
667     msg->types = htons (ntypes);
668     LOG (GNUNET_ERROR_TYPE_DEBUG,
669          "Sending %lu bytes long message %d types and %d apps\n",
670          ntohs (msg->header.size), ntypes, napps);
671     send_packet (h, &msg->header, NULL);
672   }
673 }
674
675
676 /**
677  * Reconnect to the service, retransmit all infomation to try to restore the
678  * original state.
679  *
680  * @param h handle to the mesh
681  *
682  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
683  */
684 static int
685 do_reconnect (struct GNUNET_MESH_Handle *h)
686 {
687   struct GNUNET_MESH_Tunnel *t;
688   unsigned int i;
689
690   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
691   LOG (GNUNET_ERROR_TYPE_DEBUG, "*******   RECONNECT   *******\n");
692   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
693
694   h->in_receive = GNUNET_NO;
695   /* disconnect */
696   if (NULL != h->th)
697   {
698     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
699     h->th = NULL;
700   }
701   if (NULL != h->client)
702   {
703     GNUNET_CLIENT_disconnect (h->client);
704   }
705
706   /* connect again */
707   h->client = GNUNET_CLIENT_connect ("mesh", h->cfg);
708   if (h->client == NULL)
709   {
710     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
711                                                       &reconnect_cbk, h);
712     h->reconnect_time =
713         GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
714                                   GNUNET_TIME_relative_multiply
715                                   (h->reconnect_time, 2));
716     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Next retry in %sms\n",
717          GNUNET_TIME_relative_to_string (h->reconnect_time));
718     GNUNET_break (0);
719     return GNUNET_NO;
720   }
721   else
722   {
723     h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
724   }
725   send_connect (h);
726   /* Rebuild all tunnels */
727   for (t = h->tunnels_head; NULL != t; t = t->next)
728   {
729     struct GNUNET_MESH_TunnelMessage tmsg;
730     struct GNUNET_MESH_PeerControl pmsg;
731
732     if (t->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
733     {
734       /* Tunnel was created by service (incoming tunnel) */
735       /* TODO: Notify service of missing tunnel, to request
736        * creator to recreate path (find a path to him via DHT?)
737        */
738       continue;
739     }
740     tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
741     tmsg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
742     tmsg.tunnel_id = htonl (t->tid);
743     send_packet (h, &tmsg.header, t);
744
745     pmsg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
746     pmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
747     pmsg.tunnel_id = htonl (t->tid);
748
749     /* Reconnect all peers */
750     /* If the tunnel was "by type", dont connect individual peers */
751     for (i = 0; i < t->npeers && 0 == t->napps; i++)
752     {
753       GNUNET_PEER_resolve (t->peers[i]->id, &pmsg.peer);
754       if (NULL != t->disconnect_handler && t->peers[i]->connected)
755         t->disconnect_handler (t->cls, &pmsg.peer);
756       send_packet (t->mesh, &pmsg.header, t);
757     }
758     /* Reconnect all types, if any  */
759     for (i = 0; i < t->napps; i++)
760     {
761       struct GNUNET_MESH_ConnectPeerByType msg;
762
763       msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
764       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE);
765       msg.tunnel_id = htonl (t->tid);
766       msg.type = htonl (t->apps[i]);
767       send_packet (t->mesh, &msg.header, t);
768     }
769     if (GNUNET_NO == t->buffering)
770       GNUNET_MESH_tunnel_buffer (t, GNUNET_NO);
771     if (GNUNET_YES == t->speed_min)
772       GNUNET_MESH_tunnel_speed_min (t);
773   }
774   return GNUNET_YES;
775 }
776
777 /**
778  * Reconnect callback: tries to reconnect again after a failer previous
779  * reconnecttion
780  * @param cls closure (mesh handle)
781  * @param tc task context
782  */
783 static void
784 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
785 {
786   struct GNUNET_MESH_Handle *h = cls;
787
788   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
789   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
790     return;
791   do_reconnect (h);
792 }
793
794
795 /**
796  * Reconnect to the service, retransmit all infomation to try to restore the
797  * original state.
798  *
799  * @param h handle to the mesh
800  *
801  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
802  */
803 static void
804 reconnect (struct GNUNET_MESH_Handle *h)
805 {
806   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requested RECONNECT\n");
807   if (GNUNET_SCHEDULER_NO_TASK == h->reconnect_task)
808     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
809                                                       &reconnect_cbk, h);
810 }
811
812
813 /******************************************************************************/
814 /***********************      RECEIVE HANDLERS     ****************************/
815 /******************************************************************************/
816
817 /**
818  * Process the new tunnel notification and add it to the tunnels in the handle
819  *
820  * @param h     The mesh handle
821  * @param msg   A message with the details of the new incoming tunnel
822  */
823 static void
824 process_tunnel_created (struct GNUNET_MESH_Handle *h,
825                         const struct GNUNET_MESH_TunnelNotification *msg)
826 {
827   struct GNUNET_MESH_Tunnel *t;
828   MESH_TunnelNumber tid;
829
830   tid = ntohl (msg->tunnel_id);
831   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
832   {
833     GNUNET_break (0);
834     return;
835   }
836   if (NULL != h->new_tunnel)
837   {
838     struct GNUNET_ATS_Information atsi;
839
840     t = create_tunnel (h, tid);
841     t->owner = GNUNET_PEER_intern (&msg->peer);
842     t->npeers = 1;
843     t->peers = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer *));
844     t->peers[0] = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer));
845     t->peers[0]->t = t;
846     t->peers[0]->connected = 1;
847     t->peers[0]->id = t->owner;
848     GNUNET_PEER_change_rc (t->owner, 1);
849     t->mesh = h;
850     t->tid = tid;
851     atsi.type = 0;
852     atsi.value = 0;
853     t->ctx = h->new_tunnel (h->cls, t, &msg->peer, &atsi);
854     LOG (GNUNET_ERROR_TYPE_DEBUG, "new incoming tunnel %X\n", t->tid);
855   }
856   else
857   {
858     struct GNUNET_MESH_TunnelMessage d_msg;
859
860     LOG (GNUNET_ERROR_TYPE_DEBUG, "No handler for incoming tunnels\n");
861
862     d_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
863     d_msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
864     d_msg.tunnel_id = msg->tunnel_id;
865
866     send_packet (h, &d_msg.header, NULL);
867   }
868   return;
869 }
870
871
872 /**
873  * Process the tunnel destroy notification and free associated resources
874  *
875  * @param h     The mesh handle
876  * @param msg   A message with the details of the tunnel being destroyed
877  */
878 static void
879 process_tunnel_destroy (struct GNUNET_MESH_Handle *h,
880                         const struct GNUNET_MESH_TunnelMessage *msg)
881 {
882   struct GNUNET_MESH_Tunnel *t;
883   MESH_TunnelNumber tid;
884
885   tid = ntohl (msg->tunnel_id);
886   t = retrieve_tunnel (h, tid);
887
888   if (NULL == t)
889   {
890     return;
891   }
892   if (0 == t->owner)
893   {
894     GNUNET_break (0);
895   }
896   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X destroyed\n", t->tid);
897   destroy_tunnel (t, GNUNET_YES);
898   return;
899 }
900
901
902 /**
903  * Process the new peer event and notify the upper level of it
904  *
905  * @param h     The mesh handle
906  * @param msg   A message with the details of the peer event
907  */
908 static void
909 process_peer_event (struct GNUNET_MESH_Handle *h,
910                     const struct GNUNET_MESH_PeerControl *msg)
911 {
912   struct GNUNET_MESH_Tunnel *t;
913   struct GNUNET_MESH_Peer *p;
914   struct GNUNET_ATS_Information atsi;
915   GNUNET_PEER_Id id;
916   uint16_t size;
917
918   LOG (GNUNET_ERROR_TYPE_DEBUG, "processig peer event\n");
919   size = ntohs (msg->header.size);
920   if (size != sizeof (struct GNUNET_MESH_PeerControl))
921   {
922     GNUNET_break (0);
923     return;
924   }
925   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
926   if (NULL == t)
927   {
928     GNUNET_break (0);
929     return;
930   }
931   id = GNUNET_PEER_search (&msg->peer);
932   if ((p = retrieve_peer (t, id)) == NULL)
933     p = add_peer_to_tunnel (t, &msg->peer);
934   if (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD == ntohs (msg->header.type))
935   {
936     LOG (GNUNET_ERROR_TYPE_DEBUG, "adding peer\n");
937     if (NULL != t->connect_handler)
938     {
939       atsi.type = 0;
940       atsi.value = 0;
941       t->connect_handler (t->cls, &msg->peer, &atsi);
942     }
943     p->connected = 1;
944   }
945   else
946   {
947     LOG (GNUNET_ERROR_TYPE_DEBUG, "removing peer\n");
948     if (NULL != t->disconnect_handler && p->connected)
949     {
950       t->disconnect_handler (t->cls, &msg->peer);
951     }
952     remove_peer_from_tunnel (p);
953     GNUNET_free (p);
954   }
955   LOG (GNUNET_ERROR_TYPE_DEBUG, "processing peer event END\n");
956 }
957
958
959 /**
960  * Process the incoming data packets
961  *
962  * @param h         The mesh handle
963  * @param message   A message encapsulating the data
964  * 
965  * @return GNUNET_YES if everything went fine
966  *         GNUNET_NO if client closed connection (h no longer valid)
967  */
968 static int
969 process_incoming_data (struct GNUNET_MESH_Handle *h,
970                        const struct GNUNET_MessageHeader *message)
971 {
972   const struct GNUNET_MessageHeader *payload;
973   const struct GNUNET_MESH_MessageHandler *handler;
974   const struct GNUNET_PeerIdentity *peer;
975   struct GNUNET_MESH_Unicast *ucast;
976   struct GNUNET_MESH_Multicast *mcast;
977   struct GNUNET_MESH_ToOrigin *to_orig;
978   struct GNUNET_MESH_Tunnel *t;
979   unsigned int i;
980   uint16_t type;
981
982   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a data message!\n");
983   type = ntohs (message->type);
984   switch (type)
985   {
986   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
987     ucast = (struct GNUNET_MESH_Unicast *) message;
988
989     t = retrieve_tunnel (h, ntohl (ucast->tid));
990     payload = (struct GNUNET_MessageHeader *) &ucast[1];
991     peer = &ucast->oid;
992     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ucast on tunnel %s [%X]\n",
993          GNUNET_i2s (peer), ntohl (ucast->tid));
994     break;
995   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
996     mcast = (struct GNUNET_MESH_Multicast *) message;
997     t = retrieve_tunnel (h, ntohl (mcast->tid));
998     payload = (struct GNUNET_MessageHeader *) &mcast[1];
999     peer = &mcast->oid;
1000     LOG (GNUNET_ERROR_TYPE_DEBUG, "  mcast on tunnel %s [%X]\n",
1001          GNUNET_i2s (peer), ntohl (mcast->tid));
1002     break;
1003   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1004     to_orig = (struct GNUNET_MESH_ToOrigin *) message;
1005     t = retrieve_tunnel (h, ntohl (to_orig->tid));
1006     payload = (struct GNUNET_MessageHeader *) &to_orig[1];
1007     peer = &to_orig->sender;
1008     LOG (GNUNET_ERROR_TYPE_DEBUG, "  torig on tunnel %s [%X]\n",
1009          GNUNET_i2s (peer), ntohl (to_orig->tid));
1010     break;
1011   default:
1012     GNUNET_break (0);
1013     return GNUNET_YES;
1014   }
1015   if (NULL == t)
1016   {
1017     /* Tunnel was ignored, probably service didn't get it yet */
1018     return GNUNET_YES;
1019   }
1020   type = ntohs (payload->type);
1021   for (i = 0; i < h->n_handlers; i++)
1022   {
1023     handler = &h->message_handlers[i];
1024     if (handler->type == type)
1025     {
1026       struct GNUNET_ATS_Information atsi;
1027
1028       atsi.type = 0;
1029       atsi.value = 0;
1030       if (GNUNET_OK !=
1031           handler->callback (h->cls, t, &t->ctx, peer, payload, &atsi))
1032       {
1033         LOG (GNUNET_ERROR_TYPE_DEBUG, "callback caused disconnection\n");
1034         GNUNET_MESH_disconnect (h);
1035         return GNUNET_NO;
1036       }
1037       else
1038       {
1039         LOG (GNUNET_ERROR_TYPE_DEBUG,
1040              "callback completed successfully\n");
1041       }
1042     }
1043   }
1044   return GNUNET_YES;
1045 }
1046
1047
1048 /**
1049  * Process a local ACK message, enabling the client to send
1050  * more data to the service.
1051  * 
1052  * @param h Mesh handle.
1053  * @param message Message itself.
1054  */
1055 static void
1056 process_ack (struct GNUNET_MESH_Handle *h,
1057              const struct GNUNET_MessageHeader *message)
1058 {
1059   struct GNUNET_MESH_LocalAck *msg;
1060   struct GNUNET_MESH_Tunnel *t;
1061   uint32_t ack;
1062
1063   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK!\n");
1064   msg = (struct GNUNET_MESH_LocalAck *) message;
1065
1066   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
1067
1068   if (NULL == t)
1069   {
1070     LOG (GNUNET_ERROR_TYPE_WARNING,
1071          "ACK on unknown tunnel %X\n",
1072          ntohl (msg->tunnel_id));
1073     return;
1074   }
1075   ack = ntohl (msg->max_pid);
1076   if (ack > t->max_pid || PID_OVERFLOW (t->max_pid, ack))
1077     t->max_pid = ack;
1078 }
1079
1080
1081 /**
1082  * Function to process all messages received from the service
1083  *
1084  * @param cls closure
1085  * @param msg message received, NULL on timeout or fatal error
1086  */
1087 static void
1088 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
1089 {
1090   struct GNUNET_MESH_Handle *h = cls;
1091
1092   if (msg == NULL)
1093   {
1094     LOG (GNUNET_ERROR_TYPE_DEBUG, "Received NULL msg\n");
1095     reconnect (h);
1096     return;
1097   }
1098   LOG (GNUNET_ERROR_TYPE_DEBUG, "received a message type %hu from MESH\n",
1099        ntohs (msg->type));
1100   switch (ntohs (msg->type))
1101   {
1102     /* Notify of a new incoming tunnel */
1103   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE:
1104     process_tunnel_created (h, (struct GNUNET_MESH_TunnelNotification *) msg);
1105     break;
1106     /* Notify of a tunnel disconnection */
1107   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1108     process_tunnel_destroy (h, (struct GNUNET_MESH_TunnelMessage *) msg);
1109     break;
1110     /* Notify of a new peer or a peer disconnect in the tunnel */
1111   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD:
1112   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL:
1113     process_peer_event (h, (struct GNUNET_MESH_PeerControl *) msg);
1114     break;
1115     /* Notify of a new data packet in the tunnel */
1116   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1117   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1118   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1119     if (GNUNET_NO == process_incoming_data (h, msg))
1120       return;
1121     break;
1122   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
1123     process_ack (h, msg);
1124     break;
1125   default:
1126     /* We shouldn't get any other packages, log and ignore */
1127     LOG (GNUNET_ERROR_TYPE_WARNING,
1128          "unsolicited message form service (type %d)\n",
1129          ntohs (msg->type));
1130   }
1131   LOG (GNUNET_ERROR_TYPE_DEBUG, "message processed\n");
1132   GNUNET_CLIENT_receive (h->client, &msg_received, h,
1133                          GNUNET_TIME_UNIT_FOREVER_REL);
1134 }
1135
1136
1137 /******************************************************************************/
1138 /************************       SEND FUNCTIONS     ****************************/
1139 /******************************************************************************/
1140
1141 /**
1142  * Function called to send a message to the service.
1143  * "buf" will be NULL and "size" zero if the socket was closed for writing in
1144  * the meantime.
1145  *
1146  * @param cls closure, the mesh handle
1147  * @param size number of bytes available in buf
1148  * @param buf where the callee should write the connect message
1149  * @return number of bytes written to buf
1150  */
1151 static size_t
1152 send_callback (void *cls, size_t size, void *buf)
1153 {
1154   struct GNUNET_MESH_Handle *h = cls;
1155   struct GNUNET_MESH_TransmitHandle *th;
1156   char *cbuf = buf;
1157   size_t tsize;
1158   size_t psize;
1159
1160   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send packet() Buffer %u\n", size);
1161   h->th = NULL;
1162   if ((0 == size) || (NULL == buf))
1163   {
1164     LOG (GNUNET_ERROR_TYPE_DEBUG, "Received NULL callback\n");
1165     reconnect (h);
1166     return 0;
1167   }
1168   tsize = 0;
1169   while ((NULL != (th = h->th_head)) && (size >= th->size))
1170   {
1171     if (NULL != th->notify)
1172     {
1173       if (th->tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1174       {
1175         /* traffic to origin */
1176         struct GNUNET_MESH_ToOrigin to;
1177         struct GNUNET_MessageHeader *mh;
1178
1179         GNUNET_assert (size >= th->size);
1180         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (to)];
1181         psize = th->notify (th->notify_cls, size - sizeof (to), mh);
1182         LOG (GNUNET_ERROR_TYPE_DEBUG, "  to origin, type %u\n",
1183              ntohs (mh->type));
1184         if (psize > 0)
1185         {
1186           psize += sizeof (to);
1187           GNUNET_assert (size >= psize);
1188           to.header.size = htons (psize);
1189           to.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
1190           to.tid = htonl (th->tunnel->tid);
1191           memset (&to.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1192           memset (&to.sender, 0, sizeof (struct GNUNET_PeerIdentity));
1193           memcpy (cbuf, &to, sizeof (to));
1194         }
1195       }
1196       else if (th->target == 0)
1197       {
1198         /* multicast */
1199         struct GNUNET_MESH_Multicast mc;
1200         struct GNUNET_MessageHeader *mh;
1201
1202         GNUNET_assert (size >= th->size);
1203         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (mc)];
1204         psize = th->notify (th->notify_cls, size - sizeof (mc), mh);
1205         LOG (GNUNET_ERROR_TYPE_DEBUG, "  multicast, type %u\n",
1206              ntohs (mh->type));
1207         if (psize > 0)
1208         {
1209           psize += sizeof (mc);
1210           GNUNET_assert (size >= psize);
1211           mc.header.size = htons (psize);
1212           mc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1213           mc.tid = htonl (th->tunnel->tid);
1214           mc.pid = 0;
1215           mc.ttl = 0;
1216           memset (&mc.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1217           memcpy (cbuf, &mc, sizeof (mc));
1218         }
1219       }
1220       else
1221       {
1222         /* unicast */
1223         struct GNUNET_MESH_Unicast uc;
1224         struct GNUNET_MessageHeader *mh;
1225
1226         GNUNET_assert (size >= th->size);
1227         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (uc)];
1228         psize = th->notify (th->notify_cls, size - sizeof (uc), mh);
1229         LOG (GNUNET_ERROR_TYPE_DEBUG, "  unicast, type %u\n",
1230              ntohs (mh->type));
1231         if (psize > 0)
1232         {
1233           psize += sizeof (uc);
1234           GNUNET_assert (size >= psize);
1235           uc.header.size = htons (psize);
1236           uc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1237           uc.tid = htonl (th->tunnel->tid);
1238           memset (&uc.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1239           GNUNET_PEER_resolve (th->target, &uc.destination);
1240           memcpy (cbuf, &uc, sizeof (uc));
1241         }
1242       }
1243     }
1244     else
1245     {
1246       struct GNUNET_MessageHeader *mh = (struct GNUNET_MessageHeader *) &th[1];
1247       LOG (GNUNET_ERROR_TYPE_DEBUG, "  mesh traffic, type %u\n",
1248              ntohs (mh->type));
1249       memcpy (cbuf, &th[1], th->size);
1250       psize = th->size;
1251     }
1252     if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1253       GNUNET_SCHEDULER_cancel (th->timeout_task);
1254     if (NULL != th->notify)
1255     {
1256       th->tunnel->mesh->npackets--;
1257       th->tunnel->npackets--;
1258     }
1259     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1260     GNUNET_free (th);
1261     cbuf += psize;
1262     size -= psize;
1263     tsize += psize;
1264   }
1265   LOG (GNUNET_ERROR_TYPE_DEBUG, "  total size: %u\n", tsize);
1266   if (NULL != (th = h->th_head))
1267   {
1268     LOG (GNUNET_ERROR_TYPE_DEBUG, "  next size: %u\n", th->size);
1269     if (NULL == h->th)
1270       h->th =
1271           GNUNET_CLIENT_notify_transmit_ready (h->client, th->size,
1272                                                GNUNET_TIME_UNIT_FOREVER_REL,
1273                                                GNUNET_YES, &send_callback, h);
1274   }
1275   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send packet() END\n");
1276   if (GNUNET_NO == h->in_receive)
1277   {
1278     h->in_receive = GNUNET_YES;
1279     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1280                            GNUNET_TIME_UNIT_FOREVER_REL);
1281   }
1282   return tsize;
1283 }
1284
1285
1286 /**
1287  * Auxiliary function to send an already constructed packet to the service.
1288  * Takes care of creating a new queue element, copying the message and
1289  * calling the tmt_rdy function if necessary.
1290  * 
1291  * @param h mesh handle
1292  * @param msg message to transmit
1293  * @param tunnel tunnel this send is related to (NULL if N/A)
1294  */
1295 static void
1296 send_packet (struct GNUNET_MESH_Handle *h,
1297              const struct GNUNET_MessageHeader *msg,
1298              struct GNUNET_MESH_Tunnel *tunnel)
1299 {
1300   struct GNUNET_MESH_TransmitHandle *th;
1301   size_t msize;
1302
1303   msize = ntohs (msg->size);
1304   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle) + msize);
1305   th->priority = UINT32_MAX;
1306   th->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1307   th->size = msize;
1308   th->tunnel = tunnel;
1309   memcpy (&th[1], msg, msize);
1310   add_to_queue (h, th);
1311   if (NULL != h->th)
1312     return;
1313   h->th =
1314       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
1315                                            GNUNET_TIME_UNIT_FOREVER_REL,
1316                                            GNUNET_YES, &send_callback, h);
1317 }
1318
1319
1320 /******************************************************************************/
1321 /**********************      API CALL DEFINITIONS     *************************/
1322 /******************************************************************************/
1323
1324 /**
1325  * Connect to the mesh service.
1326  *
1327  * @param cfg configuration to use
1328  * @param cls closure for the various callbacks that follow
1329  *            (including handlers in the handlers array)
1330  * @param new_tunnel function called when an *inbound* tunnel is created
1331  * @param cleaner function called when an *inbound* tunnel is destroyed by the
1332  *                remote peer, it is *not* called if GNUNET_MESH_tunnel_destroy
1333  *                is called on the tunnel
1334  * @param handlers callbacks for messages we care about, NULL-terminated
1335  *                note that the mesh is allowed to drop notifications about
1336  *                inbound messages if the client does not process them fast
1337  *                enough (for this notification type, a bounded queue is used)
1338  * @param stypes list of the applications that this client claims to provide
1339  * @return handle to the mesh service NULL on error
1340  *         (in this case, init is never called)
1341  */
1342 struct GNUNET_MESH_Handle *
1343 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, void *cls,
1344                      GNUNET_MESH_InboundTunnelNotificationHandler new_tunnel,
1345                      GNUNET_MESH_TunnelEndHandler cleaner,
1346                      const struct GNUNET_MESH_MessageHandler *handlers,
1347                      const GNUNET_MESH_ApplicationType *stypes)
1348 {
1349   struct GNUNET_MESH_Handle *h;
1350
1351   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect()\n");
1352   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
1353   h->cfg = cfg;
1354   h->new_tunnel = new_tunnel;
1355   h->cleaner = cleaner;
1356   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
1357   if (h->client == NULL)
1358   {
1359     GNUNET_break (0);
1360     GNUNET_free (h);
1361     return NULL;
1362   }
1363   h->cls = cls;
1364   /* FIXME memdup? */
1365   h->applications = stypes;
1366   h->message_handlers = handlers;
1367   h->next_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
1368   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1369   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1370
1371   /* count handlers and apps, calculate size */
1372   for (h->n_applications = 0; stypes[h->n_applications]; h->n_applications++) ;
1373   for (h->n_handlers = 0; handlers[h->n_handlers].type; h->n_handlers++) ;
1374   send_connect (h);
1375   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect() END\n");
1376   return h;
1377 }
1378
1379
1380 /**
1381  * Disconnect from the mesh service. All tunnels will be destroyed. All tunnel
1382  * disconnect callbacks will be called on any still connected peers, notifying
1383  * about their disconnection. The registered inbound tunnel cleaner will be
1384  * called should any inbound tunnels still exist.
1385  *
1386  * @param handle connection to mesh to disconnect
1387  */
1388 void
1389 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
1390 {
1391   struct GNUNET_MESH_Tunnel *t;
1392   struct GNUNET_MESH_Tunnel *aux;
1393   struct GNUNET_MESH_TransmitHandle *th;
1394
1395   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH DISCONNECT\n");
1396
1397   t = handle->tunnels_head;
1398   while (NULL != t)
1399   {
1400     aux = t->next;
1401     if (t->tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1402     {
1403       GNUNET_break (0);
1404       LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X not destroyed\n", t->tid);
1405     }
1406     destroy_tunnel (t, GNUNET_YES);
1407     t = aux;
1408   }
1409   while ( (th = handle->th_head) != NULL)
1410   {
1411     struct GNUNET_MessageHeader *msg;
1412
1413     /* Make sure it is an allowed packet (everything else should have been
1414      * already canceled).
1415      */
1416     GNUNET_break (UINT32_MAX == th->priority);
1417     GNUNET_break (NULL == th->notify);
1418     msg = (struct GNUNET_MessageHeader *) &th[1];
1419     switch (ntohs(msg->type))
1420     {
1421       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT:
1422       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1423         break;
1424       default:
1425         GNUNET_break (0);
1426         LOG (GNUNET_ERROR_TYPE_DEBUG, "unexpected msg %u\n",
1427              ntohs(msg->type));
1428     }
1429
1430     GNUNET_CONTAINER_DLL_remove (handle->th_head, handle->th_tail, th);
1431     GNUNET_free (th);
1432   }
1433
1434   if (NULL != handle->th)
1435   {
1436     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
1437     handle->th = NULL;
1438   }
1439   if (NULL != handle->client)
1440   {
1441     GNUNET_CLIENT_disconnect (handle->client);
1442     handle->client = NULL;
1443   }
1444   if (GNUNET_SCHEDULER_NO_TASK != handle->reconnect_task)
1445   {
1446     GNUNET_SCHEDULER_cancel(handle->reconnect_task);
1447     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1448   }
1449   GNUNET_free (handle);
1450 }
1451
1452
1453 /**
1454  * Announce to ther peer the availability of services described by the regex,
1455  * in order to be reachable to other peers via connect_by_string.
1456  * 
1457  * Note that the first 8 characters are considered to be part of a prefix,
1458  * (for instance 'gnunet://'). If you put a variable part in there (*, +. ()),
1459  * all matching strings will be stored in the DHT.
1460  *
1461  * @param h handle to mesh.
1462  * @param regex string with the regular expression describing local services.
1463  */
1464 void
1465 GNUNET_MESH_announce_regex (struct GNUNET_MESH_Handle *h,
1466                             const char *regex)
1467 {
1468   struct GNUNET_MessageHeader *msg;
1469   size_t len;
1470   size_t msgsize;
1471
1472   len = strlen (regex);
1473   msgsize = sizeof(struct GNUNET_MessageHeader) + len;
1474   GNUNET_assert (UINT16_MAX > msgsize);
1475
1476   {
1477     char buffer[msgsize];
1478
1479     msg = (struct GNUNET_MessageHeader *) buffer;
1480     msg->size = htons (msgsize);
1481     msg->type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX);
1482     memcpy (&msg[1], regex, len);
1483
1484     send_packet(h, msg, NULL);
1485   }
1486 }
1487
1488 /**
1489  * Create a new tunnel (we're initiator and will be allowed to add/remove peers
1490  * and to broadcast).
1491  *
1492  * @param h mesh handle
1493  * @param tunnel_ctx client's tunnel context to associate with the tunnel
1494  * @param connect_handler function to call when peers are actually connected
1495  * @param disconnect_handler function to call when peers are disconnected
1496  * @param handler_cls closure for connect/disconnect handlers
1497  */
1498 struct GNUNET_MESH_Tunnel *
1499 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h, void *tunnel_ctx,
1500                            GNUNET_MESH_PeerConnectHandler connect_handler,
1501                            GNUNET_MESH_PeerDisconnectHandler disconnect_handler,
1502                            void *handler_cls)
1503 {
1504   struct GNUNET_MESH_Tunnel *t;
1505   struct GNUNET_MESH_TunnelMessage msg;
1506
1507   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating new tunnel\n");
1508   t = create_tunnel (h, 0);
1509   t->connect_handler = connect_handler;
1510   t->disconnect_handler = disconnect_handler;
1511   t->cls = handler_cls;
1512   t->ctx = tunnel_ctx;
1513   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1514   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1515   msg.tunnel_id = htonl (t->tid);
1516   send_packet (h, &msg.header, t);
1517   return t;
1518 }
1519
1520
1521 /**
1522  * Destroy an existing tunnel. The existing callback for the tunnel will NOT
1523  * be called.
1524  *
1525  * @param tunnel tunnel handle
1526  */
1527 void
1528 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tunnel)
1529 {
1530   struct GNUNET_MESH_Handle *h;
1531   struct GNUNET_MESH_TunnelMessage msg;
1532   struct GNUNET_MESH_TransmitHandle *th;
1533
1534   LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying tunnel\n");
1535   h = tunnel->mesh;
1536
1537   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1538   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1539   msg.tunnel_id = htonl (tunnel->tid);
1540   th = h->th_head;
1541   while (th != NULL)
1542   {
1543     struct GNUNET_MESH_TransmitHandle *aux;
1544     if (th->tunnel == tunnel)
1545     {
1546       aux = th->next;
1547       /* FIXME call the handler? */
1548       if (NULL != th->notify)
1549         th->notify (th->notify_cls, 0, NULL);
1550       GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1551       GNUNET_free (th);
1552       th = aux;
1553     }
1554     else
1555       th = th->next;
1556   }
1557
1558   destroy_tunnel (tunnel, GNUNET_NO);
1559   send_packet (h, &msg.header, NULL);
1560 }
1561
1562 /**
1563  * Request that the tunnel data rate is limited to the speed of the slowest
1564  * receiver.
1565  *
1566  * @param tunnel Tunnel affected.
1567  */
1568 void
1569 GNUNET_MESH_tunnel_speed_min (struct GNUNET_MESH_Tunnel *tunnel)
1570 {
1571   struct GNUNET_MESH_TunnelMessage msg;
1572   struct GNUNET_MESH_Handle *h;
1573
1574   h = tunnel->mesh;
1575   tunnel->speed_min = GNUNET_YES;
1576
1577   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN);
1578   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1579   msg.tunnel_id = htonl (tunnel->tid);
1580
1581   send_packet (h, &msg.header, NULL);
1582 }
1583
1584
1585 /**
1586  * Request that the tunnel data rate is limited to the speed of the fastest
1587  * receiver. This is the default behavior.
1588  *
1589  * @param tunnel Tunnel affected.
1590  */
1591 void
1592 GNUNET_MESH_tunnel_speed_max (struct GNUNET_MESH_Tunnel *tunnel)
1593 {
1594   struct GNUNET_MESH_TunnelMessage msg;
1595   struct GNUNET_MESH_Handle *h;
1596
1597   h = tunnel->mesh;
1598   tunnel->speed_min = GNUNET_NO;
1599
1600   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX);
1601   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1602   msg.tunnel_id = htonl (tunnel->tid);
1603
1604   send_packet (h, &msg.header, NULL);
1605 }
1606
1607 /**
1608  * Turn on/off the buffering status of the tunnel.
1609  * 
1610  * @param tunnel Tunnel affected.
1611  * @param buffer GNUNET_YES to turn buffering on (default),
1612  *               GNUNET_NO otherwise.
1613  */
1614 void
1615 GNUNET_MESH_tunnel_buffer (struct GNUNET_MESH_Tunnel *tunnel, int buffer)
1616 {
1617   struct GNUNET_MESH_TunnelMessage msg;
1618   struct GNUNET_MESH_Handle *h;
1619
1620   h = tunnel->mesh;
1621   tunnel->buffering = buffer;
1622
1623   if (GNUNET_YES == buffer)
1624     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER);
1625   else
1626     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER);
1627   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1628   msg.tunnel_id = htonl (tunnel->tid);
1629
1630   send_packet (h, &msg.header, NULL);
1631 }
1632
1633 /**
1634  * Request that a peer should be added to the tunnel.  The existing
1635  * connect handler will be called ONCE with either success or failure.
1636  * This function should NOT be called again with the same peer before the
1637  * connect handler is called.
1638  *
1639  * @param tunnel handle to existing tunnel
1640  * @param peer peer to add
1641  */
1642 void
1643 GNUNET_MESH_peer_request_connect_add (struct GNUNET_MESH_Tunnel *tunnel,
1644                                       const struct GNUNET_PeerIdentity *peer)
1645 {
1646   struct GNUNET_MESH_PeerControl msg;
1647   GNUNET_PEER_Id peer_id;
1648   unsigned int i;
1649
1650   peer_id = GNUNET_PEER_intern (peer);
1651   for (i = 0; i < tunnel->npeers; i++)
1652   {
1653     if (tunnel->peers[i]->id == peer_id)
1654     {
1655       /* Peer already exists in tunnel */
1656       GNUNET_PEER_change_rc (peer_id, -1);
1657       GNUNET_break (0);
1658       return;
1659     }
1660   }
1661   if (NULL == add_peer_to_tunnel (tunnel, peer))
1662     return;
1663
1664   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1665   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1666   msg.tunnel_id = htonl (tunnel->tid);
1667   msg.peer = *peer;
1668   send_packet (tunnel->mesh, &msg.header, tunnel);
1669
1670   return;
1671 }
1672
1673
1674 /**
1675  * Request that a peer should be removed from the tunnel.  The existing
1676  * disconnect handler will be called ONCE if we were connected.
1677  *
1678  * @param tunnel handle to existing tunnel
1679  * @param peer peer to remove
1680  */
1681 void
1682 GNUNET_MESH_peer_request_connect_del (struct GNUNET_MESH_Tunnel *tunnel,
1683                                       const struct GNUNET_PeerIdentity *peer)
1684 {
1685   struct GNUNET_MESH_PeerControl msg;
1686   GNUNET_PEER_Id peer_id;
1687   unsigned int i;
1688
1689   peer_id = GNUNET_PEER_search (peer);
1690   if (0 == peer_id)
1691   {
1692     GNUNET_break (0);
1693     return;
1694   }
1695   for (i = 0; i < tunnel->npeers; i++)
1696     if (tunnel->peers[i]->id == peer_id)
1697       break;
1698   if (i == tunnel->npeers)
1699   {
1700     GNUNET_break (0);
1701     return;
1702   }
1703   if (NULL != tunnel->disconnect_handler && tunnel->peers[i]->connected == 1)
1704     tunnel->disconnect_handler (tunnel->cls, peer);
1705   GNUNET_PEER_change_rc (peer_id, -1);
1706   GNUNET_free (tunnel->peers[i]);
1707   tunnel->peers[i] = tunnel->peers[tunnel->npeers - 1];
1708   GNUNET_array_grow (tunnel->peers, tunnel->npeers, tunnel->npeers - 1);
1709
1710   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1711   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1712   msg.tunnel_id = htonl (tunnel->tid);
1713   memcpy (&msg.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1714   send_packet (tunnel->mesh, &msg.header, tunnel);
1715 }
1716
1717
1718 /**
1719  * Request that the mesh should try to connect to a peer supporting the given
1720  * message type.
1721  *
1722  * @param tunnel handle to existing tunnel
1723  * @param app_type application type that must be supported by the peer (MESH
1724  *                 should discover peer in proximity handling this type)
1725  */
1726 void
1727 GNUNET_MESH_peer_request_connect_by_type (struct GNUNET_MESH_Tunnel *tunnel,
1728                                           GNUNET_MESH_ApplicationType app_type)
1729 {
1730   struct GNUNET_MESH_ConnectPeerByType msg;
1731
1732   GNUNET_array_append (tunnel->apps, tunnel->napps, app_type);
1733
1734   LOG (GNUNET_ERROR_TYPE_DEBUG, "* CONNECT BY TYPE *\n");
1735   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
1736   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE);
1737   msg.tunnel_id = htonl (tunnel->tid);
1738   msg.type = htonl (app_type);
1739   send_packet (tunnel->mesh, &msg.header, tunnel);
1740 }
1741
1742
1743 /**
1744  * Request that the mesh should try to connect to a peer matching the
1745  * description given in the service string.
1746  * 
1747  * FIXME: allow multiple? how to deal with reconnect?
1748  *
1749  * @param tunnel handle to existing tunnel
1750  * @param description string describing the destination node requirements
1751  */
1752 void
1753 GNUNET_MESH_peer_request_connect_by_string (struct GNUNET_MESH_Tunnel *tunnel,
1754                                             const char *description)
1755 {
1756   struct GNUNET_MESH_ConnectPeerByString *m;
1757   size_t len;
1758   size_t msgsize;
1759
1760   len = strlen (description);
1761   msgsize = sizeof(struct GNUNET_MESH_ConnectPeerByString) + len;
1762   GNUNET_assert (UINT16_MAX > msgsize);
1763   {
1764     char buffer[msgsize];
1765
1766     m = (struct GNUNET_MESH_ConnectPeerByString *) buffer;
1767     m->header.size = htons (msgsize);
1768     m->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING);
1769     m->tunnel_id = htonl (tunnel->tid);
1770     memcpy(&m[1], description, len);
1771
1772     send_packet (tunnel->mesh, &m->header, tunnel);
1773   }
1774 }
1775
1776
1777 /**
1778  * Request that the given peer isn't added to this tunnel in calls to
1779  * connect_by_* calls, (due to misbehaviour, bad performance, ...).
1780  *
1781  * @param tunnel handle to existing tunnel.
1782  * @param peer peer identity of the peer which should be blacklisted
1783  *                  for the tunnel.
1784  */
1785 void
1786 GNUNET_MESH_peer_blacklist (struct GNUNET_MESH_Tunnel *tunnel,
1787                             const struct GNUNET_PeerIdentity *peer)
1788 {
1789   struct GNUNET_MESH_PeerControl msg;
1790
1791   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1792   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST);
1793   msg.tunnel_id = htonl (tunnel->tid);
1794   msg.peer = *peer;
1795   send_packet (tunnel->mesh, &msg.header, tunnel);
1796
1797   return;
1798 }
1799
1800
1801 /**
1802  * Request that the given peer isn't blacklisted anymore from this tunnel,
1803  * and therefore can be added in future calls to connect_by_*.
1804  * The peer must have been previously blacklisted for this tunnel.
1805  *
1806  * @param tunnel handle to existing tunnel.
1807  * @param peer peer identity of the peer which shouldn't be blacklisted
1808  *                  for the tunnel anymore.
1809  */
1810 void
1811 GNUNET_MESH_peer_unblacklist (struct GNUNET_MESH_Tunnel *tunnel,
1812                               const struct GNUNET_PeerIdentity *peer)
1813 {
1814   struct GNUNET_MESH_PeerControl msg;
1815
1816   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1817   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST);
1818   msg.tunnel_id = htonl (tunnel->tid);
1819   msg.peer = *peer;
1820   send_packet (tunnel->mesh, &msg.header, tunnel);
1821
1822   return;
1823 }
1824
1825
1826 /**
1827  * Ask the mesh to call "notify" once it is ready to transmit the
1828  * given number of bytes to the specified "target".  If we are not yet
1829  * connected to the specified peer, a call to this function will cause
1830  * us to try to establish a connection.
1831  *
1832  * @param tunnel tunnel to use for transmission
1833  * @param cork is corking allowed for this transmission?
1834  * @param priority how important is the message?
1835  * @param maxdelay how long can the message wait?
1836  * @param target destination for the message,
1837  *               NULL for multicast to all tunnel targets
1838  * @param notify_size how many bytes of buffer space does notify want?
1839  * @param notify function to call when buffer space is available;
1840  *        will be called with NULL on timeout or if the overall queue
1841  *        for this peer is larger than queue_size and this is currently
1842  *        the message with the lowest priority
1843  * @param notify_cls closure for notify
1844  * @return non-NULL if the notify callback was queued,
1845  *         NULL if we can not even queue the request (insufficient
1846  *         memory); if NULL is returned, "notify" will NOT be called.
1847  */
1848 struct GNUNET_MESH_TransmitHandle *
1849 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
1850                                    uint32_t priority,
1851                                    struct GNUNET_TIME_Relative maxdelay,
1852                                    const struct GNUNET_PeerIdentity *target,
1853                                    size_t notify_size,
1854                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1855                                    void *notify_cls)
1856 {
1857   struct GNUNET_MESH_TransmitHandle *th;
1858   struct GNUNET_MESH_TransmitHandle *least_priority_th;
1859   uint32_t least_priority;
1860   size_t overhead;
1861
1862   GNUNET_assert (NULL != tunnel);
1863   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh notify transmit ready called\n");
1864   if (NULL != target)
1865     LOG (GNUNET_ERROR_TYPE_DEBUG, "    target %s\n", GNUNET_i2s (target));
1866   else
1867     LOG (GNUNET_ERROR_TYPE_DEBUG, "    target multicast\n");
1868   GNUNET_assert (NULL != notify);
1869   if (tunnel->mesh->npackets >= tunnel->mesh->max_queue_size &&
1870       tunnel->npackets > 0)
1871   {
1872     /* queue full */
1873     if (0 == priority)
1874       return NULL;
1875     th = tunnel->mesh->th_tail;
1876     least_priority = priority;
1877     least_priority_th = NULL;
1878     while (NULL != th)
1879     {
1880       if (th->priority < least_priority && th->tunnel->npackets > 1)
1881       {
1882         least_priority_th = th;
1883         least_priority = th->priority;
1884       }
1885       th = th->prev;
1886     }
1887     if (NULL == least_priority_th)
1888       return NULL;
1889     /* Can't be a control message */
1890     GNUNET_assert (NULL != least_priority_th->notify);
1891     least_priority_th->notify (notify_cls, 0, NULL);
1892     least_priority_th->tunnel->npackets--;
1893     tunnel->mesh->npackets--;
1894     GNUNET_CONTAINER_DLL_remove (tunnel->mesh->th_head, tunnel->mesh->th_tail,
1895                                  least_priority_th);
1896     if (GNUNET_SCHEDULER_NO_TASK != least_priority_th->timeout_task)
1897       GNUNET_SCHEDULER_cancel (least_priority_th->timeout_task);
1898     GNUNET_free (least_priority_th);
1899   }
1900   tunnel->npackets++;
1901   tunnel->mesh->npackets++;
1902   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
1903   th->tunnel = tunnel;
1904   th->priority = priority;
1905   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1906   th->target = GNUNET_PEER_intern (target);
1907   if (tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1908     overhead = sizeof (struct GNUNET_MESH_ToOrigin);
1909   else if (NULL == target)
1910     overhead = sizeof (struct GNUNET_MESH_Multicast);
1911   else
1912     overhead = sizeof (struct GNUNET_MESH_Unicast);
1913   th->size = notify_size + overhead;
1914   th->notify = notify;
1915   th->notify_cls = notify_cls;
1916   add_to_queue (tunnel->mesh, th);
1917   if (NULL != tunnel->mesh->th)
1918     return th;
1919   tunnel->mesh->th =
1920       GNUNET_CLIENT_notify_transmit_ready (tunnel->mesh->client, th->size,
1921                                            GNUNET_TIME_UNIT_FOREVER_REL,
1922                                            GNUNET_YES, &send_callback,
1923                                            tunnel->mesh);
1924   return th;
1925 }
1926
1927
1928 /**
1929  * Cancel the specified transmission-ready notification.
1930  *
1931  * @param th handle that was returned by "notify_transmit_ready".
1932  */
1933 void
1934 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
1935 {
1936   struct GNUNET_MESH_Handle *mesh;
1937
1938   mesh = th->tunnel->mesh;
1939   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1940     GNUNET_SCHEDULER_cancel (th->timeout_task);
1941   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
1942   GNUNET_free (th);
1943   if ((NULL == mesh->th_head) && (NULL != mesh->th))
1944   {
1945     /* queue empty, no point in asking for transmission */
1946     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
1947     mesh->th = NULL;
1948   }
1949 }
1950
1951
1952 /**
1953  * Transition API for tunnel ctx management
1954  */
1955 void
1956 GNUNET_MESH_tunnel_set_data (struct GNUNET_MESH_Tunnel *tunnel, void *data)
1957 {
1958   tunnel->ctx = data;
1959 }
1960
1961 /**
1962  * Transition API for tunnel ctx management
1963  */
1964 void *
1965 GNUNET_MESH_tunnel_get_data (struct GNUNET_MESH_Tunnel *tunnel)
1966 {
1967   return tunnel->ctx;
1968 }
1969
1970