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