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