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