- Don't crash on bogus data from client
[oweals/gnunet.git] / src / mesh / mesh_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
4      GNUnet is free software; you can redistribute it and/or modify
5      it under the terms of the GNU General Public License as published
6      by the Free Software Foundation; either version 3, or (at your
7      option) any later version.
8      GNUnet is distributed in the hope that it will be useful, but
9      WITHOUT ANY WARRANTY; without even the implied warranty of
10      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11      General Public License for more details.
12      You should have received a copy of the GNU General Public License
13      along with GNUnet; see the file COPYING.  If not, write to the
14      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
15      Boston, MA 02111-1307, USA.
16 */
17
18 /**
19  * @file mesh/mesh_api.c
20  * @brief mesh api: client implementation of mesh service
21  * @author Bartlomiej Polot
22  *
23  * STRUCTURE:
24  * - CONSTANTS
25  * - DATA STRUCTURES
26  * - AUXILIARY FUNCTIONS
27  * - RECEIVE HANDLERS
28  * - SEND FUNCTIONS
29  * - API CALL DEFINITIONS
30  */
31 #ifdef __cplusplus
32 extern "C"
33 {
34 #if 0                           /* keep Emacsens' auto-indent happy */
35 }
36 #endif
37 #endif
38
39 #include "platform.h"
40 #include "gnunet_common.h"
41 #include "gnunet_client_lib.h"
42 #include "gnunet_util_lib.h"
43 #include "gnunet_peer_lib.h"
44 #include "gnunet_mesh_service.h"
45 #include "mesh.h"
46 #include "mesh_protocol.h"
47
48 #define MESH_API_DEBUG GNUNET_YES
49
50 #define LOG(kind,...) GNUNET_log_from (kind, "mesh-api",__VA_ARGS__)
51
52 /******************************************************************************/
53 /************************      DATA STRUCTURES     ****************************/
54 /******************************************************************************/
55
56 /**
57  * Transmission queue to the service
58  */
59 struct GNUNET_MESH_TransmitHandle
60 {
61
62     /**
63      * Double Linked list
64      */
65   struct GNUNET_MESH_TransmitHandle *next;
66
67     /**
68      * Double Linked list
69      */
70   struct GNUNET_MESH_TransmitHandle *prev;
71
72     /**
73      * Tunnel this message is sent on / for (may be NULL for control messages).
74      */
75   struct GNUNET_MESH_Tunnel *tunnel;
76
77     /**
78      * Callback to obtain the message to transmit, or NULL if we
79      * got the message in 'data'.  Notice that messages built
80      * by 'notify' need to be encapsulated with information about
81      * the 'target'.
82      */
83   GNUNET_CONNECTION_TransmitReadyNotify notify;
84
85     /**
86      * Closure for 'notify'
87      */
88   void *notify_cls;
89
90     /**
91      * How long is this message valid.  Once the timeout has been
92      * reached, the message must no longer be sent.  If this
93      * is a message with a 'notify' callback set, the 'notify'
94      * function should be called with 'buf' NULL and size 0.
95      */
96   struct GNUNET_TIME_Absolute timeout;
97
98     /**
99      * Task triggering a timeout, can be NO_TASK if the timeout is FOREVER.
100      */
101   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
102
103     /**
104      * Priority of the message.  The queue is sorted by priority,
105      * control messages have the maximum priority (UINT32_MAX).
106      */
107   uint32_t priority;
108
109     /**
110      * Target of the message, 0 for multicast.  This field
111      * is only valid if 'notify' is non-NULL.
112      */
113   GNUNET_PEER_Id target;
114
115     /**
116      * Size of 'data' -- or the desired size of 'notify' if 'data' is NULL.
117      */
118   size_t size;
119 };
120
121
122 /**
123  * Opaque handle to the service.
124  */
125 struct GNUNET_MESH_Handle
126 {
127
128     /**
129      * Handle to the server connection, to send messages later
130      */
131   struct GNUNET_CLIENT_Connection *client;
132
133     /**
134      * Set of handlers used for processing incoming messages in the tunnels
135      */
136   const struct GNUNET_MESH_MessageHandler *message_handlers;
137
138     /**
139      * Set of applications that should be claimed to be offered at this node.
140      * Note that this is just informative, the appropiate handlers must be
141      * registered independently and the mapping is up to the developer of the
142      * client application.
143      */
144   const GNUNET_MESH_ApplicationType *applications;
145
146     /**
147      * Double linked list of the tunnels this client is connected to.
148      */
149   struct GNUNET_MESH_Tunnel *tunnels_head;
150   struct GNUNET_MESH_Tunnel *tunnels_tail;
151
152     /**
153      * Callback for inbound tunnel creation
154      */
155   GNUNET_MESH_InboundTunnelNotificationHandler *new_tunnel;
156
157     /**
158      * Callback for inbound tunnel disconnection
159      */
160   GNUNET_MESH_TunnelEndHandler *cleaner;
161
162     /**
163      * Handle to cancel pending transmissions in case of disconnection
164      */
165   struct GNUNET_CLIENT_TransmitHandle *th;
166
167     /**
168      * Closure for all the handlers given by the client
169      */
170   void *cls;
171
172     /**
173      * Messages to send to the service
174      */
175   struct GNUNET_MESH_TransmitHandle *th_head;
176   struct GNUNET_MESH_TransmitHandle *th_tail;
177
178     /**
179      * tid of the next tunnel to create (to avoid reusing IDs often)
180      */
181   MESH_TunnelNumber next_tid;
182   unsigned int n_handlers;
183   unsigned int n_applications;
184   unsigned int max_queue_size;
185
186     /**
187      * Have we started the task to receive messages from the service
188      * yet? We do this after we send the 'MESH_LOCAL_CONNECT' message.
189      */
190   int in_receive;
191
192     /**
193      * Number of packets queued
194      */
195   unsigned int npackets;
196
197   /**
198    * Configuration given by the client, in case of reconnection
199    */
200   const struct GNUNET_CONFIGURATION_Handle *cfg;
201
202   /**
203    * Time to the next reconnect in case one reconnect fails
204    */
205   struct GNUNET_TIME_Relative reconnect_time;
206 };
207
208
209 /**
210  * Description of a peer
211  */
212 struct GNUNET_MESH_Peer
213 {
214     /**
215      * ID of the peer in short form
216      */
217   GNUNET_PEER_Id id;
218
219   /**
220    * Tunnel this peer belongs to
221    */
222   struct GNUNET_MESH_Tunnel *t;
223
224   /**
225    * Flag indicating whether service has informed about its connection
226    */
227   int connected;
228
229 };
230
231
232 /**
233  * Opaque handle to a tunnel.
234  */
235 struct GNUNET_MESH_Tunnel
236 {
237
238     /**
239      * DLL
240      */
241   struct GNUNET_MESH_Tunnel *next;
242   struct GNUNET_MESH_Tunnel *prev;
243
244     /**
245      * Callback to execute when peers connect to the tunnel
246      */
247   GNUNET_MESH_PeerConnectHandler connect_handler;
248
249     /**
250      * Callback to execute when peers disconnect from the tunnel
251      */
252   GNUNET_MESH_PeerDisconnectHandler disconnect_handler;
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. 0 if the tunnel is the local client.
271      */
272   GNUNET_PEER_Id owner;
273
274     /**
275      * All peers added to the tunnel
276      */
277   struct GNUNET_MESH_Peer **peers;
278
279   /**
280    * List of application types that have been requested for this tunnel
281    */
282   GNUNET_MESH_ApplicationType *apps;
283
284   /**
285    * Any data the caller wants to put in here
286    */
287   void *ctx;
288
289   /**
290      * Number of peers added to the tunnel
291      */
292   unsigned int npeers;
293
294     /**
295      * Number of packets queued in this tunnel
296      */
297   unsigned int npackets;
298
299     /**
300      * Number of applications requested this tunnel
301      */
302   unsigned int napps;
303
304 };
305
306
307 /******************************************************************************/
308 /***********************     AUXILIARY FUNCTIONS      *************************/
309 /******************************************************************************/
310
311 /**
312  * Get the tunnel handler for the tunnel specified by id from the given handle
313  * @param h Mesh handle
314  * @param tid ID of the wanted tunnel
315  * @return handle to the required tunnel or NULL if not found
316  */
317 static struct GNUNET_MESH_Tunnel *
318 retrieve_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
319 {
320   struct GNUNET_MESH_Tunnel *t;
321
322   t = h->tunnels_head;
323   while (t != NULL)
324   {
325     if (t->tid == tid)
326       return t;
327     t = t->next;
328   }
329   return NULL;
330 }
331
332
333 /**
334  * Create a new tunnel and insert it in the tunnel list of the mesh handle
335  * @param h Mesh handle
336  * @param tid desired tid of the tunnel, 0 to assign one automatically
337  * @return handle to the created tunnel
338  */
339 static struct GNUNET_MESH_Tunnel *
340 create_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
341 {
342   struct GNUNET_MESH_Tunnel *t;
343
344   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
345   GNUNET_CONTAINER_DLL_insert (h->tunnels_head, h->tunnels_tail, t);
346   t->mesh = h;
347   if (0 == tid)
348   {
349     t->tid = h->next_tid;
350     while (NULL != retrieve_tunnel (h, h->next_tid))
351     {
352       h->next_tid++;
353       h->next_tid &= ~GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
354       h->next_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
355     }
356   }
357   else
358   {
359     t->tid = tid;
360   }
361   return t;
362 }
363
364
365 /**
366  * Destroy the specified tunnel.
367  * - Destroys all peers, calling the disconnect callback on each if needed
368  * - Cancels all outgoing traffic for that tunnel, calling respective notifys
369  * - Calls cleaner if tunnel was inbound
370  * - Frees all memory used
371  *
372  * @param t Pointer to the tunnel.
373  * @param call_handler Whether to call the cleaner handler.
374  *
375  * @return Handle to the required tunnel or NULL if not found.
376  */
377 static void
378 destroy_tunnel (struct GNUNET_MESH_Tunnel *t, int call_cleaner)
379 {
380   struct GNUNET_MESH_Handle *h;
381   struct GNUNET_PeerIdentity pi;
382   struct GNUNET_MESH_TransmitHandle *th;
383   struct GNUNET_MESH_TransmitHandle *aux;
384   unsigned int i;
385
386   if (NULL == t)
387   {
388     GNUNET_break (0);
389     return;
390   }
391   h = t->mesh;
392   th = h->th_head;
393   while (NULL != th)
394   {
395     if (th->tunnel == t)
396     {
397       aux = th->next;
398       GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
399       if (NULL == h->th_head && NULL != h->th)
400       {
401         GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
402         h->th = NULL;
403       }
404       if (NULL != th->notify)
405         th->notify (th->notify_cls, 0, NULL);
406       if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
407         GNUNET_SCHEDULER_cancel (th->timeout_task);
408       GNUNET_free (th);
409       th = aux;
410     }
411     else
412     {
413       th = th->next;
414     }
415   }
416   GNUNET_CONTAINER_DLL_remove (h->tunnels_head, h->tunnels_tail, t);
417   for (i = 0; i < t->npeers; i++)
418   {
419     if (NULL != t->disconnect_handler && t->peers[i]->connected)
420     {
421       GNUNET_PEER_resolve (t->peers[i]->id, &pi);
422       t->disconnect_handler (t->cls, &pi);
423     }
424     GNUNET_PEER_change_rc (t->peers[i]->id, -1);
425     GNUNET_free (t->peers[i]);
426   }
427   if (t->npeers > 0)
428     GNUNET_free (t->peers);
429   if (NULL != h->cleaner && 0 != t->owner && GNUNET_YES == call_cleaner)
430     h->cleaner (h->cls, t, t->ctx);
431   if (0 != t->owner)
432     GNUNET_PEER_change_rc (t->owner, -1);
433   if (0 != t->napps && t->apps)
434     GNUNET_free (t->apps);
435   GNUNET_free (t);
436   return;
437 }
438
439
440 /**
441  * Get the peer descriptor for the peer with id from the given tunnel
442  * @param t Tunnel handle
443  * @param id Short form ID of the wanted peer
444  * @return handle to the requested peer or NULL if not found
445  */
446 static struct GNUNET_MESH_Peer *
447 retrieve_peer (struct GNUNET_MESH_Tunnel *t, GNUNET_PEER_Id id)
448 {
449   unsigned int i;
450
451   for (i = 0; i < t->npeers; i++)
452     if (t->peers[i]->id == id)
453       return t->peers[i];
454   return NULL;
455 }
456
457
458 /**
459  * Add a peer into a tunnel
460  * @param t Tunnel handle
461  * @param pi Full ID of the new peer
462  * @return handle to the newly created peer
463  */
464 static struct GNUNET_MESH_Peer *
465 add_peer_to_tunnel (struct GNUNET_MESH_Tunnel *t,
466                     const struct GNUNET_PeerIdentity *pi)
467 {
468   struct GNUNET_MESH_Peer *p;
469   GNUNET_PEER_Id id;
470
471   if (0 != t->owner)
472   {
473     GNUNET_break (0);
474     return NULL;
475   }
476   id = GNUNET_PEER_intern (pi);
477
478   p = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer));
479   p->id = id;
480   p->t = t;
481   GNUNET_array_append (t->peers, t->npeers, p);
482   return p;
483 }
484
485
486 /**
487  * Remove a peer from a tunnel
488  * @param p Peer handle
489  */
490 static void
491 remove_peer_from_tunnel (struct GNUNET_MESH_Peer *p)
492 {
493   unsigned int i;
494
495   for (i = 0; i < p->t->npeers; i++)
496   {
497     if (p->t->peers[i] == p)
498       break;
499   }
500   if (i == p->t->npeers)
501   {
502     GNUNET_break (0);
503     return;
504   }
505   p->t->peers[i] = p->t->peers[p->t->npeers - 1];
506   GNUNET_array_grow (p->t->peers, p->t->npeers, p->t->npeers - 1);
507 }
508
509
510 /**
511  * Notify client that the transmission has timed out
512  * @param cls closure
513  * @param tc task context
514  */
515 static void
516 timeout_transmission (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
517 {
518   struct GNUNET_MESH_TransmitHandle *th = cls;
519   struct GNUNET_MESH_Handle *mesh;
520
521   mesh = th->tunnel->mesh;
522   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
523   if (th->notify != NULL)
524     th->notify (th->notify_cls, 0, NULL);
525   GNUNET_free (th);
526   if ((NULL == mesh->th_head) && (NULL != mesh->th))
527   {
528     /* queue empty, no point in asking for transmission */
529     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
530     mesh->th = NULL;
531   }
532 }
533
534
535 /**
536  * Add a transmit handle to the transmission queue by priority and set the
537  * timeout if needed.
538  *
539  * @param h mesh handle with the queue head and tail
540  * @param th handle to the packet to be transmitted
541  */
542 static void
543 add_to_queue (struct GNUNET_MESH_Handle *h,
544               struct GNUNET_MESH_TransmitHandle *th)
545 {
546   struct GNUNET_MESH_TransmitHandle *p;
547
548   p = h->th_head;
549   while ((NULL != p) && (th->priority <= p->priority))
550     p = p->next;
551   if (NULL == p)
552     p = h->th_tail;
553   else
554     p = p->prev;
555   GNUNET_CONTAINER_DLL_insert_after (h->th_head, h->th_tail, p, th);
556   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value == th->timeout.abs_value)
557     return;
558   th->timeout_task =
559       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
560                                     (th->timeout), &timeout_transmission, th);
561 }
562
563
564 /**
565  * Auxiliary function to send an already constructed packet to the service.
566  * Takes care of creating a new queue element, copying the message and
567  * calling the tmt_rdy function if necessary.
568  *
569  * @param h mesh handle
570  * @param msg message to transmit
571  * @param tunnel tunnel this send is related to (NULL if N/A)
572  */
573 static void
574 send_packet (struct GNUNET_MESH_Handle *h,
575              const struct GNUNET_MessageHeader *msg,
576              struct GNUNET_MESH_Tunnel *tunnel);
577
578
579 /**
580  * Reconnect callback: tries to reconnect again after a failer previous
581  * reconnecttion
582  * @param cls closure (mesh handle)
583  * @param tc task context
584  */
585 static void
586 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
587
588
589 /**
590  * Send a connect packet to the service with the applications and types
591  * requested by the user.
592  *
593  * @param h The mesh handle.
594  *
595  */
596 static void
597 send_connect (struct GNUNET_MESH_Handle *h)
598 {
599   size_t size;
600
601   size = sizeof (struct GNUNET_MESH_ClientConnect);
602   size += h->n_applications * sizeof (GNUNET_MESH_ApplicationType);
603   size += h->n_handlers * sizeof (uint16_t);
604   {
605     char buf[size];
606     struct GNUNET_MESH_ClientConnect *msg;
607     GNUNET_MESH_ApplicationType *apps;
608     uint16_t napps;
609     uint16_t *types;
610     uint16_t ntypes;
611
612     /* build connection packet */
613     msg = (struct GNUNET_MESH_ClientConnect *) buf;
614     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT);
615     msg->header.size = htons (size);
616     apps = (GNUNET_MESH_ApplicationType *) &msg[1];
617     for (napps = 0; napps < h->n_applications; napps++)
618     {
619       apps[napps] = htonl (h->applications[napps]);
620       LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh:  app %u\n", h->applications[napps]);
621     }
622     types = (uint16_t *) & apps[napps];
623     for (ntypes = 0; ntypes < h->n_handlers; ntypes++)
624       types[ntypes] = htons (h->message_handlers[ntypes].type);
625     msg->applications = htons (napps);
626     msg->types = htons (ntypes);
627 #if MESH_API_DEBUG
628     LOG (GNUNET_ERROR_TYPE_DEBUG,
629          "mesh: Sending %lu bytes long message %d types and %d apps\n",
630          ntohs (msg->header.size), ntypes, napps);
631 #endif
632     send_packet (h, &msg->header, NULL);
633   }
634 }
635
636
637 /**
638  * Reconnect to the service, retransmit all infomation to try to restore the
639  * original state.
640  *
641  * @param h handle to the mesh
642  *
643  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
644  */
645 static int
646 reconnect (struct GNUNET_MESH_Handle *h)
647 {
648   struct GNUNET_MESH_Tunnel *t;
649   unsigned int i;
650
651 #if MESH_API_DEBUG
652   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: *****************************\n");
653   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: *******   RECONNECT   *******\n");
654   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: *****************************\n");
655 #endif
656   h->in_receive = GNUNET_NO;
657   /* disconnect */
658   if (NULL != h->th)
659   {
660     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
661   }
662   if (NULL != h->client)
663   {
664     GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
665   }
666
667   /* connect again */
668   h->client = GNUNET_CLIENT_connect ("mesh", h->cfg);
669   if (h->client == NULL)
670   {
671     GNUNET_SCHEDULER_add_delayed (h->reconnect_time, &reconnect_cbk, h);
672     h->reconnect_time =
673         GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
674                                   GNUNET_TIME_relative_multiply
675                                   (h->reconnect_time, 2));
676     LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh:   Next retry in %sms\n",
677          GNUNET_TIME_relative_to_string (h->reconnect_time));
678     GNUNET_break (0);
679     return GNUNET_NO;
680   }
681   else
682   {
683     h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
684   }
685   send_connect (h);
686   /* Rebuild all tunnels */
687   for (t = h->tunnels_head; NULL != t; t = t->next)
688   {
689     struct GNUNET_MESH_TunnelMessage tmsg;
690     struct GNUNET_MESH_PeerControl pmsg;
691
692     if (t->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
693     {
694       /* Tunnel was created by service (incoming tunnel) */
695       /* TODO: Notify service of missing tunnel, to request
696        * creator to recreate path (find a path to him via DHT?)
697        */
698       continue;
699     }
700     tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
701     tmsg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
702     tmsg.tunnel_id = htonl (t->tid);
703     send_packet (h, &tmsg.header, t);
704
705     pmsg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
706     pmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
707     pmsg.tunnel_id = htonl (t->tid);
708
709     /* Reconnect all peers */
710     for (i = 0; i < t->npeers; i++)
711     {
712       GNUNET_PEER_resolve (t->peers[i]->id, &pmsg.peer);
713       if (NULL != t->disconnect_handler && t->peers[i]->connected)
714         t->disconnect_handler (t->cls, &pmsg.peer);
715       /* If the tunnel was "by type", dont connect individual peers */
716       if (0 == t->napps)
717         send_packet (t->mesh, &pmsg.header, t);
718     }
719     /* Reconnect all types, if any  */
720     for (i = 0; i < t->napps; i++)
721     {
722       struct GNUNET_MESH_ConnectPeerByType msg;
723
724       msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
725       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE);
726       msg.tunnel_id = htonl (t->tid);
727       msg.type = htonl (t->apps[i]);
728       send_packet (t->mesh, &msg.header, t);
729     }
730   }
731   return GNUNET_YES;
732 }
733
734 /**
735  * Reconnect callback: tries to reconnect again after a failer previous
736  * reconnecttion
737  * @param cls closure (mesh handle)
738  * @param tc task context
739  */
740 static void
741 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
742 {
743   struct GNUNET_MESH_Handle *h = cls;
744
745   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
746     return;
747   reconnect (h);
748 }
749
750
751 /******************************************************************************/
752 /***********************      RECEIVE HANDLERS     ****************************/
753 /******************************************************************************/
754
755 /**
756  * Process the new tunnel notification and add it to the tunnels in the handle
757  *
758  * @param h     The mesh handle
759  * @param msg   A message with the details of the new incoming tunnel
760  */
761 static void
762 process_tunnel_created (struct GNUNET_MESH_Handle *h,
763                         const struct GNUNET_MESH_TunnelNotification *msg)
764 {
765   struct GNUNET_MESH_Tunnel *t;
766   MESH_TunnelNumber tid;
767
768   tid = ntohl (msg->tunnel_id);
769   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
770   {
771     GNUNET_break (0);
772     return;
773   }
774   t = create_tunnel (h, tid);
775   t->owner = GNUNET_PEER_intern (&msg->peer);
776   t->npeers = 1;
777   t->peers = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer *));
778   t->peers[0] = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer));
779   t->peers[0]->t = t;
780   t->peers[0]->connected = 1;
781   t->peers[0]->id = t->owner;
782   GNUNET_PEER_change_rc (t->owner, 1);
783   t->mesh = h;
784   t->tid = tid;
785   if (NULL != h->new_tunnel)
786   {
787     struct GNUNET_ATS_Information atsi;
788
789     atsi.type = 0;
790     atsi.value = 0;
791     t->ctx = h->new_tunnel (h->cls, t, &msg->peer, &atsi);
792   }
793 #if MESH_API_DEBUG
794   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: new incoming tunnel %X\n",
795               t->tid);
796 #endif
797   return;
798 }
799
800
801 /**
802  * Process the tunnel destroy notification and free associated resources
803  *
804  * @param h     The mesh handle
805  * @param msg   A message with the details of the tunnel being destroyed
806  */
807 static void
808 process_tunnel_destroy (struct GNUNET_MESH_Handle *h,
809                         const struct GNUNET_MESH_TunnelMessage *msg)
810 {
811   struct GNUNET_MESH_Tunnel *t;
812   MESH_TunnelNumber tid;
813
814   tid = ntohl (msg->tunnel_id);
815   t = retrieve_tunnel (h, tid);
816
817   if (NULL == t)
818   {
819     return;
820   }
821   if (0 == t->owner)
822   {
823     GNUNET_break (0);
824   }
825 #if MESH_API_DEBUG
826   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: tunnel %u destroyed\n", t->tid);
827 #endif
828   destroy_tunnel (t, GNUNET_YES);
829   return;
830 }
831
832
833 /**
834  * Process the new peer event and notify the upper level of it
835  *
836  * @param h     The mesh handle
837  * @param msg   A message with the details of the peer event
838  */
839 static void
840 process_peer_event (struct GNUNET_MESH_Handle *h,
841                     const struct GNUNET_MESH_PeerControl *msg)
842 {
843   struct GNUNET_MESH_Tunnel *t;
844   struct GNUNET_MESH_Peer *p;
845   struct GNUNET_ATS_Information atsi;
846   GNUNET_PEER_Id id;
847   uint16_t size;
848
849   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: processig peer event\n");
850   size = ntohs (msg->header.size);
851   if (size != sizeof (struct GNUNET_MESH_PeerControl))
852   {
853     GNUNET_break (0);
854     return;
855   }
856   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
857   if (NULL == t)
858   {
859     GNUNET_break (0);
860     return;
861   }
862   id = GNUNET_PEER_search (&msg->peer);
863   if ((p = retrieve_peer (t, id)) == NULL)
864     p = add_peer_to_tunnel (t, &msg->peer);
865   if (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD == ntohs (msg->header.type))
866   {
867     LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: adding peer\n");
868     if (NULL != t->connect_handler)
869     {
870       atsi.type = 0;
871       atsi.value = 0;
872       t->connect_handler (t->cls, &msg->peer, &atsi);
873     }
874     p->connected = 1;
875   }
876   else
877   {
878     LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: removing peer\n");
879     if (NULL != t->disconnect_handler && p->connected)
880     {
881       t->disconnect_handler (t->cls, &msg->peer);
882     }
883     remove_peer_from_tunnel (p);
884     GNUNET_free (p);
885   }
886   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: processing peer event END\n");
887 }
888
889
890 /**
891  * Process the incoming data packets
892  *
893  * @param h         The mesh handle
894  * @param message   A message encapsulating the data
895  */
896 static void
897 process_incoming_data (struct GNUNET_MESH_Handle *h,
898                        const struct GNUNET_MessageHeader *message)
899 {
900   const struct GNUNET_MessageHeader *payload;
901   const struct GNUNET_MESH_MessageHandler *handler;
902   const struct GNUNET_PeerIdentity *peer;
903   struct GNUNET_MESH_Unicast *ucast;
904   struct GNUNET_MESH_Multicast *mcast;
905   struct GNUNET_MESH_ToOrigin *to_orig;
906   struct GNUNET_MESH_Tunnel *t;
907   unsigned int i;
908   uint16_t type;
909
910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: Got a data message!\n");
911   type = ntohs (message->type);
912   switch (type)
913   {
914   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
915     ucast = (struct GNUNET_MESH_Unicast *) message;
916
917     t = retrieve_tunnel (h, ntohl (ucast->tid));
918     payload = (struct GNUNET_MessageHeader *) &ucast[1];
919     peer = &ucast->oid;
920     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   ucast on tunnel %s [%x]\n",
921                 GNUNET_i2s (peer), ntohl (ucast->tid));
922     break;
923   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
924     mcast = (struct GNUNET_MESH_Multicast *) message;
925     t = retrieve_tunnel (h, ntohl (mcast->tid));
926     payload = (struct GNUNET_MessageHeader *) &mcast[1];
927     peer = &mcast->oid;
928     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   mcast on tunnel %s [%x]\n",
929                 GNUNET_i2s (peer), ntohl (mcast->tid));
930     break;
931   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
932     to_orig = (struct GNUNET_MESH_ToOrigin *) message;
933     t = retrieve_tunnel (h, ntohl (to_orig->tid));
934     payload = (struct GNUNET_MessageHeader *) &to_orig[1];
935     peer = &to_orig->sender;
936     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   torig on tunnel %s [%x]\n",
937                 GNUNET_i2s (peer), ntohl (to_orig->tid));
938     break;
939   default:
940     GNUNET_break (0);
941     return;
942   }
943   if (NULL == t)
944   {
945     GNUNET_break (0);
946     return;
947   }
948   type = ntohs (payload->type);
949   for (i = 0; i < h->n_handlers; i++)
950   {
951     handler = &h->message_handlers[i];
952     if (handler->type == type)
953     {
954       struct GNUNET_ATS_Information atsi;
955
956       atsi.type = 0;
957       atsi.value = 0;
958       if (GNUNET_OK !=
959           handler->callback (h->cls, t, &t->ctx, peer, payload, &atsi))
960       {
961         LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH: callback caused disconnection\n");
962         GNUNET_MESH_disconnect (h);
963         return;
964       }
965 #if MESH_API_DEBUG
966       else
967       {
968         LOG (GNUNET_ERROR_TYPE_DEBUG,
969              "MESH: callback completed successfully\n");
970
971       }
972 #endif
973     }
974   }
975 }
976
977
978 /**
979  * Function to process all messages received from the service
980  *
981  * @param cls closure
982  * @param msg message received, NULL on timeout or fatal error
983  */
984 static void
985 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
986 {
987   struct GNUNET_MESH_Handle *h = cls;
988
989   if (msg == NULL)
990   {
991     reconnect (h);
992     return;
993   }
994   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: received a message type %hu from MESH\n",
995        ntohs (msg->type));
996   switch (ntohs (msg->type))
997   {
998     /* Notify of a new incoming tunnel */
999   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE:
1000     process_tunnel_created (h, (struct GNUNET_MESH_TunnelNotification *) msg);
1001     break;
1002     /* Notify of a tunnel disconnection */
1003   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1004     process_tunnel_destroy (h, (struct GNUNET_MESH_TunnelMessage *) msg);
1005     break;
1006     /* Notify of a new peer or a peer disconnect in the tunnel */
1007   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD:
1008   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL:
1009     process_peer_event (h, (struct GNUNET_MESH_PeerControl *) msg);
1010     break;
1011     /* Notify of a new data packet in the tunnel */
1012   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1013   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1014   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1015     process_incoming_data (h, msg);
1016     break;
1017     /* We shouldn't get any other packages, log and ignore */
1018   default:
1019     LOG (GNUNET_ERROR_TYPE_WARNING,
1020          "MESH: unsolicited message form service (type %d)\n",
1021          ntohs (msg->type));
1022   }
1023   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: message processed\n");
1024   GNUNET_CLIENT_receive (h->client, &msg_received, h,
1025                          GNUNET_TIME_UNIT_FOREVER_REL);
1026 }
1027
1028
1029 /******************************************************************************/
1030 /************************       SEND FUNCTIONS     ****************************/
1031 /******************************************************************************/
1032
1033 /**
1034  * Function called to send a message to the service.
1035  * "buf" will be NULL and "size" zero if the socket was closed for writing in
1036  * the meantime.
1037  *
1038  * @param cls closure, the mesh handle
1039  * @param size number of bytes available in buf
1040  * @param buf where the callee should write the connect message
1041  * @return number of bytes written to buf
1042  */
1043 static size_t
1044 send_callback (void *cls, size_t size, void *buf)
1045 {
1046   struct GNUNET_MESH_Handle *h = cls;
1047   struct GNUNET_MESH_TransmitHandle *th;
1048   char *cbuf = buf;
1049   size_t tsize;
1050   size_t psize;
1051
1052   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: Send packet() Buffer %u\n", size);
1053   h->th = NULL;
1054   if ((0 == size) || (NULL == buf))
1055   {
1056     reconnect (h);
1057     return 0;
1058   }
1059   tsize = 0;
1060   while ((NULL != (th = h->th_head)) && (size >= th->size))
1061   {
1062     if (NULL != th->notify)
1063     {
1064       if (th->tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1065       {
1066         /* traffic to origin */
1067         struct GNUNET_MESH_ToOrigin to;
1068         struct GNUNET_MessageHeader *mh;
1069
1070         GNUNET_assert (size >= th->size);
1071         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (to)];
1072         psize = th->notify (th->notify_cls, size - sizeof (to), mh);
1073         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   to origin, type %u\n",
1074                     ntohs (mh->type));
1075         if (psize > 0)
1076         {
1077           psize += sizeof (to);
1078           GNUNET_assert (size >= psize);
1079           to.header.size = htons (psize);
1080           to.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
1081           to.tid = htonl (th->tunnel->tid);
1082           memset (&to.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1083           memset (&to.sender, 0, sizeof (struct GNUNET_PeerIdentity));
1084           memcpy (cbuf, &to, sizeof (to));
1085         }
1086       }
1087       else if (th->target == 0)
1088       {
1089         /* multicast */
1090         struct GNUNET_MESH_Multicast mc;
1091         struct GNUNET_MessageHeader *mh;
1092
1093         GNUNET_assert (size >= th->size);
1094         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (mc)];
1095         psize = th->notify (th->notify_cls, size - sizeof (mc), mh);
1096         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   multicast, type %u\n",
1097                     ntohs (mh->type));
1098         if (psize > 0)
1099         {
1100           psize += sizeof (mc);
1101           GNUNET_assert (size >= psize);
1102           mc.header.size = htons (psize);
1103           mc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1104           mc.tid = htonl (th->tunnel->tid);
1105           mc.mid = 0;
1106           mc.ttl = 0;
1107           memset (&mc.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1108           memcpy (cbuf, &mc, sizeof (mc));
1109         }
1110       }
1111       else
1112       {
1113         /* unicast */
1114         struct GNUNET_MESH_Unicast uc;
1115         struct GNUNET_MessageHeader *mh;
1116
1117         GNUNET_assert (size >= th->size);
1118         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (uc)];
1119         psize = th->notify (th->notify_cls, size - sizeof (uc), mh);
1120         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:   unicast, type %u\n",
1121                     ntohs (mh->type));
1122         if (psize > 0)
1123         {
1124           psize += sizeof (uc);
1125           GNUNET_assert (size >= psize);
1126           uc.header.size = htons (psize);
1127           uc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1128           uc.tid = htonl (th->tunnel->tid);
1129           memset (&uc.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1130           GNUNET_PEER_resolve (th->target, &uc.destination);
1131           memcpy (cbuf, &uc, sizeof (uc));
1132         }
1133       }
1134     }
1135     else
1136     {
1137       memcpy (cbuf, &th[1], th->size);
1138       psize = th->size;
1139     }
1140     if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1141       GNUNET_SCHEDULER_cancel (th->timeout_task);
1142     if (NULL != th->tunnel)
1143     {
1144       th->tunnel->mesh->npackets--;
1145       th->tunnel->npackets--;
1146     }
1147     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1148     GNUNET_free (th);
1149     cbuf += psize;
1150     size -= psize;
1151     tsize += psize;
1152   }
1153   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh:   total size: %u\n", tsize);
1154   if (NULL != (th = h->th_head))
1155   {
1156     LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh:   next size: %u\n", th->size);
1157     h->th =
1158         GNUNET_CLIENT_notify_transmit_ready (h->client, th->size,
1159                                              GNUNET_TIME_UNIT_FOREVER_REL,
1160                                              GNUNET_YES, &send_callback, h);
1161   }
1162   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: Send packet() END\n");
1163   if (GNUNET_NO == h->in_receive)
1164   {
1165     h->in_receive = GNUNET_YES;
1166     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1167                            GNUNET_TIME_UNIT_FOREVER_REL);
1168   }
1169   return tsize;
1170 }
1171
1172
1173 /**
1174  * Auxiliary function to send an already constructed packet to the service.
1175  * Takes care of creating a new queue element, copying the message and
1176  * calling the tmt_rdy function if necessary.
1177  * 
1178  * @param h mesh handle
1179  * @param msg message to transmit
1180  * @param tunnel tunnel this send is related to (NULL if N/A)
1181  */
1182 static void
1183 send_packet (struct GNUNET_MESH_Handle *h,
1184              const struct GNUNET_MessageHeader *msg,
1185              struct GNUNET_MESH_Tunnel *tunnel)
1186 {
1187   struct GNUNET_MESH_TransmitHandle *th;
1188   size_t msize;
1189
1190   msize = ntohs (msg->size);
1191   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle) + msize);
1192   th->priority = UINT32_MAX;
1193   th->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1194   th->size = msize;
1195   th->tunnel = tunnel;
1196   memcpy (&th[1], msg, msize);
1197   add_to_queue (h, th);
1198   if (NULL != h->th)
1199     return;
1200   h->th =
1201       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
1202                                            GNUNET_TIME_UNIT_FOREVER_REL,
1203                                            GNUNET_YES, &send_callback, h);
1204 }
1205
1206
1207 /******************************************************************************/
1208 /**********************      API CALL DEFINITIONS     *************************/
1209 /******************************************************************************/
1210
1211 /**
1212  * Connect to the mesh service.
1213  *
1214  * @param cfg configuration to use
1215  * @param queue_size size of the data message queue, shared among all tunnels
1216  *                   (each tunnel is guaranteed to accept at least one message,
1217  *                    no matter what is the status of other tunnels)
1218  * @param cls closure for the various callbacks that follow
1219  *            (including handlers in the handlers array)
1220  * @param new_tunnel function called when an *inbound* tunnel is created
1221  * @param cleaner function called when an *inbound* tunnel is destroyed by the
1222  *                remote peer, it is *not* called if GNUNET_MESH_tunnel_destroy
1223  *                is called on the tunnel
1224  * @param handlers callbacks for messages we care about, NULL-terminated
1225  *                note that the mesh is allowed to drop notifications about
1226  *                inbound messages if the client does not process them fast
1227  *                enough (for this notification type, a bounded queue is used)
1228  * @param stypes list of the applications that this client claims to provide
1229  * @return handle to the mesh service NULL on error
1230  *         (in this case, init is never called)
1231  */
1232 struct GNUNET_MESH_Handle *
1233 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1234                      unsigned int queue_size, void *cls,
1235                      GNUNET_MESH_InboundTunnelNotificationHandler new_tunnel,
1236                      GNUNET_MESH_TunnelEndHandler cleaner,
1237                      const struct GNUNET_MESH_MessageHandler *handlers,
1238                      const GNUNET_MESH_ApplicationType *stypes)
1239 {
1240   struct GNUNET_MESH_Handle *h;
1241
1242   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: GNUNET_MESH_connect()\n");
1243   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
1244   h->cfg = cfg;
1245   h->max_queue_size = queue_size;
1246   h->new_tunnel = new_tunnel;
1247   h->cleaner = cleaner;
1248   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
1249   if (h->client == NULL)
1250   {
1251     GNUNET_break (0);
1252     GNUNET_free (h);
1253     return NULL;
1254   }
1255   h->cls = cls;
1256   /* FIXME memdup? */
1257   h->applications = stypes;
1258   h->message_handlers = handlers;
1259   h->next_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
1260   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1261
1262   /* count handlers and apps, calculate size */
1263   for (h->n_applications = 0; stypes[h->n_applications]; h->n_applications++) ;
1264   for (h->n_handlers = 0; handlers[h->n_handlers].type; h->n_handlers++) ;
1265   send_connect (h);
1266   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: GNUNET_MESH_connect() END\n");
1267   return h;
1268 }
1269
1270
1271 /**
1272  * Disconnect from the mesh service. All tunnels will be destroyed. All tunnel
1273  * disconnect callbacks will be called on any still connected peers, notifying
1274  * about their disconnection. The registered inbound tunnel cleaner will be
1275  * called should any inbound tunnels still exist.
1276  *
1277  * @param handle connection to mesh to disconnect
1278  */
1279 void
1280 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
1281 {
1282   struct GNUNET_MESH_Tunnel *t;
1283   struct GNUNET_MESH_Tunnel *aux;
1284   struct GNUNET_MESH_TransmitHandle *th;
1285
1286   t = handle->tunnels_head;
1287   while (NULL != t)
1288   {
1289     aux = t->next;
1290     if (t->tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1291     {
1292       GNUNET_break (0);
1293 #if MESH_API_DEBUG
1294       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: tunnel %X not destroyed\n",
1295                   t->tid);
1296 #endif
1297     }
1298     destroy_tunnel (t, GNUNET_YES);
1299     t = aux;
1300   }
1301   while ( (th = handle->th_head) != NULL)
1302   {
1303     struct GNUNET_MessageHeader *msg;
1304
1305     /* Make sure it is an allowed packet (everything else should have been
1306      * already canceled).
1307      */
1308     GNUNET_break (UINT32_MAX == th->priority);
1309     GNUNET_break (NULL == th->notify);
1310     msg = (struct GNUNET_MessageHeader *) &th[1];
1311     switch (ntohs(msg->type))
1312     {
1313       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT:
1314       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1315         break;
1316       default:
1317         GNUNET_break (0);
1318 #if MESH_API_DEBUG
1319         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh: unexpected msg %u\n",
1320                     ntohs(msg->type));
1321 #endif
1322     }
1323
1324     GNUNET_CONTAINER_DLL_remove (handle->th_head, handle->th_tail, th);
1325     GNUNET_free (th);
1326   }
1327
1328   if (NULL != handle->th)
1329   {
1330     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
1331   }
1332   if (NULL != handle->client)
1333   {
1334     GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
1335   }
1336   GNUNET_free (handle);
1337 }
1338
1339
1340 /**
1341  * Create a new tunnel (we're initiator and will be allowed to add/remove peers
1342  * and to broadcast).
1343  *
1344  * @param h mesh handle
1345  * @param tunnel_ctx client's tunnel context to associate with the tunnel
1346  * @param connect_handler function to call when peers are actually connected
1347  * @param disconnect_handler function to call when peers are disconnected
1348  * @param handler_cls closure for connect/disconnect handlers
1349  */
1350 struct GNUNET_MESH_Tunnel *
1351 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h, void *tunnel_ctx,
1352                            GNUNET_MESH_PeerConnectHandler connect_handler,
1353                            GNUNET_MESH_PeerDisconnectHandler disconnect_handler,
1354                            void *handler_cls)
1355 {
1356   struct GNUNET_MESH_Tunnel *t;
1357   struct GNUNET_MESH_TunnelMessage msg;
1358
1359   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: Creating new tunnel\n");
1360   t = create_tunnel (h, 0);
1361   t->connect_handler = connect_handler;
1362   t->disconnect_handler = disconnect_handler;
1363   t->cls = handler_cls;
1364   t->ctx = tunnel_ctx;
1365   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1366   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1367   msg.tunnel_id = htonl (t->tid);
1368   send_packet (h, &msg.header, t);
1369   return t;
1370 }
1371
1372
1373 /**
1374  * Destroy an existing tunnel. The existing callback for the tunnel will NOT
1375  * be called.
1376  *
1377  * @param tunnel tunnel handle
1378  */
1379 void
1380 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tunnel)
1381 {
1382   struct GNUNET_MESH_Handle *h;
1383   struct GNUNET_MESH_TunnelMessage msg;
1384   struct GNUNET_MESH_TransmitHandle *th;
1385
1386   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh: Destroying tunnel\n");
1387   h = tunnel->mesh;
1388
1389   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1390   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1391   msg.tunnel_id = htonl (tunnel->tid);
1392   th = h->th_head;
1393   while (th != NULL)
1394   {
1395     struct GNUNET_MESH_TransmitHandle *aux;
1396     if (th->tunnel == tunnel)
1397     {
1398       aux = th->next;
1399       /* FIXME call the handler? */
1400       if (NULL != th->notify)
1401         th->notify (th->notify_cls, 0, NULL);
1402       GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1403       GNUNET_free (th);
1404       th = aux;
1405     }
1406     else
1407       th = th->next;
1408   }
1409
1410   destroy_tunnel (tunnel, GNUNET_NO);
1411   send_packet (h, &msg.header, tunnel);
1412 }
1413
1414
1415 /**
1416  * Request that a peer should be added to the tunnel.  The existing
1417  * connect handler will be called ONCE with either success or failure.
1418  * This function should NOT be called again with the same peer before the
1419  * connect handler is called.
1420  *
1421  * @param tunnel handle to existing tunnel
1422  * @param peer peer to add
1423  */
1424 void
1425 GNUNET_MESH_peer_request_connect_add (struct GNUNET_MESH_Tunnel *tunnel,
1426                                       const struct GNUNET_PeerIdentity *peer)
1427 {
1428   struct GNUNET_MESH_PeerControl msg;
1429   GNUNET_PEER_Id peer_id;
1430   unsigned int i;
1431
1432   peer_id = GNUNET_PEER_intern (peer);
1433   for (i = 0; i < tunnel->npeers; i++)
1434   {
1435     if (tunnel->peers[i]->id == peer_id)
1436     {
1437       /* Peer already exists in tunnel */
1438       GNUNET_PEER_change_rc (peer_id, -1);
1439       GNUNET_break (0);
1440       return;
1441     }
1442   }
1443   if (NULL == add_peer_to_tunnel (tunnel, peer))
1444     return;
1445
1446   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1447   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1448   msg.tunnel_id = htonl (tunnel->tid);
1449   msg.peer = *peer;
1450   send_packet (tunnel->mesh, &msg.header, tunnel);
1451
1452   return;
1453 }
1454
1455
1456 /**
1457  * Request that a peer should be removed from the tunnel.  The existing
1458  * disconnect handler will be called ONCE if we were connected.
1459  *
1460  * @param tunnel handle to existing tunnel
1461  * @param peer peer to remove
1462  */
1463 void
1464 GNUNET_MESH_peer_request_connect_del (struct GNUNET_MESH_Tunnel *tunnel,
1465                                       const struct GNUNET_PeerIdentity *peer)
1466 {
1467   struct GNUNET_MESH_PeerControl msg;
1468   GNUNET_PEER_Id peer_id;
1469   unsigned int i;
1470
1471   peer_id = GNUNET_PEER_search (peer);
1472   if (0 == peer_id)
1473   {
1474     GNUNET_break (0);
1475     return;
1476   }
1477   for (i = 0; i < tunnel->npeers; i++)
1478     if (tunnel->peers[i]->id == peer_id)
1479       break;
1480   if (i == tunnel->npeers)
1481   {
1482     GNUNET_break (0);
1483     return;
1484   }
1485   if (NULL != tunnel->disconnect_handler && tunnel->peers[i]->connected == 1)
1486     tunnel->disconnect_handler (tunnel->cls, peer);
1487   GNUNET_PEER_change_rc (peer_id, -1);
1488   GNUNET_free (tunnel->peers[i]);
1489   tunnel->peers[i] = tunnel->peers[tunnel->npeers - 1];
1490   GNUNET_array_grow (tunnel->peers, tunnel->npeers, tunnel->npeers - 1);
1491
1492   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1493   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1494   msg.tunnel_id = htonl (tunnel->tid);
1495   memcpy (&msg.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1496   send_packet (tunnel->mesh, &msg.header, tunnel);
1497 }
1498
1499
1500 /**
1501  * Request that the mesh should try to connect to a peer supporting the given
1502  * message type.
1503  *
1504  * @param tunnel handle to existing tunnel
1505  * @param app_type application type that must be supported by the peer (MESH
1506  *                 should discover peer in proximity handling this type)
1507  */
1508 void
1509 GNUNET_MESH_peer_request_connect_by_type (struct GNUNET_MESH_Tunnel *tunnel,
1510                                           GNUNET_MESH_ApplicationType app_type)
1511 {
1512   struct GNUNET_MESH_ConnectPeerByType msg;
1513
1514   GNUNET_array_append (tunnel->apps, tunnel->napps, app_type);
1515
1516   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
1517   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE);
1518   msg.tunnel_id = htonl (tunnel->tid);
1519   msg.type = htonl (app_type);
1520   send_packet (tunnel->mesh, &msg.header, tunnel);
1521 }
1522
1523
1524 /**
1525  * Ask the mesh to call "notify" once it is ready to transmit the
1526  * given number of bytes to the specified "target".  If we are not yet
1527  * connected to the specified peer, a call to this function will cause
1528  * us to try to establish a connection.
1529  *
1530  * @param tunnel tunnel to use for transmission
1531  * @param cork is corking allowed for this transmission?
1532  * @param priority how important is the message?
1533  * @param maxdelay how long can the message wait?
1534  * @param target destination for the message,
1535  *               NULL for multicast to all tunnel targets
1536  * @param notify_size how many bytes of buffer space does notify want?
1537  * @param notify function to call when buffer space is available;
1538  *        will be called with NULL on timeout or if the overall queue
1539  *        for this peer is larger than queue_size and this is currently
1540  *        the message with the lowest priority
1541  * @param notify_cls closure for notify
1542  * @return non-NULL if the notify callback was queued,
1543  *         NULL if we can not even queue the request (insufficient
1544  *         memory); if NULL is returned, "notify" will NOT be called.
1545  */
1546 struct GNUNET_MESH_TransmitHandle *
1547 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
1548                                    uint32_t priority,
1549                                    struct GNUNET_TIME_Relative maxdelay,
1550                                    const struct GNUNET_PeerIdentity *target,
1551                                    size_t notify_size,
1552                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1553                                    void *notify_cls)
1554 {
1555   struct GNUNET_MESH_TransmitHandle *th;
1556   struct GNUNET_MESH_TransmitHandle *least_priority_th;
1557   uint32_t least_priority;
1558   size_t overhead;
1559
1560   GNUNET_assert (NULL != tunnel);
1561 #if MESH_API_DEBUG
1562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1563               "mesh: mesh notify transmit ready called\n");
1564   if (NULL != target)
1565     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:     target %s\n",
1566                 GNUNET_i2s (target));
1567   else
1568     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "mesh:     target multicast\n");
1569 #endif
1570   GNUNET_assert (NULL != notify);
1571   if (tunnel->mesh->npackets >= tunnel->mesh->max_queue_size &&
1572       tunnel->npackets > 0)
1573   {
1574     /* queue full */
1575     if (0 == priority)
1576       return NULL;
1577     th = tunnel->mesh->th_tail;
1578     least_priority = priority;
1579     least_priority_th = NULL;
1580     while (NULL != th)
1581     {
1582       if (th->priority < least_priority && th->tunnel->npackets > 1)
1583       {
1584         least_priority_th = th;
1585         least_priority = th->priority;
1586       }
1587       th = th->prev;
1588     }
1589     if (NULL == least_priority_th)
1590       return NULL;
1591     /* Can't be a control message */
1592     GNUNET_assert (NULL != least_priority_th->notify);
1593     least_priority_th->notify (notify_cls, 0, NULL);
1594     least_priority_th->tunnel->npackets--;
1595     tunnel->mesh->npackets--;
1596     GNUNET_CONTAINER_DLL_remove (tunnel->mesh->th_head, tunnel->mesh->th_tail,
1597                                  least_priority_th);
1598     if (GNUNET_SCHEDULER_NO_TASK != least_priority_th->timeout_task)
1599       GNUNET_SCHEDULER_cancel (least_priority_th->timeout_task);
1600     GNUNET_free (least_priority_th);
1601   }
1602   tunnel->npackets++;
1603   tunnel->mesh->npackets++;
1604   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
1605   th->tunnel = tunnel;
1606   th->priority = priority;
1607   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1608   th->target = GNUNET_PEER_intern (target);
1609   if (tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1610     overhead = sizeof (struct GNUNET_MESH_ToOrigin);
1611   else if (NULL == target)
1612     overhead = sizeof (struct GNUNET_MESH_Multicast);
1613   else
1614     overhead = sizeof (struct GNUNET_MESH_Unicast);
1615   th->size = notify_size + overhead;
1616   th->notify = notify;
1617   th->notify_cls = notify_cls;
1618   add_to_queue (tunnel->mesh, th);
1619   if (NULL != tunnel->mesh->th)
1620     return th;
1621   tunnel->mesh->th =
1622       GNUNET_CLIENT_notify_transmit_ready (tunnel->mesh->client, th->size,
1623                                            GNUNET_TIME_UNIT_FOREVER_REL,
1624                                            GNUNET_YES, &send_callback,
1625                                            tunnel->mesh);
1626   return th;
1627 }
1628
1629
1630 /**
1631  * Cancel the specified transmission-ready notification.
1632  *
1633  * @param th handle that was returned by "notify_transmit_ready".
1634  */
1635 void
1636 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
1637 {
1638   struct GNUNET_MESH_Handle *mesh;
1639
1640   mesh = th->tunnel->mesh;
1641   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1642     GNUNET_SCHEDULER_cancel (th->timeout_task);
1643   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
1644   GNUNET_free (th);
1645   if ((NULL == mesh->th_head) && (NULL != mesh->th))
1646   {
1647     /* queue empty, no point in asking for transmission */
1648     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
1649     mesh->th = NULL;
1650   }
1651 }
1652
1653
1654 /**
1655  * Transition API for tunnel ctx management
1656  */
1657 void
1658 GNUNET_MESH_tunnel_set_data (struct GNUNET_MESH_Tunnel *tunnel, void *data)
1659 {
1660   tunnel->ctx = data;
1661 }
1662
1663 /**
1664  * Transition API for tunnel ctx management
1665  */
1666 void *
1667 GNUNET_MESH_tunnel_get_data (struct GNUNET_MESH_Tunnel *tunnel)
1668 {
1669   return tunnel->ctx;
1670 }
1671
1672
1673 #if 0                           /* keep Emacsens' auto-indent happy */
1674 {
1675 #endif
1676 #ifdef __cplusplus
1677 }
1678 #endif