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