don't try to receive before successfully connecting and sending the local connect...
[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_queue
64 {
65     /**
66      * Double Linked list
67      */
68   struct GNUNET_MESH_queue *next;
69   struct GNUNET_MESH_queue *prev;
70
71     /**
72      * Size of the data to follow
73      */
74   uint16_t size;
75
76     /**
77      * Data itself
78      */
79   void *data;
80 };
81
82
83 /**
84  * Opaque handle to the service.
85  */
86 struct GNUNET_MESH_Handle
87 {
88     /**
89      * Handle to the server connection, to send messages later
90      */
91   struct GNUNET_CLIENT_Connection *client;
92
93     /**
94      * Set of handlers used for processing incoming messages in the tunnels
95      */
96   const struct GNUNET_MESH_MessageHandler *message_handlers;
97   int n_handlers;
98
99     /**
100      * Set of applications that should be claimed to be offered at this node.
101      * Note that this is just informative, the appropiate handlers must be
102      * registered independently and the mapping is up to the developer of the
103      * client application.
104      */
105   const GNUNET_MESH_ApplicationType *applications;
106   int n_applications;
107
108     /**
109      * Double linked list of the tunnels this client is connected to.
110      */
111   struct GNUNET_MESH_Tunnel *tunnels_head;
112   struct GNUNET_MESH_Tunnel *tunnels_tail;
113
114     /**
115      * tid of the next tunnel to create (to avoid reusing IDs often)
116      */
117   MESH_TunnelNumber next_tid;
118
119     /**
120      * Callback for tunnel disconnection
121      */
122   GNUNET_MESH_TunnelEndHandler *cleaner;
123
124     /**
125      * Handle to cancel pending transmissions in case of disconnection
126      */
127   struct GNUNET_CLIENT_TransmitHandle *th;
128
129     /**
130      * Closure for all the handlers given by the client
131      */
132   void *cls;
133
134     /**
135      * Messages to send to the service
136      */
137   struct GNUNET_MESH_queue *queue_head;
138   struct GNUNET_MESH_queue *queue_tail;
139
140   /**
141    * Have we started the task to receive messages from the service
142    * yet? We do this after we send the 'MESH_LOCAL_CONNECT' message.
143    */
144   int in_receive;
145 };
146
147 /**
148  * Opaque handle to a tunnel.
149  */
150 struct GNUNET_MESH_Tunnel
151 {
152
153     /**
154      * DLL
155      */
156   struct GNUNET_MESH_Tunnel *next;
157   struct GNUNET_MESH_Tunnel *prev;
158
159     /**
160      * Local ID of the tunnel
161      */
162   MESH_TunnelNumber tid;
163
164     /**
165      * Owner of the tunnel
166      */
167   GNUNET_PEER_Id owner;
168
169     /**
170      * Callback to execute when peers connect to the tunnel
171      */
172   GNUNET_MESH_TunnelConnectHandler connect_handler;
173
174     /**
175      * Callback to execute when peers disconnect to the tunnel
176      */
177   GNUNET_MESH_TunnelDisconnectHandler disconnect_handler;
178
179     /**
180      * All peers added to the tunnel
181      */
182   GNUNET_PEER_Id *peers;
183
184     /**
185      * Number of peer added to the tunnel
186      */
187   uint32_t npeers;
188
189     /**
190      * Closure for the connect/disconnect handlers
191      */
192   void *cls;
193
194     /**
195      * Handle to the mesh this tunnel belongs to
196      */
197   struct GNUNET_MESH_Handle *mesh;
198 };
199
200 struct GNUNET_MESH_TransmitHandle
201 {
202   struct GNUNET_MESH_Tunnel *t;
203   struct GNUNET_MESH_queue *q;
204 };
205
206 /******************************************************************************/
207 /***********************     AUXILIARY FUNCTIONS      *************************/
208 /******************************************************************************/
209
210 /**
211  * Get the tunnel handler for the tunnel specified by id from the given handle
212  * @param h Mesh handle
213  * @param tid ID of the wanted tunnel
214  * @return handle to the required tunnel or NULL if not found
215  */
216 static struct GNUNET_MESH_Tunnel *
217 retrieve_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
218 {
219   struct GNUNET_MESH_Tunnel *t;
220
221   t = h->tunnels_head;
222   while (t != NULL)
223   {
224     if (t->tid == tid)
225       return t;
226     t = t->next;
227   }
228   return NULL;
229 }
230
231 /**
232  * Get the length of the transmission queue
233  * @param h mesh handle whose queue is to be measured
234  */
235 static uint32_t
236 get_queue_length (struct GNUNET_MESH_Handle *h)
237 {
238   struct GNUNET_MESH_queue *q;
239   uint32_t i;
240
241   /* count */
242   for (q = h->queue_head, i = 0; NULL != q; q = q->next, i++) ;
243
244   return i;
245 }
246
247
248 /******************************************************************************/
249 /***********************      RECEIVE HANDLERS     ****************************/
250 /******************************************************************************/
251
252 /**
253  * Process the new tunnel notification and add it to the tunnels in the handle
254  *
255  * @param h     The mesh handle
256  * @param msg   A message with the details of the new incoming tunnel
257  */
258 static void
259 process_tunnel_create (struct GNUNET_MESH_Handle *h,
260                        const struct GNUNET_MESH_TunnelMessage *msg)
261 {
262   struct GNUNET_MESH_Tunnel *t;
263   MESH_TunnelNumber tid;
264
265   tid = ntohl (msg->tunnel_id);
266   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_MARK)
267   {
268     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
269                 "MESH: received an incoming tunnel with tid in local range (%X)\n",
270                 tid);
271     GNUNET_break_op (0);
272     return;                     //FIXME abort? reconnect?
273   }
274   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
275   t->cls = h->cls;
276   t->mesh = h;
277   t->tid = tid;
278
279   return;
280 }
281
282
283 /**
284  * Process the new peer event and notify the upper level of it
285  *
286  * @param h     The mesh handle
287  * @param msg   A message with the details of the peer event
288  */
289 static void
290 process_peer_event (struct GNUNET_MESH_Handle *h,
291                     const struct GNUNET_MESH_PeerControl *msg)
292 {
293   struct GNUNET_MESH_Tunnel *t;
294   uint16_t size;
295
296   size = ntohs (msg->header.size);
297   if (size != sizeof (struct GNUNET_MESH_PeerControl))
298   {
299     GNUNET_break_op (0);
300     return;
301   }
302   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
303   if (NULL == t)
304   {
305     GNUNET_break_op (0);
306     return;
307   }
308   if (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_CONNECTED == msg->header.type)
309   {
310     if (NULL != t->connect_handler)
311     {
312       t->connect_handler (t->cls, &msg->peer, NULL);    /* FIXME atsi */
313     }
314   }
315   else
316   {
317     if (NULL != t->disconnect_handler)
318     {
319       t->disconnect_handler (t->cls, &msg->peer);
320     }
321   }
322 }
323
324
325 /**
326  * Process the incoming data packets
327  *
328  * @param h     The mesh handle
329  * @param msh   A message encapsulating the data
330  */
331 static void
332 process_incoming_data (struct GNUNET_MESH_Handle *h,
333                        const struct GNUNET_MessageHeader *message)
334 {
335   const struct GNUNET_MessageHeader *payload;
336   const struct GNUNET_MESH_MessageHandler *handler;
337   const struct GNUNET_PeerIdentity *peer;
338   struct GNUNET_MESH_Unicast *ucast;
339   struct GNUNET_MESH_Multicast *mcast;
340   struct GNUNET_MESH_ToOrigin *to_orig;
341   struct GNUNET_MESH_Tunnel *t;
342   uint16_t type;
343   int i;
344
345   type = ntohs (message->type);
346   switch (type)
347   {
348   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
349     ucast = (struct GNUNET_MESH_Unicast *) message;
350     t = retrieve_tunnel (h, ntohl (ucast->tid));
351     payload = (struct GNUNET_MessageHeader *) &ucast[1];
352     peer = &ucast->oid;
353     break;
354   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
355     mcast = (struct GNUNET_MESH_Multicast *) message;
356     t = retrieve_tunnel (h, ntohl (mcast->tid));
357     payload = (struct GNUNET_MessageHeader *) &mcast[1];
358     peer = &mcast->oid;
359     break;
360   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
361     to_orig = (struct GNUNET_MESH_ToOrigin *) message;
362     t = retrieve_tunnel (h, ntohl (to_orig->tid));
363     payload = (struct GNUNET_MessageHeader *) &to_orig[1];
364     peer = &to_orig->sender;
365     break;
366   default:
367     GNUNET_break_op (0);
368     return;
369   }
370   if (NULL == t)
371   {
372     GNUNET_break_op (0);
373     return;
374   }
375   for (i = 0; i < h->n_handlers; i++)
376   {
377     handler = &h->message_handlers[i];
378     if (handler->type == type)
379     {
380       if (GNUNET_OK == handler->callback (h->cls, t, NULL,      /* FIXME ctx */
381                                           peer, payload, NULL)) /* FIXME atsi */
382       {
383         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
384                     "MESH: callback completed successfully\n");
385       }
386       else
387       {
388         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
389                     "MESH: callback caused disconnection\n");
390         GNUNET_MESH_disconnect (h);
391       }
392     }
393   }
394 }
395
396
397 /**
398  * Function to process all messages received from the service
399  *
400  * @param cls closure
401  * @param msg message received, NULL on timeout or fatal error
402  */
403 static void
404 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
405 {
406   struct GNUNET_MESH_Handle *h = cls;
407
408   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: received a message from MESH\n");
409   if (msg == NULL)
410   {
411     GNUNET_break (0);
412     h->in_receive = GNUNET_NO;
413     // rather: do_reconnect () -- and set 'in_receive' to NO there...
414     // FIXME: service disconnect, handle!
415     return;
416   }
417
418   switch (ntohs (msg->type))
419   {
420     /* Notify of a new incoming tunnel */
421   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE:
422     process_tunnel_create (h, (struct GNUNET_MESH_TunnelMessage *) msg);
423     break;
424     /* Notify of a new peer or a peer disconnect in the tunnel */
425   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_CONNECTED:
426   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED:
427     process_peer_event (h, (struct GNUNET_MESH_PeerControl *) msg);
428     break;
429     /* Notify of a new data packet in the tunnel */
430   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
431   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
432   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
433     process_incoming_data (h, msg);
434     break;
435     /* We shouldn't get any other packages, log and ignore */
436   default:
437     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
438                 "MESH: unsolicited message form service (type %d)\n",
439                 ntohs (msg->type));
440   }
441
442   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: message processed\n");
443   GNUNET_CLIENT_receive (h->client, &msg_received, h,
444                          GNUNET_TIME_UNIT_FOREVER_REL);
445 }
446
447
448 /******************************************************************************/
449 /************************       SEND FUNCTIONS     ****************************/
450 /******************************************************************************/
451
452 /**
453  * Function called to send a message to the service.
454  * "buf" will be NULL and "size" zero if the socket was closed for writing in
455  * the meantime.
456  *
457  * @param cls closure, the mesh handle
458  * @param size number of bytes available in buf
459  * @param buf where the callee should write the connect message
460  * @return number of bytes written to buf
461  */
462 static size_t
463 send_raw (void *cls, size_t size, void *buf)
464 {
465   struct GNUNET_MESH_Handle *h = cls;
466   struct GNUNET_MESH_queue *q;
467
468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Send packet() Buffer %u\n", size);
469   h->th = NULL;
470   if (0 == size || NULL == buf)
471   {
472     // FIXME: disconnect, reconnect, retry?
473     // do_reconnect ();
474     return 0;
475   }
476   q = h->queue_head;
477   if (sizeof (struct GNUNET_MessageHeader) > size)
478   {
479     GNUNET_break (0);
480     GNUNET_assert (sizeof (struct GNUNET_MessageHeader) > q->size);
481     h->th =
482         GNUNET_CLIENT_notify_transmit_ready (h->client, q->size,
483                                              GNUNET_TIME_UNIT_FOREVER_REL,
484                                              GNUNET_YES, &send_raw, h);
485     return 0;
486   }
487   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   type: %i\n",
488               ntohs (((struct GNUNET_MessageHeader *) q->data)->type));
489   memcpy (buf, q->data, q->size);
490   GNUNET_free (q->data);
491   size = q->size;
492   GNUNET_CONTAINER_DLL_remove (h->queue_head, h->queue_tail, q);
493   GNUNET_free (q);
494   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   size: %u\n", size);
495
496   if (NULL != h->queue_head)
497   {
498     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   next size: %u\n",
499                 h->queue_head->size);
500     h->th =
501         GNUNET_CLIENT_notify_transmit_ready (h->client, h->queue_head->size,
502                                              GNUNET_TIME_UNIT_FOREVER_REL,
503                                              GNUNET_YES, &send_raw, h);
504   }
505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Send packet() END\n");
506   if (GNUNET_NO == h->in_receive)
507     {
508       h->in_receive = GNUNET_YES;
509       GNUNET_CLIENT_receive (h->client, &msg_received, h,
510                              GNUNET_TIME_UNIT_FOREVER_REL);
511     }
512   return size;
513 }
514
515 /**
516  * Auxiliary function to send a packet to the service
517  * Takes care of creating a new queue element and calling the tmt_rdy function
518  * if necessary.
519  * @param h mesh handle
520  * @param size size of the packet to transmit
521  * @param data packet itself
522  */
523 static void
524 send_packet (struct GNUNET_MESH_Handle *h, size_t size, void *data)
525 {
526   struct GNUNET_MESH_queue *q;
527
528   q = GNUNET_malloc (sizeof (struct GNUNET_MESH_queue));
529   q->size = size;
530   q->data = data;
531   GNUNET_CONTAINER_DLL_insert_tail (h->queue_head, h->queue_tail, q);
532   if (NULL != h->th)
533     return;
534   h->th =
535     GNUNET_CLIENT_notify_transmit_ready (h->client, size,
536                                          GNUNET_TIME_UNIT_FOREVER_REL,
537                                          GNUNET_YES, &send_raw, h);
538 }
539
540 /******************************************************************************/
541 /**********************      API CALL DEFINITIONS     *************************/
542 /******************************************************************************/
543
544 /**
545  * Connect to the mesh service.
546  *
547  * @param cfg configuration to use
548  * @param cls closure for the various callbacks that follow
549  *            (including handlers in the handlers array)
550  * @param cleaner function called when an *inbound* tunnel is destroyed
551  * @param handlers callbacks for messages we care about, NULL-terminated
552  *                 note that the mesh is allowed to drop notifications about
553  *                 inbound messages if the client does not process them fast
554  *                 enough (for this notification type, a bounded queue is used)
555  * @param stypes Application Types the client claims to offer
556  * @return handle to the mesh service
557  *         NULL on error (in this case, init is never called)
558  */
559 struct GNUNET_MESH_Handle *
560 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, void *cls,
561                      GNUNET_MESH_TunnelEndHandler cleaner,
562                      const struct GNUNET_MESH_MessageHandler *handlers,
563                      const GNUNET_MESH_ApplicationType *stypes)
564 {
565   struct GNUNET_MESH_Handle *h;
566   struct GNUNET_MESH_ClientConnect *msg;
567   GNUNET_MESH_ApplicationType *apps;
568   uint16_t napps;
569   uint16_t *types;
570   uint16_t ntypes;
571   size_t size;
572
573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: GNUNET_MESH_connect()\n");
574   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
575
576   h->cleaner = cleaner;
577   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
578   if (h->client == NULL)
579   {
580     GNUNET_break (0);
581     GNUNET_free (h);
582     return NULL;
583   }
584
585   h->cls = cls;
586   h->message_handlers = handlers;
587   h->applications = stypes;
588   h->next_tid = 0x80000000;
589
590   /* count handlers and apps, calculate size */
591   for (h->n_handlers = 0; handlers[h->n_handlers].type; h->n_handlers++) ;
592   for (h->n_applications = 0; stypes[h->n_applications]; h->n_applications++) ;
593   size = sizeof (struct GNUNET_MESH_ClientConnect);
594   size += h->n_handlers * sizeof (uint16_t);
595   size += h->n_applications * sizeof (GNUNET_MESH_ApplicationType);
596
597   /* build connection packet */
598   msg = GNUNET_malloc (size);
599   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT);
600   msg->header.size = htons (size);
601   types = (uint16_t *) & msg[1];
602   for (ntypes = 0; ntypes < h->n_handlers; ntypes++)
603   {
604     types[ntypes] = h->message_handlers[ntypes].type;
605   }
606   apps = (GNUNET_MESH_ApplicationType *) &types[ntypes];
607   for (napps = 0; napps < h->n_applications; napps++)
608   {
609     apps[napps] = h->applications[napps];
610   }
611   msg->applications = htons (napps);
612   msg->types = htons (ntypes);
613
614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
615               "mesh: Sending %lu bytes long message %d types and %d apps\n",
616               ntohs (msg->header.size), ntypes, napps);
617
618   send_packet (h, size, msg);
619
620
621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: GNUNET_MESH_connect() END\n");
622
623   return h;
624 }
625
626
627 /**
628  * Disconnect from the mesh service.
629  *
630  * @param handle connection to mesh to disconnect
631  */
632 void
633 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
634 {
635   if (NULL != handle->th)
636   {
637     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
638   }
639   if (NULL != handle->client)
640   {
641     GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
642   }
643   GNUNET_free (handle);
644 }
645
646
647 /**
648  * Create a new tunnel (we're initiator and will be allowed to add/remove peers
649  * and to broadcast).
650  *
651  * @param h mesh handle
652  * @param connect_handler function to call when peers are actually connected
653  * @param disconnect_handler function to call when peers are disconnected
654  * @param handler_cls closure for connect/disconnect handlers
655  */
656 struct GNUNET_MESH_Tunnel *
657 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h,
658                            GNUNET_MESH_TunnelConnectHandler connect_handler,
659                            GNUNET_MESH_TunnelDisconnectHandler
660                            disconnect_handler, void *handler_cls)
661 {
662   struct GNUNET_MESH_Tunnel *t;
663   struct GNUNET_MESH_TunnelMessage *msg;
664
665   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Creating new tunnel\n");
666   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
667
668   t->connect_handler = connect_handler;
669   t->disconnect_handler = disconnect_handler;
670   t->cls = handler_cls;
671   t->mesh = h;
672   t->tid = h->next_tid++;
673   h->next_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_MARK;      // keep in range
674
675   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_TunnelMessage));
676   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
677   msg->header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
678   msg->tunnel_id = htonl (t->tid);
679
680   send_packet (h, sizeof (struct GNUNET_MESH_TunnelMessage), msg);
681
682   return t;
683 }
684
685
686 /**
687  * Destroy an existing tunnel.
688  *
689  * @param tun tunnel handle
690  */
691 void
692 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tun)
693 {
694   struct GNUNET_MESH_Handle *h;
695   struct GNUNET_MESH_TunnelMessage *msg;
696
697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Destroying tunnel\n");
698
699   h = tun->mesh;
700   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_TunnelMessage));
701   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
702   msg->header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
703   msg->tunnel_id = htonl (tun->tid);
704
705   GNUNET_free (tun);
706
707   send_packet (h, sizeof (struct GNUNET_MESH_TunnelMessage), msg);
708 }
709
710
711 /**
712  * Request that a peer should be added to the tunnel.  The existing
713  * connect handler will be called ONCE with either success or failure.
714  *
715  * @param tunnel handle to existing tunnel
716  * @param timeout how long to try to establish a connection
717  * @param peer peer to add
718  */
719 void
720 GNUNET_MESH_peer_request_connect_add (struct GNUNET_MESH_Tunnel *tunnel,
721                                       struct GNUNET_TIME_Relative timeout,
722                                       const struct GNUNET_PeerIdentity *peer)
723 {
724   struct GNUNET_MESH_PeerControl *msg;
725   GNUNET_PEER_Id peer_id;
726   int i;
727
728   peer_id = GNUNET_PEER_intern (peer);
729   for (i = 0; i < tunnel->npeers; i++)
730   {
731     if (tunnel->peers[i] == peer_id)
732     {
733       GNUNET_PEER_change_rc (peer_id, -1);
734       return;
735     }
736   }
737   tunnel->npeers++;
738   tunnel->peers =
739       GNUNET_realloc (tunnel->peers, tunnel->npeers * sizeof (GNUNET_PEER_Id));
740   tunnel->peers[tunnel->npeers - 1] = peer_id;
741
742   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PeerControl));
743   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
744   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_ADD);
745   msg->tunnel_id = htonl (tunnel->tid);
746   memcpy (&msg->peer, peer, sizeof (struct GNUNET_PeerIdentity));
747
748   send_packet (tunnel->mesh, sizeof (struct GNUNET_MESH_PeerControl), msg);
749
750 //   tunnel->connect_handler (tunnel->cls, peer, NULL); FIXME call this later
751 //   TODO: remember timeout
752   return;
753 }
754
755
756 /**
757  * Request that a peer should be removed from the tunnel.  The existing
758  * disconnect handler will be called ONCE if we were connected.
759  *
760  * @param tunnel handle to existing tunnel
761  * @param peer peer to remove
762  */
763 void
764 GNUNET_MESH_peer_request_connect_del (struct GNUNET_MESH_Tunnel *tunnel,
765                                       const struct GNUNET_PeerIdentity *peer)
766 {
767   struct GNUNET_MESH_PeerControl *msg;
768   GNUNET_PEER_Id peer_id;
769   int i;
770
771   peer_id = GNUNET_PEER_search (peer);
772   if (0 == peer_id)
773     return;
774   for (i = 0; i < tunnel->npeers; i++)
775   {
776     if (tunnel->peers[i] == peer_id)
777     {
778       GNUNET_PEER_change_rc (peer_id, -1);
779       tunnel->npeers--;
780       while (i < tunnel->npeers)
781       {
782         tunnel->peers[i] = tunnel->peers[i + 1];
783         i++;
784       }
785       tunnel->peers =
786           GNUNET_realloc (tunnel->peers,
787                           tunnel->npeers * sizeof (GNUNET_PEER_Id));
788       msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PeerControl));
789       msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
790       msg->header.type =
791           htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_DEL);
792       msg->tunnel_id = htonl (tunnel->tid);
793       memcpy (&msg->peer, peer, sizeof (struct GNUNET_PeerIdentity));
794
795       send_packet (tunnel->mesh, sizeof (struct GNUNET_MESH_PeerControl), msg);
796
797       return;
798     }
799   }
800   //   TODO: remember timeout
801   return;
802 }
803
804
805 /**
806  * Request that the mesh should try to connect to a peer supporting the given
807  * message type.
808  *
809  * @param tunnel handle to existing tunnel
810  * @param timeout how long to try to establish a connection
811  * @param app_type application type that must be supported by the peer (MESH
812  *                 should discover peer in proximity handling this type)
813  */
814 void
815 GNUNET_MESH_peer_request_connect_by_type (struct GNUNET_MESH_Tunnel *tunnel,
816                                           struct GNUNET_TIME_Relative timeout,
817                                           GNUNET_MESH_ApplicationType app_type)
818 {
819   struct GNUNET_MESH_ConnectPeerByType *msg;
820
821   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_ConnectPeerByType));
822   msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
823   msg->header.type =
824       htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_BY_TYPE);
825   msg->tunnel_id = htonl (tunnel->tid);
826   msg->type = htonl (app_type);
827
828   send_packet (tunnel->mesh, sizeof (struct GNUNET_MESH_ConnectPeerByType),
829                msg);
830   //   TODO: remember timeout
831   return;
832 }
833
834
835 /**
836  * Ask the mesh to call "notify" once it is ready to transmit the
837  * given number of bytes to the specified "target".  If we are not yet
838  * connected to the specified peer, a call to this function will cause
839  * us to try to establish a connection.
840  *
841  * @param tunnel tunnel to use for transmission
842  * @param cork is corking allowed for this transmission?
843  * @param priority how important is the message?
844  * @param maxdelay how long can the message wait?
845  * @param target destination for the message,
846  *               NULL for multicast to all tunnel targets
847  * @param notify_size how many bytes of buffer space does notify want?
848  * @param notify function to call when buffer space is available;
849  *        will be called with NULL on timeout or if the overall queue
850  *        for this peer is larger than queue_size and this is currently
851  *        the message with the lowest priority
852  * @param notify_cls closure for notify
853  * @return non-NULL if the notify callback was queued,
854  *         NULL if we can not even queue the request (insufficient
855  *         memory); if NULL is returned, "notify" will NOT be called.
856  */
857 struct GNUNET_MESH_TransmitHandle *
858 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
859                                    uint32_t priority,
860                                    struct GNUNET_TIME_Relative maxdelay,
861                                    const struct GNUNET_PeerIdentity *target,
862                                    size_t notify_size,
863                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
864                                    void *notify_cls)
865 {
866   struct GNUNET_MESH_TransmitHandle *handle;
867
868   handle = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
869   handle->t = tunnel;
870   handle->q = GNUNET_malloc (sizeof (struct GNUNET_MESH_queue));
871   handle->q->size = notify_size;
872   handle->q->data = GNUNET_malloc (notify_size);
873
874   if (get_queue_length (tunnel->mesh) < MESH_API_MAX_QUEUE)
875   {
876     notify (notify_cls, notify_size, handle->q->data);
877     GNUNET_CONTAINER_DLL_insert_tail (tunnel->mesh->queue_head,
878                                       tunnel->mesh->queue_tail, handle->q);
879   }
880   else
881   {
882     // TODO dataless - queue
883   }
884
885   return handle;
886 }
887
888
889 /**
890  * Cancel the specified transmission-ready notification.
891  *
892  * @param th handle that was returned by "notify_transmit_ready".
893  */
894 void
895 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
896 {
897   GNUNET_CONTAINER_DLL_remove (th->t->mesh->queue_head, th->t->mesh->queue_tail,
898                                th->q);
899   // TODO remove from dataless queue
900   GNUNET_free (th->q->data);
901   GNUNET_free (th->q);
902   GNUNET_free (th);
903 }
904
905
906 #if 0                           /* keep Emacsens' auto-indent happy */
907 {
908 #endif
909 #ifdef __cplusplus
910 }
911 #endif