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