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