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