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