use define
[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   char *cbuf = buf;
516   size_t ret;
517   size_t psize;
518
519   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Send packet() Buffer %u\n", size);
520   h->th = NULL;
521   if ( (0 == size) || (NULL == buf) )
522   {
523     // FIXME: disconnect, reconnect, retry?
524     // do_reconnect ();
525     return 0;
526   }
527   ret = 0;
528   while ( (NULL != (q = h->queue_head)) &&
529           (size >= q->size) )
530     {
531       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
532                        "mesh-api",
533                        "type: %u\n",
534                        ntohs (q->data->type));
535       if (NULL == q->data)
536         {
537           GNUNET_assert (NULL != q->notify);
538           if (q->target == 0)
539             {
540               /* multicast */
541               struct GNUNET_MESH_Multicast mc; 
542               
543               GNUNET_assert (size >= sizeof (mc) + q->size);
544               psize = q->notify (q->notify_cls,
545                                  size - sizeof (mc), 
546                                  &cbuf[sizeof(mc)]);
547               if (psize > 0)
548                 {
549                   mc.header.size = htons (sizeof (mc) + q->size);
550                   mc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
551                   mc.tid = htonl (q->tunnel->tid);
552                   memset (&mc.oid, 0, sizeof (struct GNUNET_PeerIdentity)); /* myself */
553                   memcpy (cbuf, &mc, sizeof (mc));
554                   psize = q->size + sizeof (mc);
555                 }
556             }
557           else
558             {
559               /* unicast */
560               struct GNUNET_MESH_Unicast uc; 
561               
562               GNUNET_assert (size >= sizeof (uc) + q->size);
563               psize = q->notify (q->notify_cls,
564                                  size - sizeof (uc), 
565                                  &cbuf[sizeof(uc)]);
566               if (psize > 0)
567                 {
568                   uc.header.size = htons (sizeof (uc) + q->size);
569                   uc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
570                   uc.tid = htonl (q->tunnel->tid);
571                   memset (&uc.oid, 0, sizeof (struct GNUNET_PeerIdentity)); /* myself */
572                   GNUNET_PEER_resolve (q->target, &uc.destination);
573                   memcpy (cbuf, &uc, sizeof (uc));
574                   psize = q->size + sizeof (uc);
575                 }         
576             }
577         }
578       else
579         {
580           memcpy (cbuf, q->data, q->size);
581           psize = q->size;
582         }
583       if (q->timeout_task != GNUNET_SCHEDULER_NO_TASK)
584         GNUNET_SCHEDULER_cancel (q->timeout_task);
585       GNUNET_CONTAINER_DLL_remove (h->queue_head, h->queue_tail, q);
586       GNUNET_free (q);
587       cbuf += psize;
588       size -= psize;
589       ret += psize;
590     }
591
592   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   size: %u\n", ret);
593
594   if (NULL != (q = h->queue_head))
595   {
596     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   next size: %u\n",
597                 q->size);
598     h->th =
599       GNUNET_CLIENT_notify_transmit_ready (h->client, q->size,
600                                            GNUNET_TIME_UNIT_FOREVER_REL,
601                                            GNUNET_YES, &send_raw, h);
602   }
603   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Send packet() END\n");
604   if (GNUNET_NO == h->in_receive)
605     {
606       h->in_receive = GNUNET_YES;
607       GNUNET_CLIENT_receive (h->client, &msg_received, h,
608                              GNUNET_TIME_UNIT_FOREVER_REL);
609     }
610   return ret;
611 }
612
613
614 static void
615 timeout_transmission (void *cls,
616                       const struct GNUNET_SCHEDULER_TaskContext *tc)
617 {
618   struct GNUNET_MESH_TransmitHandle *q = cls;
619   struct GNUNET_MESH_Handle *mesh;
620   
621   mesh = q->tunnel->mesh;
622   GNUNET_CONTAINER_DLL_remove (mesh->queue_head, 
623                                mesh->queue_tail,
624                                q);
625   if (q->notify != NULL)
626     q->notify (q->notify_cls, 0, NULL); /* signal timeout */
627   GNUNET_free (q);    
628   if ( (NULL == mesh->queue_head) &&
629        (NULL != mesh->th) )
630     {
631       /* queue empty, no point in asking for transmission */
632       GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
633       mesh->th = NULL;
634     }    
635 }
636
637
638 /**
639  * Add a transmit handle to the transmission queue (by priority).
640  * Also manage timeout.
641  *
642  * @param h mesh handle with the queue head and tail
643  * @param q handle to add
644  */
645 static void
646 queue_transmit_handle (struct GNUNET_MESH_Handle *h,
647                        struct GNUNET_MESH_TransmitHandle *q)
648 {
649   struct GNUNET_MESH_TransmitHandle *p;
650
651   p = h->queue_head;
652   while ( (NULL != p) && (q->priority < p->priority) )
653     p = p->next;
654   GNUNET_CONTAINER_DLL_insert_after (h->queue_head, h->queue_tail, p->prev, q);
655   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value != q->timeout.abs_value)
656     q->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (q->timeout),
657                                                     &timeout_transmission,
658                                                     q);
659 }
660
661
662 /**
663  * Auxiliary function to send a packet to the service
664  * Takes care of creating a new queue element and calling the tmt_rdy function
665  * if necessary.
666  * @param h mesh handle
667  * @param msg message to transmit
668  */
669 static void
670 send_packet (struct GNUNET_MESH_Handle *h, 
671              const struct GNUNET_MessageHeader *msg)
672 {
673   struct GNUNET_MESH_TransmitHandle *q;
674   size_t msize;
675
676   msize = ntohs (msg->size);
677   q = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle) + msize);
678   q->priority = UINT32_MAX;
679   q->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;  
680   q->size = msize;
681   q->data = (void*) &q[1];
682   memcpy (&q[1], msg, msize);
683   queue_transmit_handle (h, q);
684   if (NULL != h->th)
685     return;
686   h->th =
687     GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
688                                          GNUNET_TIME_UNIT_FOREVER_REL,
689                                          GNUNET_YES, &send_raw, h);
690 }
691
692 /******************************************************************************/
693 /**********************      API CALL DEFINITIONS     *************************/
694 /******************************************************************************/
695
696 /**
697  * Connect to the mesh service.
698  *
699  * @param cfg configuration to use
700  * @param cls closure for the various callbacks that follow
701  *            (including handlers in the handlers array)
702  * @param cleaner function called when an *inbound* tunnel is destroyed
703  * @param handlers callbacks for messages we care about, NULL-terminated
704  *                 note that the mesh is allowed to drop notifications about
705  *                 inbound messages if the client does not process them fast
706  *                 enough (for this notification type, a bounded queue is used)
707  * @param stypes Application Types the client claims to offer
708  * @return handle to the mesh service
709  *         NULL on error (in this case, init is never called)
710  */
711 struct GNUNET_MESH_Handle *
712 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, void *cls,
713                      GNUNET_MESH_TunnelEndHandler cleaner,
714                      const struct GNUNET_MESH_MessageHandler *handlers,
715                      const GNUNET_MESH_ApplicationType *stypes)
716 {
717   struct GNUNET_MESH_Handle *h;
718   struct GNUNET_MESH_ClientConnect *msg;
719   GNUNET_MESH_ApplicationType *apps;
720   uint16_t napps;
721   uint16_t *types;
722   uint16_t ntypes;
723   size_t size;
724
725   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: GNUNET_MESH_connect()\n");
726   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
727   h->max_queue_size = MESH_API_MAX_QUEUE; /* FIXME: add to arguments to 'GNUNET_MESH_connect' */
728   h->cleaner = cleaner;
729   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
730   if (h->client == NULL)
731   {
732     GNUNET_break (0);
733     GNUNET_free (h);
734     return NULL;
735   }
736
737   h->cls = cls;
738   h->message_handlers = handlers;
739   h->applications = stypes;
740   h->next_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_MARK;
741
742   /* count handlers and apps, calculate size */
743   for (h->n_handlers = 0; handlers[h->n_handlers].type; h->n_handlers++) ;
744   for (h->n_applications = 0; stypes[h->n_applications]; h->n_applications++) ;
745
746   size = sizeof (struct GNUNET_MESH_ClientConnect);
747   size += h->n_handlers * sizeof (uint16_t);
748   size += h->n_applications * sizeof (GNUNET_MESH_ApplicationType);
749
750   {
751     char buf[size];
752
753     /* build connection packet */
754     msg = (struct GNUNET_MESH_ClientConnect *) buf;
755     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT);
756     msg->header.size = htons (size);
757     types = (uint16_t *) & msg[1];
758     for (ntypes = 0; ntypes < h->n_handlers; ntypes++)
759       types[ntypes] = h->message_handlers[ntypes].type;      
760     apps = (GNUNET_MESH_ApplicationType *) &types[ntypes];
761     for (napps = 0; napps < h->n_applications; napps++)
762       apps[napps] = h->applications[napps];      
763     msg->applications = htons (napps);
764     msg->types = htons (ntypes);
765
766     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
767                 "mesh: Sending %lu bytes long message %d types and %d apps\n",
768                 ntohs (msg->header.size), ntypes, napps);
769     
770     send_packet (h, &msg->header);
771   }
772
773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: GNUNET_MESH_connect() END\n");
774
775   return h;
776 }
777
778
779 /**
780  * Disconnect from the mesh service.
781  *
782  * @param handle connection to mesh to disconnect
783  */
784 void
785 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
786 {
787   if (NULL != handle->th)
788   {
789     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
790   }
791   if (NULL != handle->client)
792   {
793     GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
794   }
795   GNUNET_free (handle);
796 }
797
798
799 /**
800  * Create a new tunnel (we're initiator and will be allowed to add/remove peers
801  * and to broadcast).
802  *
803  * @param h mesh handle
804  * @param connect_handler function to call when peers are actually connected
805  * @param disconnect_handler function to call when peers are disconnected
806  * @param handler_cls closure for connect/disconnect handlers
807  */
808 struct GNUNET_MESH_Tunnel *
809 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h,
810                            GNUNET_MESH_TunnelConnectHandler connect_handler,
811                            GNUNET_MESH_TunnelDisconnectHandler
812                            disconnect_handler, void *handler_cls)
813 {
814   struct GNUNET_MESH_Tunnel *t;
815   struct GNUNET_MESH_TunnelMessage msg;
816
817   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Creating new tunnel\n");
818   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
819
820   t->connect_handler = connect_handler;
821   t->disconnect_handler = disconnect_handler;
822   t->cls = handler_cls;
823   t->mesh = h;
824   t->tid = h->next_tid++;
825   h->next_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_MARK;      // keep in range
826
827   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
828   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
829   msg.tunnel_id = htonl (t->tid);
830   send_packet (h, &msg.header);
831   return t;
832 }
833
834
835 /**
836  * Destroy an existing tunnel.
837  *
838  * @param tun tunnel handle
839  */
840 void
841 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tun)
842 {
843   struct GNUNET_MESH_Handle *h;
844   struct GNUNET_MESH_TunnelMessage *msg;
845
846   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Destroying tunnel\n");
847
848   h = tun->mesh;
849   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_TunnelMessage));
850   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
851   msg->header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
852   msg->tunnel_id = htonl (tun->tid);
853
854   GNUNET_free (tun);
855
856   send_packet (h, &msg->header);
857 }
858
859
860 /**
861  * Request that a peer should be added to the tunnel.  The existing
862  * connect handler will be called ONCE with either success or failure.
863  *
864  * @param tunnel handle to existing tunnel
865  * @param timeout how long to try to establish a connection
866  * @param peer peer to add
867  */
868 void
869 GNUNET_MESH_peer_request_connect_add (struct GNUNET_MESH_Tunnel *tunnel,
870                                       struct GNUNET_TIME_Relative timeout,
871                                       const struct GNUNET_PeerIdentity *peer)
872 {
873   struct GNUNET_MESH_PeerControl *msg;
874   GNUNET_PEER_Id peer_id;
875   unsigned int i;
876   
877   peer_id = GNUNET_PEER_intern (peer);
878   for (i = 0; i < tunnel->npeers; i++)
879   {
880     if (tunnel->peers[i] == peer_id)
881     {
882       GNUNET_PEER_change_rc (peer_id, -1);
883       return;
884     }
885   }
886   tunnel->npeers++;
887   tunnel->peers =
888       GNUNET_realloc (tunnel->peers, tunnel->npeers * sizeof (GNUNET_PEER_Id));
889   tunnel->peers[tunnel->npeers - 1] = peer_id;
890
891   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PeerControl));
892   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
893   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_ADD);
894   msg->tunnel_id = htonl (tunnel->tid);
895   msg->timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (timeout));
896   memcpy (&msg->peer, peer, sizeof (struct GNUNET_PeerIdentity));
897
898   send_packet (tunnel->mesh, &msg->header);
899
900 //   tunnel->connect_handler (tunnel->cls, peer, NULL); FIXME call this later
901 //   TODO: remember timeout
902   return;
903 }
904
905
906 /**
907  * Request that a peer should be removed from the tunnel.  The existing
908  * disconnect handler will be called ONCE if we were connected.
909  *
910  * @param tunnel handle to existing tunnel
911  * @param peer peer to remove
912  */
913 void
914 GNUNET_MESH_peer_request_connect_del (struct GNUNET_MESH_Tunnel *tunnel,
915                                       const struct GNUNET_PeerIdentity *peer)
916 {
917   struct GNUNET_MESH_PeerControl msg;
918   GNUNET_PEER_Id peer_id;
919   unsigned int i;
920
921   peer_id = GNUNET_PEER_search (peer);
922   if (0 == peer_id)
923     {
924       GNUNET_break (0);
925       return;
926     }
927   for (i = 0; i < tunnel->npeers; i++)
928     if (tunnel->peers[i] == peer_id)
929       break;
930   if (i == tunnel->npeers)
931     {
932       GNUNET_break (0);
933       return;
934     }
935   GNUNET_PEER_change_rc (peer_id, -1);
936   tunnel->peers[i] = tunnel->peers[tunnel->npeers-1];
937   GNUNET_array_grow (tunnel->peers,
938                      tunnel->npeers,
939                      tunnel->npeers - 1);
940   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
941   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_DEL);
942   msg.tunnel_id = htonl (tunnel->tid);
943   msg.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
944   memcpy (&msg.peer, peer, sizeof (struct GNUNET_PeerIdentity));
945   send_packet (tunnel->mesh, &msg.header);
946 }
947
948
949 /**
950  * Request that the mesh should try to connect to a peer supporting the given
951  * message type.
952  *
953  * @param tunnel handle to existing tunnel
954  * @param timeout how long to try to establish a connection
955  * @param app_type application type that must be supported by the peer (MESH
956  *                 should discover peer in proximity handling this type)
957  */
958 void
959 GNUNET_MESH_peer_request_connect_by_type (struct GNUNET_MESH_Tunnel *tunnel,
960                                           struct GNUNET_TIME_Relative timeout,
961                                           GNUNET_MESH_ApplicationType app_type)
962 {
963   struct GNUNET_MESH_ConnectPeerByType msg;
964
965   /* FIXME: remember request connect by type for reconnect! */
966   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
967   msg.header.type =  htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_BY_TYPE);
968   msg.tunnel_id = htonl (tunnel->tid);
969   msg.timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (timeout));
970   msg.type = htonl (app_type);
971   send_packet (tunnel->mesh, &msg.header);
972 }
973
974
975 /**
976  * Ask the mesh to call "notify" once it is ready to transmit the
977  * given number of bytes to the specified "target".  If we are not yet
978  * connected to the specified peer, a call to this function will cause
979  * us to try to establish a connection.
980  *
981  * @param tunnel tunnel to use for transmission
982  * @param cork is corking allowed for this transmission?
983  * @param priority how important is the message?
984  * @param maxdelay how long can the message wait?
985  * @param target destination for the message,
986  *               NULL for multicast to all tunnel targets
987  * @param notify_size how many bytes of buffer space does notify want?
988  * @param notify function to call when buffer space is available;
989  *        will be called with NULL on timeout or if the overall queue
990  *        for this peer is larger than queue_size and this is currently
991  *        the message with the lowest priority
992  * @param notify_cls closure for notify
993  * @return non-NULL if the notify callback was queued,
994  *         NULL if we can not even queue the request (insufficient
995  *         memory); if NULL is returned, "notify" will NOT be called.
996  */
997 struct GNUNET_MESH_TransmitHandle *
998 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
999                                    uint32_t priority,
1000                                    struct GNUNET_TIME_Relative maxdelay,
1001                                    const struct GNUNET_PeerIdentity *target,
1002                                    size_t notify_size,
1003                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1004                                    void *notify_cls)
1005 {
1006   struct GNUNET_MESH_TransmitHandle *q;
1007   size_t overhead;
1008
1009   if (get_queue_length (tunnel->mesh) >= tunnel->mesh->max_queue_size)
1010     return NULL; /* queue full */
1011
1012   q = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
1013   q->tunnel = tunnel;
1014   q->priority = priority;
1015   q->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1016   q->target = GNUNET_PEER_intern (target);
1017   overhead = (NULL == target) ? sizeof (struct GNUNET_MESH_Multicast) : sizeof (struct GNUNET_MESH_Unicast);
1018   q->size = notify_size + overhead;
1019   q->notify = notify;
1020   q->notify_cls = notify_cls;
1021   queue_transmit_handle (tunnel->mesh, q);
1022   return q;
1023 }
1024
1025
1026 /**
1027  * Cancel the specified transmission-ready notification.
1028  *
1029  * @param th handle that was returned by "notify_transmit_ready".
1030  */
1031 void
1032 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
1033 {
1034   struct GNUNET_MESH_Handle *mesh;
1035   
1036   mesh = th->tunnel->mesh;
1037   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1038     GNUNET_SCHEDULER_cancel (th->timeout_task);
1039   GNUNET_CONTAINER_DLL_remove (mesh->queue_head, 
1040                                mesh->queue_tail,
1041                                th);
1042   GNUNET_free (th);
1043   if ( (NULL == mesh->queue_head) &&
1044        (NULL != mesh->th) )
1045     {
1046       /* queue empty, no point in asking for transmission */
1047       GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
1048       mesh->th = NULL;
1049     }    
1050 }
1051
1052
1053 #if 0                           /* keep Emacsens' auto-indent happy */
1054 {
1055 #endif
1056 #ifdef __cplusplus
1057 }
1058 #endif