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