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