-doxygen fixes
[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
738     if (t->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
739     {
740       /* Tunnel was created by service (incoming tunnel) */
741       /* TODO: Notify service of missing tunnel, to request
742        * creator to recreate path (find a path to him via DHT?)
743        */
744       continue;
745     }
746     t->last_ack_sent = (uint32_t) -1;
747     t->last_pid_sent = (uint32_t) -1;
748     t->last_ack_recv = (uint32_t) -1;
749     t->last_pid_recv = (uint32_t) -1;
750     tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
751     tmsg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
752     tmsg.tunnel_id = htonl (t->tid);
753     GNUNET_PEER_resolve (t->peer, &tmsg.peer);
754     send_packet (h, &tmsg.header, t);
755
756     if (GNUNET_NO == t->buffering)
757       GNUNET_MESH_tunnel_buffer (t, GNUNET_NO);
758
759     if (GNUNET_YES == t->reliable)
760       GNUNET_MESH_tunnel_reliable (t, GNUNET_YES);
761   }
762   return GNUNET_YES;
763 }
764
765 /**
766  * Reconnect callback: tries to reconnect again after a failer previous
767  * reconnecttion
768  * @param cls closure (mesh handle)
769  * @param tc task context
770  */
771 static void
772 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
773 {
774   struct GNUNET_MESH_Handle *h = cls;
775
776   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
777   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
778     return;
779   do_reconnect (h);
780 }
781
782
783 /**
784  * Reconnect to the service, retransmit all infomation to try to restore the
785  * original state.
786  *
787  * @param h handle to the mesh
788  *
789  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
790  */
791 static void
792 reconnect (struct GNUNET_MESH_Handle *h)
793 {
794   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requested RECONNECT\n");
795   h->in_receive = GNUNET_NO;
796   if (GNUNET_SCHEDULER_NO_TASK == h->reconnect_task)
797     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
798                                                       &reconnect_cbk, h);
799 }
800
801
802 /******************************************************************************/
803 /***********************      RECEIVE HANDLERS     ****************************/
804 /******************************************************************************/
805
806 /**
807  * Process the new tunnel notification and add it to the tunnels in the handle
808  *
809  * @param h     The mesh handle
810  * @param msg   A message with the details of the new incoming tunnel
811  */
812 static void
813 process_tunnel_created (struct GNUNET_MESH_Handle *h,
814                         const struct GNUNET_MESH_TunnelNotification *msg)
815 {
816   struct GNUNET_MESH_Tunnel *t;
817   MESH_TunnelNumber tid;
818
819   tid = ntohl (msg->tunnel_id);
820   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating incoming tunnel %X\n", tid);
821   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
822   {
823     GNUNET_break (0);
824     return;
825   }
826   if (NULL != h->new_tunnel)
827   {
828     t = create_tunnel (h, tid);
829     t->last_ack_sent = 0;
830     t->peer = GNUNET_PEER_intern (&msg->peer);
831     t->mesh = h;
832     t->tid = tid;
833     t->port = ntohl (msg->port);
834     if (0 != (msg->opt & MESH_TUNNEL_OPT_NOBUFFER))
835       t->buffering = GNUNET_NO;
836     else
837       t->buffering = GNUNET_YES;
838     LOG (GNUNET_ERROR_TYPE_DEBUG, "  created tunnel %p\n", t);
839     t->ctx = h->new_tunnel (h->cls, t, &msg->peer, t->port);
840     LOG (GNUNET_ERROR_TYPE_DEBUG, "User notified\n");
841   }
842   else
843   {
844     struct GNUNET_MESH_TunnelMessage d_msg;
845
846     LOG (GNUNET_ERROR_TYPE_DEBUG, "No handler for incoming tunnels\n");
847
848     d_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
849     d_msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
850     d_msg.tunnel_id = msg->tunnel_id;
851
852     send_packet (h, &d_msg.header, NULL);
853   }
854   return;
855 }
856
857
858 /**
859  * Process the tunnel destroy notification and free associated resources
860  *
861  * @param h     The mesh handle
862  * @param msg   A message with the details of the tunnel being destroyed
863  */
864 static void
865 process_tunnel_destroy (struct GNUNET_MESH_Handle *h,
866                         const struct GNUNET_MESH_TunnelMessage *msg)
867 {
868   struct GNUNET_MESH_Tunnel *t;
869   MESH_TunnelNumber tid;
870
871   tid = ntohl (msg->tunnel_id);
872   t = retrieve_tunnel (h, tid);
873
874   if (NULL == t)
875   {
876     return;
877   }
878   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X destroyed\n", t->tid);
879   destroy_tunnel (t, GNUNET_YES);
880   return;
881 }
882
883
884 /**
885  * Process the incoming data packets, call appropriate handlers.
886  *
887  * @param h         The mesh handle
888  * @param message   A message encapsulating the data
889  */
890 static void
891 process_incoming_data (struct GNUNET_MESH_Handle *h,
892                        const struct GNUNET_MessageHeader *message)
893 {
894   const struct GNUNET_MessageHeader *payload;
895   const struct GNUNET_MESH_MessageHandler *handler;
896   const struct GNUNET_PeerIdentity *peer;
897   struct GNUNET_PeerIdentity id;
898   struct GNUNET_MESH_Data *dmsg;
899   struct GNUNET_MESH_Tunnel *t;
900   unsigned int i;
901   uint32_t pid;
902   uint16_t type;
903
904   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a data message!\n");
905   type = ntohs (message->type);
906   switch (type)
907   {
908   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
909   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
910     dmsg = (struct GNUNET_MESH_Data *) message;
911
912     t = retrieve_tunnel (h, ntohl (dmsg->tid));
913     payload = (struct GNUNET_MessageHeader *) &dmsg[1];
914     GNUNET_PEER_resolve (t->peer, &id);
915     peer = &id;
916     pid = ntohl (dmsg->pid);
917     LOG (GNUNET_ERROR_TYPE_DEBUG, "  %s data on tunnel %s [%X]\n",
918          type == GNUNET_MESSAGE_TYPE_MESH_UNICAST ? "fwd" : "bck",
919          GNUNET_i2s (peer), ntohl (dmsg->tid));
920     break;
921   default:
922     GNUNET_break (0);
923     return;
924   }
925   LOG (GNUNET_ERROR_TYPE_DEBUG, "  pid %u\n", pid);
926   if (NULL == t)
927   {
928     /* Tunnel was ignored/destroyed, probably service didn't get it yet */
929     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ignored!\n");
930     return;
931   }
932   if (GNUNET_YES ==
933       GMC_is_pid_bigger(pid, t->last_ack_sent))
934   {
935     GNUNET_break (0);
936     LOG (GNUNET_ERROR_TYPE_WARNING,
937          "  unauthorized message! (%u, ACK %u)\n",
938          pid, t->last_ack_sent);
939     // FIXME fc what now? accept? reject?
940     return;
941   }
942   t->last_pid_recv = pid;
943   type = ntohs (payload->type);
944   for (i = 0; i < h->n_handlers; i++)
945   {
946     handler = &h->message_handlers[i];
947     if (handler->type == type)
948     {
949       if (GNUNET_OK !=
950           handler->callback (h->cls, t, &t->ctx, payload))
951       {
952         LOG (GNUNET_ERROR_TYPE_DEBUG, "callback caused disconnection\n");
953         GNUNET_MESH_tunnel_destroy (t);
954         return;
955       }
956       else
957       {
958         LOG (GNUNET_ERROR_TYPE_DEBUG,
959              "callback completed successfully\n");
960       }
961     }
962   }
963 }
964
965
966 /**
967  * Process a local ACK message, enabling the client to send
968  * more data to the service.
969  * 
970  * @param h Mesh handle.
971  * @param message Message itself.
972  */
973 static void
974 process_ack (struct GNUNET_MESH_Handle *h,
975              const struct GNUNET_MessageHeader *message)
976 {
977   struct GNUNET_MESH_LocalAck *msg;
978   struct GNUNET_MESH_Tunnel *t;
979   uint32_t ack;
980
981   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK!\n");
982   h->acks_recv++;
983   msg = (struct GNUNET_MESH_LocalAck *) message;
984
985   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
986
987   if (NULL == t)
988   {
989     LOG (GNUNET_ERROR_TYPE_WARNING,
990          "ACK on unknown tunnel %X\n",
991          ntohl (msg->tunnel_id));
992     return;
993   }
994   ack = ntohl (msg->ack);
995   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X, ack %u!\n", t->tid, ack);
996   if (GNUNET_YES == GMC_is_pid_bigger(ack, t->last_ack_recv))
997     t->last_ack_recv = ack;
998   else
999     return;
1000   if (NULL == h->th && 0 < t->packet_size)
1001   {
1002     LOG (GNUNET_ERROR_TYPE_DEBUG, "  tmt rdy was NULL, requesting!\n", t->tid, ack);
1003     h->th =
1004         GNUNET_CLIENT_notify_transmit_ready (h->client, t->packet_size,
1005                                              GNUNET_TIME_UNIT_FOREVER_REL,
1006                                              GNUNET_YES, &send_callback, h);
1007   }
1008 }
1009
1010
1011 /**
1012  * Process a local reply about info on all tunnels, pass info to the user.
1013  *
1014  * @param h Mesh handle.
1015  * @param message Message itself.
1016  */
1017 static void
1018 process_get_tunnels (struct GNUNET_MESH_Handle *h,
1019                      const struct GNUNET_MessageHeader *message)
1020 {
1021   struct GNUNET_MESH_LocalMonitor *msg;
1022
1023   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Get Tunnels messasge received\n");
1024
1025   if (NULL == h->tunnels_cb)
1026   {
1027     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  ignored\n");
1028     return;
1029   }
1030
1031   msg = (struct GNUNET_MESH_LocalMonitor *) message;
1032   if (ntohs (message->size) !=
1033       (sizeof (struct GNUNET_MESH_LocalMonitor) +
1034        sizeof (struct GNUNET_PeerIdentity)))
1035   {
1036     GNUNET_break_op (0);
1037     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1038                 "Get tunnels message: size %hu - expected %u\n",
1039                 ntohs (message->size),
1040                 sizeof (struct GNUNET_MESH_LocalMonitor));
1041     return;
1042   }
1043   h->tunnels_cb (h->tunnels_cls,
1044                  ntohl (msg->tunnel_id),
1045                  &msg->owner,
1046                  &msg->destination);
1047 }
1048
1049
1050
1051 /**
1052  * Process a local monitor_tunnel reply, pass info to the user.
1053  *
1054  * @param h Mesh handle.
1055  * @param message Message itself.
1056  */
1057 static void
1058 process_show_tunnel (struct GNUNET_MESH_Handle *h,
1059                      const struct GNUNET_MessageHeader *message)
1060 {
1061   struct GNUNET_MESH_LocalMonitor *msg;
1062   size_t esize;
1063
1064   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Show Tunnel messasge received\n");
1065
1066   if (NULL == h->tunnel_cb)
1067   {
1068     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  ignored\n");
1069     return;
1070   }
1071
1072   /* Verify message sanity */
1073   msg = (struct GNUNET_MESH_LocalMonitor *) message;
1074   esize = sizeof (struct GNUNET_MESH_LocalMonitor);
1075   if (ntohs (message->size) != esize)
1076   {
1077     GNUNET_break_op (0);
1078     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1079                 "Show tunnel message: size %hu - expected %u\n",
1080                 ntohs (message->size),
1081                 esize);
1082
1083     h->tunnel_cb (h->tunnel_cls, NULL, NULL);
1084     h->tunnel_cb = NULL;
1085     h->tunnel_cls = NULL;
1086
1087     return;
1088   }
1089
1090   h->tunnel_cb (h->tunnel_cls,
1091                 &msg->destination,
1092                 &msg->owner);
1093 }
1094
1095
1096 /**
1097  * Function to process all messages received from the service
1098  *
1099  * @param cls closure
1100  * @param msg message received, NULL on timeout or fatal error
1101  */
1102 static void
1103 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
1104 {
1105   struct GNUNET_MESH_Handle *h = cls;
1106
1107   if (msg == NULL)
1108   {
1109     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1110          "Mesh service disconnected, reconnecting\n", h);
1111     reconnect (h);
1112     return;
1113   }
1114   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n",
1115        GNUNET_MESH_DEBUG_M2S (ntohs (msg->type)));
1116   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a message: %s\n",
1117        GNUNET_MESH_DEBUG_M2S (ntohs (msg->type)));
1118   switch (ntohs (msg->type))
1119   {
1120     /* Notify of a new incoming tunnel */
1121   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE:
1122     process_tunnel_created (h, (struct GNUNET_MESH_TunnelNotification *) msg);
1123     break;
1124     /* Notify of a tunnel disconnection */
1125   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1126     process_tunnel_destroy (h, (struct GNUNET_MESH_TunnelMessage *) msg);
1127     break;
1128     /* Notify of a new data packet in the tunnel */
1129   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1130   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1131     process_incoming_data (h, msg);
1132     break;
1133   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
1134     process_ack (h, msg);
1135     break;
1136   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS:
1137         process_get_tunnels (h, msg);
1138     break;
1139   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL:
1140         process_show_tunnel (h, msg);
1141     break;
1142   default:
1143     /* We shouldn't get any other packages, log and ignore */
1144     LOG (GNUNET_ERROR_TYPE_WARNING,
1145          "unsolicited message form service (type %s)\n",
1146          GNUNET_MESH_DEBUG_M2S (ntohs (msg->type)));
1147   }
1148   LOG (GNUNET_ERROR_TYPE_DEBUG, "message processed\n");
1149   if (GNUNET_YES == h->in_receive)
1150   {
1151     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1152                            GNUNET_TIME_UNIT_FOREVER_REL);
1153   }
1154   else
1155   {
1156     LOG (GNUNET_ERROR_TYPE_DEBUG,
1157          "in receive off, not calling CLIENT_receive\n");
1158   }
1159 }
1160
1161
1162 /******************************************************************************/
1163 /************************       SEND FUNCTIONS     ****************************/
1164 /******************************************************************************/
1165
1166 /**
1167  * Function called to send a message to the service.
1168  * "buf" will be NULL and "size" zero if the socket was closed for writing in
1169  * the meantime.
1170  *
1171  * @param cls closure, the mesh handle
1172  * @param size number of bytes available in buf
1173  * @param buf where the callee should write the connect message
1174  * @return number of bytes written to buf
1175  */
1176 static size_t
1177 send_callback (void *cls, size_t size, void *buf)
1178 {
1179   struct GNUNET_MESH_Handle *h = cls;
1180   struct GNUNET_MESH_TransmitHandle *th;
1181   struct GNUNET_MESH_TransmitHandle *next;
1182   struct GNUNET_MESH_Tunnel *t;
1183   char *cbuf = buf;
1184   size_t tsize;
1185   size_t psize;
1186   size_t nsize;
1187
1188   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1189   LOG (GNUNET_ERROR_TYPE_DEBUG, "# Send packet() Buffer %u\n", size);
1190   if ((0 == size) || (NULL == buf))
1191   {
1192     LOG (GNUNET_ERROR_TYPE_DEBUG, "# Received NULL send callback on %p\n", h);
1193     reconnect (h);
1194     h->th = NULL;
1195     return 0;
1196   }
1197   tsize = 0;
1198   next = h->th_head;
1199   nsize = message_ready_size (h);
1200   while ((NULL != (th = next)) && (0 < nsize) && (size >= nsize))
1201   {
1202     t = th->tunnel;
1203     if (GNUNET_YES == th_is_payload (th))
1204     {
1205       struct GNUNET_MESH_Data *dmsg;
1206       struct GNUNET_MessageHeader *mh;
1207
1208       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  payload\n");
1209       if (GNUNET_NO == GMC_is_pid_bigger (t->last_ack_recv, t->last_pid_sent))
1210       {
1211         /* This tunnel is not ready to transmit yet, try next message */
1212         next = th->next;
1213         continue;
1214       }
1215       t->packet_size = 0;
1216       GNUNET_assert (size >= th->size);
1217       dmsg = (struct GNUNET_MESH_Data *) cbuf;
1218       mh = (struct GNUNET_MessageHeader *) &dmsg[1];
1219       psize = th->notify (th->notify_cls,
1220                           size - sizeof (struct GNUNET_MESH_Data),
1221                           mh);
1222       if (psize > 0)
1223       {
1224         psize += sizeof (struct GNUNET_MESH_Data);
1225         GNUNET_assert (size >= psize);
1226         dmsg->header.size = htons (psize);
1227         dmsg->tid = htonl (t->tid);
1228         dmsg->pid = htonl (t->last_pid_sent + 1);
1229         dmsg->ttl = 0;
1230         memset (&dmsg->oid, 0, sizeof (struct GNUNET_PeerIdentity));
1231         t->last_pid_sent++;
1232       }
1233       if (t->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1234       {
1235         dmsg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
1236         LOG (GNUNET_ERROR_TYPE_DEBUG, "#  to origin, type %s\n",
1237              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1238       }
1239       else
1240       {
1241         dmsg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1242         LOG (GNUNET_ERROR_TYPE_DEBUG, "#  unicast, type %s\n",
1243              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1244       }
1245     }
1246     else
1247     {
1248       struct GNUNET_MessageHeader *mh = (struct GNUNET_MessageHeader *) &th[1];
1249
1250       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  mesh traffic, type %s\n",
1251            GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1252       memcpy (cbuf, &th[1], th->size);
1253       psize = th->size;
1254     }
1255     if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1256       GNUNET_SCHEDULER_cancel (th->timeout_task);
1257     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1258     GNUNET_free (th);
1259     next = h->th_head;
1260     nsize = message_ready_size (h);
1261     cbuf += psize;
1262     size -= psize;
1263     tsize += psize;
1264   }
1265   LOG (GNUNET_ERROR_TYPE_DEBUG, "#  total size: %u\n", tsize);
1266   h->th = NULL;
1267   size = message_ready_size (h);
1268   if (0 != size)
1269   {
1270     LOG (GNUNET_ERROR_TYPE_DEBUG, "#  next size: %u\n", size);
1271     h->th =
1272         GNUNET_CLIENT_notify_transmit_ready (h->client, size,
1273                                              GNUNET_TIME_UNIT_FOREVER_REL,
1274                                              GNUNET_YES, &send_callback, h);
1275   }
1276   else
1277   {
1278     if (NULL != h->th_head)
1279       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  can't transmit any more\n");
1280     else
1281       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  nothing left to transmit\n");
1282   }
1283   if (GNUNET_NO == h->in_receive)
1284   {
1285     LOG (GNUNET_ERROR_TYPE_DEBUG, "# start receiving from service\n");
1286     h->in_receive = GNUNET_YES;
1287     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1288                            GNUNET_TIME_UNIT_FOREVER_REL);
1289   }
1290   LOG (GNUNET_ERROR_TYPE_DEBUG, "# Send packet() END\n");
1291   return tsize;
1292 }
1293
1294
1295 /**
1296  * Auxiliary function to send an already constructed packet to the service.
1297  * Takes care of creating a new queue element, copying the message and
1298  * calling the tmt_rdy function if necessary.
1299  * 
1300  * @param h mesh handle
1301  * @param msg message to transmit
1302  * @param tunnel tunnel this send is related to (NULL if N/A)
1303  */
1304 static void
1305 send_packet (struct GNUNET_MESH_Handle *h,
1306              const struct GNUNET_MessageHeader *msg,
1307              struct GNUNET_MESH_Tunnel *tunnel)
1308 {
1309   struct GNUNET_MESH_TransmitHandle *th;
1310   size_t msize;
1311
1312   LOG (GNUNET_ERROR_TYPE_DEBUG, " Sending message to service: %s\n",
1313        GNUNET_MESH_DEBUG_M2S(ntohs(msg->type)));
1314   msize = ntohs (msg->size);
1315   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle) + msize);
1316   th->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1317   th->size = msize;
1318   th->tunnel = tunnel;
1319   memcpy (&th[1], msg, msize);
1320   add_to_queue (h, th);
1321   LOG (GNUNET_ERROR_TYPE_DEBUG, "  queued\n");
1322   if (NULL != h->th)
1323     return;
1324   LOG (GNUNET_ERROR_TYPE_DEBUG, "  calling ntfy tmt rdy for %u bytes\n", msize);
1325   h->th =
1326       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
1327                                            GNUNET_TIME_UNIT_FOREVER_REL,
1328                                            GNUNET_YES, &send_callback, h);
1329 }
1330
1331
1332 /******************************************************************************/
1333 /**********************      API CALL DEFINITIONS     *************************/
1334 /******************************************************************************/
1335
1336 struct GNUNET_MESH_Handle *
1337 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, void *cls,
1338                      GNUNET_MESH_InboundTunnelNotificationHandler new_tunnel,
1339                      GNUNET_MESH_TunnelEndHandler cleaner,
1340                      const struct GNUNET_MESH_MessageHandler *handlers,
1341                      const uint32_t *ports)
1342 {
1343   struct GNUNET_MESH_Handle *h;
1344
1345   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect()\n");
1346   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
1347   LOG (GNUNET_ERROR_TYPE_DEBUG, " addr %p\n", h);
1348   h->cfg = cfg;
1349   h->new_tunnel = new_tunnel;
1350   h->cleaner = cleaner;
1351   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
1352   if (h->client == NULL)
1353   {
1354     GNUNET_break (0);
1355     GNUNET_free (h);
1356     return NULL;
1357   }
1358   h->cls = cls;
1359   h->message_handlers = handlers;
1360   h->ports = ports;
1361   h->next_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
1362   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1363   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1364
1365   /* count handlers */
1366   for (h->n_handlers = 0;
1367        handlers && handlers[h->n_handlers].type;
1368        h->n_handlers++) ;
1369   for (h->n_ports = 0;
1370        ports && ports[h->n_ports];
1371        h->n_ports++) ;
1372   send_connect (h);
1373   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect() END\n");
1374   return h;
1375 }
1376
1377
1378 void
1379 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
1380 {
1381   struct GNUNET_MESH_Tunnel *t;
1382   struct GNUNET_MESH_Tunnel *aux;
1383   struct GNUNET_MESH_TransmitHandle *th;
1384
1385   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH DISCONNECT\n");
1386
1387 #if DEBUG_ACK
1388   LOG (GNUNET_ERROR_TYPE_INFO, "Sent %d ACKs\n", handle->acks_sent);
1389   LOG (GNUNET_ERROR_TYPE_INFO, "Recv %d ACKs\n\n", handle->acks_recv);
1390 #endif
1391
1392   t = handle->tunnels_head;
1393   while (NULL != t)
1394   {
1395     aux = t->next;
1396     if (t->tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1397     {
1398       GNUNET_break (0);
1399       LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X not destroyed\n", t->tid);
1400     }
1401     destroy_tunnel (t, GNUNET_YES);
1402     t = aux;
1403   }
1404   while ( (th = handle->th_head) != NULL)
1405   {
1406     struct GNUNET_MessageHeader *msg;
1407
1408     /* Make sure it is an allowed packet (everything else should have been
1409      * already canceled).
1410      */
1411     GNUNET_break (GNUNET_NO == th_is_payload (th));
1412     msg = (struct GNUNET_MessageHeader *) &th[1];
1413     switch (ntohs(msg->type))
1414     {
1415       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT:
1416       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1417       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS:
1418       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL:
1419         break;
1420       default:
1421         GNUNET_break (0);
1422         LOG (GNUNET_ERROR_TYPE_ERROR, "unexpected msg %u\n",
1423              ntohs(msg->type));
1424     }
1425
1426     GNUNET_CONTAINER_DLL_remove (handle->th_head, handle->th_tail, th);
1427     GNUNET_free (th);
1428   }
1429
1430   if (NULL != handle->th)
1431   {
1432     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
1433     handle->th = NULL;
1434   }
1435   if (NULL != handle->client)
1436   {
1437     GNUNET_CLIENT_disconnect (handle->client);
1438     handle->client = NULL;
1439   }
1440   if (GNUNET_SCHEDULER_NO_TASK != handle->reconnect_task)
1441   {
1442     GNUNET_SCHEDULER_cancel(handle->reconnect_task);
1443     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1444   }
1445   GNUNET_free (handle);
1446 }
1447
1448
1449 struct GNUNET_MESH_Tunnel *
1450 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h, 
1451                            void *tunnel_ctx,
1452                            const struct GNUNET_PeerIdentity *peer,
1453                            uint32_t port)
1454 {
1455   struct GNUNET_MESH_Tunnel *t;
1456   struct GNUNET_MESH_TunnelMessage msg;
1457
1458   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating new tunnel\n");
1459   t = create_tunnel (h, 0);
1460   LOG (GNUNET_ERROR_TYPE_DEBUG, "  at %p\n", t);
1461   LOG (GNUNET_ERROR_TYPE_DEBUG, "  number %X\n", t->tid);
1462   t->ctx = tunnel_ctx;
1463   t->peer = GNUNET_PEER_intern (peer);
1464   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1465   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1466   msg.tunnel_id = htonl (t->tid);
1467   msg.port = htonl (port);
1468   msg.peer = *peer;
1469   t->last_ack_sent = 0;
1470   send_packet (h, &msg.header, t);
1471   return t;
1472 }
1473
1474
1475 void
1476 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tunnel)
1477 {
1478   struct GNUNET_MESH_Handle *h;
1479   struct GNUNET_MESH_TunnelMessage msg;
1480   struct GNUNET_MESH_TransmitHandle *th;
1481
1482   LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying tunnel\n");
1483   h = tunnel->mesh;
1484
1485   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1486   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1487   msg.tunnel_id = htonl (tunnel->tid);
1488   th = h->th_head;
1489   while (th != NULL)
1490   {
1491     struct GNUNET_MESH_TransmitHandle *aux;
1492     if (th->tunnel == tunnel)
1493     {
1494       aux = th->next;
1495       /* FIXME call the handler? */
1496       if (GNUNET_YES == th_is_payload (th))
1497         th->notify (th->notify_cls, 0, NULL);
1498       GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1499       GNUNET_free (th);
1500       th = aux;
1501     }
1502     else
1503       th = th->next;
1504   }
1505
1506   destroy_tunnel (tunnel, GNUNET_YES);
1507   send_packet (h, &msg.header, NULL);
1508 }
1509
1510
1511 void
1512 GNUNET_MESH_tunnel_buffer (struct GNUNET_MESH_Tunnel *tunnel, int buffer)
1513 {
1514   struct GNUNET_MESH_TunnelMessage msg;
1515   struct GNUNET_MESH_Handle *h;
1516
1517   h = tunnel->mesh;
1518   tunnel->buffering = buffer;
1519
1520   if (GNUNET_YES == buffer)
1521     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER);
1522   else
1523     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER);
1524   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1525   msg.tunnel_id = htonl (tunnel->tid);
1526
1527   send_packet (h, &msg.header, NULL);
1528 }
1529
1530
1531 /**
1532  * Turn on/off the reliability of the tunnel.
1533  * 
1534  * If reliability is on, mesh will resend lost messages, similar to TCP.
1535  * If reliability is off, mesh just do best effort, similar to UDP.
1536  * 
1537  * @param tunnel Tunnel affected.
1538  * @param reliable GNUNET_YES to turn reliability on, 
1539  *                 GNUNET_NO to have a best effort tunnel (default).
1540  */
1541 void
1542 GNUNET_MESH_tunnel_reliable (struct GNUNET_MESH_Tunnel *tunnel, int reliable)
1543 {
1544   struct GNUNET_MESH_TunnelMessage msg;
1545   struct GNUNET_MESH_Handle *h;
1546
1547   h = tunnel->mesh;
1548   tunnel->reliable = reliable;
1549
1550   if (GNUNET_YES == reliable)
1551     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_RELIABLE);
1552   else
1553     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_UNRELIABLE);
1554   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1555   msg.tunnel_id = htonl (tunnel->tid);
1556
1557   send_packet (h, &msg.header, NULL);
1558 }
1559
1560
1561 struct GNUNET_MESH_TransmitHandle *
1562 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
1563                                    struct GNUNET_TIME_Relative maxdelay,
1564                                    size_t notify_size,
1565                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1566                                    void *notify_cls)
1567 {
1568   struct GNUNET_MESH_TransmitHandle *th;
1569
1570   GNUNET_assert (NULL != tunnel);
1571   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH NOTIFY TRANSMIT READY\n");
1572   LOG (GNUNET_ERROR_TYPE_DEBUG, "    on tunnel %X\n", tunnel->tid);
1573   if (tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1574     LOG (GNUNET_ERROR_TYPE_DEBUG, "    to origin\n");
1575   else
1576     LOG (GNUNET_ERROR_TYPE_DEBUG, "    to destination\n");
1577   LOG (GNUNET_ERROR_TYPE_DEBUG, "    payload size %u\n", notify_size);
1578   GNUNET_assert (NULL != notify);
1579   GNUNET_assert (0 == tunnel->packet_size); // Only one data packet allowed
1580   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
1581   th->tunnel = tunnel;
1582   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1583   th->size = notify_size + sizeof (struct GNUNET_MESH_Data);
1584   tunnel->packet_size = th->size;
1585   LOG (GNUNET_ERROR_TYPE_DEBUG, "    total size %u\n", th->size);
1586   th->notify = notify;
1587   th->notify_cls = notify_cls;
1588   add_to_queue (tunnel->mesh, th);
1589   if (NULL != tunnel->mesh->th)
1590     return th;
1591   if (!GMC_is_pid_bigger (tunnel->last_ack_recv, tunnel->last_pid_sent))
1592     return th;
1593   LOG (GNUNET_ERROR_TYPE_DEBUG, "    call client notify tmt rdy\n");
1594   tunnel->mesh->th =
1595       GNUNET_CLIENT_notify_transmit_ready (tunnel->mesh->client, th->size,
1596                                            GNUNET_TIME_UNIT_FOREVER_REL,
1597                                            GNUNET_YES, &send_callback,
1598                                            tunnel->mesh);
1599   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH NOTIFY TRANSMIT READY END\n");
1600   return th;
1601 }
1602
1603
1604 void
1605 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
1606 {
1607   struct GNUNET_MESH_Handle *mesh;
1608
1609   th->tunnel->packet_size = 0;
1610   mesh = th->tunnel->mesh;
1611   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1612     GNUNET_SCHEDULER_cancel (th->timeout_task);
1613   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
1614   GNUNET_free (th);
1615   if ((0 == message_ready_size (mesh)) && (NULL != mesh->th))
1616   {
1617     /* queue empty, no point in asking for transmission */
1618     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
1619     mesh->th = NULL;
1620   }
1621 }
1622
1623 void
1624 GNUNET_MESH_receive_done (struct GNUNET_MESH_Tunnel *tunnel)
1625 {
1626   send_ack (tunnel);
1627 }
1628
1629
1630 /**
1631  * Request information about the running mesh peer.
1632  * The callback will be called for every tunnel known to the service,
1633  * listing all active peers that blong to the tunnel.
1634  *
1635  * If called again on the same handle, it will overwrite the previous
1636  * callback and cls. To retrieve the cls, monitor_cancel must be
1637  * called first.
1638  *
1639  * WARNING: unstable API, likely to change in the future!
1640  *
1641  * @param h Handle to the mesh peer.
1642  * @param callback Function to call with the requested data.
1643  * @param callback_cls Closure for @c callback.
1644  */
1645 void
1646 GNUNET_MESH_get_tunnels (struct GNUNET_MESH_Handle *h,
1647                          GNUNET_MESH_TunnelsCB callback,
1648                          void *callback_cls)
1649 {
1650   struct GNUNET_MessageHeader msg;
1651
1652   msg.size = htons (sizeof (msg));
1653   msg.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
1654   send_packet (h, &msg, NULL);
1655   h->tunnels_cb = callback;
1656   h->tunnels_cls = callback_cls;
1657
1658   return;
1659 }
1660
1661
1662 /**
1663  * Cancel a monitor request. The monitor callback will not be called.
1664  *
1665  * @param h Mesh handle.
1666  *
1667  * @return Closure given to GNUNET_MESH_monitor, if any.
1668  */
1669 void *
1670 GNUNET_MESH_get_tunnels_cancel (struct GNUNET_MESH_Handle *h)
1671 {
1672   void *cls;
1673
1674   cls = h->tunnels_cls;
1675   h->tunnels_cb = NULL;
1676   h->tunnels_cls = NULL;
1677   return cls;
1678 }
1679
1680
1681 /**
1682  * Request information about a specific tunnel of the running mesh peer.
1683  *
1684  * WARNING: unstable API, likely to change in the future!
1685  * FIXME Add destination option.
1686  *
1687  * @param h Handle to the mesh peer.
1688  * @param initiator ID of the owner of the tunnel.
1689  * @param tunnel_number Tunnel number.
1690  * @param callback Function to call with the requested data.
1691  * @param callback_cls Closure for @c callback.
1692  */
1693 void
1694 GNUNET_MESH_show_tunnel (struct GNUNET_MESH_Handle *h,
1695                          struct GNUNET_PeerIdentity *initiator,
1696                          unsigned int tunnel_number,
1697                          GNUNET_MESH_TunnelCB callback,
1698                          void *callback_cls)
1699 {
1700   struct GNUNET_MESH_LocalMonitor msg;
1701
1702   msg.header.size = htons (sizeof (msg));
1703   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL);
1704   msg.owner = *initiator;
1705   msg.tunnel_id = htonl (tunnel_number);
1706   msg.reserved = 0;
1707   send_packet (h, &msg.header, NULL);
1708   h->tunnel_cb = callback;
1709   h->tunnel_cls = callback_cls;
1710
1711   return;
1712 }
1713
1714
1715 /**
1716  * Function called to notify a client about the connection
1717  * begin ready to queue more data.  "buf" will be
1718  * NULL and "size" zero if the connection was closed for
1719  * writing in the meantime.
1720  *
1721  * @param cls closure
1722  * @param size number of bytes available in buf
1723  * @param buf where the callee should write the message
1724  * @return number of bytes written to buf
1725  */
1726 static size_t
1727 mesh_mq_ntr (void *cls, size_t size,
1728              void *buf)
1729 {
1730   struct GNUNET_MQ_Handle *mq = cls; 
1731   struct MeshMQState *state = GNUNET_MQ_impl_state (mq);
1732   const struct GNUNET_MessageHeader *msg = GNUNET_MQ_impl_current (mq);
1733   uint16_t msize;
1734
1735   state->th = NULL;
1736   if (NULL == buf)
1737   {
1738     GNUNET_MQ_inject_error (mq, GNUNET_MQ_ERROR_WRITE);
1739     return 0;
1740   }
1741   msize = ntohs (msg->size);
1742   GNUNET_assert (msize <= size);
1743   memcpy (buf, msg, msize);
1744   GNUNET_MQ_impl_send_continue (mq);
1745   return msize;
1746 }
1747
1748
1749 /**
1750  * Signature of functions implementing the
1751  * sending functionality of a message queue.
1752  *
1753  * @param mq the message queue
1754  * @param msg the message to send
1755  * @param impl_state state of the implementation
1756  */
1757 static void
1758 mesh_mq_send_impl (struct GNUNET_MQ_Handle *mq,
1759                    const struct GNUNET_MessageHeader *msg, void *impl_state)
1760 {
1761   struct MeshMQState *state = impl_state;
1762
1763   GNUNET_assert (NULL == state->th);
1764   GNUNET_MQ_impl_send_commit (mq);
1765   state->th =
1766       GNUNET_MESH_notify_transmit_ready (state->tunnel,
1767                                          /* FIXME: add option for corking */
1768                                          GNUNET_NO,
1769                                          GNUNET_TIME_UNIT_FOREVER_REL, 
1770                                          ntohs (msg->size),
1771                                          mesh_mq_ntr, mq);
1772
1773 }
1774
1775
1776 /**
1777  * Signature of functions implementing the
1778  * destruction of a message queue.
1779  * Implementations must not free 'mq', but should
1780  * take care of 'impl_state'.
1781  * 
1782  * @param mq the message queue to destroy
1783  * @param impl_state state of the implementation
1784  */
1785 static void
1786 mesh_mq_destroy_impl (struct GNUNET_MQ_Handle *mq, void *impl_state)
1787 {
1788   struct MeshMQState *state = impl_state;
1789
1790   if (NULL != state->th)
1791     GNUNET_MESH_notify_transmit_ready_cancel (state->th);
1792
1793   GNUNET_free (state);
1794 }
1795
1796
1797 /**
1798  * Create a message queue for a mesh tunnel.
1799  * The message queue can only be used to transmit messages,
1800  * not to receive them.
1801  *
1802  * @param tunnel the tunnel to create the message qeue for
1803  * @return a message queue to messages over the tunnel
1804  */
1805 struct GNUNET_MQ_Handle *
1806 GNUNET_MESH_mq_create (struct GNUNET_MESH_Tunnel *tunnel)
1807 {
1808   struct GNUNET_MQ_Handle *mq;
1809   struct MeshMQState *state;
1810
1811   state = GNUNET_new (struct MeshMQState);
1812   state->tunnel = tunnel;
1813
1814   mq = GNUNET_MQ_queue_for_callbacks (mesh_mq_send_impl,
1815                                       mesh_mq_destroy_impl,
1816                                       NULL, /* FIXME: cancel impl. */
1817                                       state,
1818                                       NULL, /* no msg handlers */
1819                                       NULL, /* no err handlers */
1820                                       NULL); /* no handler cls */
1821   return mq;
1822 }
1823