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