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