- explicit bck counter
[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 mesh service
21  * @author Bartlomiej Polot
22  *
23  * STRUCTURE:
24  * - DATA STRUCTURES
25  * - DECLARATIONS
26  * - AUXILIARY FUNCTIONS
27  * - RECEIVE HANDLERS
28  * - SEND FUNCTIONS
29  * - API CALL DEFINITIONS
30  *
31  * TODO: add regex to reconnect
32  */
33 #include "platform.h"
34 #include "gnunet_common.h"
35 #include "gnunet_client_lib.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_peer_lib.h"
38 #include "gnunet_mesh_service.h"
39 #include "mesh.h"
40 #include "mesh_protocol.h"
41
42 #define LOG(kind,...) GNUNET_log_from (kind, "mesh-api",__VA_ARGS__)
43
44
45 /******************************************************************************/
46 /************************      DATA STRUCTURES     ****************************/
47 /******************************************************************************/
48
49 /**
50  * Transmission queue to the service
51  */
52 struct GNUNET_MESH_TransmitHandle
53 {
54
55     /**
56      * Double Linked list
57      */
58   struct GNUNET_MESH_TransmitHandle *next;
59
60     /**
61      * Double Linked list
62      */
63   struct GNUNET_MESH_TransmitHandle *prev;
64
65     /**
66      * Tunnel this message is sent on / for (may be NULL for control messages).
67      */
68   struct GNUNET_MESH_Tunnel *tunnel;
69
70     /**
71      * Callback to obtain the message to transmit, or NULL if we
72      * got the message in 'data'.  Notice that messages built
73      * by 'notify' need to be encapsulated with information about
74      * the 'target'.
75      */
76   GNUNET_CONNECTION_TransmitReadyNotify notify;
77
78     /**
79      * Closure for 'notify'
80      */
81   void *notify_cls;
82
83     /**
84      * How long is this message valid.  Once the timeout has been
85      * reached, the message must no longer be sent.  If this
86      * is a message with a 'notify' callback set, the 'notify'
87      * function should be called with 'buf' NULL and size 0.
88      */
89   struct GNUNET_TIME_Absolute timeout;
90
91     /**
92      * Task triggering a timeout, can be NO_TASK if the timeout is FOREVER.
93      */
94   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
95
96     /**
97      * Target of the message, 0 for multicast.  This field
98      * is only valid if 'notify' is non-NULL.
99      */
100   GNUNET_PEER_Id target;
101
102     /**
103      * Size of 'data' -- or the desired size of 'notify' if 'data' is NULL.
104      */
105   size_t size;
106 };
107
108
109 /**
110  * Opaque handle to the service.
111  */
112 struct GNUNET_MESH_Handle
113 {
114
115     /**
116      * Handle to the server connection, to send messages later
117      */
118   struct GNUNET_CLIENT_Connection *client;
119
120     /**
121      * Set of handlers used for processing incoming messages in the tunnels
122      */
123   const struct GNUNET_MESH_MessageHandler *message_handlers;
124
125     /**
126      * Set of applications that should be claimed to be offered at this node.
127      * Note that this is just informative, the appropiate handlers must be
128      * registered independently and the mapping is up to the developer of the
129      * client application.
130      */
131   const GNUNET_MESH_ApplicationType *applications;
132
133     /**
134      * Double linked list of the tunnels this client is connected to, head.
135      */
136   struct GNUNET_MESH_Tunnel *tunnels_head;
137
138     /**
139      * Double linked list of the tunnels this client is connected to, tail.
140      */
141   struct GNUNET_MESH_Tunnel *tunnels_tail;
142
143     /**
144      * Callback for inbound tunnel creation
145      */
146   GNUNET_MESH_InboundTunnelNotificationHandler *new_tunnel;
147
148     /**
149      * Callback for inbound tunnel disconnection
150      */
151   GNUNET_MESH_TunnelEndHandler *cleaner;
152
153     /**
154      * Handle to cancel pending transmissions in case of disconnection
155      */
156   struct GNUNET_CLIENT_TransmitHandle *th;
157
158     /**
159      * Closure for all the handlers given by the client
160      */
161   void *cls;
162
163     /**
164      * Messages to send to the service, head.
165      */
166   struct GNUNET_MESH_TransmitHandle *th_head;
167
168     /**
169      * Messages to send to the service, tail.
170      */
171   struct GNUNET_MESH_TransmitHandle *th_tail;
172
173     /**
174      * tid of the next tunnel to create (to avoid reusing IDs often)
175      */
176   MESH_TunnelNumber next_tid;
177
178     /**
179      * Number of handlers in the handlers array.
180      */
181   unsigned int n_handlers;
182
183     /**
184      * Number of applications in the applications array.
185      */
186   unsigned int n_applications;
187
188     /**
189      * Have we started the task to receive messages from the service
190      * yet? We do this after we send the 'MESH_LOCAL_CONNECT' message.
191      */
192   int in_receive;
193
194   /**
195    * Configuration given by the client, in case of reconnection
196    */
197   const struct GNUNET_CONFIGURATION_Handle *cfg;
198
199   /**
200    * Time to the next reconnect in case one reconnect fails
201    */
202   struct GNUNET_TIME_Relative reconnect_time;
203   
204   /**
205    * Task for trying to reconnect.
206    */
207   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
208 };
209
210
211 /**
212  * Description of a peer
213  */
214 struct GNUNET_MESH_Peer
215 {
216     /**
217      * ID of the peer in short form
218      */
219   GNUNET_PEER_Id id;
220
221   /**
222    * Tunnel this peer belongs to
223    */
224   struct GNUNET_MESH_Tunnel *t;
225
226   /**
227    * Flag indicating whether service has informed about its connection
228    */
229   int connected;
230
231 };
232
233
234 /**
235  * Opaque handle to a tunnel.
236  */
237 struct GNUNET_MESH_Tunnel
238 {
239
240     /**
241      * DLL next
242      */
243   struct GNUNET_MESH_Tunnel *next;
244
245     /**
246      * DLL prev
247      */
248   struct GNUNET_MESH_Tunnel *prev;
249
250     /**
251      * Callback to execute when peers connect to the tunnel
252      */
253   GNUNET_MESH_PeerConnectHandler connect_handler;
254
255     /**
256      * Callback to execute when peers disconnect from the tunnel
257      */
258   GNUNET_MESH_PeerDisconnectHandler disconnect_handler;
259
260     /**
261      * Closure for the connect/disconnect handlers
262      */
263   void *cls;
264
265     /**
266      * Handle to the mesh this tunnel belongs to
267      */
268   struct GNUNET_MESH_Handle *mesh;
269
270     /**
271      * Local ID of the tunnel
272      */
273   MESH_TunnelNumber tid;
274
275     /**
276      * Owner of the tunnel. 0 if the tunnel is the local client.
277      */
278   GNUNET_PEER_Id owner;
279
280     /**
281      * All peers added to the tunnel
282      */
283   struct GNUNET_MESH_Peer **peers;
284
285   /**
286    * List of application types that have been requested for this tunnel
287    */
288   GNUNET_MESH_ApplicationType *apps;
289
290   /**
291    * Any data the caller wants to put in here
292    */
293   void *ctx;
294
295   /**
296      * Number of peers added to the tunnel
297      */
298   unsigned int npeers;
299
300     /**
301      * Size of packet queued in this tunnel
302      */
303   unsigned int packet_size;
304
305     /**
306      * Number of applications requested this tunnel
307      */
308   unsigned int napps;
309
310     /**
311      * Is the tunnel throttled to the slowest peer?
312      */
313   int speed_min;
314
315     /**
316      * Is the tunnel allowed to buffer?
317      */
318   int buffering;
319
320     /**
321      * Next packet ID to send.
322      */
323   uint32_t next_send_pid;
324
325     /**
326      * Maximum allowed PID to send (ACK recevied).
327      */
328   uint32_t max_send_pid;
329
330     /**
331      * Last pid received from the service.
332      */
333   uint32_t last_recv_pid;
334 };
335
336
337 /******************************************************************************/
338 /***********************         DECLARATIONS         *************************/
339 /******************************************************************************/
340
341 /**
342  * Function called to send a message to the service.
343  * "buf" will be NULL and "size" zero if the socket was closed for writing in
344  * the meantime.
345  *
346  * @param cls closure, the mesh handle
347  * @param size number of bytes available in buf
348  * @param buf where the callee should write the connect message
349  * @return number of bytes written to buf
350  */
351 static size_t
352 send_callback (void *cls, size_t size, void *buf);
353
354
355 /******************************************************************************/
356 /***********************     AUXILIARY FUNCTIONS      *************************/
357 /******************************************************************************/
358
359 /**
360  * Check if transmission is a payload packet.
361  *
362  * @param th Transmission handle.
363  *
364  * @return GNUNET_YES if it is a payload packet,
365  *         GNUNET_NO if it is a mesh management packet.
366  */
367 static int
368 th_is_payload (struct GNUNET_MESH_TransmitHandle *th)
369 {
370   return (th->notify != NULL) ? GNUNET_YES : GNUNET_NO;
371 }
372
373
374 /**
375  * Check whether there is any message ready in the queue and find the size.
376  * 
377  * @param h Mesh handle.
378  * 
379  * @return The size of the first ready message in the queue,
380  *         0 if there is none.
381  */
382 static size_t
383 message_ready_size (struct GNUNET_MESH_Handle *h)
384 {
385   struct GNUNET_MESH_TransmitHandle *th;
386   struct GNUNET_MESH_Tunnel *t;
387
388   for (th = h->th_head; NULL != th; th = th->next)
389   {
390     t = th->tunnel;
391     if (GNUNET_NO == th_is_payload (th) ||
392         GNUNET_NO == GMC_is_pid_bigger(t->next_send_pid, t->max_send_pid))
393       return th->size;
394   }
395   return 0;
396 }
397
398
399 /**
400  * Get the tunnel handler for the tunnel specified by id from the given handle
401  * @param h Mesh handle
402  * @param tid ID of the wanted tunnel
403  * @return handle to the required tunnel or NULL if not found
404  */
405 static struct GNUNET_MESH_Tunnel *
406 retrieve_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
407 {
408   struct GNUNET_MESH_Tunnel *t;
409
410   t = h->tunnels_head;
411   while (t != NULL)
412   {
413     if (t->tid == tid)
414       return t;
415     t = t->next;
416   }
417   return NULL;
418 }
419
420
421 /**
422  * Create a new tunnel and insert it in the tunnel list of the mesh handle
423  * @param h Mesh handle
424  * @param tid desired tid of the tunnel, 0 to assign one automatically
425  * @return handle to the created tunnel
426  */
427 static struct GNUNET_MESH_Tunnel *
428 create_tunnel (struct GNUNET_MESH_Handle *h, MESH_TunnelNumber tid)
429 {
430   struct GNUNET_MESH_Tunnel *t;
431
432   t = GNUNET_malloc (sizeof (struct GNUNET_MESH_Tunnel));
433   GNUNET_CONTAINER_DLL_insert (h->tunnels_head, h->tunnels_tail, t);
434   t->mesh = h;
435   if (0 == tid)
436   {
437     t->tid = h->next_tid;
438     while (NULL != retrieve_tunnel (h, h->next_tid))
439     {
440       h->next_tid++;
441       h->next_tid &= ~GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
442       h->next_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
443     }
444   }
445   else
446   {
447     t->tid = tid;
448   }
449   t->max_send_pid = 1;
450   return t;
451 }
452
453
454 /**
455  * Destroy the specified tunnel.
456  * - Destroys all peers, calling the disconnect callback on each if needed
457  * - Cancels all outgoing traffic for that tunnel, calling respective notifys
458  * - Calls cleaner if tunnel was inbound
459  * - Frees all memory used
460  *
461  * @param t Pointer to the tunnel.
462  * @param call_cleaner Whether to call the cleaner handler.
463  *
464  * @return Handle to the required tunnel or NULL if not found.
465  */
466 static void
467 destroy_tunnel (struct GNUNET_MESH_Tunnel *t, int call_cleaner)
468 {
469   struct GNUNET_MESH_Handle *h;
470   struct GNUNET_PeerIdentity pi;
471   struct GNUNET_MESH_TransmitHandle *th;
472   struct GNUNET_MESH_TransmitHandle *next;
473   unsigned int i;
474
475   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroy_tunnel %X\n", t->tid);
476
477   if (NULL == t)
478   {
479     GNUNET_break (0);
480     return;
481   }
482   h = t->mesh;
483
484   /* disconnect all peers */
485   GNUNET_CONTAINER_DLL_remove (h->tunnels_head, h->tunnels_tail, t);
486   for (i = 0; i < t->npeers; i++)
487   {
488     if ( (NULL != t->disconnect_handler) && t->peers[i]->connected)
489     {
490       GNUNET_PEER_resolve (t->peers[i]->id, &pi);
491       t->disconnect_handler (t->cls, &pi);
492     }
493     GNUNET_PEER_change_rc (t->peers[i]->id, -1);
494     GNUNET_free (t->peers[i]);
495   }
496
497   /* signal tunnel destruction */
498   if ( (NULL != h->cleaner) && (0 != t->owner) && (GNUNET_YES == call_cleaner) )
499     h->cleaner (h->cls, t, t->ctx);
500
501   /* check that clients did not leave messages behind in the queue */
502   for (th = h->th_head; NULL != th; th = next)
503   {
504     next = th->next;
505     if (th->tunnel != t)
506       continue;
507     /* Clients should have aborted their requests already.
508      * Management traffic should be ok, as clients can't cancel that */
509     GNUNET_break (GNUNET_NO == th_is_payload(th));
510     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
511
512     /* clean up request */
513     if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
514       GNUNET_SCHEDULER_cancel (th->timeout_task);
515     GNUNET_free (th);    
516   }
517
518   /* if there are no more pending requests with mesh service, cancel active request */
519   /* Note: this should be unnecessary... */
520   if ((0 == message_ready_size (h)) && (NULL != h->th))
521   {
522     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
523     h->th = NULL;
524   }
525
526
527   if (t->npeers > 0)
528     GNUNET_free (t->peers);
529   if (0 != t->owner)
530     GNUNET_PEER_change_rc (t->owner, -1);
531   if (0 != t->napps && t->apps)
532     GNUNET_free (t->apps);
533   GNUNET_free (t);
534   return;
535 }
536
537
538 /**
539  * Get the peer descriptor for the peer with id from the given tunnel
540  * @param t Tunnel handle
541  * @param id Short form ID of the wanted peer
542  * @return handle to the requested peer or NULL if not found
543  */
544 static struct GNUNET_MESH_Peer *
545 retrieve_peer (struct GNUNET_MESH_Tunnel *t, GNUNET_PEER_Id id)
546 {
547   unsigned int i;
548
549   for (i = 0; i < t->npeers; i++)
550     if (t->peers[i]->id == id)
551       return t->peers[i];
552   return NULL;
553 }
554
555
556 /**
557  * Add a peer into a tunnel
558  * @param t Tunnel handle
559  * @param pi Full ID of the new peer
560  * @return handle to the newly created peer
561  */
562 static struct GNUNET_MESH_Peer *
563 add_peer_to_tunnel (struct GNUNET_MESH_Tunnel *t,
564                     const struct GNUNET_PeerIdentity *pi)
565 {
566   struct GNUNET_MESH_Peer *p;
567   GNUNET_PEER_Id id;
568
569   if (0 != t->owner)
570   {
571     GNUNET_break (0);
572     return NULL;
573   }
574   id = GNUNET_PEER_intern (pi);
575
576   p = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer));
577   p->id = id;
578   p->t = t;
579   GNUNET_array_append (t->peers, t->npeers, p);
580   return p;
581 }
582
583
584 /**
585  * Remove a peer from a tunnel
586  * @param p Peer handle
587  */
588 static void
589 remove_peer_from_tunnel (struct GNUNET_MESH_Peer *p)
590 {
591   unsigned int i;
592
593   for (i = 0; i < p->t->npeers; i++)
594   {
595     if (p->t->peers[i] == p)
596       break;
597   }
598   if (i == p->t->npeers)
599   {
600     GNUNET_break (0);
601     return;
602   }
603   p->t->peers[i] = p->t->peers[p->t->npeers - 1];
604   GNUNET_array_grow (p->t->peers, p->t->npeers, p->t->npeers - 1);
605 }
606
607
608 /**
609  * Notify client that the transmission has timed out
610  * 
611  * @param cls closure
612  * @param tc task context
613  */
614 static void
615 timeout_transmission (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
616 {
617   struct GNUNET_MESH_TransmitHandle *th = cls;
618   struct GNUNET_MESH_Handle *mesh;
619
620   mesh = th->tunnel->mesh;
621   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
622   th->tunnel->packet_size = 0;
623   if (GNUNET_YES == th_is_payload (th))
624     th->notify (th->notify_cls, 0, NULL);
625   GNUNET_free (th);
626   if ((0 == message_ready_size (mesh)) && (NULL != mesh->th))
627   {
628     /* nothing ready to transmit, no point in asking for transmission */
629     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
630     mesh->th = NULL;
631   }
632 }
633
634
635 /**
636  * Add a transmit handle to the transmission queue by priority and set the
637  * timeout if needed.
638  *
639  * @param h mesh handle with the queue head and tail
640  * @param th handle to the packet to be transmitted
641  */
642 static void
643 add_to_queue (struct GNUNET_MESH_Handle *h,
644               struct GNUNET_MESH_TransmitHandle *th)
645 {
646   struct GNUNET_MESH_TransmitHandle *p;
647
648   p = h->th_head;
649   while ((NULL != p))
650     p = p->next;
651   if (NULL == p)
652     p = h->th_tail;
653   else
654     p = p->prev;
655   GNUNET_CONTAINER_DLL_insert_after (h->th_head, h->th_tail, p, th);
656   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value == th->timeout.abs_value)
657     return;
658   th->timeout_task =
659       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
660                                     (th->timeout), &timeout_transmission, th);
661 }
662
663
664 /**
665  * Auxiliary function to send an already constructed packet to the service.
666  * Takes care of creating a new queue element, copying the message and
667  * calling the tmt_rdy function if necessary.
668  *
669  * @param h mesh handle
670  * @param msg message to transmit
671  * @param tunnel tunnel this send is related to (NULL if N/A)
672  */
673 static void
674 send_packet (struct GNUNET_MESH_Handle *h,
675              const struct GNUNET_MessageHeader *msg,
676              struct GNUNET_MESH_Tunnel *tunnel);
677
678
679 /**
680  * Send an ack on the tunnel to confirm the processing of a message.
681  * 
682  * @param h Mesh handle.
683  * @param t Tunnel on which to send the ACK.
684  */
685 static void
686 send_ack (struct GNUNET_MESH_Handle *h, struct GNUNET_MESH_Tunnel *t)
687 {
688   struct GNUNET_MESH_LocalAck msg;
689
690   LOG (GNUNET_ERROR_TYPE_DEBUG,
691        "Sending ACK on tunnel %X: %u\n",
692        t->tid, t->last_recv_pid + 1);
693   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
694   msg.header.size = htons (sizeof (msg));
695   msg.tunnel_id = htonl (t->tid);
696   msg.max_pid = t->last_recv_pid + 1;
697
698   send_packet (h, &msg.header, t);
699   return;
700 }
701
702
703
704 /**
705  * Reconnect callback: tries to reconnect again after a failer previous
706  * reconnecttion
707  * @param cls closure (mesh handle)
708  * @param tc task context
709  */
710 static void
711 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
712
713
714 /**
715  * Send a connect packet to the service with the applications and types
716  * requested by the user.
717  *
718  * @param h The mesh handle.
719  *
720  */
721 static void
722 send_connect (struct GNUNET_MESH_Handle *h)
723 {
724   size_t size;
725
726   size = sizeof (struct GNUNET_MESH_ClientConnect);
727   size += h->n_applications * sizeof (GNUNET_MESH_ApplicationType);
728   size += h->n_handlers * sizeof (uint16_t);
729   {
730     char buf[size] GNUNET_ALIGN;
731     struct GNUNET_MESH_ClientConnect *msg;
732     GNUNET_MESH_ApplicationType *apps;
733     uint16_t napps;
734     uint16_t *types;
735     uint16_t ntypes;
736
737     /* build connection packet */
738     msg = (struct GNUNET_MESH_ClientConnect *) buf;
739     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT);
740     msg->header.size = htons (size);
741     apps = (GNUNET_MESH_ApplicationType *) &msg[1];
742     for (napps = 0; napps < h->n_applications; napps++)
743     {
744       apps[napps] = htonl (h->applications[napps]);
745       LOG (GNUNET_ERROR_TYPE_DEBUG, " app %u\n", h->applications[napps]);
746     }
747     types = (uint16_t *) & apps[napps];
748     for (ntypes = 0; ntypes < h->n_handlers; ntypes++)
749       types[ntypes] = htons (h->message_handlers[ntypes].type);
750     msg->applications = htons (napps);
751     msg->types = htons (ntypes);
752     LOG (GNUNET_ERROR_TYPE_DEBUG,
753          "Sending %lu bytes long message %d types and %d apps\n",
754          ntohs (msg->header.size), ntypes, napps);
755     send_packet (h, &msg->header, NULL);
756   }
757 }
758
759
760 /**
761  * Reconnect to the service, retransmit all infomation to try to restore the
762  * original state.
763  *
764  * @param h handle to the mesh
765  *
766  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
767  */
768 static int
769 do_reconnect (struct GNUNET_MESH_Handle *h)
770 {
771   struct GNUNET_MESH_Tunnel *t;
772   unsigned int i;
773
774   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
775   LOG (GNUNET_ERROR_TYPE_DEBUG, "*******   RECONNECT   *******\n");
776   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
777   LOG (GNUNET_ERROR_TYPE_DEBUG, "******** on %p *******\n", h);
778   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
779
780   /* disconnect */
781   if (NULL != h->th)
782   {
783     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
784     h->th = NULL;
785   }
786   if (NULL != h->client)
787   {
788     GNUNET_CLIENT_disconnect (h->client);
789   }
790
791   /* connect again */
792   h->client = GNUNET_CLIENT_connect ("mesh", h->cfg);
793   if (h->client == NULL)
794   {
795     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
796                                                       &reconnect_cbk, h);
797     h->reconnect_time =
798         GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
799                                   GNUNET_TIME_relative_multiply
800                                   (h->reconnect_time, 2));
801     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Next retry in %sms\n",
802          GNUNET_TIME_relative_to_string (h->reconnect_time));
803     GNUNET_break (0);
804     return GNUNET_NO;
805   }
806   else
807   {
808     h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
809   }
810   send_connect (h);
811   /* Rebuild all tunnels */
812   for (t = h->tunnels_head; NULL != t; t = t->next)
813   {
814     struct GNUNET_MESH_TunnelMessage tmsg;
815     struct GNUNET_MESH_PeerControl pmsg;
816
817     if (t->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
818     {
819       /* Tunnel was created by service (incoming tunnel) */
820       /* TODO: Notify service of missing tunnel, to request
821        * creator to recreate path (find a path to him via DHT?)
822        */
823       continue;
824     }
825     tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
826     tmsg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
827     tmsg.tunnel_id = htonl (t->tid);
828     send_packet (h, &tmsg.header, t);
829
830     pmsg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
831     pmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
832     pmsg.tunnel_id = htonl (t->tid);
833
834     /* Reconnect all peers */
835     /* If the tunnel was "by type", dont connect individual peers */
836     for (i = 0; i < t->npeers && 0 == t->napps; i++)
837     {
838       GNUNET_PEER_resolve (t->peers[i]->id, &pmsg.peer);
839       if (NULL != t->disconnect_handler && t->peers[i]->connected)
840         t->disconnect_handler (t->cls, &pmsg.peer);
841       send_packet (t->mesh, &pmsg.header, t);
842     }
843     /* Reconnect all types, if any  */
844     for (i = 0; i < t->napps; i++)
845     {
846       struct GNUNET_MESH_ConnectPeerByType msg;
847
848       msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
849       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE);
850       msg.tunnel_id = htonl (t->tid);
851       msg.type = htonl (t->apps[i]);
852       send_packet (t->mesh, &msg.header, t);
853     }
854     if (GNUNET_NO == t->buffering)
855       GNUNET_MESH_tunnel_buffer (t, GNUNET_NO);
856     if (GNUNET_YES == t->speed_min)
857       GNUNET_MESH_tunnel_speed_min (t);
858   }
859   return GNUNET_YES;
860 }
861
862 /**
863  * Reconnect callback: tries to reconnect again after a failer previous
864  * reconnecttion
865  * @param cls closure (mesh handle)
866  * @param tc task context
867  */
868 static void
869 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
870 {
871   struct GNUNET_MESH_Handle *h = cls;
872
873   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
874   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
875     return;
876   do_reconnect (h);
877 }
878
879
880 /**
881  * Reconnect to the service, retransmit all infomation to try to restore the
882  * original state.
883  *
884  * @param h handle to the mesh
885  *
886  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
887  */
888 static void
889 reconnect (struct GNUNET_MESH_Handle *h)
890 {
891   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requested RECONNECT\n");
892   h->in_receive = GNUNET_NO;
893   if (GNUNET_SCHEDULER_NO_TASK == h->reconnect_task)
894     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
895                                                       &reconnect_cbk, h);
896 }
897
898
899 /******************************************************************************/
900 /***********************      RECEIVE HANDLERS     ****************************/
901 /******************************************************************************/
902
903 /**
904  * Process the new tunnel notification and add it to the tunnels in the handle
905  *
906  * @param h     The mesh handle
907  * @param msg   A message with the details of the new incoming tunnel
908  */
909 static void
910 process_tunnel_created (struct GNUNET_MESH_Handle *h,
911                         const struct GNUNET_MESH_TunnelNotification *msg)
912 {
913   struct GNUNET_MESH_Tunnel *t;
914   MESH_TunnelNumber tid;
915
916   tid = ntohl (msg->tunnel_id);
917   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating incoming tunnel %X\n", tid);
918   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
919   {
920     GNUNET_break (0);
921     return;
922   }
923   if (NULL != h->new_tunnel)
924   {
925     struct GNUNET_ATS_Information atsi;
926
927     t = create_tunnel (h, tid);
928     t->owner = GNUNET_PEER_intern (&msg->peer);
929     t->npeers = 1;
930     t->peers = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer *));
931     t->peers[0] = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer));
932     t->peers[0]->t = t;
933     t->peers[0]->connected = 1;
934     t->peers[0]->id = t->owner;
935     GNUNET_PEER_change_rc (t->owner, 1);
936     t->mesh = h;
937     t->tid = tid;
938     atsi.type = 0;
939     atsi.value = 0;
940     LOG (GNUNET_ERROR_TYPE_DEBUG, "  created tunnel %p\n", t);
941     t->ctx = h->new_tunnel (h->cls, t, &msg->peer, &atsi);
942     LOG (GNUNET_ERROR_TYPE_DEBUG, "User notified\n");
943   }
944   else
945   {
946     struct GNUNET_MESH_TunnelMessage d_msg;
947
948     LOG (GNUNET_ERROR_TYPE_DEBUG, "No handler for incoming tunnels\n");
949
950     d_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
951     d_msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
952     d_msg.tunnel_id = msg->tunnel_id;
953
954     send_packet (h, &d_msg.header, NULL);
955   }
956   return;
957 }
958
959
960 /**
961  * Process the tunnel destroy notification and free associated resources
962  *
963  * @param h     The mesh handle
964  * @param msg   A message with the details of the tunnel being destroyed
965  */
966 static void
967 process_tunnel_destroy (struct GNUNET_MESH_Handle *h,
968                         const struct GNUNET_MESH_TunnelMessage *msg)
969 {
970   struct GNUNET_MESH_Tunnel *t;
971   MESH_TunnelNumber tid;
972
973   tid = ntohl (msg->tunnel_id);
974   t = retrieve_tunnel (h, tid);
975
976   if (NULL == t)
977   {
978     return;
979   }
980   if (0 == t->owner)
981   {
982     GNUNET_break (0);
983   }
984   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X destroyed\n", t->tid);
985   destroy_tunnel (t, GNUNET_YES);
986   return;
987 }
988
989
990 /**
991  * Process the new peer event and notify the upper level of it
992  *
993  * @param h     The mesh handle
994  * @param msg   A message with the details of the peer event
995  */
996 static void
997 process_peer_event (struct GNUNET_MESH_Handle *h,
998                     const struct GNUNET_MESH_PeerControl *msg)
999 {
1000   struct GNUNET_MESH_Tunnel *t;
1001   struct GNUNET_MESH_Peer *p;
1002   struct GNUNET_ATS_Information atsi;
1003   GNUNET_PEER_Id id;
1004   uint16_t size;
1005
1006   LOG (GNUNET_ERROR_TYPE_DEBUG, "processig peer event\n");
1007   size = ntohs (msg->header.size);
1008   if (size != sizeof (struct GNUNET_MESH_PeerControl))
1009   {
1010     GNUNET_break (0);
1011     return;
1012   }
1013   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
1014   if (NULL == t)
1015   {
1016     GNUNET_break (0);
1017     return;
1018   }
1019   id = GNUNET_PEER_search (&msg->peer);
1020   if ((p = retrieve_peer (t, id)) == NULL)
1021     p = add_peer_to_tunnel (t, &msg->peer);
1022   if (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD == ntohs (msg->header.type))
1023   {
1024     LOG (GNUNET_ERROR_TYPE_DEBUG, "adding peer\n");
1025     if (NULL != t->connect_handler)
1026     {
1027       atsi.type = 0;
1028       atsi.value = 0;
1029       t->connect_handler (t->cls, &msg->peer, &atsi);
1030     }
1031     p->connected = 1;
1032   }
1033   else
1034   {
1035     LOG (GNUNET_ERROR_TYPE_DEBUG, "removing peer\n");
1036     if (NULL != t->disconnect_handler && p->connected)
1037     {
1038       t->disconnect_handler (t->cls, &msg->peer);
1039     }
1040     remove_peer_from_tunnel (p);
1041     GNUNET_free (p);
1042   }
1043   LOG (GNUNET_ERROR_TYPE_DEBUG, "processing peer event END\n");
1044 }
1045
1046
1047 /**
1048  * Process the incoming data packets
1049  *
1050  * @param h         The mesh handle
1051  * @param message   A message encapsulating the data
1052  * 
1053  * @return GNUNET_YES if everything went fine
1054  *         GNUNET_NO if client closed connection (h no longer valid)
1055  */
1056 static int
1057 process_incoming_data (struct GNUNET_MESH_Handle *h,
1058                        const struct GNUNET_MessageHeader *message)
1059 {
1060   const struct GNUNET_MessageHeader *payload;
1061   const struct GNUNET_MESH_MessageHandler *handler;
1062   const struct GNUNET_PeerIdentity *peer;
1063   struct GNUNET_MESH_Unicast *ucast;
1064   struct GNUNET_MESH_Multicast *mcast;
1065   struct GNUNET_MESH_ToOrigin *to_orig;
1066   struct GNUNET_MESH_Tunnel *t;
1067   unsigned int i;
1068   uint32_t pid;
1069   uint16_t type;
1070
1071   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a data message!\n");
1072   type = ntohs (message->type);
1073   switch (type)
1074   {
1075   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1076     ucast = (struct GNUNET_MESH_Unicast *) message;
1077
1078     t = retrieve_tunnel (h, ntohl (ucast->tid));
1079     payload = (struct GNUNET_MessageHeader *) &ucast[1];
1080     peer = &ucast->oid;
1081     pid = ntohl (ucast->pid);
1082     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ucast on tunnel %s [%X]\n",
1083          GNUNET_i2s (peer), ntohl (ucast->tid));
1084     break;
1085   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1086     mcast = (struct GNUNET_MESH_Multicast *) message;
1087     t = retrieve_tunnel (h, ntohl (mcast->tid));
1088     payload = (struct GNUNET_MessageHeader *) &mcast[1];
1089     peer = &mcast->oid;
1090     pid = ntohl (mcast->pid);
1091     LOG (GNUNET_ERROR_TYPE_DEBUG, "  mcast on tunnel %s [%X]\n",
1092          GNUNET_i2s (peer), ntohl (mcast->tid));
1093     break;
1094   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1095     to_orig = (struct GNUNET_MESH_ToOrigin *) message;
1096     t = retrieve_tunnel (h, ntohl (to_orig->tid));
1097     payload = (struct GNUNET_MessageHeader *) &to_orig[1];
1098     peer = &to_orig->sender;
1099     pid = ntohl (to_orig->pid);
1100     LOG (GNUNET_ERROR_TYPE_DEBUG, "  torig on tunnel %s [%X]\n",
1101          GNUNET_i2s (peer), ntohl (to_orig->tid));
1102     break;
1103   default:
1104     GNUNET_break (0);
1105     return GNUNET_YES;
1106   }
1107   LOG (GNUNET_ERROR_TYPE_DEBUG, "  pid %u\n", pid);
1108   if (NULL == t)
1109   {
1110     /* Tunnel was ignored, probably service didn't get it yet */
1111     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ignored!\n");
1112     return GNUNET_YES;
1113   }
1114   if (GMC_is_pid_bigger(pid, t->last_recv_pid + 1))
1115   {
1116     GNUNET_break (0);
1117     LOG (GNUNET_ERROR_TYPE_WARNING, "  unauthorized message!\n");
1118     // FIXME fc what now? accept? reject?
1119     return GNUNET_YES;
1120   }
1121   t->last_recv_pid = pid;
1122   type = ntohs (payload->type);
1123   for (i = 0; i < h->n_handlers; i++)
1124   {
1125     handler = &h->message_handlers[i];
1126     if (handler->type == type)
1127     {
1128       struct GNUNET_ATS_Information atsi;
1129
1130       atsi.type = 0;
1131       atsi.value = 0;
1132       if (GNUNET_OK !=
1133           handler->callback (h->cls, t, &t->ctx, peer, payload, &atsi))
1134       {
1135         LOG (GNUNET_ERROR_TYPE_DEBUG, "callback caused disconnection\n");
1136         GNUNET_MESH_disconnect (h);
1137         return GNUNET_NO;
1138       }
1139       else
1140       {
1141         LOG (GNUNET_ERROR_TYPE_DEBUG,
1142              "callback completed successfully\n");
1143         send_ack (h, t);
1144       }
1145     }
1146   }
1147   return GNUNET_YES;
1148 }
1149
1150
1151 /**
1152  * Process a local ACK message, enabling the client to send
1153  * more data to the service.
1154  * 
1155  * @param h Mesh handle.
1156  * @param message Message itself.
1157  */
1158 static void
1159 process_ack (struct GNUNET_MESH_Handle *h,
1160              const struct GNUNET_MessageHeader *message)
1161 {
1162   struct GNUNET_MESH_LocalAck *msg;
1163   struct GNUNET_MESH_Tunnel *t;
1164   uint32_t ack;
1165
1166   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK!\n");
1167   msg = (struct GNUNET_MESH_LocalAck *) message;
1168
1169   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
1170
1171   if (NULL == t)
1172   {
1173     LOG (GNUNET_ERROR_TYPE_WARNING,
1174          "ACK on unknown tunnel %X\n",
1175          ntohl (msg->tunnel_id));
1176     return;
1177   }
1178   ack = ntohl (msg->max_pid);
1179   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X, ack %u!\n", t->tid, ack);
1180   if (ack > t->max_send_pid || PID_OVERFLOW (t->max_send_pid, ack))
1181     t->max_send_pid = ack;
1182   else
1183     return;
1184   if (NULL == h->th && 0 < t->packet_size)
1185   {
1186     LOG (GNUNET_ERROR_TYPE_DEBUG, "  tmt rdy was NULL, requesting!\n", t->tid, ack);
1187     h->th =
1188         GNUNET_CLIENT_notify_transmit_ready (h->client, t->packet_size,
1189                                              GNUNET_TIME_UNIT_FOREVER_REL,
1190                                              GNUNET_YES, &send_callback, h);
1191   }
1192 }
1193
1194
1195 /**
1196  * Function to process all messages received from the service
1197  *
1198  * @param cls closure
1199  * @param msg message received, NULL on timeout or fatal error
1200  */
1201 static void
1202 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
1203 {
1204   struct GNUNET_MESH_Handle *h = cls;
1205
1206   if (msg == NULL)
1207   {
1208     LOG (GNUNET_ERROR_TYPE_WARNING, "Received NULL msg on %p\n", h);
1209     reconnect (h);
1210     return;
1211   }
1212   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n",
1213        GNUNET_MESH_DEBUG_M2S (ntohs (msg->type)));
1214   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a message: %s\n",
1215        GNUNET_MESH_DEBUG_M2S (ntohs (msg->type)));
1216   switch (ntohs (msg->type))
1217   {
1218     /* Notify of a new incoming tunnel */
1219   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE:
1220     process_tunnel_created (h, (struct GNUNET_MESH_TunnelNotification *) msg);
1221     break;
1222     /* Notify of a tunnel disconnection */
1223   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1224     process_tunnel_destroy (h, (struct GNUNET_MESH_TunnelMessage *) msg);
1225     break;
1226     /* Notify of a new peer or a peer disconnect in the tunnel */
1227   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD:
1228   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL:
1229     process_peer_event (h, (struct GNUNET_MESH_PeerControl *) msg);
1230     break;
1231     /* Notify of a new data packet in the tunnel */
1232   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1233   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1234   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1235     if (GNUNET_NO == process_incoming_data (h, msg))
1236       return;
1237     break;
1238   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
1239     process_ack (h, msg);
1240     break;
1241   default:
1242     /* We shouldn't get any other packages, log and ignore */
1243     LOG (GNUNET_ERROR_TYPE_WARNING,
1244          "unsolicited message form service (type %hu)\n",
1245          ntohs (msg->type));
1246   }
1247   LOG (GNUNET_ERROR_TYPE_DEBUG, "message processed\n");
1248   if (GNUNET_YES == h->in_receive)
1249   {
1250     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1251                            GNUNET_TIME_UNIT_FOREVER_REL);
1252   }
1253   else
1254   {
1255     LOG (GNUNET_ERROR_TYPE_DEBUG,
1256          "in receive off, not calling CLIENT_receive\n");
1257   }
1258 }
1259
1260
1261 /******************************************************************************/
1262 /************************       SEND FUNCTIONS     ****************************/
1263 /******************************************************************************/
1264
1265 /**
1266  * Function called to send a message to the service.
1267  * "buf" will be NULL and "size" zero if the socket was closed for writing in
1268  * the meantime.
1269  *
1270  * @param cls closure, the mesh handle
1271  * @param size number of bytes available in buf
1272  * @param buf where the callee should write the connect message
1273  * @return number of bytes written to buf
1274  */
1275 static size_t
1276 send_callback (void *cls, size_t size, void *buf)
1277 {
1278   struct GNUNET_MESH_Handle *h = cls;
1279   struct GNUNET_MESH_TransmitHandle *th;
1280   struct GNUNET_MESH_TransmitHandle *next;
1281   struct GNUNET_MESH_Tunnel *t;
1282   char *cbuf = buf;
1283   size_t tsize;
1284   size_t psize;
1285
1286   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1287   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send packet() Buffer %u\n", size);
1288   if ((0 == size) || (NULL == buf))
1289   {
1290     LOG (GNUNET_ERROR_TYPE_DEBUG, "Received NULL send callback on %p\n", h);
1291     reconnect (h);
1292     h->th = NULL;
1293     return 0;
1294   }
1295   tsize = 0;
1296   next = h->th_head;
1297   while ((NULL != (th = next)) && (size >= th->size))
1298   {
1299     t = th->tunnel;
1300     if (GNUNET_YES == th_is_payload (th))
1301     {
1302       LOG (GNUNET_ERROR_TYPE_DEBUG, " payload\n");
1303       if (t->max_send_pid < t->next_send_pid && GNUNET_NO == PID_OVERFLOW (t->next_send_pid, t->max_send_pid))
1304       {
1305         /* This tunnel is not ready to transmit yet, try next message */
1306         next = th->next;
1307         continue;
1308       }
1309       t->packet_size = 0;
1310       if (t->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1311       {
1312         /* traffic to origin */
1313         struct GNUNET_MESH_ToOrigin to;
1314         struct GNUNET_MessageHeader *mh;
1315
1316         GNUNET_assert (size >= th->size);
1317         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (to)];
1318         psize = th->notify (th->notify_cls, size - sizeof (to), mh);
1319         LOG (GNUNET_ERROR_TYPE_DEBUG, "  to origin, type %s\n",
1320              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1321         if (psize > 0)
1322         {
1323           psize += sizeof (to);
1324           GNUNET_assert (size >= psize);
1325           to.header.size = htons (psize);
1326           to.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
1327           to.tid = htonl (t->tid);
1328           to.pid = htonl (t->next_send_pid);
1329           memset (&to.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1330           memset (&to.sender, 0, sizeof (struct GNUNET_PeerIdentity));
1331           memcpy (cbuf, &to, sizeof (to));
1332         }
1333       }
1334       else if (th->target == 0)
1335       {
1336         /* multicast */
1337         struct GNUNET_MESH_Multicast mc;
1338         struct GNUNET_MessageHeader *mh;
1339
1340         GNUNET_assert (size >= th->size);
1341         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (mc)];
1342         psize = th->notify (th->notify_cls, size - sizeof (mc), mh);
1343         LOG (GNUNET_ERROR_TYPE_DEBUG, "  multicast, type %s\n",
1344              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1345         if (psize > 0)
1346         {
1347           psize += sizeof (mc);
1348           GNUNET_assert (size >= psize);
1349           mc.header.size = htons (psize);
1350           mc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1351           mc.tid = htonl (t->tid);
1352           mc.pid = htonl (t->next_send_pid);
1353           mc.ttl = 0;
1354           memset (&mc.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1355           memcpy (cbuf, &mc, sizeof (mc));
1356         }
1357       }
1358       else
1359       {
1360         /* unicast */
1361         struct GNUNET_MESH_Unicast uc;
1362         struct GNUNET_MessageHeader *mh;
1363
1364         GNUNET_assert (size >= th->size);
1365         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (uc)];
1366         psize = th->notify (th->notify_cls, size - sizeof (uc), mh);
1367         LOG (GNUNET_ERROR_TYPE_DEBUG, "  unicast, type %s\n",
1368              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1369         if (psize > 0)
1370         {
1371           psize += sizeof (uc);
1372           GNUNET_assert (size >= psize);
1373           uc.header.size = htons (psize);
1374           uc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1375           uc.tid = htonl (t->tid);
1376           uc.pid = htonl (t->next_send_pid);
1377           memset (&uc.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1378           GNUNET_PEER_resolve (th->target, &uc.destination);
1379           memcpy (cbuf, &uc, sizeof (uc));
1380         }
1381       }
1382       t->next_send_pid++;
1383     }
1384     else
1385     {
1386       struct GNUNET_MessageHeader *mh = (struct GNUNET_MessageHeader *) &th[1];
1387
1388       LOG (GNUNET_ERROR_TYPE_DEBUG, "  mesh traffic, type %s\n",
1389              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1390       memcpy (cbuf, &th[1], th->size);
1391       psize = th->size;
1392     }
1393     if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1394       GNUNET_SCHEDULER_cancel (th->timeout_task);
1395     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1396     GNUNET_free (th);
1397     next = h->th_head;
1398     cbuf += psize;
1399     size -= psize;
1400     tsize += psize;
1401   }
1402   LOG (GNUNET_ERROR_TYPE_DEBUG, "  total size: %u\n", tsize);
1403   h->th = NULL;
1404   size = message_ready_size (h);
1405   if (0 != size)
1406   {
1407     LOG (GNUNET_ERROR_TYPE_DEBUG, "  next size: %u\n", size);
1408     h->th =
1409         GNUNET_CLIENT_notify_transmit_ready (h->client, size,
1410                                              GNUNET_TIME_UNIT_FOREVER_REL,
1411                                              GNUNET_YES, &send_callback, h);
1412   }
1413   else
1414   {
1415     LOG (GNUNET_ERROR_TYPE_DEBUG, "  nothing left to transmit\n");
1416   }
1417   if (GNUNET_NO == h->in_receive)
1418   {
1419     LOG (GNUNET_ERROR_TYPE_DEBUG, " start receiving from service\n");
1420     h->in_receive = GNUNET_YES;
1421     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1422                            GNUNET_TIME_UNIT_FOREVER_REL);
1423   }
1424   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send packet() END\n");
1425   return tsize;
1426 }
1427
1428
1429 /**
1430  * Auxiliary function to send an already constructed packet to the service.
1431  * Takes care of creating a new queue element, copying the message and
1432  * calling the tmt_rdy function if necessary.
1433  * 
1434  * @param h mesh handle
1435  * @param msg message to transmit
1436  * @param tunnel tunnel this send is related to (NULL if N/A)
1437  */
1438 static void
1439 send_packet (struct GNUNET_MESH_Handle *h,
1440              const struct GNUNET_MessageHeader *msg,
1441              struct GNUNET_MESH_Tunnel *tunnel)
1442 {
1443   struct GNUNET_MESH_TransmitHandle *th;
1444   size_t msize;
1445
1446   msize = ntohs (msg->size);
1447   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle) + msize);
1448   th->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1449   th->size = msize;
1450   th->tunnel = tunnel;
1451   memcpy (&th[1], msg, msize);
1452   add_to_queue (h, th);
1453   if (NULL != h->th)
1454     return;
1455   h->th =
1456       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
1457                                            GNUNET_TIME_UNIT_FOREVER_REL,
1458                                            GNUNET_YES, &send_callback, h);
1459 }
1460
1461
1462 /******************************************************************************/
1463 /**********************      API CALL DEFINITIONS     *************************/
1464 /******************************************************************************/
1465
1466 /**
1467  * Connect to the mesh service.
1468  *
1469  * @param cfg configuration to use
1470  * @param cls closure for the various callbacks that follow
1471  *            (including handlers in the handlers array)
1472  * @param new_tunnel function called when an *inbound* tunnel is created
1473  * @param cleaner function called when an *inbound* tunnel is destroyed by the
1474  *                remote peer, it is *not* called if GNUNET_MESH_tunnel_destroy
1475  *                is called on the tunnel
1476  * @param handlers callbacks for messages we care about, NULL-terminated
1477  *                note that the mesh is allowed to drop notifications about
1478  *                inbound messages if the client does not process them fast
1479  *                enough (for this notification type, a bounded queue is used)
1480  * @param stypes list of the applications that this client claims to provide
1481  * @return handle to the mesh service NULL on error
1482  *         (in this case, init is never called)
1483  */
1484 struct GNUNET_MESH_Handle *
1485 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, void *cls,
1486                      GNUNET_MESH_InboundTunnelNotificationHandler new_tunnel,
1487                      GNUNET_MESH_TunnelEndHandler cleaner,
1488                      const struct GNUNET_MESH_MessageHandler *handlers,
1489                      const GNUNET_MESH_ApplicationType *stypes)
1490 {
1491   struct GNUNET_MESH_Handle *h;
1492
1493   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect()\n");
1494   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
1495   LOG (GNUNET_ERROR_TYPE_DEBUG, " addr %p\n", h);
1496   h->cfg = cfg;
1497   h->new_tunnel = new_tunnel;
1498   h->cleaner = cleaner;
1499   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
1500   if (h->client == NULL)
1501   {
1502     GNUNET_break (0);
1503     GNUNET_free (h);
1504     return NULL;
1505   }
1506   h->cls = cls;
1507   /* FIXME memdup? */
1508   h->applications = stypes;
1509   h->message_handlers = handlers;
1510   h->next_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
1511   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1512   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1513
1514   /* count handlers and apps, calculate size */
1515   for (h->n_applications = 0; stypes[h->n_applications]; h->n_applications++) ;
1516   for (h->n_handlers = 0; handlers[h->n_handlers].type; h->n_handlers++) ;
1517   send_connect (h);
1518   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect() END\n");
1519   return h;
1520 }
1521
1522
1523 /**
1524  * Disconnect from the mesh service. All tunnels will be destroyed. All tunnel
1525  * disconnect callbacks will be called on any still connected peers, notifying
1526  * about their disconnection. The registered inbound tunnel cleaner will be
1527  * called should any inbound tunnels still exist.
1528  *
1529  * @param handle connection to mesh to disconnect
1530  */
1531 void
1532 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
1533 {
1534   struct GNUNET_MESH_Tunnel *t;
1535   struct GNUNET_MESH_Tunnel *aux;
1536   struct GNUNET_MESH_TransmitHandle *th;
1537
1538   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH DISCONNECT\n");
1539
1540   t = handle->tunnels_head;
1541   while (NULL != t)
1542   {
1543     aux = t->next;
1544     if (t->tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1545     {
1546       GNUNET_break (0);
1547       LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X not destroyed\n", t->tid);
1548     }
1549     destroy_tunnel (t, GNUNET_YES);
1550     t = aux;
1551   }
1552   while ( (th = handle->th_head) != NULL)
1553   {
1554     struct GNUNET_MessageHeader *msg;
1555
1556     /* Make sure it is an allowed packet (everything else should have been
1557      * already canceled).
1558      */
1559     GNUNET_break (GNUNET_NO == th_is_payload (th));
1560     msg = (struct GNUNET_MessageHeader *) &th[1];
1561     switch (ntohs(msg->type))
1562     {
1563       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT:
1564       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1565         break;
1566       default:
1567         GNUNET_break (0);
1568         LOG (GNUNET_ERROR_TYPE_DEBUG, "unexpected msg %u\n",
1569              ntohs(msg->type));
1570     }
1571
1572     GNUNET_CONTAINER_DLL_remove (handle->th_head, handle->th_tail, th);
1573     GNUNET_free (th);
1574   }
1575
1576   if (NULL != handle->th)
1577   {
1578     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
1579     handle->th = NULL;
1580   }
1581   if (NULL != handle->client)
1582   {
1583     GNUNET_CLIENT_disconnect (handle->client);
1584     handle->client = NULL;
1585   }
1586   if (GNUNET_SCHEDULER_NO_TASK != handle->reconnect_task)
1587   {
1588     GNUNET_SCHEDULER_cancel(handle->reconnect_task);
1589     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1590   }
1591   GNUNET_free (handle);
1592 }
1593
1594
1595 /**
1596  * Announce to ther peer the availability of services described by the regex,
1597  * in order to be reachable to other peers via connect_by_string.
1598  * 
1599  * Note that the first 8 characters are considered to be part of a prefix,
1600  * (for instance 'gnunet://'). If you put a variable part in there (*, +. ()),
1601  * all matching strings will be stored in the DHT.
1602  *
1603  * @param h handle to mesh.
1604  * @param regex string with the regular expression describing local services.
1605  */
1606 void
1607 GNUNET_MESH_announce_regex (struct GNUNET_MESH_Handle *h,
1608                             const char *regex)
1609 {
1610   struct GNUNET_MessageHeader *msg;
1611   size_t len;
1612   size_t msgsize;
1613
1614   len = strlen (regex);
1615   msgsize = sizeof(struct GNUNET_MessageHeader) + len;
1616   GNUNET_assert (UINT16_MAX > msgsize);
1617
1618   {
1619     char buffer[msgsize];
1620
1621     msg = (struct GNUNET_MessageHeader *) buffer;
1622     msg->size = htons (msgsize);
1623     msg->type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX);
1624     memcpy (&msg[1], regex, len);
1625
1626     send_packet(h, msg, NULL);
1627   }
1628 }
1629
1630 /**
1631  * Create a new tunnel (we're initiator and will be allowed to add/remove peers
1632  * and to broadcast).
1633  *
1634  * @param h mesh handle
1635  * @param tunnel_ctx client's tunnel context to associate with the tunnel
1636  * @param connect_handler function to call when peers are actually connected
1637  * @param disconnect_handler function to call when peers are disconnected
1638  * @param handler_cls closure for connect/disconnect handlers
1639  */
1640 struct GNUNET_MESH_Tunnel *
1641 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h, void *tunnel_ctx,
1642                            GNUNET_MESH_PeerConnectHandler connect_handler,
1643                            GNUNET_MESH_PeerDisconnectHandler disconnect_handler,
1644                            void *handler_cls)
1645 {
1646   struct GNUNET_MESH_Tunnel *t;
1647   struct GNUNET_MESH_TunnelMessage msg;
1648
1649   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating new tunnel\n");
1650   t = create_tunnel (h, 0);
1651   LOG (GNUNET_ERROR_TYPE_DEBUG, "  at %p\n", t);
1652   LOG (GNUNET_ERROR_TYPE_DEBUG, "  number %X\n", t->tid);
1653   t->connect_handler = connect_handler;
1654   t->disconnect_handler = disconnect_handler;
1655   t->cls = handler_cls;
1656   t->ctx = tunnel_ctx;
1657   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1658   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1659   msg.tunnel_id = htonl (t->tid);
1660   send_packet (h, &msg.header, t);
1661   return t;
1662 }
1663
1664
1665 /**
1666  * Destroy an existing tunnel. The existing callback for the tunnel will NOT
1667  * be called.
1668  *
1669  * @param tunnel tunnel handle
1670  */
1671 void
1672 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tunnel)
1673 {
1674   struct GNUNET_MESH_Handle *h;
1675   struct GNUNET_MESH_TunnelMessage msg;
1676   struct GNUNET_MESH_TransmitHandle *th;
1677
1678   LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying tunnel\n");
1679   h = tunnel->mesh;
1680
1681   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1682   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1683   msg.tunnel_id = htonl (tunnel->tid);
1684   th = h->th_head;
1685   while (th != NULL)
1686   {
1687     struct GNUNET_MESH_TransmitHandle *aux;
1688     if (th->tunnel == tunnel)
1689     {
1690       aux = th->next;
1691       /* FIXME call the handler? */
1692       if (GNUNET_YES == th_is_payload (th))
1693         th->notify (th->notify_cls, 0, NULL);
1694       GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1695       GNUNET_free (th);
1696       th = aux;
1697     }
1698     else
1699       th = th->next;
1700   }
1701
1702   destroy_tunnel (tunnel, GNUNET_NO);
1703   send_packet (h, &msg.header, NULL);
1704 }
1705
1706 /**
1707  * Request that the tunnel data rate is limited to the speed of the slowest
1708  * receiver.
1709  *
1710  * @param tunnel Tunnel affected.
1711  */
1712 void
1713 GNUNET_MESH_tunnel_speed_min (struct GNUNET_MESH_Tunnel *tunnel)
1714 {
1715   struct GNUNET_MESH_TunnelMessage msg;
1716   struct GNUNET_MESH_Handle *h;
1717
1718   h = tunnel->mesh;
1719   tunnel->speed_min = GNUNET_YES;
1720
1721   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN);
1722   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1723   msg.tunnel_id = htonl (tunnel->tid);
1724
1725   send_packet (h, &msg.header, NULL);
1726 }
1727
1728
1729 /**
1730  * Request that the tunnel data rate is limited to the speed of the fastest
1731  * receiver. This is the default behavior.
1732  *
1733  * @param tunnel Tunnel affected.
1734  */
1735 void
1736 GNUNET_MESH_tunnel_speed_max (struct GNUNET_MESH_Tunnel *tunnel)
1737 {
1738   struct GNUNET_MESH_TunnelMessage msg;
1739   struct GNUNET_MESH_Handle *h;
1740
1741   h = tunnel->mesh;
1742   tunnel->speed_min = GNUNET_NO;
1743
1744   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX);
1745   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1746   msg.tunnel_id = htonl (tunnel->tid);
1747
1748   send_packet (h, &msg.header, NULL);
1749 }
1750
1751 /**
1752  * Turn on/off the buffering status of the tunnel.
1753  * 
1754  * @param tunnel Tunnel affected.
1755  * @param buffer GNUNET_YES to turn buffering on (default),
1756  *               GNUNET_NO otherwise.
1757  */
1758 void
1759 GNUNET_MESH_tunnel_buffer (struct GNUNET_MESH_Tunnel *tunnel, int buffer)
1760 {
1761   struct GNUNET_MESH_TunnelMessage msg;
1762   struct GNUNET_MESH_Handle *h;
1763
1764   h = tunnel->mesh;
1765   tunnel->buffering = buffer;
1766
1767   if (GNUNET_YES == buffer)
1768     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER);
1769   else
1770     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER);
1771   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1772   msg.tunnel_id = htonl (tunnel->tid);
1773
1774   send_packet (h, &msg.header, NULL);
1775 }
1776
1777 /**
1778  * Request that a peer should be added to the tunnel.  The existing
1779  * connect handler will be called ONCE with either success or failure.
1780  * This function should NOT be called again with the same peer before the
1781  * connect handler is called.
1782  *
1783  * @param tunnel handle to existing tunnel
1784  * @param peer peer to add
1785  */
1786 void
1787 GNUNET_MESH_peer_request_connect_add (struct GNUNET_MESH_Tunnel *tunnel,
1788                                       const struct GNUNET_PeerIdentity *peer)
1789 {
1790   struct GNUNET_MESH_PeerControl msg;
1791   GNUNET_PEER_Id peer_id;
1792   unsigned int i;
1793
1794   peer_id = GNUNET_PEER_intern (peer);
1795   for (i = 0; i < tunnel->npeers; i++)
1796   {
1797     if (tunnel->peers[i]->id == peer_id)
1798     {
1799       /* Peer already exists in tunnel */
1800       GNUNET_PEER_change_rc (peer_id, -1);
1801       GNUNET_break (0);
1802       return;
1803     }
1804   }
1805   if (NULL == add_peer_to_tunnel (tunnel, peer))
1806     return;
1807
1808   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1809   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1810   msg.tunnel_id = htonl (tunnel->tid);
1811   msg.peer = *peer;
1812   send_packet (tunnel->mesh, &msg.header, tunnel);
1813
1814   return;
1815 }
1816
1817
1818 /**
1819  * Request that a peer should be removed from the tunnel.  The existing
1820  * disconnect handler will be called ONCE if we were connected.
1821  *
1822  * @param tunnel handle to existing tunnel
1823  * @param peer peer to remove
1824  */
1825 void
1826 GNUNET_MESH_peer_request_connect_del (struct GNUNET_MESH_Tunnel *tunnel,
1827                                       const struct GNUNET_PeerIdentity *peer)
1828 {
1829   struct GNUNET_MESH_PeerControl msg;
1830   GNUNET_PEER_Id peer_id;
1831   unsigned int i;
1832
1833   peer_id = GNUNET_PEER_search (peer);
1834   if (0 == peer_id)
1835   {
1836     GNUNET_break (0);
1837     return;
1838   }
1839   for (i = 0; i < tunnel->npeers; i++)
1840     if (tunnel->peers[i]->id == peer_id)
1841       break;
1842   if (i == tunnel->npeers)
1843   {
1844     GNUNET_break (0);
1845     return;
1846   }
1847   if (NULL != tunnel->disconnect_handler && tunnel->peers[i]->connected == 1)
1848     tunnel->disconnect_handler (tunnel->cls, peer);
1849   GNUNET_PEER_change_rc (peer_id, -1);
1850   GNUNET_free (tunnel->peers[i]);
1851   tunnel->peers[i] = tunnel->peers[tunnel->npeers - 1];
1852   GNUNET_array_grow (tunnel->peers, tunnel->npeers, tunnel->npeers - 1);
1853
1854   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1855   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1856   msg.tunnel_id = htonl (tunnel->tid);
1857   memcpy (&msg.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1858   send_packet (tunnel->mesh, &msg.header, tunnel);
1859 }
1860
1861
1862 /**
1863  * Request that the mesh should try to connect to a peer supporting the given
1864  * message type.
1865  *
1866  * @param tunnel handle to existing tunnel
1867  * @param app_type application type that must be supported by the peer (MESH
1868  *                 should discover peer in proximity handling this type)
1869  */
1870 void
1871 GNUNET_MESH_peer_request_connect_by_type (struct GNUNET_MESH_Tunnel *tunnel,
1872                                           GNUNET_MESH_ApplicationType app_type)
1873 {
1874   struct GNUNET_MESH_ConnectPeerByType msg;
1875
1876   GNUNET_array_append (tunnel->apps, tunnel->napps, app_type);
1877
1878   LOG (GNUNET_ERROR_TYPE_DEBUG, "* CONNECT BY TYPE *\n");
1879   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
1880   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE);
1881   msg.tunnel_id = htonl (tunnel->tid);
1882   msg.type = htonl (app_type);
1883   send_packet (tunnel->mesh, &msg.header, tunnel);
1884 }
1885
1886
1887 /**
1888  * Request that the mesh should try to connect to a peer matching the
1889  * description given in the service string.
1890  * 
1891  * FIXME: allow multiple? how to deal with reconnect?
1892  *
1893  * @param tunnel handle to existing tunnel
1894  * @param description string describing the destination node requirements
1895  */
1896 void
1897 GNUNET_MESH_peer_request_connect_by_string (struct GNUNET_MESH_Tunnel *tunnel,
1898                                             const char *description)
1899 {
1900   struct GNUNET_MESH_ConnectPeerByString *m;
1901   size_t len;
1902   size_t msgsize;
1903
1904   len = strlen (description);
1905   msgsize = sizeof(struct GNUNET_MESH_ConnectPeerByString) + len;
1906   GNUNET_assert (UINT16_MAX > msgsize);
1907   {
1908     char buffer[msgsize];
1909
1910     m = (struct GNUNET_MESH_ConnectPeerByString *) buffer;
1911     m->header.size = htons (msgsize);
1912     m->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING);
1913     m->tunnel_id = htonl (tunnel->tid);
1914     memcpy(&m[1], description, len);
1915
1916     send_packet (tunnel->mesh, &m->header, tunnel);
1917   }
1918 }
1919
1920
1921 /**
1922  * Request that the given peer isn't added to this tunnel in calls to
1923  * connect_by_* calls, (due to misbehaviour, bad performance, ...).
1924  *
1925  * @param tunnel handle to existing tunnel.
1926  * @param peer peer identity of the peer which should be blacklisted
1927  *                  for the tunnel.
1928  */
1929 void
1930 GNUNET_MESH_peer_blacklist (struct GNUNET_MESH_Tunnel *tunnel,
1931                             const struct GNUNET_PeerIdentity *peer)
1932 {
1933   struct GNUNET_MESH_PeerControl msg;
1934
1935   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1936   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST);
1937   msg.tunnel_id = htonl (tunnel->tid);
1938   msg.peer = *peer;
1939   send_packet (tunnel->mesh, &msg.header, tunnel);
1940
1941   return;
1942 }
1943
1944
1945 /**
1946  * Request that the given peer isn't blacklisted anymore from this tunnel,
1947  * and therefore can be added in future calls to connect_by_*.
1948  * The peer must have been previously blacklisted for this tunnel.
1949  *
1950  * @param tunnel handle to existing tunnel.
1951  * @param peer peer identity of the peer which shouldn't be blacklisted
1952  *                  for the tunnel anymore.
1953  */
1954 void
1955 GNUNET_MESH_peer_unblacklist (struct GNUNET_MESH_Tunnel *tunnel,
1956                               const struct GNUNET_PeerIdentity *peer)
1957 {
1958   struct GNUNET_MESH_PeerControl msg;
1959
1960   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1961   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST);
1962   msg.tunnel_id = htonl (tunnel->tid);
1963   msg.peer = *peer;
1964   send_packet (tunnel->mesh, &msg.header, tunnel);
1965
1966   return;
1967 }
1968
1969
1970 /**
1971  * Ask the mesh to call "notify" once it is ready to transmit the
1972  * given number of bytes to the specified tunnel or target.
1973  * Only one call can be active at any time, to issue another request,
1974  * wait for the callback or cancel the current request.
1975  *
1976  * @param tunnel tunnel to use for transmission
1977  * @param cork is corking allowed for this transmission?
1978  * @param maxdelay how long can the message wait?
1979  * @param target destination for the message
1980  *               NULL for multicast to all tunnel targets
1981  * @param notify_size how many bytes of buffer space does notify want?
1982  * @param notify function to call when buffer space is available;
1983  *        will be called with NULL on timeout or if the overall queue
1984  *        for this peer is larger than queue_size and this is currently
1985  *        the message with the lowest priority
1986  * @param notify_cls closure for notify
1987  * @return non-NULL if the notify callback was queued,
1988  *         NULL if we can not even queue the request (insufficient
1989  *         memory); if NULL is returned, "notify" will NOT be called.
1990  */
1991 struct GNUNET_MESH_TransmitHandle *
1992 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
1993                                    struct GNUNET_TIME_Relative maxdelay,
1994                                    const struct GNUNET_PeerIdentity *target,
1995                                    size_t notify_size,
1996                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1997                                    void *notify_cls)
1998 {
1999   struct GNUNET_MESH_TransmitHandle *th;
2000   size_t overhead;
2001
2002   GNUNET_assert (NULL != tunnel);
2003   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH NOTIFY TRANSMIT READY\n");
2004   LOG (GNUNET_ERROR_TYPE_DEBUG, "    on tunnel %X\n", tunnel->tid);
2005   if (tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2006     LOG (GNUNET_ERROR_TYPE_DEBUG, "    to origin\n");
2007   else if (NULL != target)
2008     LOG (GNUNET_ERROR_TYPE_DEBUG, "    target %s\n", GNUNET_i2s (target));
2009   else
2010     LOG (GNUNET_ERROR_TYPE_DEBUG, "    target multicast\n");
2011   LOG (GNUNET_ERROR_TYPE_DEBUG, "    payload size %u\n", notify_size);
2012   GNUNET_assert (NULL != notify);
2013   GNUNET_assert (0 == tunnel->packet_size); // Only one data packet allowed
2014   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
2015   th->tunnel = tunnel;
2016   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
2017   th->target = GNUNET_PEER_intern (target);
2018   if (tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2019     overhead = sizeof (struct GNUNET_MESH_ToOrigin);
2020   else if (NULL == target)
2021     overhead = sizeof (struct GNUNET_MESH_Multicast);
2022   else
2023     overhead = sizeof (struct GNUNET_MESH_Unicast);
2024   tunnel->packet_size = th->size = notify_size + overhead;
2025   LOG (GNUNET_ERROR_TYPE_DEBUG, "    total size %u\n", th->size);
2026   th->notify = notify;
2027   th->notify_cls = notify_cls;
2028   add_to_queue (tunnel->mesh, th);
2029   if (NULL != tunnel->mesh->th)
2030     return th;
2031   if (GNUNET_NO == PID_OVERFLOW(tunnel->next_send_pid, tunnel->max_send_pid) &&
2032       tunnel->max_send_pid <= tunnel->next_send_pid)
2033     return th;
2034   LOG (GNUNET_ERROR_TYPE_DEBUG, "    call notify tmt rdy\n");
2035   tunnel->mesh->th =
2036       GNUNET_CLIENT_notify_transmit_ready (tunnel->mesh->client, th->size,
2037                                            GNUNET_TIME_UNIT_FOREVER_REL,
2038                                            GNUNET_YES, &send_callback,
2039                                            tunnel->mesh);
2040   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH NOTIFY TRANSMIT READY END\n");
2041   return th;
2042 }
2043
2044
2045 /**
2046  * Cancel the specified transmission-ready notification.
2047  *
2048  * @param th handle that was returned by "notify_transmit_ready".
2049  */
2050 void
2051 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
2052 {
2053   struct GNUNET_MESH_Handle *mesh;
2054
2055   th->tunnel->packet_size = 0;
2056   mesh = th->tunnel->mesh;
2057   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2058     GNUNET_SCHEDULER_cancel (th->timeout_task);
2059   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
2060   GNUNET_free (th);
2061   if ((0 == message_ready_size (mesh)) && (NULL != mesh->th))
2062   {
2063     /* queue empty, no point in asking for transmission */
2064     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
2065     mesh->th = NULL;
2066   }
2067 }
2068
2069
2070 /**
2071  * Transition API for tunnel ctx management
2072  */
2073 void
2074 GNUNET_MESH_tunnel_set_data (struct GNUNET_MESH_Tunnel *tunnel, void *data)
2075 {
2076   tunnel->ctx = data;
2077 }
2078
2079 /**
2080  * Transition API for tunnel ctx management
2081  */
2082 void *
2083 GNUNET_MESH_tunnel_get_data (struct GNUNET_MESH_Tunnel *tunnel)
2084 {
2085   return tunnel->ctx;
2086 }
2087
2088