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