- Fixed reconnect procedure
[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 #if MESH_API_DEBUG
51 #define LOG(kind,...) GNUNET_log_from (kind, "mesh-api",__VA_ARGS__)
52 #else
53 #define LOG(kind,...)
54 #endif
55
56 /******************************************************************************/
57 /************************      DATA STRUCTURES     ****************************/
58 /******************************************************************************/
59
60 /**
61  * Transmission queue to the service
62  */
63 struct GNUNET_MESH_TransmitHandle
64 {
65
66     /**
67      * Double Linked list
68      */
69   struct GNUNET_MESH_TransmitHandle *next;
70
71     /**
72      * Double Linked list
73      */
74   struct GNUNET_MESH_TransmitHandle *prev;
75
76     /**
77      * Tunnel this message is sent on / for (may be NULL for control messages).
78      */
79   struct GNUNET_MESH_Tunnel *tunnel;
80
81     /**
82      * Callback to obtain the message to transmit, or NULL if we
83      * got the message in 'data'.  Notice that messages built
84      * by 'notify' need to be encapsulated with information about
85      * the 'target'.
86      */
87   GNUNET_CONNECTION_TransmitReadyNotify notify;
88
89     /**
90      * Closure for 'notify'
91      */
92   void *notify_cls;
93
94     /**
95      * How long is this message valid.  Once the timeout has been
96      * reached, the message must no longer be sent.  If this
97      * is a message with a 'notify' callback set, the 'notify'
98      * function should be called with 'buf' NULL and size 0.
99      */
100   struct GNUNET_TIME_Absolute timeout;
101
102     /**
103      * Task triggering a timeout, can be NO_TASK if the timeout is FOREVER.
104      */
105   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
106
107     /**
108      * Priority of the message.  The queue is sorted by priority,
109      * control messages have the maximum priority (UINT32_MAX).
110      */
111   uint32_t priority;
112
113     /**
114      * Target of the message, 0 for multicast.  This field
115      * is only valid if 'notify' is non-NULL.
116      */
117   GNUNET_PEER_Id target;
118
119     /**
120      * Size of 'data' -- or the desired size of 'notify' if 'data' is NULL.
121      */
122   size_t size;
123 };
124
125
126 /**
127  * Opaque handle to the service.
128  */
129 struct GNUNET_MESH_Handle
130 {
131
132     /**
133      * Handle to the server connection, to send messages later
134      */
135   struct GNUNET_CLIENT_Connection *client;
136
137     /**
138      * Set of handlers used for processing incoming messages in the tunnels
139      */
140   const struct GNUNET_MESH_MessageHandler *message_handlers;
141
142     /**
143      * Set of applications that should be claimed to be offered at this node.
144      * Note that this is just informative, the appropiate handlers must be
145      * registered independently and the mapping is up to the developer of the
146      * client application.
147      */
148   const GNUNET_MESH_ApplicationType *applications;
149
150     /**
151      * Double linked list of the tunnels this client is connected to.
152      */
153   struct GNUNET_MESH_Tunnel *tunnels_head;
154   struct GNUNET_MESH_Tunnel *tunnels_tail;
155
156     /**
157      * Callback for inbound tunnel creation
158      */
159   GNUNET_MESH_InboundTunnelNotificationHandler *new_tunnel;
160
161     /**
162      * Callback for inbound tunnel disconnection
163      */
164   GNUNET_MESH_TunnelEndHandler *cleaner;
165
166     /**
167      * Handle to cancel pending transmissions in case of disconnection
168      */
169   struct GNUNET_CLIENT_TransmitHandle *th;
170
171     /**
172      * Closure for all the handlers given by the client
173      */
174   void *cls;
175
176     /**
177      * Messages to send to the service
178      */
179   struct GNUNET_MESH_TransmitHandle *th_head;
180   struct GNUNET_MESH_TransmitHandle *th_tail;
181
182     /**
183      * tid of the next tunnel to create (to avoid reusing IDs often)
184      */
185   MESH_TunnelNumber next_tid;
186   unsigned int n_handlers;
187   unsigned int n_applications;
188   unsigned int max_queue_size;
189
190     /**
191      * Have we started the task to receive messages from the service
192      * yet? We do this after we send the 'MESH_LOCAL_CONNECT' message.
193      */
194   int in_receive;
195
196     /**
197      * Number of packets queued
198      */
199   unsigned int npackets;
200
201   /**
202    * Configuration given by the client, in case of reconnection
203    */
204   const struct GNUNET_CONFIGURATION_Handle *cfg;
205
206   /**
207    * Time to the next reconnect in case one reconnect fails
208    */
209   struct GNUNET_TIME_Relative reconnect_time;
210   
211   /**
212    * Task for trying to reconnect.
213    */
214   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
215 };
216
217
218 /**
219  * Description of a peer
220  */
221 struct GNUNET_MESH_Peer
222 {
223     /**
224      * ID of the peer in short form
225      */
226   GNUNET_PEER_Id id;
227
228   /**
229    * Tunnel this peer belongs to
230    */
231   struct GNUNET_MESH_Tunnel *t;
232
233   /**
234    * Flag indicating whether service has informed about its connection
235    */
236   int connected;
237
238 };
239
240
241 /**
242  * Opaque handle to a tunnel.
243  */
244 struct GNUNET_MESH_Tunnel
245 {
246
247     /**
248      * DLL
249      */
250   struct GNUNET_MESH_Tunnel *next;
251   struct GNUNET_MESH_Tunnel *prev;
252
253     /**
254      * Callback to execute when peers connect to the tunnel
255      */
256   GNUNET_MESH_PeerConnectHandler connect_handler;
257
258     /**
259      * Callback to execute when peers disconnect from the tunnel
260      */
261   GNUNET_MESH_PeerDisconnectHandler disconnect_handler;
262
263     /**
264      * Closure for the connect/disconnect handlers
265      */
266   void *cls;
267
268     /**
269      * Handle to the mesh this tunnel belongs to
270      */
271   struct GNUNET_MESH_Handle *mesh;
272
273     /**
274      * Local ID of the tunnel
275      */
276   MESH_TunnelNumber tid;
277
278     /**
279      * Owner of the tunnel. 0 if the tunnel is the local client.
280      */
281   GNUNET_PEER_Id owner;
282
283     /**
284      * All peers added to the tunnel
285      */
286   struct GNUNET_MESH_Peer **peers;
287
288   /**
289    * List of application types that have been requested for this tunnel
290    */
291   GNUNET_MESH_ApplicationType *apps;
292
293   /**
294    * Any data the caller wants to put in here
295    */
296   void *ctx;
297
298   /**
299      * Number of peers added to the tunnel
300      */
301   unsigned int npeers;
302
303     /**
304      * Number of packets queued in this tunnel
305      */
306   unsigned int npackets;
307
308     /**
309      * Number of applications requested this tunnel
310      */
311   unsigned int napps;
312
313 };
314
315
316 /******************************************************************************/
317 /***********************     AUXILIARY FUNCTIONS      *************************/
318 /******************************************************************************/
319
320 /**
321  * Get the tunnel handler for the tunnel specified by id from the given handle
322  * @param h Mesh handle
323  * @param tid ID of the wanted tunnel
324  * @return handle to the required tunnel or NULL if not found
325  */
326 static struct GNUNET_MESH_Tunnel *
327 retrieve_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
328 {
329   struct GNUNET_MESH_Tunnel *t;
330
331   t = h->tunnels_head;
332   while (t != NULL)
333   {
334     if (t->tid == tid)
335       return t;
336     t = t->next;
337   }
338   return NULL;
339 }
340
341
342 /**
343  * Create a new tunnel and insert it in the tunnel list of the mesh handle
344  * @param h Mesh handle
345  * @param tid desired tid of the tunnel, 0 to assign one automatically
346  * @return handle to the created tunnel
347  */
348 static struct GNUNET_MESH_Tunnel *
349 create_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
350 {
351   struct GNUNET_MESH_Tunnel *t;
352
353   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
354   GNUNET_CONTAINER_DLL_insert (h->tunnels_head, h->tunnels_tail, t);
355   t->mesh = h;
356   if (0 == tid)
357   {
358     t->tid = h->next_tid;
359     while (NULL != retrieve_tunnel (h, h->next_tid))
360     {
361       h->next_tid++;
362       h->next_tid &= ~GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
363       h->next_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
364     }
365   }
366   else
367   {
368     t->tid = tid;
369   }
370   return t;
371 }
372
373
374 /**
375  * Destroy the specified tunnel.
376  * - Destroys all peers, calling the disconnect callback on each if needed
377  * - Cancels all outgoing traffic for that tunnel, calling respective notifys
378  * - Calls cleaner if tunnel was inbound
379  * - Frees all memory used
380  *
381  * @param t Pointer to the tunnel.
382  * @param call_cleaner Whether to call the cleaner handler.
383  *
384  * @return Handle to the required tunnel or NULL if not found.
385  */
386 static void
387 destroy_tunnel (struct GNUNET_MESH_Tunnel *t, int call_cleaner)
388 {
389   struct GNUNET_MESH_Handle *h;
390   struct GNUNET_PeerIdentity pi;
391   struct GNUNET_MESH_TransmitHandle *th;
392   struct GNUNET_MESH_TransmitHandle *next;
393   unsigned int i;
394
395   if (NULL == t)
396   {
397     GNUNET_break (0);
398     return;
399   }
400   h = t->mesh;
401
402   /* disconnect all peers */
403   GNUNET_CONTAINER_DLL_remove (h->tunnels_head, h->tunnels_tail, t);
404   for (i = 0; i < t->npeers; i++)
405   {
406     if ( (NULL != t->disconnect_handler) && t->peers[i]->connected)
407     {
408       GNUNET_PEER_resolve (t->peers[i]->id, &pi);
409       t->disconnect_handler (t->cls, &pi);
410     }
411     GNUNET_PEER_change_rc (t->peers[i]->id, -1);
412     GNUNET_free (t->peers[i]);
413   }
414
415   /* signal tunnel destruction */
416   if ( (NULL != h->cleaner) && (0 != t->owner) && (GNUNET_YES == call_cleaner) )
417     h->cleaner (h->cls, t, t->ctx);
418
419   /* check that clients did not leave messages behind in the queue */
420   for (th = h->th_head; NULL != th; th = next)
421   {
422     next = th->next;
423     if (th->tunnel != t)
424       continue;
425     /* we should not really get here, as clients should have
426        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];
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, GNUNET_NO);
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     for (i = 0; i < t->npeers; i++)
727     {
728       GNUNET_PEER_resolve (t->peers[i]->id, &pmsg.peer);
729       if (NULL != t->disconnect_handler && t->peers[i]->connected)
730         t->disconnect_handler (t->cls, &pmsg.peer);
731       /* If the tunnel was "by type", dont connect individual peers */
732       if (0 == t->napps)
733         send_packet (t->mesh, &pmsg.header, t);
734     }
735     /* Reconnect all types, if any  */
736     for (i = 0; i < t->napps; i++)
737     {
738       struct GNUNET_MESH_ConnectPeerByType msg;
739
740       msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
741       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE);
742       msg.tunnel_id = htonl (t->tid);
743       msg.type = htonl (t->apps[i]);
744       send_packet (t->mesh, &msg.header, t);
745     }
746   }
747   return GNUNET_YES;
748 }
749
750 /**
751  * Reconnect callback: tries to reconnect again after a failer previous
752  * reconnecttion
753  * @param cls closure (mesh handle)
754  * @param tc task context
755  */
756 static void
757 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
758 {
759   struct GNUNET_MESH_Handle *h = cls;
760
761   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
762   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
763     return;
764   do_reconnect (h);
765 }
766
767
768 /**
769  * Reconnect to the service, retransmit all infomation to try to restore the
770  * original state.
771  *
772  * @param h handle to the mesh
773  *
774  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
775  */
776 static void
777 reconnect (struct GNUNET_MESH_Handle *h)
778 {
779   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requested RECONNECT\n");
780   if (GNUNET_SCHEDULER_NO_TASK == h->reconnect_task)
781     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
782                                                       &reconnect_cbk, h);
783 }
784
785
786 /******************************************************************************/
787 /***********************      RECEIVE HANDLERS     ****************************/
788 /******************************************************************************/
789
790 /**
791  * Process the new tunnel notification and add it to the tunnels in the handle
792  *
793  * @param h     The mesh handle
794  * @param msg   A message with the details of the new incoming tunnel
795  */
796 static void
797 process_tunnel_created (struct GNUNET_MESH_Handle *h,
798                         const struct GNUNET_MESH_TunnelNotification *msg)
799 {
800   struct GNUNET_MESH_Tunnel *t;
801   MESH_TunnelNumber tid;
802
803   tid = ntohl (msg->tunnel_id);
804   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
805   {
806     GNUNET_break (0);
807     return;
808   }
809   t = create_tunnel (h, tid);
810   t->owner = GNUNET_PEER_intern (&msg->peer);
811   t->npeers = 1;
812   t->peers = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer *));
813   t->peers[0] = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer));
814   t->peers[0]->t = t;
815   t->peers[0]->connected = 1;
816   t->peers[0]->id = t->owner;
817   GNUNET_PEER_change_rc (t->owner, 1);
818   t->mesh = h;
819   t->tid = tid;
820   if (NULL != h->new_tunnel)
821   {
822     struct GNUNET_ATS_Information atsi;
823
824     atsi.type = 0;
825     atsi.value = 0;
826     t->ctx = h->new_tunnel (h->cls, t, &msg->peer, &atsi);
827   }
828   LOG (GNUNET_ERROR_TYPE_DEBUG, "new incoming tunnel %X\n", t->tid);
829   return;
830 }
831
832
833 /**
834  * Process the tunnel destroy notification and free associated resources
835  *
836  * @param h     The mesh handle
837  * @param msg   A message with the details of the tunnel being destroyed
838  */
839 static void
840 process_tunnel_destroy (struct GNUNET_MESH_Handle *h,
841                         const struct GNUNET_MESH_TunnelMessage *msg)
842 {
843   struct GNUNET_MESH_Tunnel *t;
844   MESH_TunnelNumber tid;
845
846   tid = ntohl (msg->tunnel_id);
847   t = retrieve_tunnel (h, tid);
848
849   if (NULL == t)
850   {
851     return;
852   }
853   if (0 == t->owner)
854   {
855     GNUNET_break (0);
856   }
857   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %u destroyed\n", t->tid);
858   destroy_tunnel (t, GNUNET_YES);
859   return;
860 }
861
862
863 /**
864  * Process the new peer event and notify the upper level of it
865  *
866  * @param h     The mesh handle
867  * @param msg   A message with the details of the peer event
868  */
869 static void
870 process_peer_event (struct GNUNET_MESH_Handle *h,
871                     const struct GNUNET_MESH_PeerControl *msg)
872 {
873   struct GNUNET_MESH_Tunnel *t;
874   struct GNUNET_MESH_Peer *p;
875   struct GNUNET_ATS_Information atsi;
876   GNUNET_PEER_Id id;
877   uint16_t size;
878
879   LOG (GNUNET_ERROR_TYPE_DEBUG, "processig peer event\n");
880   size = ntohs (msg->header.size);
881   if (size != sizeof (struct GNUNET_MESH_PeerControl))
882   {
883     GNUNET_break (0);
884     return;
885   }
886   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
887   if (NULL == t)
888   {
889     GNUNET_break (0);
890     return;
891   }
892   id = GNUNET_PEER_search (&msg->peer);
893   if ((p = retrieve_peer (t, id)) == NULL)
894     p = add_peer_to_tunnel (t, &msg->peer);
895   if (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD == ntohs (msg->header.type))
896   {
897     LOG (GNUNET_ERROR_TYPE_DEBUG, "adding peer\n");
898     if (NULL != t->connect_handler)
899     {
900       atsi.type = 0;
901       atsi.value = 0;
902       t->connect_handler (t->cls, &msg->peer, &atsi);
903     }
904     p->connected = 1;
905   }
906   else
907   {
908     LOG (GNUNET_ERROR_TYPE_DEBUG, "removing peer\n");
909     if (NULL != t->disconnect_handler && p->connected)
910     {
911       t->disconnect_handler (t->cls, &msg->peer);
912     }
913     remove_peer_from_tunnel (p);
914     GNUNET_free (p);
915   }
916   LOG (GNUNET_ERROR_TYPE_DEBUG, "processing peer event END\n");
917 }
918
919
920 /**
921  * Process the incoming data packets
922  *
923  * @param h         The mesh handle
924  * @param message   A message encapsulating the data
925  * 
926  * @return GNUNET_YES if everything went fine
927  *         GNUNET_NO if client closed connection (h no longer valid)
928  */
929 static int
930 process_incoming_data (struct GNUNET_MESH_Handle *h,
931                        const struct GNUNET_MessageHeader *message)
932 {
933   const struct GNUNET_MessageHeader *payload;
934   const struct GNUNET_MESH_MessageHandler *handler;
935   const struct GNUNET_PeerIdentity *peer;
936   struct GNUNET_MESH_Unicast *ucast;
937   struct GNUNET_MESH_Multicast *mcast;
938   struct GNUNET_MESH_ToOrigin *to_orig;
939   struct GNUNET_MESH_Tunnel *t;
940   unsigned int i;
941   uint16_t type;
942
943   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a data message!\n");
944   type = ntohs (message->type);
945   switch (type)
946   {
947   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
948     ucast = (struct GNUNET_MESH_Unicast *) message;
949
950     t = retrieve_tunnel (h, ntohl (ucast->tid));
951     payload = (struct GNUNET_MessageHeader *) &ucast[1];
952     peer = &ucast->oid;
953     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ucast on tunnel %s [%x]\n",
954          GNUNET_i2s (peer), ntohl (ucast->tid));
955     break;
956   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
957     mcast = (struct GNUNET_MESH_Multicast *) message;
958     t = retrieve_tunnel (h, ntohl (mcast->tid));
959     payload = (struct GNUNET_MessageHeader *) &mcast[1];
960     peer = &mcast->oid;
961     LOG (GNUNET_ERROR_TYPE_DEBUG, "  mcast on tunnel %s [%x]\n",
962          GNUNET_i2s (peer), ntohl (mcast->tid));
963     break;
964   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
965     to_orig = (struct GNUNET_MESH_ToOrigin *) message;
966     t = retrieve_tunnel (h, ntohl (to_orig->tid));
967     payload = (struct GNUNET_MessageHeader *) &to_orig[1];
968     peer = &to_orig->sender;
969     LOG (GNUNET_ERROR_TYPE_DEBUG, "  torig on tunnel %s [%x]\n",
970          GNUNET_i2s (peer), ntohl (to_orig->tid));
971     break;
972   default:
973     GNUNET_break (0);
974     return GNUNET_YES;
975   }
976   if (NULL == t)
977   {
978     GNUNET_break (0);
979     return GNUNET_YES;
980   }
981   type = ntohs (payload->type);
982   for (i = 0; i < h->n_handlers; i++)
983   {
984     handler = &h->message_handlers[i];
985     if (handler->type == type)
986     {
987       struct GNUNET_ATS_Information atsi;
988
989       atsi.type = 0;
990       atsi.value = 0;
991       if (GNUNET_OK !=
992           handler->callback (h->cls, t, &t->ctx, peer, payload, &atsi))
993       {
994         LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH: callback caused disconnection\n");
995         GNUNET_MESH_disconnect (h);
996         return GNUNET_NO;
997       }
998       else
999       {
1000         LOG (GNUNET_ERROR_TYPE_DEBUG,
1001              "MESH: callback completed successfully\n");
1002
1003       }
1004     }
1005   }
1006   return GNUNET_YES;
1007 }
1008
1009
1010 /**
1011  * Function to process all messages received from the service
1012  *
1013  * @param cls closure
1014  * @param msg message received, NULL on timeout or fatal error
1015  */
1016 static void
1017 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
1018 {
1019   struct GNUNET_MESH_Handle *h = cls;
1020
1021   if (msg == NULL)
1022   {
1023     LOG (GNUNET_ERROR_TYPE_DEBUG, "Received NULL msg\n");
1024     reconnect (h);
1025     return;
1026   }
1027   LOG (GNUNET_ERROR_TYPE_DEBUG, "received a message type %hu from MESH\n",
1028        ntohs (msg->type));
1029   switch (ntohs (msg->type))
1030   {
1031     /* Notify of a new incoming tunnel */
1032   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE:
1033     process_tunnel_created (h, (struct GNUNET_MESH_TunnelNotification *) msg);
1034     break;
1035     /* Notify of a tunnel disconnection */
1036   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1037     process_tunnel_destroy (h, (struct GNUNET_MESH_TunnelMessage *) msg);
1038     break;
1039     /* Notify of a new peer or a peer disconnect in the tunnel */
1040   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD:
1041   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL:
1042     process_peer_event (h, (struct GNUNET_MESH_PeerControl *) msg);
1043     break;
1044     /* Notify of a new data packet in the tunnel */
1045   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1046   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1047   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1048     if (GNUNET_NO == process_incoming_data (h, msg))
1049       return;
1050     break;
1051     /* We shouldn't get any other packages, log and ignore */
1052   default:
1053     LOG (GNUNET_ERROR_TYPE_WARNING,
1054          "MESH: unsolicited message form service (type %d)\n",
1055          ntohs (msg->type));
1056   }
1057   LOG (GNUNET_ERROR_TYPE_DEBUG, "message processed\n");
1058   GNUNET_CLIENT_receive (h->client, &msg_received, h,
1059                          GNUNET_TIME_UNIT_FOREVER_REL);
1060 }
1061
1062
1063 /******************************************************************************/
1064 /************************       SEND FUNCTIONS     ****************************/
1065 /******************************************************************************/
1066
1067 /**
1068  * Function called to send a message to the service.
1069  * "buf" will be NULL and "size" zero if the socket was closed for writing in
1070  * the meantime.
1071  *
1072  * @param cls closure, the mesh handle
1073  * @param size number of bytes available in buf
1074  * @param buf where the callee should write the connect message
1075  * @return number of bytes written to buf
1076  */
1077 static size_t
1078 send_callback (void *cls, size_t size, void *buf)
1079 {
1080   struct GNUNET_MESH_Handle *h = cls;
1081   struct GNUNET_MESH_TransmitHandle *th;
1082   char *cbuf = buf;
1083   size_t tsize;
1084   size_t psize;
1085
1086   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send packet() Buffer %u\n", size);
1087   h->th = NULL;
1088   if ((0 == size) || (NULL == buf))
1089   {
1090     LOG (GNUNET_ERROR_TYPE_DEBUG, "Received NULL callback\n");
1091     reconnect (h);
1092     return 0;
1093   }
1094   tsize = 0;
1095   while ((NULL != (th = h->th_head)) && (size >= th->size))
1096   {
1097     if (NULL != th->notify)
1098     {
1099       if (th->tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1100       {
1101         /* traffic to origin */
1102         struct GNUNET_MESH_ToOrigin to;
1103         struct GNUNET_MessageHeader *mh;
1104
1105         GNUNET_assert (size >= th->size);
1106         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (to)];
1107         psize = th->notify (th->notify_cls, size - sizeof (to), mh);
1108         LOG (GNUNET_ERROR_TYPE_DEBUG, "  to origin, type %u\n",
1109              ntohs (mh->type));
1110         if (psize > 0)
1111         {
1112           psize += sizeof (to);
1113           GNUNET_assert (size >= psize);
1114           to.header.size = htons (psize);
1115           to.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
1116           to.tid = htonl (th->tunnel->tid);
1117           memset (&to.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1118           memset (&to.sender, 0, sizeof (struct GNUNET_PeerIdentity));
1119           memcpy (cbuf, &to, sizeof (to));
1120         }
1121       }
1122       else if (th->target == 0)
1123       {
1124         /* multicast */
1125         struct GNUNET_MESH_Multicast mc;
1126         struct GNUNET_MessageHeader *mh;
1127
1128         GNUNET_assert (size >= th->size);
1129         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (mc)];
1130         psize = th->notify (th->notify_cls, size - sizeof (mc), mh);
1131         LOG (GNUNET_ERROR_TYPE_DEBUG, "  multicast, type %u\n",
1132              ntohs (mh->type));
1133         if (psize > 0)
1134         {
1135           psize += sizeof (mc);
1136           GNUNET_assert (size >= psize);
1137           mc.header.size = htons (psize);
1138           mc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1139           mc.tid = htonl (th->tunnel->tid);
1140           mc.mid = 0;
1141           mc.ttl = 0;
1142           memset (&mc.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1143           memcpy (cbuf, &mc, sizeof (mc));
1144         }
1145       }
1146       else
1147       {
1148         /* unicast */
1149         struct GNUNET_MESH_Unicast uc;
1150         struct GNUNET_MessageHeader *mh;
1151
1152         GNUNET_assert (size >= th->size);
1153         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (uc)];
1154         psize = th->notify (th->notify_cls, size - sizeof (uc), mh);
1155         LOG (GNUNET_ERROR_TYPE_DEBUG, "  unicast, type %u\n",
1156              ntohs (mh->type));
1157         if (psize > 0)
1158         {
1159           psize += sizeof (uc);
1160           GNUNET_assert (size >= psize);
1161           uc.header.size = htons (psize);
1162           uc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1163           uc.tid = htonl (th->tunnel->tid);
1164           memset (&uc.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1165           GNUNET_PEER_resolve (th->target, &uc.destination);
1166           memcpy (cbuf, &uc, sizeof (uc));
1167         }
1168       }
1169     }
1170     else
1171     {
1172       memcpy (cbuf, &th[1], th->size);
1173       psize = th->size;
1174     }
1175     if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1176       GNUNET_SCHEDULER_cancel (th->timeout_task);
1177     if (NULL != th->notify)
1178     {
1179       th->tunnel->mesh->npackets--;
1180       th->tunnel->npackets--;
1181     }
1182     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1183     GNUNET_free (th);
1184     cbuf += psize;
1185     size -= psize;
1186     tsize += psize;
1187   }
1188   LOG (GNUNET_ERROR_TYPE_DEBUG, "  total size: %u\n", tsize);
1189   if (NULL != (th = h->th_head))
1190   {
1191     LOG (GNUNET_ERROR_TYPE_DEBUG, "  next size: %u\n", th->size);
1192     if (NULL == h->th)
1193       h->th =
1194           GNUNET_CLIENT_notify_transmit_ready (h->client, th->size,
1195                                                GNUNET_TIME_UNIT_FOREVER_REL,
1196                                                GNUNET_YES, &send_callback, h);
1197   }
1198   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send packet() END\n");
1199   if (GNUNET_NO == h->in_receive)
1200   {
1201     h->in_receive = GNUNET_YES;
1202     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1203                            GNUNET_TIME_UNIT_FOREVER_REL);
1204   }
1205   return tsize;
1206 }
1207
1208
1209 /**
1210  * Auxiliary function to send an already constructed packet to the service.
1211  * Takes care of creating a new queue element, copying the message and
1212  * calling the tmt_rdy function if necessary.
1213  * 
1214  * @param h mesh handle
1215  * @param msg message to transmit
1216  * @param tunnel tunnel this send is related to (NULL if N/A)
1217  */
1218 static void
1219 send_packet (struct GNUNET_MESH_Handle *h,
1220              const struct GNUNET_MessageHeader *msg,
1221              struct GNUNET_MESH_Tunnel *tunnel)
1222 {
1223   struct GNUNET_MESH_TransmitHandle *th;
1224   size_t msize;
1225
1226   msize = ntohs (msg->size);
1227   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle) + msize);
1228   th->priority = UINT32_MAX;
1229   th->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1230   th->size = msize;
1231   th->tunnel = tunnel;
1232   memcpy (&th[1], msg, msize);
1233   add_to_queue (h, th);
1234   if (NULL != h->th)
1235     return;
1236   h->th =
1237       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
1238                                            GNUNET_TIME_UNIT_FOREVER_REL,
1239                                            GNUNET_YES, &send_callback, h);
1240 }
1241
1242
1243 /******************************************************************************/
1244 /**********************      API CALL DEFINITIONS     *************************/
1245 /******************************************************************************/
1246
1247 /**
1248  * Connect to the mesh service.
1249  *
1250  * @param cfg configuration to use
1251  * @param queue_size size of the data message queue, shared among all tunnels
1252  *                   (each tunnel is guaranteed to accept at least one message,
1253  *                    no matter what is the status of other tunnels)
1254  * @param cls closure for the various callbacks that follow
1255  *            (including handlers in the handlers array)
1256  * @param new_tunnel function called when an *inbound* tunnel is created
1257  * @param cleaner function called when an *inbound* tunnel is destroyed by the
1258  *                remote peer, it is *not* called if GNUNET_MESH_tunnel_destroy
1259  *                is called on the tunnel
1260  * @param handlers callbacks for messages we care about, NULL-terminated
1261  *                note that the mesh is allowed to drop notifications about
1262  *                inbound messages if the client does not process them fast
1263  *                enough (for this notification type, a bounded queue is used)
1264  * @param stypes list of the applications that this client claims to provide
1265  * @return handle to the mesh service NULL on error
1266  *         (in this case, init is never called)
1267  */
1268 struct GNUNET_MESH_Handle *
1269 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1270                      unsigned int queue_size, void *cls,
1271                      GNUNET_MESH_InboundTunnelNotificationHandler new_tunnel,
1272                      GNUNET_MESH_TunnelEndHandler cleaner,
1273                      const struct GNUNET_MESH_MessageHandler *handlers,
1274                      const GNUNET_MESH_ApplicationType *stypes)
1275 {
1276   struct GNUNET_MESH_Handle *h;
1277
1278   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect()\n");
1279   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
1280   h->cfg = cfg;
1281   h->max_queue_size = queue_size;
1282   h->new_tunnel = new_tunnel;
1283   h->cleaner = cleaner;
1284   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
1285   if (h->client == NULL)
1286   {
1287     GNUNET_break (0);
1288     GNUNET_free (h);
1289     return NULL;
1290   }
1291   h->cls = cls;
1292   /* FIXME memdup? */
1293   h->applications = stypes;
1294   h->message_handlers = handlers;
1295   h->next_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
1296   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1297   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1298
1299   /* count handlers and apps, calculate size */
1300   for (h->n_applications = 0; stypes[h->n_applications]; h->n_applications++) ;
1301   for (h->n_handlers = 0; handlers[h->n_handlers].type; h->n_handlers++) ;
1302   send_connect (h);
1303   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect() END\n");
1304   return h;
1305 }
1306
1307
1308 /**
1309  * Disconnect from the mesh service. All tunnels will be destroyed. All tunnel
1310  * disconnect callbacks will be called on any still connected peers, notifying
1311  * about their disconnection. The registered inbound tunnel cleaner will be
1312  * called should any inbound tunnels still exist.
1313  *
1314  * @param handle connection to mesh to disconnect
1315  */
1316 void
1317 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
1318 {
1319   struct GNUNET_MESH_Tunnel *t;
1320   struct GNUNET_MESH_Tunnel *aux;
1321   struct GNUNET_MESH_TransmitHandle *th;
1322
1323   t = handle->tunnels_head;
1324   while (NULL != t)
1325   {
1326     aux = t->next;
1327     if (t->tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1328     {
1329       GNUNET_break (0);
1330       LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X not destroyed\n", t->tid);
1331     }
1332     destroy_tunnel (t, GNUNET_YES);
1333     t = aux;
1334   }
1335   while ( (th = handle->th_head) != NULL)
1336   {
1337     struct GNUNET_MessageHeader *msg;
1338
1339     /* Make sure it is an allowed packet (everything else should have been
1340      * already canceled).
1341      */
1342     GNUNET_break (UINT32_MAX == th->priority);
1343     GNUNET_break (NULL == th->notify);
1344     msg = (struct GNUNET_MessageHeader *) &th[1];
1345     switch (ntohs(msg->type))
1346     {
1347       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT:
1348       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1349         break;
1350       default:
1351         GNUNET_break (0);
1352         LOG (GNUNET_ERROR_TYPE_DEBUG, "unexpected msg %u\n",
1353              ntohs(msg->type));
1354     }
1355
1356     GNUNET_CONTAINER_DLL_remove (handle->th_head, handle->th_tail, th);
1357     GNUNET_free (th);
1358   }
1359
1360   if (NULL != handle->th)
1361   {
1362     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
1363     handle->th = NULL;
1364   }
1365   if (NULL != handle->client)
1366   {
1367     GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
1368     handle->client = NULL;
1369   }
1370   if (GNUNET_SCHEDULER_NO_TASK != handle->reconnect_task)
1371   {
1372     GNUNET_SCHEDULER_cancel(handle->reconnect_task);
1373     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1374   }
1375   GNUNET_free (handle);
1376 }
1377
1378
1379 /**
1380  * Create a new tunnel (we're initiator and will be allowed to add/remove peers
1381  * and to broadcast).
1382  *
1383  * @param h mesh handle
1384  * @param tunnel_ctx client's tunnel context to associate with the tunnel
1385  * @param connect_handler function to call when peers are actually connected
1386  * @param disconnect_handler function to call when peers are disconnected
1387  * @param handler_cls closure for connect/disconnect handlers
1388  */
1389 struct GNUNET_MESH_Tunnel *
1390 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h, void *tunnel_ctx,
1391                            GNUNET_MESH_PeerConnectHandler connect_handler,
1392                            GNUNET_MESH_PeerDisconnectHandler disconnect_handler,
1393                            void *handler_cls)
1394 {
1395   struct GNUNET_MESH_Tunnel *t;
1396   struct GNUNET_MESH_TunnelMessage msg;
1397
1398   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating new tunnel\n");
1399   t = create_tunnel (h, 0);
1400   t->connect_handler = connect_handler;
1401   t->disconnect_handler = disconnect_handler;
1402   t->cls = handler_cls;
1403   t->ctx = tunnel_ctx;
1404   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1405   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1406   msg.tunnel_id = htonl (t->tid);
1407   send_packet (h, &msg.header, t);
1408   return t;
1409 }
1410
1411
1412 /**
1413  * Destroy an existing tunnel. The existing callback for the tunnel will NOT
1414  * be called.
1415  *
1416  * @param tunnel tunnel handle
1417  */
1418 void
1419 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tunnel)
1420 {
1421   struct GNUNET_MESH_Handle *h;
1422   struct GNUNET_MESH_TunnelMessage msg;
1423   struct GNUNET_MESH_TransmitHandle *th;
1424
1425   LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying tunnel\n");
1426   h = tunnel->mesh;
1427
1428   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1429   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1430   msg.tunnel_id = htonl (tunnel->tid);
1431   th = h->th_head;
1432   while (th != NULL)
1433   {
1434     struct GNUNET_MESH_TransmitHandle *aux;
1435     if (th->tunnel == tunnel)
1436     {
1437       aux = th->next;
1438       /* FIXME call the handler? */
1439       if (NULL != th->notify)
1440         th->notify (th->notify_cls, 0, NULL);
1441       GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1442       GNUNET_free (th);
1443       th = aux;
1444     }
1445     else
1446       th = th->next;
1447   }
1448
1449   destroy_tunnel (tunnel, GNUNET_NO);
1450   send_packet (h, &msg.header, tunnel);
1451 }
1452
1453
1454 /**
1455  * Request that a peer should be added to the tunnel.  The existing
1456  * connect handler will be called ONCE with either success or failure.
1457  * This function should NOT be called again with the same peer before the
1458  * connect handler is called.
1459  *
1460  * @param tunnel handle to existing tunnel
1461  * @param peer peer to add
1462  */
1463 void
1464 GNUNET_MESH_peer_request_connect_add (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_intern (peer);
1472   for (i = 0; i < tunnel->npeers; i++)
1473   {
1474     if (tunnel->peers[i]->id == peer_id)
1475     {
1476       /* Peer already exists in tunnel */
1477       GNUNET_PEER_change_rc (peer_id, -1);
1478       GNUNET_break (0);
1479       return;
1480     }
1481   }
1482   if (NULL == add_peer_to_tunnel (tunnel, peer))
1483     return;
1484
1485   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1486   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1487   msg.tunnel_id = htonl (tunnel->tid);
1488   msg.peer = *peer;
1489   send_packet (tunnel->mesh, &msg.header, tunnel);
1490
1491   return;
1492 }
1493
1494
1495 /**
1496  * Request that a peer should be removed from the tunnel.  The existing
1497  * disconnect handler will be called ONCE if we were connected.
1498  *
1499  * @param tunnel handle to existing tunnel
1500  * @param peer peer to remove
1501  */
1502 void
1503 GNUNET_MESH_peer_request_connect_del (struct GNUNET_MESH_Tunnel *tunnel,
1504                                       const struct GNUNET_PeerIdentity *peer)
1505 {
1506   struct GNUNET_MESH_PeerControl msg;
1507   GNUNET_PEER_Id peer_id;
1508   unsigned int i;
1509
1510   peer_id = GNUNET_PEER_search (peer);
1511   if (0 == peer_id)
1512   {
1513     GNUNET_break (0);
1514     return;
1515   }
1516   for (i = 0; i < tunnel->npeers; i++)
1517     if (tunnel->peers[i]->id == peer_id)
1518       break;
1519   if (i == tunnel->npeers)
1520   {
1521     GNUNET_break (0);
1522     return;
1523   }
1524   if (NULL != tunnel->disconnect_handler && tunnel->peers[i]->connected == 1)
1525     tunnel->disconnect_handler (tunnel->cls, peer);
1526   GNUNET_PEER_change_rc (peer_id, -1);
1527   GNUNET_free (tunnel->peers[i]);
1528   tunnel->peers[i] = tunnel->peers[tunnel->npeers - 1];
1529   GNUNET_array_grow (tunnel->peers, tunnel->npeers, tunnel->npeers - 1);
1530
1531   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1532   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1533   msg.tunnel_id = htonl (tunnel->tid);
1534   memcpy (&msg.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1535   send_packet (tunnel->mesh, &msg.header, tunnel);
1536 }
1537
1538
1539 /**
1540  * Request that the mesh should try to connect to a peer supporting the given
1541  * message type.
1542  *
1543  * @param tunnel handle to existing tunnel
1544  * @param app_type application type that must be supported by the peer (MESH
1545  *                 should discover peer in proximity handling this type)
1546  */
1547 void
1548 GNUNET_MESH_peer_request_connect_by_type (struct GNUNET_MESH_Tunnel *tunnel,
1549                                           GNUNET_MESH_ApplicationType app_type)
1550 {
1551   struct GNUNET_MESH_ConnectPeerByType msg;
1552
1553   GNUNET_array_append (tunnel->apps, tunnel->napps, app_type);
1554
1555   LOG (GNUNET_ERROR_TYPE_DEBUG, "* CONNECT BY TYPE *\n");
1556   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
1557   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE);
1558   msg.tunnel_id = htonl (tunnel->tid);
1559   msg.type = htonl (app_type);
1560   send_packet (tunnel->mesh, &msg.header, tunnel);
1561 }
1562
1563
1564 /**
1565  * Ask the mesh to call "notify" once it is ready to transmit the
1566  * given number of bytes to the specified "target".  If we are not yet
1567  * connected to the specified peer, a call to this function will cause
1568  * us to try to establish a connection.
1569  *
1570  * @param tunnel tunnel to use for transmission
1571  * @param cork is corking allowed for this transmission?
1572  * @param priority how important is the message?
1573  * @param maxdelay how long can the message wait?
1574  * @param target destination for the message,
1575  *               NULL for multicast to all tunnel targets
1576  * @param notify_size how many bytes of buffer space does notify want?
1577  * @param notify function to call when buffer space is available;
1578  *        will be called with NULL on timeout or if the overall queue
1579  *        for this peer is larger than queue_size and this is currently
1580  *        the message with the lowest priority
1581  * @param notify_cls closure for notify
1582  * @return non-NULL if the notify callback was queued,
1583  *         NULL if we can not even queue the request (insufficient
1584  *         memory); if NULL is returned, "notify" will NOT be called.
1585  */
1586 struct GNUNET_MESH_TransmitHandle *
1587 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
1588                                    uint32_t priority,
1589                                    struct GNUNET_TIME_Relative maxdelay,
1590                                    const struct GNUNET_PeerIdentity *target,
1591                                    size_t notify_size,
1592                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1593                                    void *notify_cls)
1594 {
1595   struct GNUNET_MESH_TransmitHandle *th;
1596   struct GNUNET_MESH_TransmitHandle *least_priority_th;
1597   uint32_t least_priority;
1598   size_t overhead;
1599
1600   GNUNET_assert (NULL != tunnel);
1601   LOG (GNUNET_ERROR_TYPE_DEBUG, "mesh notify transmit ready called\n");
1602   if (NULL != target)
1603     LOG (GNUNET_ERROR_TYPE_DEBUG, "    target %s\n", GNUNET_i2s (target));
1604   else
1605     LOG (GNUNET_ERROR_TYPE_DEBUG, "    target multicast\n");
1606   GNUNET_assert (NULL != notify);
1607   if (tunnel->mesh->npackets >= tunnel->mesh->max_queue_size &&
1608       tunnel->npackets > 0)
1609   {
1610     /* queue full */
1611     if (0 == priority)
1612       return NULL;
1613     th = tunnel->mesh->th_tail;
1614     least_priority = priority;
1615     least_priority_th = NULL;
1616     while (NULL != th)
1617     {
1618       if (th->priority < least_priority && th->tunnel->npackets > 1)
1619       {
1620         least_priority_th = th;
1621         least_priority = th->priority;
1622       }
1623       th = th->prev;
1624     }
1625     if (NULL == least_priority_th)
1626       return NULL;
1627     /* Can't be a control message */
1628     GNUNET_assert (NULL != least_priority_th->notify);
1629     least_priority_th->notify (notify_cls, 0, NULL);
1630     least_priority_th->tunnel->npackets--;
1631     tunnel->mesh->npackets--;
1632     GNUNET_CONTAINER_DLL_remove (tunnel->mesh->th_head, tunnel->mesh->th_tail,
1633                                  least_priority_th);
1634     if (GNUNET_SCHEDULER_NO_TASK != least_priority_th->timeout_task)
1635       GNUNET_SCHEDULER_cancel (least_priority_th->timeout_task);
1636     GNUNET_free (least_priority_th);
1637   }
1638   tunnel->npackets++;
1639   tunnel->mesh->npackets++;
1640   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
1641   th->tunnel = tunnel;
1642   th->priority = priority;
1643   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1644   th->target = GNUNET_PEER_intern (target);
1645   if (tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1646     overhead = sizeof (struct GNUNET_MESH_ToOrigin);
1647   else if (NULL == target)
1648     overhead = sizeof (struct GNUNET_MESH_Multicast);
1649   else
1650     overhead = sizeof (struct GNUNET_MESH_Unicast);
1651   th->size = notify_size + overhead;
1652   th->notify = notify;
1653   th->notify_cls = notify_cls;
1654   add_to_queue (tunnel->mesh, th);
1655   if (NULL != tunnel->mesh->th)
1656     return th;
1657   tunnel->mesh->th =
1658       GNUNET_CLIENT_notify_transmit_ready (tunnel->mesh->client, th->size,
1659                                            GNUNET_TIME_UNIT_FOREVER_REL,
1660                                            GNUNET_YES, &send_callback,
1661                                            tunnel->mesh);
1662   return th;
1663 }
1664
1665
1666 /**
1667  * Cancel the specified transmission-ready notification.
1668  *
1669  * @param th handle that was returned by "notify_transmit_ready".
1670  */
1671 void
1672 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
1673 {
1674   struct GNUNET_MESH_Handle *mesh;
1675
1676   mesh = th->tunnel->mesh;
1677   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1678     GNUNET_SCHEDULER_cancel (th->timeout_task);
1679   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
1680   GNUNET_free (th);
1681   if ((NULL == mesh->th_head) && (NULL != mesh->th))
1682   {
1683     /* queue empty, no point in asking for transmission */
1684     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
1685     mesh->th = NULL;
1686   }
1687 }
1688
1689
1690 /**
1691  * Transition API for tunnel ctx management
1692  */
1693 void
1694 GNUNET_MESH_tunnel_set_data (struct GNUNET_MESH_Tunnel *tunnel, void *data)
1695 {
1696   tunnel->ctx = data;
1697 }
1698
1699 /**
1700  * Transition API for tunnel ctx management
1701  */
1702 void *
1703 GNUNET_MESH_tunnel_get_data (struct GNUNET_MESH_Tunnel *tunnel)
1704 {
1705   return tunnel->ctx;
1706 }
1707
1708
1709 #if 0                           /* keep Emacsens' auto-indent happy */
1710 {
1711 #endif
1712 #ifdef __cplusplus
1713 }
1714 #endif