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