- full message struct initialization
[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 new mesh service
21  * @author Bartlomiej Polot
22  *
23  * STRUCTURE:
24  * - DATA STRUCTURES
25  * - DECLARATIONS
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 #define DEBUG_ACK GNUNET_YES
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      * Size of 'data' -- or the desired size of 'notify' if 'data' is NULL.
98      */
99   size_t size;
100 };
101
102
103 /**
104  * Opaque handle to the service.
105  */
106 struct GNUNET_MESH_Handle
107 {
108
109     /**
110      * Handle to the server connection, to send messages later
111      */
112   struct GNUNET_CLIENT_Connection *client;
113
114     /**
115      * Set of handlers used for processing incoming messages in the tunnels
116      */
117   const struct GNUNET_MESH_MessageHandler *message_handlers;
118
119   /**
120    * Number of handlers in the handlers array.
121    */
122   unsigned int n_handlers;
123
124   /**
125    * Ports open.
126    */
127   const uint32_t *ports;
128
129   /**
130    * Number of ports.
131    */
132   unsigned int n_ports;
133
134     /**
135      * Double linked list of the tunnels this client is connected to, head.
136      */
137   struct GNUNET_MESH_Tunnel *tunnels_head;
138
139     /**
140      * Double linked list of the tunnels this client is connected to, tail.
141      */
142   struct GNUNET_MESH_Tunnel *tunnels_tail;
143
144     /**
145      * Callback for inbound tunnel creation
146      */
147   GNUNET_MESH_InboundTunnelNotificationHandler *new_tunnel;
148
149     /**
150      * Callback for inbound tunnel disconnection
151      */
152   GNUNET_MESH_TunnelEndHandler *cleaner;
153
154     /**
155      * Handle to cancel pending transmissions in case of disconnection
156      */
157   struct GNUNET_CLIENT_TransmitHandle *th;
158
159     /**
160      * Closure for all the handlers given by the client
161      */
162   void *cls;
163
164     /**
165      * Messages to send to the service, head.
166      */
167   struct GNUNET_MESH_TransmitHandle *th_head;
168
169     /**
170      * Messages to send to the service, tail.
171      */
172   struct GNUNET_MESH_TransmitHandle *th_tail;
173
174     /**
175      * tid of the next tunnel to create (to avoid reusing IDs often)
176      */
177   MESH_TunnelNumber next_tid;
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    * Configuration given by the client, in case of reconnection
187    */
188   const struct GNUNET_CONFIGURATION_Handle *cfg;
189
190   /**
191    * Time to the next reconnect in case one reconnect fails
192    */
193   struct GNUNET_TIME_Relative reconnect_time;
194   
195   /**
196    * Task for trying to reconnect.
197    */
198   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
199
200   /**
201    * Monitor callback
202    */
203   GNUNET_MESH_TunnelsCB tunnels_cb;
204
205   /**
206    * Monitor callback closure.
207    */
208   void *tunnels_cls;
209
210   /**
211    * Tunnel callback.
212    */
213   GNUNET_MESH_TunnelCB tunnel_cb;
214
215   /**
216    * Tunnel callback closure.
217    */
218   void *tunnel_cls;
219
220 #if DEBUG_ACK
221   unsigned int acks_sent;
222   unsigned int acks_recv;
223 #endif
224 };
225
226
227 /**
228  * Description of a peer
229  */
230 struct GNUNET_MESH_Peer
231 {
232     /**
233      * ID of the peer in short form
234      */
235   GNUNET_PEER_Id id;
236
237   /**
238    * Tunnel this peer belongs to
239    */
240   struct GNUNET_MESH_Tunnel *t;
241
242   /**
243    * Flag indicating whether service has informed about its connection
244    */
245   int connected;
246
247 };
248
249
250 /**
251  * Opaque handle to a tunnel.
252  */
253 struct GNUNET_MESH_Tunnel
254 {
255
256     /**
257      * DLL next
258      */
259   struct GNUNET_MESH_Tunnel *next;
260
261     /**
262      * DLL prev
263      */
264   struct GNUNET_MESH_Tunnel *prev;
265
266     /**
267      * Handle to the mesh this tunnel belongs to
268      */
269   struct GNUNET_MESH_Handle *mesh;
270
271     /**
272      * Local ID of the tunnel
273      */
274   MESH_TunnelNumber tid;
275
276     /**
277      * Port number.
278      */
279   uint32_t port;
280
281     /**
282      * Other end of the tunnel.
283      */
284   GNUNET_PEER_Id peer;
285
286   /**
287    * Any data the caller wants to put in here
288    */
289   void *ctx;
290
291     /**
292      * Size of packet queued in this tunnel
293      */
294   unsigned int packet_size;
295
296     /**
297      * Is the tunnel allowed to buffer?
298      */
299   int buffering;
300
301     /**
302      * Is the tunnel allowed to buffer?
303      */
304   int reliable;
305
306     /**
307      * Maximum allowed PID to send (last ACK recevied).
308      */
309   uint32_t last_ack_recv;
310
311     /**
312      * Last PID received from the service.
313      */
314   uint32_t last_pid_recv;
315
316   /**
317    * Last packet ID sent to the service.
318    */
319   uint32_t last_pid_sent;
320
321   /**
322    * Last ACK value sent to the service: how much are we willing to accept?
323    */
324   uint32_t last_ack_sent;
325 };
326
327
328 /**
329  * Implementation state for mesh's message queue.
330  */
331 struct MeshMQState
332 {
333   /**
334    * The current transmit handle, or NULL
335    * if no transmit is active.
336    */
337   struct GNUNET_MESH_TransmitHandle *th;
338
339   /**
340    * Tunnel to send the data over.
341    */
342   struct GNUNET_MESH_Tunnel *tunnel;
343 };
344
345
346 /******************************************************************************/
347 /***********************         DECLARATIONS         *************************/
348 /******************************************************************************/
349
350 /**
351  * Function called to send a message to the service.
352  * "buf" will be NULL and "size" zero if the socket was closed for writing in
353  * the meantime.
354  *
355  * @param cls closure, the mesh handle
356  * @param size number of bytes available in buf
357  * @param buf where the callee should write the connect message
358  * @return number of bytes written to buf
359  */
360 static size_t
361 send_callback (void *cls, size_t size, void *buf);
362
363
364 /******************************************************************************/
365 /***********************     AUXILIARY FUNCTIONS      *************************/
366 /******************************************************************************/
367
368 /**
369  * Check if transmission is a payload packet.
370  *
371  * @param th Transmission handle.
372  *
373  * @return GNUNET_YES if it is a payload packet,
374  *         GNUNET_NO if it is a mesh management packet.
375  */
376 static int
377 th_is_payload (struct GNUNET_MESH_TransmitHandle *th)
378 {
379   return (th->notify != NULL) ? GNUNET_YES : GNUNET_NO;
380 }
381
382
383 /**
384  * Check whether there is any message ready in the queue and find the size.
385  * 
386  * @param h Mesh handle.
387  * 
388  * @return The size of the first ready message in the queue,
389  *         0 if there is none.
390  */
391 static size_t
392 message_ready_size (struct GNUNET_MESH_Handle *h)
393 {
394   struct GNUNET_MESH_TransmitHandle *th;
395   struct GNUNET_MESH_Tunnel *t;
396
397   for (th = h->th_head; NULL != th; th = th->next)
398   {
399     t = th->tunnel;
400     if (GNUNET_NO == th_is_payload (th))
401     {
402       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  message internal\n");
403       return th->size;
404     }
405     if (GNUNET_YES == GMC_is_pid_bigger(t->last_ack_recv, t->last_pid_sent))
406     {
407       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  message payload ok (%u =< %u)\n",
408            t->last_pid_sent + 1, t->last_ack_recv);
409       return th->size;
410     }
411   }
412   return 0;
413 }
414
415
416 /**
417  * Get the tunnel handler for the tunnel specified by id from the given handle
418  * @param h Mesh handle
419  * @param tid ID of the wanted tunnel
420  * @return handle to the required tunnel or NULL if not found
421  */
422 static struct GNUNET_MESH_Tunnel *
423 retrieve_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
424 {
425   struct GNUNET_MESH_Tunnel *t;
426
427   t = h->tunnels_head;
428   while (t != NULL)
429   {
430     if (t->tid == tid)
431       return t;
432     t = t->next;
433   }
434   return NULL;
435 }
436
437
438 /**
439  * Create a new tunnel and insert it in the tunnel list of the mesh handle
440  * @param h Mesh handle
441  * @param tid desired tid of the tunnel, 0 to assign one automatically
442  * @return handle to the created tunnel
443  */
444 static struct GNUNET_MESH_Tunnel *
445 create_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
446 {
447   struct GNUNET_MESH_Tunnel *t;
448
449   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
450   GNUNET_CONTAINER_DLL_insert (h->tunnels_head, h->tunnels_tail, t);
451   t->mesh = h;
452   if (0 == tid)
453   {
454     t->tid = h->next_tid;
455     while (NULL != retrieve_tunnel (h, h->next_tid))
456     {
457       h->next_tid++;
458       h->next_tid &= ~GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
459       h->next_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
460     }
461   }
462   else
463   {
464     t->tid = tid;
465   }
466   t->last_ack_recv = (uint32_t) -1;
467   t->last_pid_recv = (uint32_t) -1;
468   t->last_ack_sent = (uint32_t) -1;
469   t->last_pid_sent = (uint32_t) -1;
470   t->buffering = GNUNET_YES;
471   return t;
472 }
473
474
475 /**
476  * Destroy the specified tunnel.
477  * - Destroys all peers, calling the disconnect callback on each if needed
478  * - Cancels all outgoing traffic for that tunnel, calling respective notifys
479  * - Calls cleaner if tunnel was inbound
480  * - Frees all memory used
481  *
482  * @param t Pointer to the tunnel.
483  * @param call_cleaner Whether to call the cleaner handler.
484  *
485  * @return Handle to the required tunnel or NULL if not found.
486  */
487 static void
488 destroy_tunnel (struct GNUNET_MESH_Tunnel *t, int call_cleaner)
489 {
490   struct GNUNET_MESH_Handle *h;
491   struct GNUNET_MESH_TransmitHandle *th;
492   struct GNUNET_MESH_TransmitHandle *next;
493
494   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroy_tunnel %X\n", t->tid);
495
496   if (NULL == t)
497   {
498     GNUNET_break (0);
499     return;
500   }
501   h = t->mesh;
502
503   GNUNET_CONTAINER_DLL_remove (h->tunnels_head, h->tunnels_tail, t);
504
505   /* signal tunnel destruction */
506   if ( (NULL != h->cleaner) && (0 != t->peer) && (GNUNET_YES == call_cleaner) )
507     h->cleaner (h->cls, t, t->ctx);
508
509   /* check that clients did not leave messages behind in the queue */
510   for (th = h->th_head; NULL != th; th = next)
511   {
512     next = th->next;
513     if (th->tunnel != t)
514       continue;
515     /* Clients should have aborted their requests already.
516      * Management traffic should be ok, as clients can't cancel that */
517     GNUNET_break (GNUNET_NO == th_is_payload(th));
518     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
519
520     /* clean up request */
521     if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
522       GNUNET_SCHEDULER_cancel (th->timeout_task);
523     GNUNET_free (th);    
524   }
525
526   /* if there are no more pending requests with mesh service, cancel active request */
527   /* Note: this should be unnecessary... */
528   if ((0 == message_ready_size (h)) && (NULL != h->th))
529   {
530     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
531     h->th = NULL;
532   }
533
534   if (0 != t->peer)
535     GNUNET_PEER_change_rc (t->peer, -1);
536   GNUNET_free (t);
537   return;
538 }
539
540
541 /**
542  * Notify client that the transmission has timed out
543  * 
544  * @param cls closure
545  * @param tc task context
546  */
547 static void
548 timeout_transmission (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
549 {
550   struct GNUNET_MESH_TransmitHandle *th = cls;
551   struct GNUNET_MESH_Handle *mesh;
552
553   mesh = th->tunnel->mesh;
554   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
555   th->tunnel->packet_size = 0;
556   if (GNUNET_YES == th_is_payload (th))
557     th->notify (th->notify_cls, 0, NULL);
558   GNUNET_free (th);
559   if ((0 == message_ready_size (mesh)) && (NULL != mesh->th))
560   {
561     /* nothing ready to transmit, no point in asking for transmission */
562     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
563     mesh->th = NULL;
564   }
565 }
566
567
568 /**
569  * Add a transmit handle to the transmission queue and set the
570  * timeout if needed.
571  *
572  * @param h mesh handle with the queue head and tail
573  * @param th handle to the packet to be transmitted
574  */
575 static void
576 add_to_queue (struct GNUNET_MESH_Handle *h,
577               struct GNUNET_MESH_TransmitHandle *th)
578 {
579   GNUNET_CONTAINER_DLL_insert_tail (h->th_head, h->th_tail, th);
580   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value == th->timeout.abs_value)
581     return;
582   th->timeout_task =
583       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
584                                     (th->timeout), &timeout_transmission, th);
585 }
586
587
588 /**
589  * Auxiliary function to send an already constructed packet to the service.
590  * Takes care of creating a new queue element, copying the message and
591  * calling the tmt_rdy function if necessary.
592  *
593  * @param h mesh handle
594  * @param msg message to transmit
595  * @param tunnel tunnel this send is related to (NULL if N/A)
596  */
597 static void
598 send_packet (struct GNUNET_MESH_Handle *h,
599              const struct GNUNET_MessageHeader *msg,
600              struct GNUNET_MESH_Tunnel *tunnel);
601
602
603 /**
604  * Send an ack on the tunnel to confirm the processing of a message.
605  * 
606  * @param t Tunnel on which to send the ACK.
607  */
608 static void
609 send_ack (struct GNUNET_MESH_Tunnel *t)
610 {
611   struct GNUNET_MESH_LocalAck msg;
612
613   t->last_ack_sent = t->last_pid_recv + 1;
614   LOG (GNUNET_ERROR_TYPE_DEBUG,
615        "Sending ACK on tunnel %X: %u\n",
616        t->tid, t->last_ack_sent);
617   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
618   msg.header.size = htons (sizeof (msg));
619   msg.tunnel_id = htonl (t->tid);
620   msg.ack = htonl (t->last_ack_sent);
621
622 #if DEBUG_ACK
623   t->mesh->acks_sent++;
624 #endif
625
626   send_packet (t->mesh, &msg.header, t);
627   return;
628 }
629
630
631
632 /**
633  * Reconnect callback: tries to reconnect again after a failer previous
634  * reconnecttion
635  * @param cls closure (mesh handle)
636  * @param tc task context
637  */
638 static void
639 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
640
641
642 /**
643  * Send a connect packet to the service with the applications and types
644  * requested by the user.
645  *
646  * @param h The mesh handle.
647  *
648  */
649 static void
650 send_connect (struct GNUNET_MESH_Handle *h)
651 {
652   size_t size;
653
654   size = sizeof (struct GNUNET_MESH_ClientConnect);
655   size += h->n_ports * sizeof (uint32_t);
656   {
657     char buf[size] GNUNET_ALIGN;
658     struct GNUNET_MESH_ClientConnect *msg;
659     uint32_t *ports;
660     uint16_t i;
661
662     /* build connection packet */
663     msg = (struct GNUNET_MESH_ClientConnect *) buf;
664     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT);
665     msg->header.size = htons (size);
666     ports = (uint32_t *) &msg[1];
667     for (i = 0; i < h->n_ports; i++)
668     {
669       ports[i] = htonl (h->ports[i]);
670       LOG (GNUNET_ERROR_TYPE_DEBUG, " port %u\n",
671            h->ports[i]);
672     }
673     LOG (GNUNET_ERROR_TYPE_DEBUG,
674          "Sending %lu bytes long message with %u ports\n",
675          ntohs (msg->header.size), h->n_ports);
676     send_packet (h, &msg->header, NULL);
677   }
678 }
679
680
681 /**
682  * Reconnect to the service, retransmit all infomation to try to restore the
683  * original state.
684  *
685  * @param h handle to the mesh
686  *
687  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
688  */
689 static int
690 do_reconnect (struct GNUNET_MESH_Handle *h)
691 {
692   struct GNUNET_MESH_Tunnel *t;
693
694   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
695   LOG (GNUNET_ERROR_TYPE_DEBUG, "*******   RECONNECT   *******\n");
696   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
697   LOG (GNUNET_ERROR_TYPE_DEBUG, "******** on %p *******\n", h);
698   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
699
700   /* disconnect */
701   if (NULL != h->th)
702   {
703     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
704     h->th = NULL;
705   }
706   if (NULL != h->client)
707   {
708     GNUNET_CLIENT_disconnect (h->client);
709   }
710
711   /* connect again */
712   h->client = GNUNET_CLIENT_connect ("mesh", h->cfg);
713   if (h->client == NULL)
714   {
715     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
716                                                       &reconnect_cbk, h);
717     h->reconnect_time =
718         GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
719                                   GNUNET_TIME_relative_multiply
720                                   (h->reconnect_time, 2));
721     LOG (GNUNET_ERROR_TYPE_DEBUG, 
722          "Next retry in %s\n",
723          GNUNET_STRINGS_relative_time_to_string (h->reconnect_time,
724                                                  GNUNET_NO));
725     GNUNET_break (0);
726     return GNUNET_NO;
727   }
728   else
729   {
730     h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
731   }
732   send_connect (h);
733   /* Rebuild all tunnels */
734   for (t = h->tunnels_head; NULL != t; t = t->next)
735   {
736     struct GNUNET_MESH_TunnelMessage tmsg;
737     uint32_t options;
738
739     if (t->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
740     {
741       /* Tunnel was created by service (incoming tunnel) */
742       /* TODO: Notify service of missing tunnel, to request
743        * creator to recreate path (find a path to him via DHT?)
744        */
745       continue;
746     }
747     t->last_ack_sent = (uint32_t) -1;
748     t->last_pid_sent = (uint32_t) -1;
749     t->last_ack_recv = (uint32_t) -1;
750     t->last_pid_recv = (uint32_t) -1;
751     tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
752     tmsg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
753     tmsg.tunnel_id = htonl (t->tid);
754     tmsg.port = htonl (t->port);
755     GNUNET_PEER_resolve (t->peer, &tmsg.peer);
756
757     options = 0;
758     if (GNUNET_NO == t->buffering)
759       options |= GNUNET_MESH_OPTION_NOBUFFER;
760
761     if (GNUNET_YES == t->reliable)
762       options |= GNUNET_MESH_OPTION_RELIABLE;
763
764     tmsg.options = htonl (options);
765     send_packet (h, &tmsg.header, t);
766   }
767   return GNUNET_YES;
768 }
769
770 /**
771  * Reconnect callback: tries to reconnect again after a failer previous
772  * reconnecttion
773  * @param cls closure (mesh handle)
774  * @param tc task context
775  */
776 static void
777 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
778 {
779   struct GNUNET_MESH_Handle *h = cls;
780
781   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
782   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
783     return;
784   do_reconnect (h);
785 }
786
787
788 /**
789  * Reconnect to the service, retransmit all infomation to try to restore the
790  * original state.
791  *
792  * @param h handle to the mesh
793  *
794  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
795  */
796 static void
797 reconnect (struct GNUNET_MESH_Handle *h)
798 {
799   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requested RECONNECT\n");
800   h->in_receive = GNUNET_NO;
801   if (GNUNET_SCHEDULER_NO_TASK == h->reconnect_task)
802     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
803                                                       &reconnect_cbk, h);
804 }
805
806
807 /******************************************************************************/
808 /***********************      RECEIVE HANDLERS     ****************************/
809 /******************************************************************************/
810
811 /**
812  * Process the new tunnel notification and add it to the tunnels in the handle
813  *
814  * @param h     The mesh handle
815  * @param msg   A message with the details of the new incoming tunnel
816  */
817 static void
818 process_tunnel_created (struct GNUNET_MESH_Handle *h,
819                         const struct GNUNET_MESH_TunnelNotification *msg)
820 {
821   struct GNUNET_MESH_Tunnel *t;
822   MESH_TunnelNumber tid;
823
824   tid = ntohl (msg->tunnel_id);
825   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating incoming tunnel %X\n", tid);
826   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
827   {
828     GNUNET_break (0);
829     return;
830   }
831   if (NULL != h->new_tunnel)
832   {
833     t = create_tunnel (h, tid);
834     t->last_ack_sent = 0;
835     t->peer = GNUNET_PEER_intern (&msg->peer);
836     t->mesh = h;
837     t->tid = tid;
838     t->port = ntohl (msg->port);
839     if (0 != (msg->opt & GNUNET_MESH_OPTION_NOBUFFER))
840       t->buffering = GNUNET_NO;
841     else
842       t->buffering = GNUNET_YES;
843     if (0 != (msg->opt & GNUNET_MESH_OPTION_RELIABLE))
844       t->reliable = GNUNET_YES;
845     else
846       t->reliable = GNUNET_NO;
847     LOG (GNUNET_ERROR_TYPE_DEBUG, "  created tunnel %p\n", t);
848     t->ctx = h->new_tunnel (h->cls, t, &msg->peer, t->port);
849     LOG (GNUNET_ERROR_TYPE_DEBUG, "User notified\n");
850   }
851   else
852   {
853     struct GNUNET_MESH_TunnelMessage d_msg;
854
855     LOG (GNUNET_ERROR_TYPE_DEBUG, "No handler for incoming tunnels\n");
856
857     d_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
858     d_msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
859     d_msg.tunnel_id = msg->tunnel_id;
860     memset (&d_msg.peer, 0, sizeof (struct GNUNET_PeerIdentity));
861     d_msg.port = 0;
862     d_msg.options = 0;
863
864     send_packet (h, &d_msg.header, NULL);
865   }
866   return;
867 }
868
869
870 /**
871  * Process the tunnel destroy notification and free associated resources
872  *
873  * @param h     The mesh handle
874  * @param msg   A message with the details of the tunnel being destroyed
875  */
876 static void
877 process_tunnel_destroy (struct GNUNET_MESH_Handle *h,
878                         const struct GNUNET_MESH_TunnelMessage *msg)
879 {
880   struct GNUNET_MESH_Tunnel *t;
881   MESH_TunnelNumber tid;
882
883   tid = ntohl (msg->tunnel_id);
884   t = retrieve_tunnel (h, tid);
885
886   if (NULL == t)
887   {
888     return;
889   }
890   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X destroyed\n", t->tid);
891   destroy_tunnel (t, GNUNET_YES);
892   return;
893 }
894
895
896 /**
897  * Process the incoming data packets, call appropriate handlers.
898  *
899  * @param h         The mesh handle
900  * @param message   A message encapsulating the data
901  */
902 static void
903 process_incoming_data (struct GNUNET_MESH_Handle *h,
904                        const struct GNUNET_MessageHeader *message)
905 {
906   const struct GNUNET_MessageHeader *payload;
907   const struct GNUNET_MESH_MessageHandler *handler;
908   const struct GNUNET_PeerIdentity *peer;
909   struct GNUNET_PeerIdentity id;
910   struct GNUNET_MESH_Data *dmsg;
911   struct GNUNET_MESH_Tunnel *t;
912   unsigned int i;
913   uint32_t pid;
914   uint16_t type;
915
916   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a data message!\n");
917   type = ntohs (message->type);
918   switch (type)
919   {
920   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
921   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
922     dmsg = (struct GNUNET_MESH_Data *) message;
923
924     t = retrieve_tunnel (h, ntohl (dmsg->tid));
925     payload = (struct GNUNET_MessageHeader *) &dmsg[1];
926     GNUNET_PEER_resolve (t->peer, &id);
927     peer = &id;
928     pid = ntohl (dmsg->pid);
929     LOG (GNUNET_ERROR_TYPE_DEBUG, "  %s data on tunnel %s [%X]\n",
930          type == GNUNET_MESSAGE_TYPE_MESH_UNICAST ? "fwd" : "bck",
931          GNUNET_i2s (peer), ntohl (dmsg->tid));
932     break;
933   default:
934     GNUNET_break (0);
935     return;
936   }
937   LOG (GNUNET_ERROR_TYPE_DEBUG, "  pid %u\n", pid);
938   if (NULL == t)
939   {
940     /* Tunnel was ignored/destroyed, probably service didn't get it yet */
941     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ignored!\n");
942     return;
943   }
944   if (GNUNET_YES ==
945       GMC_is_pid_bigger(pid, t->last_ack_sent))
946   {
947     GNUNET_break (0);
948     LOG (GNUNET_ERROR_TYPE_DEBUG,
949          "  unauthorized message! (%u, ACK %u)\n",
950          pid, t->last_ack_sent);
951     // FIXME fc what now? accept? reject?
952   }
953   t->last_pid_recv = pid;
954   type = ntohs (payload->type);
955   for (i = 0; i < h->n_handlers; i++)
956   {
957     handler = &h->message_handlers[i];
958     if (handler->type == type)
959     {
960       if (GNUNET_OK !=
961           handler->callback (h->cls, t, &t->ctx, payload))
962       {
963         LOG (GNUNET_ERROR_TYPE_DEBUG, "callback caused disconnection\n");
964         GNUNET_MESH_tunnel_destroy (t);
965         return;
966       }
967       else
968       {
969         LOG (GNUNET_ERROR_TYPE_DEBUG,
970              "callback completed successfully\n");
971       }
972     }
973   }
974 }
975
976
977 /**
978  * Process a local ACK message, enabling the client to send
979  * more data to the service.
980  * 
981  * @param h Mesh handle.
982  * @param message Message itself.
983  */
984 static void
985 process_ack (struct GNUNET_MESH_Handle *h,
986              const struct GNUNET_MessageHeader *message)
987 {
988   struct GNUNET_MESH_LocalAck *msg;
989   struct GNUNET_MESH_Tunnel *t;
990   MESH_TunnelNumber tid;
991   uint32_t ack;
992
993   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK!\n");
994   h->acks_recv++;
995   msg = (struct GNUNET_MESH_LocalAck *) message;
996   tid = ntohl (msg->tunnel_id);
997   t = retrieve_tunnel (h, tid);
998   if (NULL == t)
999   {
1000     LOG (GNUNET_ERROR_TYPE_WARNING, "ACK on unknown tunnel %X\n", tid);
1001     return;
1002   }
1003   ack = ntohl (msg->ack);
1004   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X, ack %u!\n", t->tid, ack);
1005   if (GNUNET_YES == GMC_is_pid_bigger(ack, t->last_ack_recv))
1006     t->last_ack_recv = ack;
1007   else
1008     return;
1009   if (NULL == h->th && 0 < t->packet_size)
1010   {
1011     LOG (GNUNET_ERROR_TYPE_DEBUG, "  tmt rdy was NULL, requesting!\n", t->tid, ack);
1012     h->th =
1013         GNUNET_CLIENT_notify_transmit_ready (h->client, t->packet_size,
1014                                              GNUNET_TIME_UNIT_FOREVER_REL,
1015                                              GNUNET_YES, &send_callback, h);
1016   }
1017 }
1018
1019
1020 /**
1021  * Process a local reply about info on all tunnels, pass info to the user.
1022  *
1023  * @param h Mesh handle.
1024  * @param message Message itself.
1025  */
1026 static void
1027 process_get_tunnels (struct GNUNET_MESH_Handle *h,
1028                      const struct GNUNET_MessageHeader *message)
1029 {
1030   struct GNUNET_MESH_LocalMonitor *msg;
1031
1032   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Get Tunnels messasge received\n");
1033
1034   if (NULL == h->tunnels_cb)
1035   {
1036     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  ignored\n");
1037     return;
1038   }
1039
1040   msg = (struct GNUNET_MESH_LocalMonitor *) message;
1041   if (ntohs (message->size) !=
1042       (sizeof (struct GNUNET_MESH_LocalMonitor) +
1043        sizeof (struct GNUNET_PeerIdentity)))
1044   {
1045     GNUNET_break_op (0);
1046     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1047                 "Get tunnels message: size %hu - expected %u\n",
1048                 ntohs (message->size),
1049                 sizeof (struct GNUNET_MESH_LocalMonitor));
1050     return;
1051   }
1052   h->tunnels_cb (h->tunnels_cls,
1053                  ntohl (msg->tunnel_id),
1054                  &msg->owner,
1055                  &msg->destination);
1056 }
1057
1058
1059
1060 /**
1061  * Process a local monitor_tunnel reply, pass info to the user.
1062  *
1063  * @param h Mesh handle.
1064  * @param message Message itself.
1065  */
1066 static void
1067 process_show_tunnel (struct GNUNET_MESH_Handle *h,
1068                      const struct GNUNET_MessageHeader *message)
1069 {
1070   struct GNUNET_MESH_LocalMonitor *msg;
1071   size_t esize;
1072
1073   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Show Tunnel messasge received\n");
1074
1075   if (NULL == h->tunnel_cb)
1076   {
1077     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  ignored\n");
1078     return;
1079   }
1080
1081   /* Verify message sanity */
1082   msg = (struct GNUNET_MESH_LocalMonitor *) message;
1083   esize = sizeof (struct GNUNET_MESH_LocalMonitor);
1084   if (ntohs (message->size) != esize)
1085   {
1086     GNUNET_break_op (0);
1087     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1088                 "Show tunnel message: size %hu - expected %u\n",
1089                 ntohs (message->size),
1090                 esize);
1091
1092     h->tunnel_cb (h->tunnel_cls, NULL, NULL);
1093     h->tunnel_cb = NULL;
1094     h->tunnel_cls = NULL;
1095
1096     return;
1097   }
1098
1099   h->tunnel_cb (h->tunnel_cls,
1100                 &msg->destination,
1101                 &msg->owner);
1102 }
1103
1104
1105 /**
1106  * Function to process all messages received from the service
1107  *
1108  * @param cls closure
1109  * @param msg message received, NULL on timeout or fatal error
1110  */
1111 static void
1112 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
1113 {
1114   struct GNUNET_MESH_Handle *h = cls;
1115
1116   if (msg == NULL)
1117   {
1118     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1119          "Mesh service disconnected, reconnecting\n", h);
1120     reconnect (h);
1121     return;
1122   }
1123   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n",
1124        GNUNET_MESH_DEBUG_M2S (ntohs (msg->type)));
1125   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a message: %s\n",
1126        GNUNET_MESH_DEBUG_M2S (ntohs (msg->type)));
1127   switch (ntohs (msg->type))
1128   {
1129     /* Notify of a new incoming tunnel */
1130   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE:
1131     process_tunnel_created (h, (struct GNUNET_MESH_TunnelNotification *) msg);
1132     break;
1133     /* Notify of a tunnel disconnection */
1134   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1135     process_tunnel_destroy (h, (struct GNUNET_MESH_TunnelMessage *) msg);
1136     break;
1137     /* Notify of a new data packet in the tunnel */
1138   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1139   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1140     process_incoming_data (h, msg);
1141     break;
1142   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
1143     process_ack (h, msg);
1144     break;
1145   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS:
1146     process_get_tunnels (h, msg);
1147     break;
1148   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL:
1149     process_show_tunnel (h, msg);
1150     break;
1151   default:
1152     /* We shouldn't get any other packages, log and ignore */
1153     LOG (GNUNET_ERROR_TYPE_WARNING,
1154          "unsolicited message form service (type %s)\n",
1155          GNUNET_MESH_DEBUG_M2S (ntohs (msg->type)));
1156   }
1157   LOG (GNUNET_ERROR_TYPE_DEBUG, "message processed\n");
1158   if (GNUNET_YES == h->in_receive)
1159   {
1160     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1161                            GNUNET_TIME_UNIT_FOREVER_REL);
1162   }
1163   else
1164   {
1165     LOG (GNUNET_ERROR_TYPE_DEBUG,
1166          "in receive off, not calling CLIENT_receive\n");
1167   }
1168 }
1169
1170
1171 /******************************************************************************/
1172 /************************       SEND FUNCTIONS     ****************************/
1173 /******************************************************************************/
1174
1175 /**
1176  * Function called to send a message to the service.
1177  * "buf" will be NULL and "size" zero if the socket was closed for writing in
1178  * the meantime.
1179  *
1180  * @param cls closure, the mesh handle
1181  * @param size number of bytes available in buf
1182  * @param buf where the callee should write the connect message
1183  * @return number of bytes written to buf
1184  */
1185 static size_t
1186 send_callback (void *cls, size_t size, void *buf)
1187 {
1188   struct GNUNET_MESH_Handle *h = cls;
1189   struct GNUNET_MESH_TransmitHandle *th;
1190   struct GNUNET_MESH_TransmitHandle *next;
1191   struct GNUNET_MESH_Tunnel *t;
1192   char *cbuf = buf;
1193   size_t tsize;
1194   size_t psize;
1195   size_t nsize;
1196
1197   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1198   LOG (GNUNET_ERROR_TYPE_DEBUG, "# Send packet() Buffer %u\n", size);
1199   if ((0 == size) || (NULL == buf))
1200   {
1201     LOG (GNUNET_ERROR_TYPE_DEBUG, "# Received NULL send callback on %p\n", h);
1202     reconnect (h);
1203     h->th = NULL;
1204     return 0;
1205   }
1206   tsize = 0;
1207   next = h->th_head;
1208   nsize = message_ready_size (h);
1209   while ((NULL != (th = next)) && (0 < nsize) && (size >= nsize))
1210   {
1211     t = th->tunnel;
1212     if (GNUNET_YES == th_is_payload (th))
1213     {
1214       struct GNUNET_MESH_Data *dmsg;
1215       struct GNUNET_MessageHeader *mh;
1216
1217       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  payload\n");
1218       if (GNUNET_NO == GMC_is_pid_bigger (t->last_ack_recv, t->last_pid_sent))
1219       {
1220         /* This tunnel is not ready to transmit yet, try next message */
1221         next = th->next;
1222         continue;
1223       }
1224       t->packet_size = 0;
1225       GNUNET_assert (size >= th->size);
1226       dmsg = (struct GNUNET_MESH_Data *) cbuf;
1227       mh = (struct GNUNET_MessageHeader *) &dmsg[1];
1228       psize = th->notify (th->notify_cls,
1229                           size - sizeof (struct GNUNET_MESH_Data),
1230                           mh);
1231       if (psize > 0)
1232       {
1233         psize += sizeof (struct GNUNET_MESH_Data);
1234         GNUNET_assert (size >= psize);
1235         dmsg->header.size = htons (psize);
1236         dmsg->tid = htonl (t->tid);
1237         dmsg->pid = htonl (t->last_pid_sent + 1);
1238         dmsg->ttl = 0;
1239         memset (&dmsg->oid, 0, sizeof (struct GNUNET_PeerIdentity));
1240         t->last_pid_sent++;
1241       }
1242       if (t->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1243       {
1244         dmsg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
1245         LOG (GNUNET_ERROR_TYPE_DEBUG, "#  to origin, type %s\n",
1246              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1247       }
1248       else
1249       {
1250         dmsg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1251         LOG (GNUNET_ERROR_TYPE_DEBUG, "#  unicast, type %s\n",
1252              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1253       }
1254     }
1255     else
1256     {
1257       struct GNUNET_MessageHeader *mh = (struct GNUNET_MessageHeader *) &th[1];
1258
1259       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  mesh traffic, type %s\n",
1260            GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1261       memcpy (cbuf, &th[1], th->size);
1262       psize = th->size;
1263     }
1264     if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1265       GNUNET_SCHEDULER_cancel (th->timeout_task);
1266     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1267     GNUNET_free (th);
1268     next = h->th_head;
1269     nsize = message_ready_size (h);
1270     cbuf += psize;
1271     size -= psize;
1272     tsize += psize;
1273   }
1274   LOG (GNUNET_ERROR_TYPE_DEBUG, "#  total size: %u\n", tsize);
1275   h->th = NULL;
1276   size = message_ready_size (h);
1277   if (0 != size)
1278   {
1279     LOG (GNUNET_ERROR_TYPE_DEBUG, "#  next size: %u\n", size);
1280     h->th =
1281         GNUNET_CLIENT_notify_transmit_ready (h->client, size,
1282                                              GNUNET_TIME_UNIT_FOREVER_REL,
1283                                              GNUNET_YES, &send_callback, h);
1284   }
1285   else
1286   {
1287     if (NULL != h->th_head)
1288       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  can't transmit any more\n");
1289     else
1290       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  nothing left to transmit\n");
1291   }
1292   if (GNUNET_NO == h->in_receive)
1293   {
1294     LOG (GNUNET_ERROR_TYPE_DEBUG, "# start receiving from service\n");
1295     h->in_receive = GNUNET_YES;
1296     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1297                            GNUNET_TIME_UNIT_FOREVER_REL);
1298   }
1299   LOG (GNUNET_ERROR_TYPE_DEBUG, "# Send packet() END\n");
1300   return tsize;
1301 }
1302
1303
1304 /**
1305  * Auxiliary function to send an already constructed packet to the service.
1306  * Takes care of creating a new queue element, copying the message and
1307  * calling the tmt_rdy function if necessary.
1308  * 
1309  * @param h mesh handle
1310  * @param msg message to transmit
1311  * @param tunnel tunnel this send is related to (NULL if N/A)
1312  */
1313 static void
1314 send_packet (struct GNUNET_MESH_Handle *h,
1315              const struct GNUNET_MessageHeader *msg,
1316              struct GNUNET_MESH_Tunnel *tunnel)
1317 {
1318   struct GNUNET_MESH_TransmitHandle *th;
1319   size_t msize;
1320
1321   LOG (GNUNET_ERROR_TYPE_DEBUG, " Sending message to service: %s\n",
1322        GNUNET_MESH_DEBUG_M2S(ntohs(msg->type)));
1323   msize = ntohs (msg->size);
1324   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle) + msize);
1325   th->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1326   th->size = msize;
1327   th->tunnel = tunnel;
1328   memcpy (&th[1], msg, msize);
1329   add_to_queue (h, th);
1330   LOG (GNUNET_ERROR_TYPE_DEBUG, "  queued\n");
1331   if (NULL != h->th)
1332     return;
1333   LOG (GNUNET_ERROR_TYPE_DEBUG, "  calling ntfy tmt rdy for %u bytes\n", msize);
1334   h->th =
1335       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
1336                                            GNUNET_TIME_UNIT_FOREVER_REL,
1337                                            GNUNET_YES, &send_callback, h);
1338 }
1339
1340
1341 /******************************************************************************/
1342 /**********************      API CALL DEFINITIONS     *************************/
1343 /******************************************************************************/
1344
1345 struct GNUNET_MESH_Handle *
1346 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, void *cls,
1347                      GNUNET_MESH_InboundTunnelNotificationHandler new_tunnel,
1348                      GNUNET_MESH_TunnelEndHandler cleaner,
1349                      const struct GNUNET_MESH_MessageHandler *handlers,
1350                      const uint32_t *ports)
1351 {
1352   struct GNUNET_MESH_Handle *h;
1353
1354   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect()\n");
1355   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
1356   LOG (GNUNET_ERROR_TYPE_DEBUG, " addr %p\n", h);
1357   h->cfg = cfg;
1358   h->new_tunnel = new_tunnel;
1359   h->cleaner = cleaner;
1360   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
1361   if (h->client == NULL)
1362   {
1363     GNUNET_break (0);
1364     GNUNET_free (h);
1365     return NULL;
1366   }
1367   h->cls = cls;
1368   h->message_handlers = handlers;
1369   h->ports = ports;
1370   h->next_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
1371   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1372   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1373
1374   /* count handlers */
1375   for (h->n_handlers = 0;
1376        handlers && handlers[h->n_handlers].type;
1377        h->n_handlers++) ;
1378   for (h->n_ports = 0;
1379        ports && ports[h->n_ports];
1380        h->n_ports++) ;
1381   send_connect (h);
1382   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect() END\n");
1383   return h;
1384 }
1385
1386
1387 void
1388 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
1389 {
1390   struct GNUNET_MESH_Tunnel *t;
1391   struct GNUNET_MESH_Tunnel *aux;
1392   struct GNUNET_MESH_TransmitHandle *th;
1393
1394   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH DISCONNECT\n");
1395
1396 #if DEBUG_ACK
1397   LOG (GNUNET_ERROR_TYPE_INFO, "Sent %d ACKs\n", handle->acks_sent);
1398   LOG (GNUNET_ERROR_TYPE_INFO, "Recv %d ACKs\n\n", handle->acks_recv);
1399 #endif
1400
1401   t = handle->tunnels_head;
1402   while (NULL != t)
1403   {
1404     aux = t->next;
1405     if (t->tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1406     {
1407       GNUNET_break (0);
1408       LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X not destroyed\n", t->tid);
1409     }
1410     destroy_tunnel (t, GNUNET_YES);
1411     t = aux;
1412   }
1413   while ( (th = handle->th_head) != NULL)
1414   {
1415     struct GNUNET_MessageHeader *msg;
1416
1417     /* Make sure it is an allowed packet (everything else should have been
1418      * already canceled).
1419      */
1420     GNUNET_break (GNUNET_NO == th_is_payload (th));
1421     msg = (struct GNUNET_MessageHeader *) &th[1];
1422     switch (ntohs(msg->type))
1423     {
1424       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT:
1425       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1426       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS:
1427       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL:
1428         break;
1429       default:
1430         GNUNET_break (0);
1431         LOG (GNUNET_ERROR_TYPE_ERROR, "unexpected msg %u\n",
1432              ntohs(msg->type));
1433     }
1434
1435     GNUNET_CONTAINER_DLL_remove (handle->th_head, handle->th_tail, th);
1436     GNUNET_free (th);
1437   }
1438
1439   if (NULL != handle->th)
1440   {
1441     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
1442     handle->th = NULL;
1443   }
1444   if (NULL != handle->client)
1445   {
1446     GNUNET_CLIENT_disconnect (handle->client);
1447     handle->client = NULL;
1448   }
1449   if (GNUNET_SCHEDULER_NO_TASK != handle->reconnect_task)
1450   {
1451     GNUNET_SCHEDULER_cancel(handle->reconnect_task);
1452     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1453   }
1454   GNUNET_free (handle);
1455 }
1456
1457
1458 /**
1459  * Create a new tunnel (we're initiator and will be allowed to add/remove peers
1460  * and to broadcast).
1461  *
1462  * @param h mesh handle
1463  * @param tunnel_ctx client's tunnel context to associate with the tunnel
1464  * @param peer peer identity the tunnel should go to
1465  * @param port Port number.
1466  * @param buffer Flag for buffering on relay nodes.
1467  * @param reliable Flag for end-to-end reliability.
1468  *
1469  * @return handle to the tunnel
1470  */
1471 struct GNUNET_MESH_Tunnel *
1472 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h, 
1473                            void *tunnel_ctx,
1474                            const struct GNUNET_PeerIdentity *peer,
1475                            uint32_t port,
1476                            int buffer,
1477                            int reliable)
1478 {
1479   struct GNUNET_MESH_Tunnel *t;
1480   struct GNUNET_MESH_TunnelMessage msg;
1481
1482   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating new tunnel\n");
1483   t = create_tunnel (h, 0);
1484   LOG (GNUNET_ERROR_TYPE_DEBUG, "  at %p\n", t);
1485   LOG (GNUNET_ERROR_TYPE_DEBUG, "  number %X\n", t->tid);
1486   t->ctx = tunnel_ctx;
1487   t->peer = GNUNET_PEER_intern (peer);
1488   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1489   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1490   msg.tunnel_id = htonl (t->tid);
1491   msg.port = htonl (port);
1492   msg.peer = *peer;
1493   msg.options = 0;
1494   t->last_ack_sent = 0;
1495   send_packet (h, &msg.header, t);
1496   return t;
1497 }
1498
1499
1500 void
1501 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tunnel)
1502 {
1503   struct GNUNET_MESH_Handle *h;
1504   struct GNUNET_MESH_TunnelMessage msg;
1505   struct GNUNET_MESH_TransmitHandle *th;
1506
1507   LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying tunnel\n");
1508   h = tunnel->mesh;
1509
1510   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1511   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1512   msg.tunnel_id = htonl (tunnel->tid);
1513   memset (&msg.peer, 0, sizeof (struct GNUNET_PeerIdentity));
1514   msg.port = 0;
1515   msg.options = 0;
1516   th = h->th_head;
1517   while (th != NULL)
1518   {
1519     struct GNUNET_MESH_TransmitHandle *aux;
1520     if (th->tunnel == tunnel)
1521     {
1522       aux = th->next;
1523       /* FIXME call the handler? */
1524       if (GNUNET_YES == th_is_payload (th))
1525         th->notify (th->notify_cls, 0, NULL);
1526       GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1527       GNUNET_free (th);
1528       th = aux;
1529     }
1530     else
1531       th = th->next;
1532   }
1533
1534   destroy_tunnel (tunnel, GNUNET_YES);
1535   send_packet (h, &msg.header, NULL);
1536 }
1537
1538
1539 /**
1540  * Get information about a tunnel.
1541  * 
1542  * The existing end callback for the tunnel will be called immediately.
1543  * Any pending outgoing messages will be sent but no incoming messages will be
1544  * accepted and no data callbacks will be called.
1545  *
1546  * @param tunnel Tunnel handle.
1547  * 
1548  * @return Allocated, {0, NULL} terminated set of tunnel properties.
1549  */
1550 struct MeshTunnelInfo *
1551 GNUNET_MESH_tunnel_get_info (struct GNUNET_MESH_Tunnel *tunnel)
1552 {
1553   struct MeshTunnelInfo *ret;
1554
1555   ret = GNUNET_malloc (sizeof (struct MeshTunnelInfo) * 3);
1556   ret[0].prop = GNUNET_MESH_OPTION_NOBUFFER;
1557   ret[0].value = &tunnel->buffering; // FIXME return ¬buffering ("nobuffer")
1558   ret[1].prop = GNUNET_MESH_OPTION_RELIABLE;
1559   ret[1].value = &tunnel->reliable;
1560   ret[2].prop = 0;
1561   ret[2].value = NULL;
1562
1563   return ret;
1564 }
1565
1566 struct GNUNET_MESH_TransmitHandle *
1567 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
1568                                    struct GNUNET_TIME_Relative maxdelay,
1569                                    size_t notify_size,
1570                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1571                                    void *notify_cls)
1572 {
1573   struct GNUNET_MESH_TransmitHandle *th;
1574
1575   GNUNET_assert (NULL != tunnel);
1576   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH NOTIFY TRANSMIT READY\n");
1577   LOG (GNUNET_ERROR_TYPE_DEBUG, "    on tunnel %X\n", tunnel->tid);
1578   if (tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1579     LOG (GNUNET_ERROR_TYPE_DEBUG, "    to origin\n");
1580   else
1581     LOG (GNUNET_ERROR_TYPE_DEBUG, "    to destination\n");
1582   LOG (GNUNET_ERROR_TYPE_DEBUG, "    payload size %u\n", notify_size);
1583   GNUNET_assert (NULL != notify);
1584   GNUNET_assert (0 == tunnel->packet_size); // Only one data packet allowed
1585   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
1586   th->tunnel = tunnel;
1587   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1588   th->size = notify_size + sizeof (struct GNUNET_MESH_Data);
1589   tunnel->packet_size = th->size;
1590   LOG (GNUNET_ERROR_TYPE_DEBUG, "    total size %u\n", th->size);
1591   th->notify = notify;
1592   th->notify_cls = notify_cls;
1593   add_to_queue (tunnel->mesh, th);
1594   if (NULL != tunnel->mesh->th)
1595     return th;
1596   if (!GMC_is_pid_bigger (tunnel->last_ack_recv, tunnel->last_pid_sent))
1597     return th;
1598   LOG (GNUNET_ERROR_TYPE_DEBUG, "    call client notify tmt rdy\n");
1599   tunnel->mesh->th =
1600       GNUNET_CLIENT_notify_transmit_ready (tunnel->mesh->client, th->size,
1601                                            GNUNET_TIME_UNIT_FOREVER_REL,
1602                                            GNUNET_YES, &send_callback,
1603                                            tunnel->mesh);
1604   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH NOTIFY TRANSMIT READY END\n");
1605   return th;
1606 }
1607
1608
1609 void
1610 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
1611 {
1612   struct GNUNET_MESH_Handle *mesh;
1613
1614   th->tunnel->packet_size = 0;
1615   mesh = th->tunnel->mesh;
1616   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1617     GNUNET_SCHEDULER_cancel (th->timeout_task);
1618   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
1619   GNUNET_free (th);
1620   if ((0 == message_ready_size (mesh)) && (NULL != mesh->th))
1621   {
1622     /* queue empty, no point in asking for transmission */
1623     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
1624     mesh->th = NULL;
1625   }
1626 }
1627
1628 void
1629 GNUNET_MESH_receive_done (struct GNUNET_MESH_Tunnel *tunnel)
1630 {
1631   send_ack (tunnel);
1632 }
1633
1634
1635 /**
1636  * Request information about the running mesh peer.
1637  * The callback will be called for every tunnel known to the service,
1638  * listing all active peers that blong to the tunnel.
1639  *
1640  * If called again on the same handle, it will overwrite the previous
1641  * callback and cls. To retrieve the cls, monitor_cancel must be
1642  * called first.
1643  *
1644  * WARNING: unstable API, likely to change in the future!
1645  *
1646  * @param h Handle to the mesh peer.
1647  * @param callback Function to call with the requested data.
1648  * @param callback_cls Closure for @c callback.
1649  */
1650 void
1651 GNUNET_MESH_get_tunnels (struct GNUNET_MESH_Handle *h,
1652                          GNUNET_MESH_TunnelsCB callback,
1653                          void *callback_cls)
1654 {
1655   struct GNUNET_MessageHeader msg;
1656
1657   msg.size = htons (sizeof (msg));
1658   msg.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
1659   send_packet (h, &msg, NULL);
1660   h->tunnels_cb = callback;
1661   h->tunnels_cls = callback_cls;
1662
1663   return;
1664 }
1665
1666
1667 /**
1668  * Cancel a monitor request. The monitor callback will not be called.
1669  *
1670  * @param h Mesh handle.
1671  *
1672  * @return Closure given to GNUNET_MESH_monitor, if any.
1673  */
1674 void *
1675 GNUNET_MESH_get_tunnels_cancel (struct GNUNET_MESH_Handle *h)
1676 {
1677   void *cls;
1678
1679   cls = h->tunnels_cls;
1680   h->tunnels_cb = NULL;
1681   h->tunnels_cls = NULL;
1682   return cls;
1683 }
1684
1685
1686 /**
1687  * Request information about a specific tunnel of the running mesh peer.
1688  *
1689  * WARNING: unstable API, likely to change in the future!
1690  * FIXME Add destination option.
1691  *
1692  * @param h Handle to the mesh peer.
1693  * @param initiator ID of the owner of the tunnel.
1694  * @param tunnel_number Tunnel number.
1695  * @param callback Function to call with the requested data.
1696  * @param callback_cls Closure for @c callback.
1697  */
1698 void
1699 GNUNET_MESH_show_tunnel (struct GNUNET_MESH_Handle *h,
1700                          struct GNUNET_PeerIdentity *initiator,
1701                          unsigned int tunnel_number,
1702                          GNUNET_MESH_TunnelCB callback,
1703                          void *callback_cls)
1704 {
1705   struct GNUNET_MESH_LocalMonitor msg;
1706
1707   msg.header.size = htons (sizeof (msg));
1708   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL);
1709   msg.owner = *initiator;
1710   msg.tunnel_id = htonl (tunnel_number);
1711   msg.reserved = 0;
1712   send_packet (h, &msg.header, NULL);
1713   h->tunnel_cb = callback;
1714   h->tunnel_cls = callback_cls;
1715
1716   return;
1717 }
1718
1719
1720 /**
1721  * Function called to notify a client about the connection
1722  * begin ready to queue more data.  "buf" will be
1723  * NULL and "size" zero if the connection was closed for
1724  * writing in the meantime.
1725  *
1726  * @param cls closure
1727  * @param size number of bytes available in buf
1728  * @param buf where the callee should write the message
1729  * @return number of bytes written to buf
1730  */
1731 static size_t
1732 mesh_mq_ntr (void *cls, size_t size,
1733              void *buf)
1734 {
1735   struct GNUNET_MQ_Handle *mq = cls; 
1736   struct MeshMQState *state = GNUNET_MQ_impl_state (mq);
1737   const struct GNUNET_MessageHeader *msg = GNUNET_MQ_impl_current (mq);
1738   uint16_t msize;
1739
1740   state->th = NULL;
1741   if (NULL == buf)
1742   {
1743     GNUNET_MQ_inject_error (mq, GNUNET_MQ_ERROR_WRITE);
1744     return 0;
1745   }
1746   msize = ntohs (msg->size);
1747   GNUNET_assert (msize <= size);
1748   memcpy (buf, msg, msize);
1749   GNUNET_MQ_impl_send_continue (mq);
1750   return msize;
1751 }
1752
1753
1754 /**
1755  * Signature of functions implementing the
1756  * sending functionality of a message queue.
1757  *
1758  * @param mq the message queue
1759  * @param msg the message to send
1760  * @param impl_state state of the implementation
1761  */
1762 static void
1763 mesh_mq_send_impl (struct GNUNET_MQ_Handle *mq,
1764                    const struct GNUNET_MessageHeader *msg, void *impl_state)
1765 {
1766   struct MeshMQState *state = impl_state;
1767
1768   GNUNET_assert (NULL == state->th);
1769   GNUNET_MQ_impl_send_commit (mq);
1770   state->th =
1771       GNUNET_MESH_notify_transmit_ready (state->tunnel,
1772                                          /* FIXME: add option for corking */
1773                                          GNUNET_NO,
1774                                          GNUNET_TIME_UNIT_FOREVER_REL, 
1775                                          ntohs (msg->size),
1776                                          mesh_mq_ntr, mq);
1777
1778 }
1779
1780
1781 /**
1782  * Signature of functions implementing the
1783  * destruction of a message queue.
1784  * Implementations must not free 'mq', but should
1785  * take care of 'impl_state'.
1786  * 
1787  * @param mq the message queue to destroy
1788  * @param impl_state state of the implementation
1789  */
1790 static void
1791 mesh_mq_destroy_impl (struct GNUNET_MQ_Handle *mq, void *impl_state)
1792 {
1793   struct MeshMQState *state = impl_state;
1794
1795   if (NULL != state->th)
1796     GNUNET_MESH_notify_transmit_ready_cancel (state->th);
1797
1798   GNUNET_free (state);
1799 }
1800
1801
1802 /**
1803  * Create a message queue for a mesh tunnel.
1804  * The message queue can only be used to transmit messages,
1805  * not to receive them.
1806  *
1807  * @param tunnel the tunnel to create the message qeue for
1808  * @return a message queue to messages over the tunnel
1809  */
1810 struct GNUNET_MQ_Handle *
1811 GNUNET_MESH_mq_create (struct GNUNET_MESH_Tunnel *tunnel)
1812 {
1813   struct GNUNET_MQ_Handle *mq;
1814   struct MeshMQState *state;
1815
1816   state = GNUNET_new (struct MeshMQState);
1817   state->tunnel = tunnel;
1818
1819   mq = GNUNET_MQ_queue_for_callbacks (mesh_mq_send_impl,
1820                                       mesh_mq_destroy_impl,
1821                                       NULL, /* FIXME: cancel impl. */
1822                                       state,
1823                                       NULL, /* no msg handlers */
1824                                       NULL, /* no err handlers */
1825                                       NULL); /* no handler cls */
1826   return mq;
1827 }
1828