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