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