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