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