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