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