timeout support, handle empty queue due to cancel/timeout
[oweals/gnunet.git] / src / mesh / mesh_api_new.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/mesh_api_new.c
23  * @brief mesh api: client implementation of mesh service
24  * @author Bartlomiej Polot
25  *
26  * STRUCTURE:
27  * - CONSTANTS
28  * - DATA STRUCTURES
29  * - AUXILIARY FUNCTIONS
30  * - RECEIVE HANDLERS
31  * - SEND FUNCTIONS
32  * - API CALL DEFINITIONS
33  */
34
35 #ifdef __cplusplus
36
37 extern "C"
38 {
39 #if 0                           /* keep Emacsens' auto-indent happy */
40 }
41 #endif
42 #endif
43
44
45 #include "platform.h"
46 #include "gnunet_common.h"
47 #include "gnunet_client_lib.h"
48 #include "gnunet_util_lib.h"
49 #include "gnunet_peer_lib.h"
50 #include "gnunet_mesh_service_new.h"
51 #include "mesh.h"
52 #include "mesh_protocol.h"
53
54 #define MESH_API_MAX_QUEUE 10
55
56 /******************************************************************************/
57 /************************      DATA STRUCTURES     ****************************/
58 /******************************************************************************/
59
60 /**
61  * Transmission queue to the service
62  */
63 struct GNUNET_MESH_TransmitHandle
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      * Data itself, currently points to the end of this struct if 
77      * we have a message already, NULL if the message is to be 
78      * obtained from the callback.
79      */
80   const struct GNUNET_MessageHeader *data;
81
82   /**
83    * Tunnel this message is sent over (may be NULL for control messages).
84    */
85   struct GNUNET_MESH_Tunnel *tunnel;
86
87   /**
88    * Callback to obtain the message to transmit, or NULL if we
89    * got the message in 'data'.  Notice that messages built
90    * by 'notify' need to be encapsulated with information about
91    * the 'target'.
92    */
93   GNUNET_CONNECTION_TransmitReadyNotify notify;
94
95   /**
96    * Closure for 'notify'
97    */
98   void *notify_cls;
99   
100   /**
101    * How long is this message valid.  Once the timeout has been
102    * reached, the message must no longer be sent.  If this 
103    * is a message with a 'notify' callback set, the 'notify'
104    * function should be called with 'buf' NULL and size 0.
105    */
106   struct GNUNET_TIME_Absolute timeout;
107
108   /**
109    * Task triggering a timeout, can be NO_TASK if the timeout is FOREVER.
110    */
111   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
112
113   /**
114    * Priority of the message.  The queue is sorted by priority,
115    * control messages have the maximum priority (UINT32_MAX).
116    */
117   uint32_t priority;
118  
119   /**
120    * Target of the message, 0 for broadcast.  This field
121    * is only valid if 'notify' is non-NULL.
122    */
123   GNUNET_PEER_Id target;
124                                  
125   /**
126    * Size of 'data' -- or the desired size of 'notify' if 'data' is NULL.
127    */
128   size_t size;
129 };
130
131
132 /**
133  * Opaque handle to the service.
134  */
135 struct GNUNET_MESH_Handle
136 {
137     /**
138      * Handle to the server connection, to send messages later
139      */
140   struct GNUNET_CLIENT_Connection *client;
141
142     /**
143      * Set of handlers used for processing incoming messages in the tunnels
144      */
145   const struct GNUNET_MESH_MessageHandler *message_handlers;
146
147     /**
148      * Set of applications that should be claimed to be offered at this node.
149      * Note that this is just informative, the appropiate handlers must be
150      * registered independently and the mapping is up to the developer of the
151      * client application.
152      */
153   const GNUNET_MESH_ApplicationType *applications; 
154
155     /**
156      * Double linked list of the tunnels this client is connected to.
157      */
158   struct GNUNET_MESH_Tunnel *tunnels_head;
159   struct GNUNET_MESH_Tunnel *tunnels_tail;
160
161     /**
162      * Callback for tunnel disconnection
163      */
164   GNUNET_MESH_TunnelEndHandler *cleaner;
165
166     /**
167      * Handle to cancel pending transmissions in case of disconnection
168      */
169   struct GNUNET_CLIENT_TransmitHandle *th;
170
171     /**
172      * Closure for all the handlers given by the client
173      */
174   void *cls;
175
176     /**
177      * Messages to send to the service
178      */
179   struct GNUNET_MESH_TransmitHandle *queue_head;
180   struct GNUNET_MESH_TransmitHandle *queue_tail;
181
182     /**
183      * tid of the next tunnel to create (to avoid reusing IDs often)
184      */
185   MESH_TunnelNumber next_tid;
186
187   unsigned int n_handlers;
188
189   unsigned int n_applications;
190
191   unsigned int max_queue_size;
192
193   /**
194    * Have we started the task to receive messages from the service
195    * yet? We do this after we send the 'MESH_LOCAL_CONNECT' message.
196    */
197   int in_receive;
198 };
199
200 /**
201  * Opaque handle to a tunnel.
202  */
203 struct GNUNET_MESH_Tunnel
204 {
205
206     /**
207      * DLL
208      */
209   struct GNUNET_MESH_Tunnel *next;
210   struct GNUNET_MESH_Tunnel *prev;
211
212     /**
213      * Callback to execute when peers connect to the tunnel
214      */
215   GNUNET_MESH_TunnelConnectHandler connect_handler;
216
217     /**
218      * Callback to execute when peers disconnect to the tunnel
219      */
220   GNUNET_MESH_TunnelDisconnectHandler disconnect_handler;
221
222     /**
223      * All peers added to the tunnel
224      */
225   GNUNET_PEER_Id *peers;
226
227     /**
228      * Closure for the connect/disconnect handlers
229      */
230   void *cls;
231
232     /**
233      * Handle to the mesh this tunnel belongs to
234      */
235   struct GNUNET_MESH_Handle *mesh;
236
237     /**
238      * Local ID of the tunnel
239      */
240   MESH_TunnelNumber tid;
241
242     /**
243      * Owner of the tunnel
244      */
245   GNUNET_PEER_Id owner;
246
247     /**
248      * Number of peer added to the tunnel
249      */
250   unsigned int npeers;
251 };
252
253
254 /******************************************************************************/
255 /***********************     AUXILIARY FUNCTIONS      *************************/
256 /******************************************************************************/
257
258 /**
259  * Get the tunnel handler for the tunnel specified by id from the given handle
260  * @param h Mesh handle
261  * @param tid ID of the wanted tunnel
262  * @return handle to the required tunnel or NULL if not found
263  */
264 static struct GNUNET_MESH_Tunnel *
265 retrieve_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
266 {
267   struct GNUNET_MESH_Tunnel *t;
268
269   t = h->tunnels_head;
270   while (t != NULL)
271   {
272     if (t->tid == tid)
273       return t;
274     t = t->next;
275   }
276   return NULL;
277 }
278
279 /**
280  * Get the length of the transmission queue
281  * @param h mesh handle whose queue is to be measured
282  */
283 static unsigned int
284 get_queue_length (struct GNUNET_MESH_Handle *h)
285 {
286   struct GNUNET_MESH_TransmitHandle *q;
287   unsigned int i;
288
289   /* count */
290   for (q = h->queue_head, i = 0; NULL != q; q = q->next, i++) ;
291
292   return i;
293 }
294
295
296 /******************************************************************************/
297 /***********************      RECEIVE HANDLERS     ****************************/
298 /******************************************************************************/
299
300 /**
301  * Process the new tunnel notification and add it to the tunnels in the handle
302  *
303  * @param h     The mesh handle
304  * @param msg   A message with the details of the new incoming tunnel
305  */
306 static void
307 process_tunnel_create (struct GNUNET_MESH_Handle *h,
308                        const struct GNUNET_MESH_TunnelMessage *msg)
309 {
310   struct GNUNET_MESH_Tunnel *t;
311   MESH_TunnelNumber tid;
312
313   tid = ntohl (msg->tunnel_id);
314   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_MARK)
315   {
316     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
317                 "MESH: received an incoming tunnel with tid in local range (%X)\n",
318                 tid);
319     GNUNET_break_op (0);
320     return;                     //FIXME abort? reconnect?
321   }
322   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
323   t->cls = h->cls;
324   t->mesh = h;
325   t->tid = tid;
326
327   return;
328 }
329
330
331 /**
332  * Process the new peer event and notify the upper level of it
333  *
334  * @param h     The mesh handle
335  * @param msg   A message with the details of the peer event
336  */
337 static void
338 process_peer_event (struct GNUNET_MESH_Handle *h,
339                     const struct GNUNET_MESH_PeerControl *msg)
340 {
341   struct GNUNET_MESH_Tunnel *t;
342   uint16_t size;
343
344   size = ntohs (msg->header.size);
345   if (size != sizeof (struct GNUNET_MESH_PeerControl))
346   {
347     GNUNET_break_op (0);
348     return;
349   }
350   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
351   if (NULL == t)
352   {
353     GNUNET_break_op (0);
354     return;
355   }
356   if (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_CONNECTED == msg->header.type)
357   {
358     if (NULL != t->connect_handler)
359     {
360       t->connect_handler (t->cls, &msg->peer, NULL);    /* FIXME atsi */
361     }
362   }
363   else
364   {
365     if (NULL != t->disconnect_handler)
366     {
367       t->disconnect_handler (t->cls, &msg->peer);
368     }
369   }
370 }
371
372
373 /**
374  * Process the incoming data packets
375  *
376  * @param h     The mesh handle
377  * @param msh   A message encapsulating the data
378  */
379 static void
380 process_incoming_data (struct GNUNET_MESH_Handle *h,
381                        const struct GNUNET_MessageHeader *message)
382 {
383   const struct GNUNET_MessageHeader *payload;
384   const struct GNUNET_MESH_MessageHandler *handler;
385   const struct GNUNET_PeerIdentity *peer;
386   struct GNUNET_MESH_Unicast *ucast;
387   struct GNUNET_MESH_Multicast *mcast;
388   struct GNUNET_MESH_ToOrigin *to_orig;
389   struct GNUNET_MESH_Tunnel *t;
390   uint16_t type;
391   int i;
392
393   type = ntohs (message->type);
394   switch (type)
395   {
396   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
397     ucast = (struct GNUNET_MESH_Unicast *) message;
398     t = retrieve_tunnel (h, ntohl (ucast->tid));
399     payload = (struct GNUNET_MessageHeader *) &ucast[1];
400     peer = &ucast->oid;
401     break;
402   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
403     mcast = (struct GNUNET_MESH_Multicast *) message;
404     t = retrieve_tunnel (h, ntohl (mcast->tid));
405     payload = (struct GNUNET_MessageHeader *) &mcast[1];
406     peer = &mcast->oid;
407     break;
408   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
409     to_orig = (struct GNUNET_MESH_ToOrigin *) message;
410     t = retrieve_tunnel (h, ntohl (to_orig->tid));
411     payload = (struct GNUNET_MessageHeader *) &to_orig[1];
412     peer = &to_orig->sender;
413     break;
414   default:
415     GNUNET_break_op (0);
416     return;
417   }
418   if (NULL == t)
419   {
420     GNUNET_break_op (0);
421     return;
422   }
423   for (i = 0; i < h->n_handlers; i++)
424   {
425     handler = &h->message_handlers[i];
426     if (handler->type == type)
427     {
428       if (GNUNET_OK == handler->callback (h->cls, t, NULL,      /* FIXME ctx */
429                                           peer, payload, NULL)) /* FIXME atsi */
430       {
431         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
432                     "MESH: callback completed successfully\n");
433       }
434       else
435       {
436         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
437                     "MESH: callback caused disconnection\n");
438         GNUNET_MESH_disconnect (h);
439       }
440     }
441   }
442 }
443
444
445 /**
446  * Function to process all messages received from the service
447  *
448  * @param cls closure
449  * @param msg message received, NULL on timeout or fatal error
450  */
451 static void
452 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
453 {
454   struct GNUNET_MESH_Handle *h = cls;
455
456   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: received a message from MESH\n");
457   if (msg == NULL)
458   {
459     GNUNET_break (0);
460     h->in_receive = GNUNET_NO;
461     // rather: do_reconnect () -- and set 'in_receive' to NO there...
462     // FIXME: service disconnect, handle!
463     return;
464   }
465
466   switch (ntohs (msg->type))
467   {
468     /* Notify of a new incoming tunnel */
469   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE:
470     process_tunnel_create (h, (struct GNUNET_MESH_TunnelMessage *) msg);
471     break;
472     /* Notify of a new peer or a peer disconnect in the tunnel */
473   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_CONNECTED:
474   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED:
475     process_peer_event (h, (struct GNUNET_MESH_PeerControl *) msg);
476     break;
477     /* Notify of a new data packet in the tunnel */
478   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
479   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
480   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
481     process_incoming_data (h, msg);
482     break;
483     /* We shouldn't get any other packages, log and ignore */
484   default:
485     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
486                 "MESH: unsolicited message form service (type %d)\n",
487                 ntohs (msg->type));
488   }
489
490   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: message processed\n");
491   GNUNET_CLIENT_receive (h->client, &msg_received, h,
492                          GNUNET_TIME_UNIT_FOREVER_REL);
493 }
494
495
496 /******************************************************************************/
497 /************************       SEND FUNCTIONS     ****************************/
498 /******************************************************************************/
499
500 /**
501  * Function called to send a message to the service.
502  * "buf" will be NULL and "size" zero if the socket was closed for writing in
503  * the meantime.
504  *
505  * @param cls closure, the mesh handle
506  * @param size number of bytes available in buf
507  * @param buf where the callee should write the connect message
508  * @return number of bytes written to buf
509  */
510 static size_t
511 send_raw (void *cls, size_t size, void *buf)
512 {
513   struct GNUNET_MESH_Handle *h = cls;
514   struct GNUNET_MESH_TransmitHandle *q;
515
516   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Send packet() Buffer %u\n", size);
517   h->th = NULL;
518   if (0 == size || NULL == buf)
519   {
520     // FIXME: disconnect, reconnect, retry?
521     // do_reconnect ();
522     return 0;
523   }
524   q = h->queue_head;
525   GNUNET_assert (NULL != q);
526   if (sizeof (struct GNUNET_MessageHeader) > size)
527   {
528     GNUNET_break (0);
529     GNUNET_assert (sizeof (struct GNUNET_MessageHeader) > ntohs (q->data->size));
530     h->th =
531         GNUNET_CLIENT_notify_transmit_ready (h->client, q->size,
532                                              GNUNET_TIME_UNIT_FOREVER_REL,
533                                              GNUNET_YES, &send_raw, h);
534     return 0;
535   }
536   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   type: %i\n",
537               ntohs (q->data->type));
538   if (NULL == q->data)
539     {
540       GNUNET_assert (NULL != q->notify);
541       if (q->target == 0)
542         {
543           /* multicast */
544           struct GNUNET_MESH_Multicast mc; 
545           char *cbuf;
546
547           GNUNET_assert (size >= sizeof (mc) + q->size);
548           cbuf = buf;
549           q->size = q->notify (q->notify_cls,
550                                size - sizeof (mc), 
551                                &cbuf[sizeof(mc)]);
552           if (q->size == 0)
553             {
554               size = 0;       
555             }
556           else
557             {
558               mc.header.size = htons (sizeof (mc) + q->size);
559               mc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
560               mc.tid = htonl (q->tunnel->tid);
561               memset (&mc.oid, 0, sizeof (struct GNUNET_PeerIdentity)); /* myself */
562               memcpy (buf, &mc, sizeof (mc));
563               size = q->size + sizeof (mc);
564             }
565         }
566       else
567         {
568           /* unicast */
569           struct GNUNET_MESH_Unicast uc; 
570           char *cbuf;
571
572           GNUNET_assert (size >= sizeof (uc) + q->size);
573           cbuf = buf;
574           q->size = q->notify (q->notify_cls,
575                                size - sizeof (uc), 
576                                &cbuf[sizeof(uc)]);
577           if (q->size == 0)
578             {
579               size = 0;       
580             }
581           else
582             {
583               uc.header.size = htons (sizeof (uc) + q->size);
584               uc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
585               uc.tid = htonl (q->tunnel->tid);
586               memset (&uc.oid, 0, sizeof (struct GNUNET_PeerIdentity)); /* myself */
587               GNUNET_PEER_resolve (q->target, &uc.destination);
588               memcpy (buf, &uc, sizeof (uc));
589               size = q->size + sizeof (uc);
590             }     
591         }
592     }
593   else
594     {
595       memcpy (buf, q->data, q->size);
596       size = q->size;
597     }
598   if (q->timeout_task != GNUNET_SCHEDULER_NO_TASK)
599     GNUNET_SCHEDULER_cancel (q->timeout_task);
600   GNUNET_CONTAINER_DLL_remove (h->queue_head, h->queue_tail, q);
601   GNUNET_free (q);
602   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   size: %u\n", size);
603
604   if (NULL != h->queue_head)
605   {
606     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   next size: %u\n",
607                 h->queue_head->size);
608     h->th =
609         GNUNET_CLIENT_notify_transmit_ready (h->client, h->queue_head->size,
610                                              GNUNET_TIME_UNIT_FOREVER_REL,
611                                              GNUNET_YES, &send_raw, h);
612   }
613   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Send packet() END\n");
614   if (GNUNET_NO == h->in_receive)
615     {
616       h->in_receive = GNUNET_YES;
617       GNUNET_CLIENT_receive (h->client, &msg_received, h,
618                              GNUNET_TIME_UNIT_FOREVER_REL);
619     }
620   return size;
621 }
622
623
624 static void
625 timeout_transmission (void *cls,
626                       const struct GNUNET_SCHEDULER_TaskContext *tc)
627 {
628   struct GNUNET_MESH_TransmitHandle *q = cls;
629   struct GNUNET_MESH_Handle *mesh;
630   
631   mesh = q->tunnel->mesh;
632   GNUNET_CONTAINER_DLL_remove (mesh->queue_head, 
633                                mesh->queue_tail,
634                                q);
635   if (q->notify != NULL)
636     q->notify (q->notify_cls, 0, NULL); /* signal timeout */
637   GNUNET_free (q);    
638   if ( (NULL == mesh->queue_head) &&
639        (NULL != mesh->th) )
640     {
641       /* queue empty, no point in asking for transmission */
642       GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
643       mesh->th = NULL;
644     }    
645 }
646
647
648 /**
649  * Add a transmit handle to the transmission queue (by priority).
650  * Also manage timeout.
651  *
652  * @param h mesh handle with the queue head and tail
653  * @param q handle to add
654  */
655 static void
656 queue_transmit_handle (struct GNUNET_MESH_Handle *h,
657                        struct GNUNET_MESH_TransmitHandle *q)
658 {
659   struct GNUNET_MESH_TransmitHandle *p;
660
661   p = h->queue_head;
662   while ( (NULL != p) && (q->priority < p->priority) )
663     p = p->next;
664   GNUNET_CONTAINER_DLL_insert_after (h->queue_head, h->queue_tail, p->prev, q);
665   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value != q->timeout.abs_value)
666     q->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (q->timeout),
667                                                     &timeout_transmission,
668                                                     q);
669 }
670
671
672 /**
673  * Auxiliary function to send a packet to the service
674  * Takes care of creating a new queue element and calling the tmt_rdy function
675  * if necessary.
676  * @param h mesh handle
677  * @param msg message to transmit
678  */
679 static void
680 send_packet (struct GNUNET_MESH_Handle *h, 
681              const struct GNUNET_MessageHeader *msg)
682 {
683   struct GNUNET_MESH_TransmitHandle *q;
684   size_t msize;
685
686   msize = ntohs (msg->size);
687   q = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle) + msize);
688   q->priority = UINT32_MAX;
689   q->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;  
690   q->size = msize;
691   q->data = (void*) &q[1];
692   memcpy (&q[1], msg, msize);
693   queue_transmit_handle (h, q);
694   if (NULL != h->th)
695     return;
696   h->th =
697     GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
698                                          GNUNET_TIME_UNIT_FOREVER_REL,
699                                          GNUNET_YES, &send_raw, h);
700 }
701
702 /******************************************************************************/
703 /**********************      API CALL DEFINITIONS     *************************/
704 /******************************************************************************/
705
706 /**
707  * Connect to the mesh service.
708  *
709  * @param cfg configuration to use
710  * @param cls closure for the various callbacks that follow
711  *            (including handlers in the handlers array)
712  * @param cleaner function called when an *inbound* tunnel is destroyed
713  * @param handlers callbacks for messages we care about, NULL-terminated
714  *                 note that the mesh is allowed to drop notifications about
715  *                 inbound messages if the client does not process them fast
716  *                 enough (for this notification type, a bounded queue is used)
717  * @param stypes Application Types the client claims to offer
718  * @return handle to the mesh service
719  *         NULL on error (in this case, init is never called)
720  */
721 struct GNUNET_MESH_Handle *
722 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, void *cls,
723                      GNUNET_MESH_TunnelEndHandler cleaner,
724                      const struct GNUNET_MESH_MessageHandler *handlers,
725                      const GNUNET_MESH_ApplicationType *stypes)
726 {
727   struct GNUNET_MESH_Handle *h;
728   struct GNUNET_MESH_ClientConnect *msg;
729   GNUNET_MESH_ApplicationType *apps;
730   uint16_t napps;
731   uint16_t *types;
732   uint16_t ntypes;
733   size_t size;
734
735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: GNUNET_MESH_connect()\n");
736   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
737   h->max_queue_size = MESH_API_MAX_QUEUE; /* FIXME: add to arguments to 'GNUNET_MESH_connect' */
738   h->cleaner = cleaner;
739   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
740   if (h->client == NULL)
741   {
742     GNUNET_break (0);
743     GNUNET_free (h);
744     return NULL;
745   }
746
747   h->cls = cls;
748   h->message_handlers = handlers;
749   h->applications = stypes;
750   h->next_tid = 0x80000000;
751
752   /* count handlers and apps, calculate size */
753   for (h->n_handlers = 0; handlers[h->n_handlers].type; h->n_handlers++) ;
754   for (h->n_applications = 0; stypes[h->n_applications]; h->n_applications++) ;
755
756   size = sizeof (struct GNUNET_MESH_ClientConnect);
757   size += h->n_handlers * sizeof (uint16_t);
758   size += h->n_applications * sizeof (GNUNET_MESH_ApplicationType);
759
760   {
761     char buf[size];
762
763     /* build connection packet */
764     msg = (struct GNUNET_MESH_ClientConnect *) buf;
765     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT);
766     msg->header.size = htons (size);
767     types = (uint16_t *) & msg[1];
768     for (ntypes = 0; ntypes < h->n_handlers; ntypes++)
769       types[ntypes] = h->message_handlers[ntypes].type;      
770     apps = (GNUNET_MESH_ApplicationType *) &types[ntypes];
771     for (napps = 0; napps < h->n_applications; napps++)
772       apps[napps] = h->applications[napps];      
773     msg->applications = htons (napps);
774     msg->types = htons (ntypes);
775
776     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
777                 "mesh: Sending %lu bytes long message %d types and %d apps\n",
778                 ntohs (msg->header.size), ntypes, napps);
779     
780     send_packet (h, &msg->header);
781   }
782
783   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: GNUNET_MESH_connect() END\n");
784
785   return h;
786 }
787
788
789 /**
790  * Disconnect from the mesh service.
791  *
792  * @param handle connection to mesh to disconnect
793  */
794 void
795 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
796 {
797   if (NULL != handle->th)
798   {
799     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
800   }
801   if (NULL != handle->client)
802   {
803     GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
804   }
805   GNUNET_free (handle);
806 }
807
808
809 /**
810  * Create a new tunnel (we're initiator and will be allowed to add/remove peers
811  * and to broadcast).
812  *
813  * @param h mesh handle
814  * @param connect_handler function to call when peers are actually connected
815  * @param disconnect_handler function to call when peers are disconnected
816  * @param handler_cls closure for connect/disconnect handlers
817  */
818 struct GNUNET_MESH_Tunnel *
819 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h,
820                            GNUNET_MESH_TunnelConnectHandler connect_handler,
821                            GNUNET_MESH_TunnelDisconnectHandler
822                            disconnect_handler, void *handler_cls)
823 {
824   struct GNUNET_MESH_Tunnel *t;
825   struct GNUNET_MESH_TunnelMessage msg;
826
827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Creating new tunnel\n");
828   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
829
830   t->connect_handler = connect_handler;
831   t->disconnect_handler = disconnect_handler;
832   t->cls = handler_cls;
833   t->mesh = h;
834   t->tid = h->next_tid++;
835   h->next_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_MARK;      // keep in range
836
837   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
838   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
839   msg.tunnel_id = htonl (t->tid);
840   send_packet (h, &msg.header);
841   return t;
842 }
843
844
845 /**
846  * Destroy an existing tunnel.
847  *
848  * @param tun tunnel handle
849  */
850 void
851 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tun)
852 {
853   struct GNUNET_MESH_Handle *h;
854   struct GNUNET_MESH_TunnelMessage *msg;
855
856   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Destroying tunnel\n");
857
858   h = tun->mesh;
859   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_TunnelMessage));
860   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
861   msg->header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
862   msg->tunnel_id = htonl (tun->tid);
863
864   GNUNET_free (tun);
865
866   send_packet (h, &msg->header);
867 }
868
869
870 /**
871  * Request that a peer should be added to the tunnel.  The existing
872  * connect handler will be called ONCE with either success or failure.
873  *
874  * @param tunnel handle to existing tunnel
875  * @param timeout how long to try to establish a connection
876  * @param peer peer to add
877  */
878 void
879 GNUNET_MESH_peer_request_connect_add (struct GNUNET_MESH_Tunnel *tunnel,
880                                       struct GNUNET_TIME_Relative timeout,
881                                       const struct GNUNET_PeerIdentity *peer)
882 {
883   struct GNUNET_MESH_PeerControl *msg;
884   GNUNET_PEER_Id peer_id;
885   unsigned int i;
886   
887   peer_id = GNUNET_PEER_intern (peer);
888   for (i = 0; i < tunnel->npeers; i++)
889   {
890     if (tunnel->peers[i] == peer_id)
891     {
892       GNUNET_PEER_change_rc (peer_id, -1);
893       return;
894     }
895   }
896   tunnel->npeers++;
897   tunnel->peers =
898       GNUNET_realloc (tunnel->peers, tunnel->npeers * sizeof (GNUNET_PEER_Id));
899   tunnel->peers[tunnel->npeers - 1] = peer_id;
900
901   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PeerControl));
902   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
903   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_ADD);
904   msg->tunnel_id = htonl (tunnel->tid);
905   memcpy (&msg->peer, peer, sizeof (struct GNUNET_PeerIdentity));
906
907   send_packet (tunnel->mesh, &msg->header);
908
909 //   tunnel->connect_handler (tunnel->cls, peer, NULL); FIXME call this later
910 //   TODO: remember timeout
911   return;
912 }
913
914
915 /**
916  * Request that a peer should be removed from the tunnel.  The existing
917  * disconnect handler will be called ONCE if we were connected.
918  *
919  * @param tunnel handle to existing tunnel
920  * @param peer peer to remove
921  */
922 void
923 GNUNET_MESH_peer_request_connect_del (struct GNUNET_MESH_Tunnel *tunnel,
924                                       const struct GNUNET_PeerIdentity *peer)
925 {
926   struct GNUNET_MESH_PeerControl msg;
927   GNUNET_PEER_Id peer_id;
928   unsigned int i;
929
930   peer_id = GNUNET_PEER_search (peer);
931   if (0 == peer_id)
932     {
933       GNUNET_break (0);
934       return;
935     }
936   for (i = 0; i < tunnel->npeers; i++)
937     if (tunnel->peers[i] == peer_id)
938       break;
939   if (i == tunnel->npeers)
940     {
941       GNUNET_break (0);
942       return;
943     }
944   GNUNET_PEER_change_rc (peer_id, -1);
945   tunnel->peers[i] = tunnel->peers[tunnel->npeers-1];
946   GNUNET_array_grow (tunnel->peers,
947                      tunnel->npeers,
948                      tunnel->npeers - 1);
949   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
950   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_DEL);
951   msg.tunnel_id = htonl (tunnel->tid);
952   memcpy (&msg.peer, peer, sizeof (struct GNUNET_PeerIdentity));
953   send_packet (tunnel->mesh, &msg.header);
954 }
955
956
957 /**
958  * Request that the mesh should try to connect to a peer supporting the given
959  * message type.
960  *
961  * @param tunnel handle to existing tunnel
962  * @param timeout how long to try to establish a connection
963  * @param app_type application type that must be supported by the peer (MESH
964  *                 should discover peer in proximity handling this type)
965  */
966 void
967 GNUNET_MESH_peer_request_connect_by_type (struct GNUNET_MESH_Tunnel *tunnel,
968                                           struct GNUNET_TIME_Relative timeout,
969                                           GNUNET_MESH_ApplicationType app_type)
970 {
971   struct GNUNET_MESH_ConnectPeerByType msg;
972
973   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
974   msg.header.type =  htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_BY_TYPE);
975   msg.tunnel_id = htonl (tunnel->tid);
976   msg.type = htonl (app_type);
977   send_packet (tunnel->mesh, &msg.header);
978   //   TODO: remember timeout
979 }
980
981
982 /**
983  * Ask the mesh to call "notify" once it is ready to transmit the
984  * given number of bytes to the specified "target".  If we are not yet
985  * connected to the specified peer, a call to this function will cause
986  * us to try to establish a connection.
987  *
988  * @param tunnel tunnel to use for transmission
989  * @param cork is corking allowed for this transmission?
990  * @param priority how important is the message?
991  * @param maxdelay how long can the message wait?
992  * @param target destination for the message,
993  *               NULL for multicast to all tunnel targets
994  * @param notify_size how many bytes of buffer space does notify want?
995  * @param notify function to call when buffer space is available;
996  *        will be called with NULL on timeout or if the overall queue
997  *        for this peer is larger than queue_size and this is currently
998  *        the message with the lowest priority
999  * @param notify_cls closure for notify
1000  * @return non-NULL if the notify callback was queued,
1001  *         NULL if we can not even queue the request (insufficient
1002  *         memory); if NULL is returned, "notify" will NOT be called.
1003  */
1004 struct GNUNET_MESH_TransmitHandle *
1005 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
1006                                    uint32_t priority,
1007                                    struct GNUNET_TIME_Relative maxdelay,
1008                                    const struct GNUNET_PeerIdentity *target,
1009                                    size_t notify_size,
1010                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1011                                    void *notify_cls)
1012 {
1013   struct GNUNET_MESH_TransmitHandle *q;
1014
1015   if (get_queue_length (tunnel->mesh) >= tunnel->mesh->max_queue_size)
1016     return NULL; /* queue full */
1017
1018   q = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
1019   q->tunnel = tunnel;
1020   q->priority = priority;
1021   q->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1022   q->target = GNUNET_PEER_intern (target);
1023   q->size = notify_size;
1024   q->notify = notify;
1025   q->notify_cls = notify_cls;
1026   queue_transmit_handle (tunnel->mesh, q);
1027   return q;
1028 }
1029
1030
1031 /**
1032  * Cancel the specified transmission-ready notification.
1033  *
1034  * @param th handle that was returned by "notify_transmit_ready".
1035  */
1036 void
1037 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
1038 {
1039   struct GNUNET_MESH_Handle *mesh;
1040   
1041   mesh = th->tunnel->mesh;
1042   if (q->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1043     GNUNET_SCHEDULER_cancel (q->timeout_task);
1044   GNUNET_CONTAINER_DLL_remove (mesh->queue_head, 
1045                                mesh->queue_tail,
1046                                th);
1047   GNUNET_free (th);
1048   if ( (NULL == mesh->queue_head) &&
1049        (NULL != mesh->th) )
1050     {
1051       /* queue empty, no point in asking for transmission */
1052       GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
1053       mesh->th = NULL;
1054     }    
1055 }
1056
1057
1058 #if 0                           /* keep Emacsens' auto-indent happy */
1059 {
1060 #endif
1061 #ifdef __cplusplus
1062 }
1063 #endif