Added peer add timeout handling, tunnel connect/disconnect notifications
[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  * Notify client that the transmission has timed out
318  * @param cls closure
319  * @param tc task context
320  */
321 static void
322 timeout_transmission (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
323 {
324   struct GNUNET_MESH_TransmitHandle *th = cls;
325   struct GNUNET_MESH_Handle *mesh;
326
327   mesh = th->tunnel->mesh;
328   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
329   if (th->notify != NULL)
330     th->notify (th->notify_cls, 0, NULL);
331   GNUNET_free (th);
332   if ((NULL == mesh->th_head) && (NULL != mesh->th))
333   {
334     /* queue empty, no point in asking for transmission */
335     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
336     mesh->th = NULL;
337   }
338 }
339
340
341 /**
342  * Notify client that the transmission has timed out
343  * @param cls closure
344  * @param tc task context
345  */
346 static void
347 timeout_peer_request (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
348 {
349   struct GNUNET_MESH_Peer *p = cls;
350   struct GNUNET_PeerIdentity id;
351   unsigned int i;
352
353   GNUNET_assert (0 == p->connected);
354   for (i = 0; i < p->t->npeers; i++)
355   {
356     if (p->t->peers[i] == p)
357       break;
358   }
359   if (i == p->t->npeers)
360   {
361     GNUNET_break (0);
362     return;
363   }
364   p->t->peers[i] = p->t->peers[p->t->npeers - 1];
365   GNUNET_array_grow (p->t->peers, p->t->npeers, p->t->npeers - 1);
366
367   if (NULL != p->t->connect_handler)
368     p->t->connect_handler (p->t->cls, 0, NULL);
369
370   GNUNET_PEER_resolve (p->id, &id);
371   GNUNET_MESH_peer_request_connect_del (p->t, &id);
372 }
373
374 /**
375  * Add a transmit handle to the transmission queue by priority and set the
376  * timeout if needed.
377  *
378  * @param h mesh handle with the queue head and tail
379  * @param q handle to the packet to be transmitted
380  */
381 static void
382 add_to_queue (struct GNUNET_MESH_Handle *h,
383               struct GNUNET_MESH_TransmitHandle *th)
384 {
385   struct GNUNET_MESH_TransmitHandle *p;
386
387   p = h->th_head;
388   while ((NULL != p) && (th->priority < p->priority))
389     p = p->next;
390   if (NULL == p)
391     p = h->th_tail;
392   else
393     p = p->prev;
394   GNUNET_CONTAINER_DLL_insert_after (h->th_head, h->th_tail, p, th);
395   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value == th->timeout.abs_value)
396     return;
397   th->timeout_task =
398       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
399                                     (th->timeout), &timeout_transmission, th);
400 }
401
402
403 /******************************************************************************/
404 /***********************      RECEIVE HANDLERS     ****************************/
405 /******************************************************************************/
406
407 /**
408  * Process the new tunnel notification and add it to the tunnels in the handle
409  *
410  * @param h     The mesh handle
411  * @param msg   A message with the details of the new incoming tunnel
412  */
413 static void
414 process_tunnel_create (struct GNUNET_MESH_Handle *h,
415                        const struct GNUNET_MESH_TunnelMessage *msg)
416 {
417   struct GNUNET_MESH_Tunnel *t;
418   MESH_TunnelNumber tid;
419
420   tid = ntohl (msg->tunnel_id);
421   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_MARK)
422   {
423     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
424                 "MESH: received an incoming tunnel with tid in local range (%X)\n",
425                 tid);
426     GNUNET_break_op (0);
427     return;                     //FIXME abort? reconnect?
428   }
429   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
430   t->cls = h->cls;
431   t->mesh = h;
432   t->tid = tid;
433   return;
434 }
435
436
437 /**
438  * Process the new peer event and notify the upper level of it
439  *
440  * @param h     The mesh handle
441  * @param msg   A message with the details of the peer event
442  */
443 static void
444 process_peer_event (struct GNUNET_MESH_Handle *h,
445                     const struct GNUNET_MESH_PeerControl *msg)
446 {
447   struct GNUNET_MESH_Tunnel *t;
448   uint16_t size;
449
450   size = ntohs (msg->header.size);
451   if (size != sizeof (struct GNUNET_MESH_PeerControl))
452   {
453     GNUNET_break_op (0);
454     return;
455   }
456   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
457   if (NULL == t)
458   {
459     GNUNET_break_op (0);
460     return;
461   }
462   if (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_CONNECTED == msg->header.type)
463   {
464     if (NULL != t->connect_handler)
465     {
466       t->connect_handler (t->cls, &msg->peer, NULL);    /* FIXME atsi */
467     }
468   }
469   else
470   {
471     if (NULL != t->disconnect_handler)
472     {
473       t->disconnect_handler (t->cls, &msg->peer);
474     }
475   }
476 }
477
478
479 /**
480  * Process the incoming data packets
481  *
482  * @param h     The mesh handle
483  * @param msh   A message encapsulating the data
484  */
485 static void
486 process_incoming_data (struct GNUNET_MESH_Handle *h,
487                        const struct GNUNET_MessageHeader *message)
488 {
489   const struct GNUNET_MessageHeader *payload;
490   const struct GNUNET_MESH_MessageHandler *handler;
491   const struct GNUNET_PeerIdentity *peer;
492   struct GNUNET_MESH_Unicast *ucast;
493   struct GNUNET_MESH_Multicast *mcast;
494   struct GNUNET_MESH_ToOrigin *to_orig;
495   struct GNUNET_MESH_Tunnel *t;
496   uint16_t type;
497   int i;
498
499   type = ntohs (message->type);
500   switch (type)
501   {
502   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
503     ucast = (struct GNUNET_MESH_Unicast *) message;
504     t = retrieve_tunnel (h, ntohl (ucast->tid));
505     payload = (struct GNUNET_MessageHeader *) &ucast[1];
506     peer = &ucast->oid;
507     break;
508   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
509     mcast = (struct GNUNET_MESH_Multicast *) message;
510     t = retrieve_tunnel (h, ntohl (mcast->tid));
511     payload = (struct GNUNET_MessageHeader *) &mcast[1];
512     peer = &mcast->oid;
513     break;
514   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
515     to_orig = (struct GNUNET_MESH_ToOrigin *) message;
516     t = retrieve_tunnel (h, ntohl (to_orig->tid));
517     payload = (struct GNUNET_MessageHeader *) &to_orig[1];
518     peer = &to_orig->sender;
519     break;
520   default:
521     GNUNET_break_op (0);
522     return;
523   }
524   if (NULL == t)
525   {
526     GNUNET_break_op (0);
527     return;
528   }
529   for (i = 0; i < h->n_handlers; i++)
530   {
531     handler = &h->message_handlers[i];
532     if (handler->type == type)
533     {
534       if (GNUNET_OK == handler->callback (h->cls, t, NULL,      /* FIXME ctx */
535                                           peer, payload, NULL))
536       {                         /* FIXME atsi */
537         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
538                     "MESH: callback completed successfully\n");
539       }
540       else
541       {
542         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
543                     "MESH: callback caused disconnection\n");
544         GNUNET_MESH_disconnect (h);
545       }
546     }
547   }
548 }
549
550
551 /**
552  * Function to process all messages received from the service
553  *
554  * @param cls closure
555  * @param msg message received, NULL on timeout or fatal error
556  */
557 static void
558 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
559 {
560   struct GNUNET_MESH_Handle *h = cls;
561
562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: received a message from MESH\n");
563   if (msg == NULL)
564   {
565     GNUNET_break (0);
566     h->in_receive = GNUNET_NO;
567     // rather: do_reconnect () -- and set 'in_receive' to NO there...
568     // FIXME: service disconnect, handle!
569     return;
570   }
571   switch (ntohs (msg->type))
572   {
573     /* Notify of a new incoming tunnel */
574   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE:
575     process_tunnel_create (h, (struct GNUNET_MESH_TunnelMessage *) msg);
576     break;
577     /* Notify of a new peer or a peer disconnect in the tunnel */
578   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_CONNECTED:
579   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED:
580     process_peer_event (h, (struct GNUNET_MESH_PeerControl *) msg);
581     break;
582     /* Notify of a new data packet in the tunnel */
583   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
584   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
585   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
586     process_incoming_data (h, msg);
587     break;
588     /* We shouldn't get any other packages, log and ignore */
589   default:
590     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
591                 "MESH: unsolicited message form service (type %d)\n",
592                 ntohs (msg->type));
593   }
594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: message processed\n");
595   GNUNET_CLIENT_receive (h->client, &msg_received, h,
596                          GNUNET_TIME_UNIT_FOREVER_REL);
597 }
598
599
600 /******************************************************************************/
601 /************************       SEND FUNCTIONS     ****************************/
602 /******************************************************************************/
603
604 /**
605  * Function called to send a message to the service.
606  * "buf" will be NULL and "size" zero if the socket was closed for writing in
607  * the meantime.
608  *
609  * @param cls closure, the mesh handle
610  * @param size number of bytes available in buf
611  * @param buf where the callee should write the connect message
612  * @return number of bytes written to buf
613  */
614 static size_t
615 send_raw (void *cls, size_t size, void *buf)
616 {
617   struct GNUNET_MESH_Handle *h = cls;
618   struct GNUNET_MESH_TransmitHandle *th;
619   char *cbuf = buf;
620   size_t ret;
621   size_t psize;
622
623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Send packet() Buffer %u\n", size);
624   h->th = NULL;
625   if ((0 == size) || (NULL == buf))
626   {
627     // FIXME: disconnect, reconnect, retry?
628     // do_reconnect ();
629     return 0;
630   }
631   ret = 0;
632   while ((NULL != (th = h->th_head)) && (size >= th->size))
633   {
634     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "mesh-api", "type: %u\n",
635                      ntohs (th->data->type));
636     if (NULL == th->data)
637     {
638       GNUNET_assert (NULL != th->notify);
639       if (th->target == 0)
640       {
641         /* multicast */
642         struct GNUNET_MESH_Multicast mc;
643
644         GNUNET_assert (size >= sizeof (mc) + th->size);
645         psize =
646             th->notify (th->notify_cls, size - sizeof (mc), &cbuf[sizeof (mc)]);
647         if (psize > 0)
648         {
649           mc.header.size = htons (sizeof (mc) + th->size);
650           mc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
651           mc.tid = htonl (th->tunnel->tid);
652           memset (&mc.oid, 0, sizeof (struct GNUNET_PeerIdentity));     /* myself */
653           memcpy (cbuf, &mc, sizeof (mc));
654           psize = th->size + sizeof (mc);
655         }
656       }
657       else
658       {
659         /* unicast */
660         struct GNUNET_MESH_Unicast uc;
661
662         GNUNET_assert (size >= sizeof (uc) + th->size);
663         psize =
664             th->notify (th->notify_cls, size - sizeof (uc), &cbuf[sizeof (uc)]);
665         if (psize > 0)
666         {
667           uc.header.size = htons (sizeof (uc) + th->size);
668           uc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
669           uc.tid = htonl (th->tunnel->tid);
670           memset (&uc.oid, 0, sizeof (struct GNUNET_PeerIdentity));     /* myself */
671           GNUNET_PEER_resolve (th->target, &uc.destination);
672           memcpy (cbuf, &uc, sizeof (uc));
673           psize = th->size + sizeof (uc);
674         }
675       }
676     }
677     else
678     {
679       memcpy (cbuf, th->data, th->size);
680       psize = th->size;
681     }
682     if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
683       GNUNET_SCHEDULER_cancel (th->timeout_task);
684     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
685     GNUNET_free (th);
686     cbuf += psize;
687     size -= psize;
688     ret += psize;
689   }
690   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   size: %u\n", ret);
691   if (NULL != (th = h->th_head))
692   {
693     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   next size: %u\n", th->size);
694     h->th =
695         GNUNET_CLIENT_notify_transmit_ready (h->client, th->size,
696                                              GNUNET_TIME_UNIT_FOREVER_REL,
697                                              GNUNET_YES, &send_raw, h);
698   }
699   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Send packet() END\n");
700   if (GNUNET_NO == h->in_receive)
701   {
702     h->in_receive = GNUNET_YES;
703     GNUNET_CLIENT_receive (h->client, &msg_received, h,
704                            GNUNET_TIME_UNIT_FOREVER_REL);
705   }
706   return ret;
707 }
708
709
710 /**
711  * Auxiliary function to send an already constructed packet to the service.
712  * Takes care of creating a new queue element, copying the message and
713  * calling the tmt_rdy function if necessary.
714  * @param h mesh handle
715  * @param msg message to transmit
716  */
717 static void
718 send_packet (struct GNUNET_MESH_Handle *h,
719              const struct GNUNET_MessageHeader *msg)
720 {
721   struct GNUNET_MESH_TransmitHandle *th;
722   size_t msize;
723
724   msize = ntohs (msg->size);
725   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle) + msize);
726   th->priority = UINT32_MAX;
727   th->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
728   th->size = msize;
729   th->data = (void *) &th[1];
730   memcpy (&th[1], msg, msize);
731   add_to_queue (h, th);
732   if (NULL != h->th)
733     return;
734   h->th =
735       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
736                                            GNUNET_TIME_UNIT_FOREVER_REL,
737                                            GNUNET_YES, &send_raw, h);
738 }
739
740
741 /******************************************************************************/
742 /**********************      API CALL DEFINITIONS     *************************/
743 /******************************************************************************/
744
745 /**
746  * Connect to the mesh service.
747  *
748  * @param cfg configuration to use
749  * @param cls closure for the various callbacks that follow
750  *            (including handlers in the handlers array)
751  * @param queue_size size of the data message queue, shared among all tunnels
752  *                   (each tunnel is guaranteed to accept at least one message,
753  *                    no matter what is the status of other tunnels)
754  * @param cleaner function called when an *inbound* tunnel is destroyed
755  * @param handlers callbacks for messages we care about, NULL-terminated
756  *                 note that the mesh is allowed to drop notifications about
757  *                 inbound messages if the client does not process them fast
758  *                 enough (for this notification type, a bounded queue is used)
759  * @param stypes Application Types the client claims to offer
760  * @return handle to the mesh service
761  *         NULL on error (in this case, init is never called)
762  */
763 struct GNUNET_MESH_Handle *
764 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
765                      unsigned int queue_size, void *cls,
766                      GNUNET_MESH_TunnelEndHandler cleaner,
767                      const struct GNUNET_MESH_MessageHandler *handlers,
768                      const GNUNET_MESH_ApplicationType *stypes)
769 {
770   struct GNUNET_MESH_Handle *h;
771   struct GNUNET_MESH_ClientConnect *msg;
772   GNUNET_MESH_ApplicationType *apps;
773   uint16_t napps;
774   uint16_t *types;
775   uint16_t ntypes;
776   size_t size;
777
778   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: GNUNET_MESH_connect()\n");
779   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
780   h->max_queue_size = queue_size;
781   h->cleaner = cleaner;
782   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
783   if (h->client == NULL)
784   {
785     GNUNET_break (0);
786     GNUNET_free (h);
787     return NULL;
788   }
789   h->cls = cls;
790   h->message_handlers = handlers;
791   h->applications = stypes;
792   h->next_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_MARK;
793
794   /* count handlers and apps, calculate size */
795   for (h->n_handlers = 0; handlers[h->n_handlers].type; h->n_handlers++) ;
796   for (h->n_applications = 0; stypes[h->n_applications]; h->n_applications++) ;
797   size = sizeof (struct GNUNET_MESH_ClientConnect);
798   size += h->n_handlers * sizeof (uint16_t);
799   size += h->n_applications * sizeof (GNUNET_MESH_ApplicationType);
800
801   {
802     char buf[size];
803
804     /* build connection packet */
805     msg = (struct GNUNET_MESH_ClientConnect *) buf;
806     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT);
807     msg->header.size = htons (size);
808     types = (uint16_t *) & msg[1];
809     for (ntypes = 0; ntypes < h->n_handlers; ntypes++)
810       types[ntypes] = h->message_handlers[ntypes].type;
811     apps = (GNUNET_MESH_ApplicationType *) &types[ntypes];
812     for (napps = 0; napps < h->n_applications; napps++)
813       apps[napps] = h->applications[napps];
814     msg->applications = htons (napps);
815     msg->types = htons (ntypes);
816     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
817                 "mesh: Sending %lu bytes long message %d types and %d apps\n",
818                 ntohs (msg->header.size), ntypes, napps);
819     send_packet (h, &msg->header);
820   }
821   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: GNUNET_MESH_connect() END\n");
822   return h;
823 }
824
825
826 /**
827  * Disconnect from the mesh service.
828  *
829  * @param handle connection to mesh to disconnect
830  */
831 void
832 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
833 {
834   if (NULL != handle->th)
835   {
836     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
837   }
838   if (NULL != handle->client)
839   {
840     GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
841   }
842   GNUNET_free (handle);
843 }
844
845
846 /**
847  * Create a new tunnel (we're initiator and will be allowed to add/remove peers
848  * and to broadcast).
849  *
850  * @param h mesh handle
851  * @param connect_handler function to call when peers are actually connected
852  * @param disconnect_handler function to call when peers are disconnected
853  * @param handler_cls closure for connect/disconnect handlers
854  */
855 struct GNUNET_MESH_Tunnel *
856 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h,
857                            GNUNET_MESH_TunnelConnectHandler connect_handler,
858                            GNUNET_MESH_TunnelDisconnectHandler
859                            disconnect_handler, void *handler_cls)
860 {
861   struct GNUNET_MESH_Tunnel *t;
862   struct GNUNET_MESH_TunnelMessage msg;
863
864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Creating new tunnel\n");
865   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
866   t->connect_handler = connect_handler;
867   t->disconnect_handler = disconnect_handler;
868   t->cls = handler_cls;
869   t->mesh = h;
870   t->tid = h->next_tid++;
871   h->next_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_MARK;      // keep in range
872   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
873   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
874   msg.tunnel_id = htonl (t->tid);
875   send_packet (h, &msg.header);
876   return t;
877 }
878
879
880 /**
881  * Destroy an existing tunnel.
882  *
883  * @param tun tunnel handle
884  */
885 void
886 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tun)
887 {
888   struct GNUNET_MESH_Handle *h;
889   struct GNUNET_MESH_TunnelMessage msg;
890
891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Destroying tunnel\n");
892   h = tun->mesh;
893
894   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
895   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
896   msg.tunnel_id = htonl (tun->tid);
897   GNUNET_free (tun);
898   send_packet (h, &msg.header);
899 }
900
901
902 /**
903  * Request that a peer should be added to the tunnel.  The existing
904  * connect handler will be called ONCE with either success or failure.
905  * This function should NOT be called again with the same peer before the
906  * connect handler is called
907  *
908  * @param tunnel handle to existing tunnel
909  * @param timeout how long to try to establish a connection
910  * @param peer peer to add
911  */
912 void
913 GNUNET_MESH_peer_request_connect_add (struct GNUNET_MESH_Tunnel *tunnel,
914                                       struct GNUNET_TIME_Relative timeout,
915                                       const struct GNUNET_PeerIdentity *peer)
916 {
917   struct GNUNET_MESH_PeerControl msg;
918   struct GNUNET_MESH_Peer *p;
919   GNUNET_PEER_Id peer_id;
920   unsigned int i;
921
922   peer_id = GNUNET_PEER_intern (peer);
923   for (i = 0; i < tunnel->npeers; i++)
924   {
925     if (tunnel->peers[i]->id == peer_id)
926     {
927       GNUNET_PEER_change_rc (peer_id, -1);
928       /* FIXME: peer was already in the tunnel */
929       return;
930     }
931   }
932   p = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer));
933   p->id = peer_id;
934   p->t = tunnel;
935   p->cancel = GNUNET_SCHEDULER_add_delayed (timeout, &timeout_peer_request, p);
936   GNUNET_array_append (tunnel->peers, tunnel->npeers, p);
937
938   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
939   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_ADD);
940   msg.tunnel_id = htonl (tunnel->tid);
941   msg.peer = *peer;
942   send_packet (tunnel->mesh, &msg.header);
943 //   tunnel->connect_handler (tunnel->cls, peer, NULL); FIXME call this later
944 //   TODO: remember timeout
945   return;
946 }
947
948
949 /**
950  * Request that a peer should be removed from the tunnel.  The existing
951  * disconnect handler will be called ONCE if we were connected.
952  *
953  * @param tunnel handle to existing tunnel
954  * @param peer peer to remove
955  */
956 void
957 GNUNET_MESH_peer_request_connect_del (struct GNUNET_MESH_Tunnel *tunnel,
958                                       const struct GNUNET_PeerIdentity *peer)
959 {
960   struct GNUNET_MESH_PeerControl msg;
961   GNUNET_PEER_Id peer_id;
962   unsigned int i;
963
964   peer_id = GNUNET_PEER_search (peer);
965   if (0 == peer_id)
966   {
967     GNUNET_break (0);
968     return;
969   }
970   for (i = 0; i < tunnel->npeers; i++)
971     if (tunnel->peers[i]->id == peer_id)
972       break;
973   if (i == tunnel->npeers)
974   {
975     GNUNET_break (0);
976     return;
977   }
978   if (NULL != tunnel->disconnect_handler && tunnel->peers[i]->connected == 1)
979       tunnel->disconnect_handler (tunnel->cls, peer);
980   GNUNET_PEER_change_rc (peer_id, -1);
981   GNUNET_free (tunnel->peers[i]);
982   tunnel->peers[i] = tunnel->peers[tunnel->npeers - 1];
983   GNUNET_array_grow (tunnel->peers, tunnel->npeers, tunnel->npeers - 1);
984
985   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
986   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_DEL);
987   msg.tunnel_id = htonl (tunnel->tid);
988   memcpy (&msg.peer, peer, sizeof (struct GNUNET_PeerIdentity));
989   send_packet (tunnel->mesh, &msg.header);
990 }
991
992
993 /**
994  * Request that the mesh should try to connect to a peer supporting the given
995  * message type.
996  *
997  * @param tunnel handle to existing tunnel
998  * @param timeout how long to try to establish a connection
999  * @param app_type application type that must be supported by the peer (MESH
1000  *                 should discover peer in proximity handling this type)
1001  */
1002 void
1003 GNUNET_MESH_peer_request_connect_by_type (struct GNUNET_MESH_Tunnel *tunnel,
1004                                           struct GNUNET_TIME_Relative timeout,
1005                                           GNUNET_MESH_ApplicationType app_type)
1006 {
1007   struct GNUNET_MESH_ConnectPeerByType msg;
1008
1009   /* FIXME: remember request connect by type for reconnect! */
1010   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
1011   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_BY_TYPE);
1012   msg.tunnel_id = htonl (tunnel->tid);
1013   msg.type = htonl (app_type);
1014   send_packet (tunnel->mesh, &msg.header);
1015 }
1016
1017
1018 /**
1019  * Ask the mesh to call "notify" once it is ready to transmit the
1020  * given number of bytes to the specified "target".  If we are not yet
1021  * connected to the specified peer, a call to this function will cause
1022  * us to try to establish a connection.
1023  *
1024  * @param tunnel tunnel to use for transmission
1025  * @param cork is corking allowed for this transmission?
1026  * @param priority how important is the message?
1027  * @param maxdelay how long can the message wait?
1028  * @param target destination for the message,
1029  *               NULL for multicast to all tunnel targets
1030  * @param notify_size how many bytes of buffer space does notify want?
1031  * @param notify function to call when buffer space is available;
1032  *        will be called with NULL on timeout or if the overall queue
1033  *        for this peer is larger than queue_size and this is currently
1034  *        the message with the lowest priority
1035  * @param notify_cls closure for notify
1036  * @return non-NULL if the notify callback was queued,
1037  *         NULL if we can not even queue the request (insufficient
1038  *         memory); if NULL is returned, "notify" will NOT be called.
1039  */
1040 struct GNUNET_MESH_TransmitHandle *
1041 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
1042                                    uint32_t priority,
1043                                    struct GNUNET_TIME_Relative maxdelay,
1044                                    const struct GNUNET_PeerIdentity *target,
1045                                    size_t notify_size,
1046                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1047                                    void *notify_cls)
1048 {
1049   struct GNUNET_MESH_TransmitHandle *th;
1050   size_t overhead;
1051
1052   if (tunnel->mesh->npackets >= tunnel->mesh->max_queue_size &&
1053       tunnel->npackets > 0)
1054     return NULL;                /* queue full */
1055   tunnel->npackets++;
1056   tunnel->mesh->npackets++;
1057   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
1058   th->tunnel = tunnel;
1059   th->priority = priority;
1060   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1061   th->target = GNUNET_PEER_intern (target);
1062   overhead =
1063       (NULL ==
1064        target) ? sizeof (struct GNUNET_MESH_Multicast) : sizeof (struct
1065                                                                  GNUNET_MESH_Unicast);
1066   th->size = notify_size + overhead;
1067   th->notify = notify;
1068   th->notify_cls = notify_cls;
1069   add_to_queue (tunnel->mesh, th);
1070   return th;
1071 }
1072
1073
1074 /**
1075  * Cancel the specified transmission-ready notification.
1076  *
1077  * @param th handle that was returned by "notify_transmit_ready".
1078  */
1079 void
1080 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
1081 {
1082   struct GNUNET_MESH_Handle *mesh;
1083
1084   mesh = th->tunnel->mesh;
1085   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1086     GNUNET_SCHEDULER_cancel (th->timeout_task);
1087   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
1088   GNUNET_free (th);
1089   if ((NULL == mesh->th_head) && (NULL != mesh->th))
1090   {
1091     /* queue empty, no point in asking for transmission */
1092     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
1093     mesh->th = NULL;
1094   }
1095 }
1096
1097
1098 #if 0                           /* keep Emacsens' auto-indent happy */
1099 {
1100 #endif
1101 #ifdef __cplusplus
1102 }
1103 #endif