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