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