- disable debug by default
[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 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   GNUNET_CONTAINER_DLL_insert_tail (h->th_head, h->th_tail, th);
667   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value == th->timeout.abs_value)
668     return;
669   th->timeout_task =
670       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
671                                     (th->timeout), &timeout_transmission, th);
672 }
673
674
675 /**
676  * Auxiliary function to send an already constructed packet to the service.
677  * Takes care of creating a new queue element, copying the message and
678  * calling the tmt_rdy function if necessary.
679  *
680  * @param h mesh handle
681  * @param msg message to transmit
682  * @param tunnel tunnel this send is related to (NULL if N/A)
683  */
684 static void
685 send_packet (struct GNUNET_MESH_Handle *h,
686              const struct GNUNET_MessageHeader *msg,
687              struct GNUNET_MESH_Tunnel *tunnel);
688
689
690 /**
691  * Send an ack on the tunnel to confirm the processing of a message.
692  * 
693  * @param h Mesh handle.
694  * @param t Tunnel on which to send the ACK.
695  */
696 static void
697 send_ack (struct GNUNET_MESH_Handle *h, struct GNUNET_MESH_Tunnel *t)
698 {
699   struct GNUNET_MESH_LocalAck msg;
700   uint32_t delta;
701
702   delta = t->max_recv_pid - t->last_recv_pid;
703   if (delta > ACK_THRESHOLD)
704   {
705     LOG (GNUNET_ERROR_TYPE_DEBUG,
706          "Not sending ACK on tunnel %X: ACK: %u, PID: %u, buffer %u\n",
707          t->tid, t->max_recv_pid, t->last_recv_pid, delta);
708     return;
709   }
710   t->max_recv_pid = t->last_recv_pid + INITIAL_WINDOW_SIZE;
711   LOG (GNUNET_ERROR_TYPE_DEBUG,
712        "Sending ACK on tunnel %X: %u\n",
713        t->tid, t->max_recv_pid);
714   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
715   msg.header.size = htons (sizeof (msg));
716   msg.tunnel_id = htonl (t->tid);
717   msg.max_pid = htonl (t->max_recv_pid);
718
719 #if DEBUG_ACK
720   t->mesh->acks_sent++;
721 #endif
722
723   send_packet (h, &msg.header, t);
724   return;
725 }
726
727
728
729 /**
730  * Reconnect callback: tries to reconnect again after a failer previous
731  * reconnecttion
732  * @param cls closure (mesh handle)
733  * @param tc task context
734  */
735 static void
736 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
737
738
739 /**
740  * Send a connect packet to the service with the applications and types
741  * requested by the user.
742  *
743  * @param h The mesh handle.
744  *
745  */
746 static void
747 send_connect (struct GNUNET_MESH_Handle *h)
748 {
749   size_t size;
750
751   size = sizeof (struct GNUNET_MESH_ClientConnect);
752   size += h->n_applications * sizeof (GNUNET_MESH_ApplicationType);
753   size += h->n_handlers * sizeof (uint16_t);
754   {
755     char buf[size] GNUNET_ALIGN;
756     struct GNUNET_MESH_ClientConnect *msg;
757     GNUNET_MESH_ApplicationType *apps;
758     uint16_t napps;
759     uint16_t *types;
760     uint16_t ntypes;
761
762     /* build connection packet */
763     msg = (struct GNUNET_MESH_ClientConnect *) buf;
764     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT);
765     msg->header.size = htons (size);
766     apps = (GNUNET_MESH_ApplicationType *) &msg[1];
767     for (napps = 0; napps < h->n_applications; napps++)
768     {
769       apps[napps] = htonl (h->applications[napps]);
770       LOG (GNUNET_ERROR_TYPE_DEBUG, " app %u\n",
771            h->applications[napps]);
772     }
773     types = (uint16_t *) & apps[napps];
774     for (ntypes = 0; ntypes < h->n_handlers; ntypes++)
775     {
776       types[ntypes] = htons (h->message_handlers[ntypes].type);
777       LOG (GNUNET_ERROR_TYPE_DEBUG, " type %u\n",
778            h->message_handlers[ntypes].type);
779     }
780     msg->applications = htons (napps);
781     msg->types = htons (ntypes);
782     LOG (GNUNET_ERROR_TYPE_DEBUG,
783          "Sending %lu bytes long message %d types and %d apps\n",
784          ntohs (msg->header.size), ntypes, napps);
785     send_packet (h, &msg->header, NULL);
786   }
787 }
788
789
790 /**
791  * Reconnect to the service, retransmit all infomation to try to restore the
792  * original state.
793  *
794  * @param h handle to the mesh
795  *
796  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
797  */
798 static int
799 do_reconnect (struct GNUNET_MESH_Handle *h)
800 {
801   struct GNUNET_MESH_Tunnel *t;
802   unsigned int i;
803
804   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
805   LOG (GNUNET_ERROR_TYPE_DEBUG, "*******   RECONNECT   *******\n");
806   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
807   LOG (GNUNET_ERROR_TYPE_DEBUG, "******** on %p *******\n", h);
808   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
809
810   /* disconnect */
811   if (NULL != h->th)
812   {
813     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
814     h->th = NULL;
815   }
816   if (NULL != h->client)
817   {
818     GNUNET_CLIENT_disconnect (h->client);
819   }
820
821   /* connect again */
822   h->client = GNUNET_CLIENT_connect ("mesh", h->cfg);
823   if (h->client == NULL)
824   {
825     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
826                                                       &reconnect_cbk, h);
827     h->reconnect_time =
828         GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
829                                   GNUNET_TIME_relative_multiply
830                                   (h->reconnect_time, 2));
831     LOG (GNUNET_ERROR_TYPE_DEBUG, 
832          "Next retry in %s\n",
833          GNUNET_STRINGS_relative_time_to_string (h->reconnect_time,
834                                                  GNUNET_NO));
835     GNUNET_break (0);
836     return GNUNET_NO;
837   }
838   else
839   {
840     h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
841   }
842   send_connect (h);
843   /* Rebuild all tunnels */
844   for (t = h->tunnels_head; NULL != t; t = t->next)
845   {
846     struct GNUNET_MESH_TunnelMessage tmsg;
847     struct GNUNET_MESH_PeerControl pmsg;
848
849     if (t->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
850     {
851       /* Tunnel was created by service (incoming tunnel) */
852       /* TODO: Notify service of missing tunnel, to request
853        * creator to recreate path (find a path to him via DHT?)
854        */
855       continue;
856     }
857     t->next_send_pid = 0;
858     t->max_send_pid = INITIAL_WINDOW_SIZE - 1;
859     t->last_recv_pid = (uint32_t) -1;
860     tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
861     tmsg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
862     tmsg.tunnel_id = htonl (t->tid);
863     send_packet (h, &tmsg.header, t);
864
865     pmsg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
866     pmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
867     pmsg.tunnel_id = htonl (t->tid);
868
869     /* Reconnect all peers */
870     /* If the tunnel was "by type", dont connect individual peers */
871     for (i = 0; i < t->npeers && 0 == t->napps; i++)
872     {
873       GNUNET_PEER_resolve (t->peers[i]->id, &pmsg.peer);
874       if (NULL != t->disconnect_handler && t->peers[i]->connected)
875         t->disconnect_handler (t->cls, &pmsg.peer);
876       send_packet (t->mesh, &pmsg.header, t);
877     }
878     /* Reconnect all types, if any  */
879     for (i = 0; i < t->napps; i++)
880     {
881       struct GNUNET_MESH_ConnectPeerByType msg;
882
883       msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
884       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE);
885       msg.tunnel_id = htonl (t->tid);
886       msg.type = htonl (t->apps[i]);
887       send_packet (t->mesh, &msg.header, t);
888     }
889     if (GNUNET_NO == t->buffering)
890       GNUNET_MESH_tunnel_buffer (t, GNUNET_NO);
891     if (GNUNET_YES == t->speed_min)
892       GNUNET_MESH_tunnel_speed_min (t);
893   }
894   return GNUNET_YES;
895 }
896
897 /**
898  * Reconnect callback: tries to reconnect again after a failer previous
899  * reconnecttion
900  * @param cls closure (mesh handle)
901  * @param tc task context
902  */
903 static void
904 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
905 {
906   struct GNUNET_MESH_Handle *h = cls;
907
908   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
909   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
910     return;
911   do_reconnect (h);
912 }
913
914
915 /**
916  * Reconnect to the service, retransmit all infomation to try to restore the
917  * original state.
918  *
919  * @param h handle to the mesh
920  *
921  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
922  */
923 static void
924 reconnect (struct GNUNET_MESH_Handle *h)
925 {
926   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requested RECONNECT\n");
927   h->in_receive = GNUNET_NO;
928   if (GNUNET_SCHEDULER_NO_TASK == h->reconnect_task)
929     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
930                                                       &reconnect_cbk, h);
931 }
932
933
934 /******************************************************************************/
935 /***********************      RECEIVE HANDLERS     ****************************/
936 /******************************************************************************/
937
938 /**
939  * Process the new tunnel notification and add it to the tunnels in the handle
940  *
941  * @param h     The mesh handle
942  * @param msg   A message with the details of the new incoming tunnel
943  */
944 static void
945 process_tunnel_created (struct GNUNET_MESH_Handle *h,
946                         const struct GNUNET_MESH_TunnelNotification *msg)
947 {
948   struct GNUNET_MESH_Tunnel *t;
949   MESH_TunnelNumber tid;
950
951   tid = ntohl (msg->tunnel_id);
952   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating incoming tunnel %X\n", tid);
953   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
954   {
955     GNUNET_break (0);
956     return;
957   }
958   if (NULL != h->new_tunnel)
959   {
960     struct GNUNET_ATS_Information atsi;
961
962     t = create_tunnel (h, tid);
963     t->owner = GNUNET_PEER_intern (&msg->peer);
964     t->npeers = 1;
965     t->peers = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer *));
966     t->peers[0] = GNUNET_malloc (sizeof (struct GNUNET_MESH_Peer));
967     t->peers[0]->t = t;
968     t->peers[0]->connected = 1;
969     t->peers[0]->id = t->owner;
970     GNUNET_PEER_change_rc (t->owner, 1);
971     t->mesh = h;
972     t->tid = tid;
973     atsi.type = 0;
974     atsi.value = 0;
975     LOG (GNUNET_ERROR_TYPE_DEBUG, "  created tunnel %p\n", t);
976     t->ctx = h->new_tunnel (h->cls, t, &msg->peer, &atsi);
977     LOG (GNUNET_ERROR_TYPE_DEBUG, "User notified\n");
978   }
979   else
980   {
981     struct GNUNET_MESH_TunnelMessage d_msg;
982
983     LOG (GNUNET_ERROR_TYPE_DEBUG, "No handler for incoming tunnels\n");
984
985     d_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
986     d_msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
987     d_msg.tunnel_id = msg->tunnel_id;
988
989     send_packet (h, &d_msg.header, NULL);
990   }
991   return;
992 }
993
994
995 /**
996  * Process the tunnel destroy notification and free associated resources
997  *
998  * @param h     The mesh handle
999  * @param msg   A message with the details of the tunnel being destroyed
1000  */
1001 static void
1002 process_tunnel_destroy (struct GNUNET_MESH_Handle *h,
1003                         const struct GNUNET_MESH_TunnelMessage *msg)
1004 {
1005   struct GNUNET_MESH_Tunnel *t;
1006   MESH_TunnelNumber tid;
1007
1008   tid = ntohl (msg->tunnel_id);
1009   t = retrieve_tunnel (h, tid);
1010
1011   if (NULL == t)
1012   {
1013     return;
1014   }
1015   if (0 == t->owner)
1016   {
1017     GNUNET_break (0);
1018   }
1019   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X destroyed\n", t->tid);
1020   destroy_tunnel (t, GNUNET_YES);
1021   return;
1022 }
1023
1024
1025 /**
1026  * Process the new peer event and notify the upper level of it
1027  *
1028  * @param h     The mesh handle
1029  * @param msg   A message with the details of the peer event
1030  */
1031 static void
1032 process_peer_event (struct GNUNET_MESH_Handle *h,
1033                     const struct GNUNET_MESH_PeerControl *msg)
1034 {
1035   struct GNUNET_MESH_Tunnel *t;
1036   struct GNUNET_MESH_Peer *p;
1037   struct GNUNET_ATS_Information atsi;
1038   GNUNET_PEER_Id id;
1039   uint16_t size;
1040
1041   LOG (GNUNET_ERROR_TYPE_DEBUG, "processig peer event\n");
1042   size = ntohs (msg->header.size);
1043   if (size != sizeof (struct GNUNET_MESH_PeerControl))
1044   {
1045     GNUNET_break (0);
1046     return;
1047   }
1048   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
1049   if (NULL == t)
1050   {
1051     GNUNET_break (0);
1052     return;
1053   }
1054   id = GNUNET_PEER_search (&msg->peer);
1055   if ((p = retrieve_peer (t, id)) == NULL)
1056     p = add_peer_to_tunnel (t, &msg->peer);
1057   if (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD == ntohs (msg->header.type))
1058   {
1059     LOG (GNUNET_ERROR_TYPE_DEBUG, "adding peer\n");
1060     if (NULL != t->connect_handler)
1061     {
1062       atsi.type = 0;
1063       atsi.value = 0;
1064       t->connect_handler (t->cls, &msg->peer, &atsi);
1065     }
1066     p->connected = 1;
1067   }
1068   else
1069   {
1070     LOG (GNUNET_ERROR_TYPE_DEBUG, "removing peer\n");
1071     if (NULL != t->disconnect_handler && p->connected)
1072     {
1073       t->disconnect_handler (t->cls, &msg->peer);
1074     }
1075     remove_peer_from_tunnel (p);
1076     GNUNET_free (p);
1077   }
1078   LOG (GNUNET_ERROR_TYPE_DEBUG, "processing peer event END\n");
1079 }
1080
1081
1082 /**
1083  * Process the incoming data packets
1084  *
1085  * @param h         The mesh handle
1086  * @param message   A message encapsulating the data
1087  * 
1088  * @return GNUNET_YES if everything went fine
1089  *         GNUNET_NO if client closed connection (h no longer valid)
1090  */
1091 static int
1092 process_incoming_data (struct GNUNET_MESH_Handle *h,
1093                        const struct GNUNET_MessageHeader *message)
1094 {
1095   const struct GNUNET_MessageHeader *payload;
1096   const struct GNUNET_MESH_MessageHandler *handler;
1097   const struct GNUNET_PeerIdentity *peer;
1098   struct GNUNET_MESH_Unicast *ucast;
1099   struct GNUNET_MESH_Multicast *mcast;
1100   struct GNUNET_MESH_ToOrigin *to_orig;
1101   struct GNUNET_MESH_Tunnel *t;
1102   unsigned int i;
1103   uint32_t pid;
1104   uint16_t type;
1105
1106   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a data message!\n");
1107   type = ntohs (message->type);
1108   switch (type)
1109   {
1110   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1111     ucast = (struct GNUNET_MESH_Unicast *) message;
1112
1113     t = retrieve_tunnel (h, ntohl (ucast->tid));
1114     payload = (struct GNUNET_MessageHeader *) &ucast[1];
1115     peer = &ucast->oid;
1116     pid = ntohl (ucast->pid);
1117     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ucast on tunnel %s [%X]\n",
1118          GNUNET_i2s (peer), ntohl (ucast->tid));
1119     break;
1120   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1121     mcast = (struct GNUNET_MESH_Multicast *) message;
1122     t = retrieve_tunnel (h, ntohl (mcast->tid));
1123     payload = (struct GNUNET_MessageHeader *) &mcast[1];
1124     peer = &mcast->oid;
1125     pid = ntohl (mcast->pid);
1126     LOG (GNUNET_ERROR_TYPE_DEBUG, "  mcast on tunnel %s [%X]\n",
1127          GNUNET_i2s (peer), ntohl (mcast->tid));
1128     break;
1129   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1130     to_orig = (struct GNUNET_MESH_ToOrigin *) message;
1131     t = retrieve_tunnel (h, ntohl (to_orig->tid));
1132     payload = (struct GNUNET_MessageHeader *) &to_orig[1];
1133     peer = &to_orig->sender;
1134     pid = ntohl (to_orig->pid);
1135     LOG (GNUNET_ERROR_TYPE_DEBUG, "  torig on tunnel %s [%X]\n",
1136          GNUNET_i2s (peer), ntohl (to_orig->tid));
1137     break;
1138   default:
1139     GNUNET_break (0);
1140     return GNUNET_YES;
1141   }
1142   LOG (GNUNET_ERROR_TYPE_DEBUG, "  pid %u\n", pid);
1143   if (NULL == t)
1144   {
1145     /* Tunnel was ignored, probably service didn't get it yet */
1146     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ignored!\n");
1147     return GNUNET_YES;
1148   }
1149     if (GNUNET_YES ==
1150         GMC_is_pid_bigger(pid, t->max_recv_pid))
1151   {
1152     GNUNET_break (0);
1153     LOG (GNUNET_ERROR_TYPE_WARNING, "  unauthorized message!\n");
1154     // FIXME fc what now? accept? reject?
1155     return GNUNET_YES;
1156   }
1157   t->last_recv_pid = pid;
1158   type = ntohs (payload->type);
1159   send_ack (h, t);
1160   for (i = 0; i < h->n_handlers; i++)
1161   {
1162     handler = &h->message_handlers[i];
1163     if (handler->type == type)
1164     {
1165       struct GNUNET_ATS_Information atsi;
1166
1167       atsi.type = 0;
1168       atsi.value = 0;
1169       if (GNUNET_OK !=
1170           handler->callback (h->cls, t, &t->ctx, peer, payload, &atsi))
1171       {
1172         LOG (GNUNET_ERROR_TYPE_DEBUG, "callback caused disconnection\n");
1173         GNUNET_MESH_disconnect (h);
1174         return GNUNET_NO;
1175       }
1176       else
1177       {
1178         LOG (GNUNET_ERROR_TYPE_DEBUG,
1179              "callback completed successfully\n");
1180       }
1181     }
1182   }
1183   return GNUNET_YES;
1184 }
1185
1186
1187 /**
1188  * Process a local ACK message, enabling the client to send
1189  * more data to the service.
1190  * 
1191  * @param h Mesh handle.
1192  * @param message Message itself.
1193  */
1194 static void
1195 process_ack (struct GNUNET_MESH_Handle *h,
1196              const struct GNUNET_MessageHeader *message)
1197 {
1198   struct GNUNET_MESH_LocalAck *msg;
1199   struct GNUNET_MESH_Tunnel *t;
1200   uint32_t ack;
1201
1202   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK!\n");
1203   h->acks_recv++;
1204   msg = (struct GNUNET_MESH_LocalAck *) message;
1205
1206   t = retrieve_tunnel (h, ntohl (msg->tunnel_id));
1207
1208   if (NULL == t)
1209   {
1210     LOG (GNUNET_ERROR_TYPE_WARNING,
1211          "ACK on unknown tunnel %X\n",
1212          ntohl (msg->tunnel_id));
1213     return;
1214   }
1215   ack = ntohl (msg->max_pid);
1216   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X, ack %u!\n", t->tid, ack);
1217   if (GNUNET_YES == GMC_is_pid_bigger(ack, t->max_send_pid))
1218     t->max_send_pid = ack;
1219   else
1220     return;
1221   if (NULL == h->th && 0 < t->packet_size)
1222   {
1223     LOG (GNUNET_ERROR_TYPE_DEBUG, "  tmt rdy was NULL, requesting!\n", t->tid, ack);
1224     h->th =
1225         GNUNET_CLIENT_notify_transmit_ready (h->client, t->packet_size,
1226                                              GNUNET_TIME_UNIT_FOREVER_REL,
1227                                              GNUNET_YES, &send_callback, h);
1228   }
1229 }
1230
1231
1232 /**
1233  * Function to process all messages received from the service
1234  *
1235  * @param cls closure
1236  * @param msg message received, NULL on timeout or fatal error
1237  */
1238 static void
1239 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
1240 {
1241   struct GNUNET_MESH_Handle *h = cls;
1242
1243   if (msg == NULL)
1244   {
1245     LOG (GNUNET_ERROR_TYPE_WARNING, "Received NULL msg on %p\n", h);
1246     reconnect (h);
1247     return;
1248   }
1249   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n",
1250        GNUNET_MESH_DEBUG_M2S (ntohs (msg->type)));
1251   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a message: %s\n",
1252        GNUNET_MESH_DEBUG_M2S (ntohs (msg->type)));
1253   switch (ntohs (msg->type))
1254   {
1255     /* Notify of a new incoming tunnel */
1256   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE:
1257     process_tunnel_created (h, (struct GNUNET_MESH_TunnelNotification *) msg);
1258     break;
1259     /* Notify of a tunnel disconnection */
1260   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1261     process_tunnel_destroy (h, (struct GNUNET_MESH_TunnelMessage *) msg);
1262     break;
1263     /* Notify of a new peer or a peer disconnect in the tunnel */
1264   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD:
1265   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL:
1266     process_peer_event (h, (struct GNUNET_MESH_PeerControl *) msg);
1267     break;
1268     /* Notify of a new data packet in the tunnel */
1269   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1270   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1271   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1272     if (GNUNET_NO == process_incoming_data (h, msg))
1273       return;
1274     break;
1275   case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
1276     process_ack (h, msg);
1277     break;
1278   default:
1279     /* We shouldn't get any other packages, log and ignore */
1280     LOG (GNUNET_ERROR_TYPE_WARNING,
1281          "unsolicited message form service (type %hu)\n",
1282          ntohs (msg->type));
1283   }
1284   LOG (GNUNET_ERROR_TYPE_DEBUG, "message processed\n");
1285   if (GNUNET_YES == h->in_receive)
1286   {
1287     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1288                            GNUNET_TIME_UNIT_FOREVER_REL);
1289   }
1290   else
1291   {
1292     LOG (GNUNET_ERROR_TYPE_DEBUG,
1293          "in receive off, not calling CLIENT_receive\n");
1294   }
1295 }
1296
1297
1298 /******************************************************************************/
1299 /************************       SEND FUNCTIONS     ****************************/
1300 /******************************************************************************/
1301
1302 /**
1303  * Function called to send a message to the service.
1304  * "buf" will be NULL and "size" zero if the socket was closed for writing in
1305  * the meantime.
1306  *
1307  * @param cls closure, the mesh handle
1308  * @param size number of bytes available in buf
1309  * @param buf where the callee should write the connect message
1310  * @return number of bytes written to buf
1311  */
1312 static size_t
1313 send_callback (void *cls, size_t size, void *buf)
1314 {
1315   struct GNUNET_MESH_Handle *h = cls;
1316   struct GNUNET_MESH_TransmitHandle *th;
1317   struct GNUNET_MESH_TransmitHandle *next;
1318   struct GNUNET_MESH_Tunnel *t;
1319   char *cbuf = buf;
1320   size_t tsize;
1321   size_t psize;
1322   size_t nsize;
1323
1324   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1325   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send packet() Buffer %u\n", size);
1326   if ((0 == size) || (NULL == buf))
1327   {
1328     LOG (GNUNET_ERROR_TYPE_DEBUG, "Received NULL send callback on %p\n", h);
1329     reconnect (h);
1330     h->th = NULL;
1331     return 0;
1332   }
1333   tsize = 0;
1334   next = h->th_head;
1335   nsize = message_ready_size (h);
1336   while ((NULL != (th = next)) && (0 < nsize) && (size >= nsize))
1337   {
1338     t = th->tunnel;
1339     if (GNUNET_YES == th_is_payload (th))
1340     {
1341       LOG (GNUNET_ERROR_TYPE_DEBUG, " payload\n");
1342       if (GNUNET_YES == GMC_is_pid_bigger(t->next_send_pid, t->max_send_pid))
1343       {
1344         /* This tunnel is not ready to transmit yet, try next message */
1345         next = th->next;
1346         continue;
1347       }
1348       t->packet_size = 0;
1349       if (t->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1350       {
1351         /* traffic to origin */
1352         struct GNUNET_MESH_ToOrigin to;
1353         struct GNUNET_MessageHeader *mh;
1354
1355         GNUNET_assert (size >= th->size);
1356         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (to)];
1357         psize = th->notify (th->notify_cls, size - sizeof (to), mh);
1358         LOG (GNUNET_ERROR_TYPE_DEBUG, "  to origin, type %s\n",
1359              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1360         if (psize > 0)
1361         {
1362           psize += sizeof (to);
1363           GNUNET_assert (size >= psize);
1364           to.header.size = htons (psize);
1365           to.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
1366           to.tid = htonl (t->tid);
1367           to.pid = htonl (t->next_send_pid);
1368           to.ttl = 0;
1369           memset (&to.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1370           memset (&to.sender, 0, sizeof (struct GNUNET_PeerIdentity));
1371           memcpy (cbuf, &to, sizeof (to));
1372         }
1373       }
1374       else if (th->target == 0)
1375       {
1376         /* multicast */
1377         struct GNUNET_MESH_Multicast mc;
1378         struct GNUNET_MessageHeader *mh;
1379
1380         GNUNET_assert (size >= th->size);
1381         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (mc)];
1382         psize = th->notify (th->notify_cls, size - sizeof (mc), mh);
1383         LOG (GNUNET_ERROR_TYPE_DEBUG, "  multicast, type %s\n",
1384              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1385         if (psize > 0)
1386         {
1387           psize += sizeof (mc);
1388           GNUNET_assert (size >= psize);
1389           mc.header.size = htons (psize);
1390           mc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1391           mc.tid = htonl (t->tid);
1392           mc.pid = htonl (t->next_send_pid);
1393           mc.ttl = 0;
1394           memset (&mc.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1395           memcpy (cbuf, &mc, sizeof (mc));
1396         }
1397       }
1398       else
1399       {
1400         /* unicast */
1401         struct GNUNET_MESH_Unicast uc;
1402         struct GNUNET_MessageHeader *mh;
1403
1404         GNUNET_assert (size >= th->size);
1405         mh = (struct GNUNET_MessageHeader *) &cbuf[sizeof (uc)];
1406         psize = th->notify (th->notify_cls, size - sizeof (uc), mh);
1407         LOG (GNUNET_ERROR_TYPE_DEBUG, "  unicast, type %s\n",
1408              GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1409         if (psize > 0)
1410         {
1411           psize += sizeof (uc);
1412           GNUNET_assert (size >= psize);
1413           uc.header.size = htons (psize);
1414           uc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1415           uc.tid = htonl (t->tid);
1416           uc.pid = htonl (t->next_send_pid);
1417           uc.ttl = 0;
1418           memset (&uc.oid, 0, sizeof (struct GNUNET_PeerIdentity));
1419           GNUNET_PEER_resolve (th->target, &uc.destination);
1420           memcpy (cbuf, &uc, sizeof (uc));
1421         }
1422       }
1423       t->next_send_pid++;
1424     }
1425     else
1426     {
1427       struct GNUNET_MessageHeader *mh = (struct GNUNET_MessageHeader *) &th[1];
1428
1429       LOG (GNUNET_ERROR_TYPE_DEBUG, "  mesh traffic, type %s\n",
1430            GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
1431       memcpy (cbuf, &th[1], th->size);
1432       psize = th->size;
1433     }
1434     if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1435       GNUNET_SCHEDULER_cancel (th->timeout_task);
1436     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1437     GNUNET_free (th);
1438     next = h->th_head;
1439     nsize = message_ready_size (h);
1440     cbuf += psize;
1441     size -= psize;
1442     tsize += psize;
1443   }
1444   LOG (GNUNET_ERROR_TYPE_DEBUG, "  total size: %u\n", tsize);
1445   h->th = NULL;
1446   size = message_ready_size (h);
1447   if (0 != size)
1448   {
1449     LOG (GNUNET_ERROR_TYPE_DEBUG, "  next size: %u\n", size);
1450     h->th =
1451         GNUNET_CLIENT_notify_transmit_ready (h->client, size,
1452                                              GNUNET_TIME_UNIT_FOREVER_REL,
1453                                              GNUNET_YES, &send_callback, h);
1454   }
1455   else
1456   {
1457     if (NULL != h->th_head)
1458       LOG (GNUNET_ERROR_TYPE_DEBUG, "  can't transmit any more\n");
1459     else
1460       LOG (GNUNET_ERROR_TYPE_DEBUG, "  nothing left to transmit\n");
1461   }
1462   if (GNUNET_NO == h->in_receive)
1463   {
1464     LOG (GNUNET_ERROR_TYPE_DEBUG, " start receiving from service\n");
1465     h->in_receive = GNUNET_YES;
1466     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1467                            GNUNET_TIME_UNIT_FOREVER_REL);
1468   }
1469   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send packet() END\n");
1470   return tsize;
1471 }
1472
1473
1474 /**
1475  * Auxiliary function to send an already constructed packet to the service.
1476  * Takes care of creating a new queue element, copying the message and
1477  * calling the tmt_rdy function if necessary.
1478  * 
1479  * @param h mesh handle
1480  * @param msg message to transmit
1481  * @param tunnel tunnel this send is related to (NULL if N/A)
1482  */
1483 static void
1484 send_packet (struct GNUNET_MESH_Handle *h,
1485              const struct GNUNET_MessageHeader *msg,
1486              struct GNUNET_MESH_Tunnel *tunnel)
1487 {
1488   struct GNUNET_MESH_TransmitHandle *th;
1489   size_t msize;
1490
1491   LOG (GNUNET_ERROR_TYPE_DEBUG, " Sending message to service: %s\n",
1492        GNUNET_MESH_DEBUG_M2S(ntohs(msg->type)));
1493   msize = ntohs (msg->size);
1494   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle) + msize);
1495   th->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1496   th->size = msize;
1497   th->tunnel = tunnel;
1498   memcpy (&th[1], msg, msize);
1499   add_to_queue (h, th);
1500   LOG (GNUNET_ERROR_TYPE_DEBUG, "  queued\n");
1501   if (NULL != h->th)
1502     return;
1503   LOG (GNUNET_ERROR_TYPE_DEBUG, "  calling ntfy tmt rdy for %u bytes\n", msize);
1504   h->th =
1505       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
1506                                            GNUNET_TIME_UNIT_FOREVER_REL,
1507                                            GNUNET_YES, &send_callback, h);
1508 }
1509
1510
1511 /******************************************************************************/
1512 /**********************      API CALL DEFINITIONS     *************************/
1513 /******************************************************************************/
1514
1515 /**
1516  * Connect to the mesh service.
1517  *
1518  * @param cfg configuration to use
1519  * @param cls closure for the various callbacks that follow
1520  *            (including handlers in the handlers array)
1521  * @param new_tunnel function called when an *inbound* tunnel is created
1522  * @param cleaner function called when an *inbound* tunnel is destroyed by the
1523  *                remote peer, it is *not* called if GNUNET_MESH_tunnel_destroy
1524  *                is called on the tunnel
1525  * @param handlers callbacks for messages we care about, NULL-terminated
1526  *                note that the mesh is allowed to drop notifications about
1527  *                inbound messages if the client does not process them fast
1528  *                enough (for this notification type, a bounded queue is used)
1529  * @param stypes list of the applications that this client claims to provide
1530  * @return handle to the mesh service NULL on error
1531  *         (in this case, init is never called)
1532  */
1533 struct GNUNET_MESH_Handle *
1534 GNUNET_MESH_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, void *cls,
1535                      GNUNET_MESH_InboundTunnelNotificationHandler new_tunnel,
1536                      GNUNET_MESH_TunnelEndHandler cleaner,
1537                      const struct GNUNET_MESH_MessageHandler *handlers,
1538                      const GNUNET_MESH_ApplicationType *stypes)
1539 {
1540   struct GNUNET_MESH_Handle *h;
1541
1542   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect()\n");
1543   h = GNUNET_malloc (sizeof (struct GNUNET_MESH_Handle));
1544   LOG (GNUNET_ERROR_TYPE_DEBUG, " addr %p\n", h);
1545   h->cfg = cfg;
1546   h->new_tunnel = new_tunnel;
1547   h->cleaner = cleaner;
1548   h->client = GNUNET_CLIENT_connect ("mesh", cfg);
1549   if (h->client == NULL)
1550   {
1551     GNUNET_break (0);
1552     GNUNET_free (h);
1553     return NULL;
1554   }
1555   h->cls = cls;
1556   /* FIXME memdup? */
1557   h->applications = stypes;
1558   h->message_handlers = handlers;
1559   h->next_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
1560   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1561   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1562
1563   /* count handlers and apps, calculate size */
1564   for (h->n_applications = 0; stypes[h->n_applications]; h->n_applications++) ;
1565   for (h->n_handlers = 0; handlers[h->n_handlers].type; h->n_handlers++) ;
1566   send_connect (h);
1567   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_MESH_connect() END\n");
1568   return h;
1569 }
1570
1571
1572 /**
1573  * Disconnect from the mesh service. All tunnels will be destroyed. All tunnel
1574  * disconnect callbacks will be called on any still connected peers, notifying
1575  * about their disconnection. The registered inbound tunnel cleaner will be
1576  * called should any inbound tunnels still exist.
1577  *
1578  * @param handle connection to mesh to disconnect
1579  */
1580 void
1581 GNUNET_MESH_disconnect (struct GNUNET_MESH_Handle *handle)
1582 {
1583   struct GNUNET_MESH_Tunnel *t;
1584   struct GNUNET_MESH_Tunnel *aux;
1585   struct GNUNET_MESH_TransmitHandle *th;
1586
1587   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH DISCONNECT\n");
1588
1589 #if DEBUG_ACK
1590   LOG (GNUNET_ERROR_TYPE_INFO, "Sent %d ACKs\n", handle->acks_sent);
1591   LOG (GNUNET_ERROR_TYPE_INFO, "Recv %d ACKs\n\n", handle->acks_recv);
1592 #endif
1593
1594   t = handle->tunnels_head;
1595   while (NULL != t)
1596   {
1597     aux = t->next;
1598     if (t->tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1599     {
1600       GNUNET_break (0);
1601       LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel %X not destroyed\n", t->tid);
1602     }
1603     destroy_tunnel (t, GNUNET_YES);
1604     t = aux;
1605   }
1606   while ( (th = handle->th_head) != NULL)
1607   {
1608     struct GNUNET_MessageHeader *msg;
1609
1610     /* Make sure it is an allowed packet (everything else should have been
1611      * already canceled).
1612      */
1613     GNUNET_break (GNUNET_NO == th_is_payload (th));
1614     msg = (struct GNUNET_MessageHeader *) &th[1];
1615     switch (ntohs(msg->type))
1616     {
1617       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT:
1618       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY:
1619         break;
1620       default:
1621         GNUNET_break (0);
1622         LOG (GNUNET_ERROR_TYPE_DEBUG, "unexpected msg %u\n",
1623              ntohs(msg->type));
1624     }
1625
1626     GNUNET_CONTAINER_DLL_remove (handle->th_head, handle->th_tail, th);
1627     GNUNET_free (th);
1628   }
1629
1630   if (NULL != handle->th)
1631   {
1632     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
1633     handle->th = NULL;
1634   }
1635   if (NULL != handle->client)
1636   {
1637     GNUNET_CLIENT_disconnect (handle->client);
1638     handle->client = NULL;
1639   }
1640   if (GNUNET_SCHEDULER_NO_TASK != handle->reconnect_task)
1641   {
1642     GNUNET_SCHEDULER_cancel(handle->reconnect_task);
1643     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1644   }
1645   GNUNET_free (handle);
1646 }
1647
1648
1649 /**
1650  * Announce to ther peer the availability of services described by the regex,
1651  * in order to be reachable to other peers via connect_by_string.
1652  * 
1653  * Note that the first 8 characters are considered to be part of a prefix,
1654  * (for instance 'gnunet://'). If you put a variable part in there (*, +. ()),
1655  * all matching strings will be stored in the DHT.
1656  *
1657  * @param h handle to mesh.
1658  * @param regex string with the regular expression describing local services.
1659  */
1660 void
1661 GNUNET_MESH_announce_regex (struct GNUNET_MESH_Handle *h,
1662                             const char *regex)
1663 {
1664   struct GNUNET_MessageHeader *msg;
1665   size_t len;
1666   size_t msgsize;
1667
1668   len = strlen (regex);
1669   msgsize = sizeof(struct GNUNET_MessageHeader) + len;
1670   GNUNET_assert (UINT16_MAX > msgsize);
1671
1672   {
1673     char buffer[msgsize];
1674
1675     msg = (struct GNUNET_MessageHeader *) buffer;
1676     msg->size = htons (msgsize);
1677     msg->type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX);
1678     memcpy (&msg[1], regex, len);
1679
1680     send_packet(h, msg, NULL);
1681   }
1682 }
1683
1684 /**
1685  * Create a new tunnel (we're initiator and will be allowed to add/remove peers
1686  * and to broadcast).
1687  *
1688  * @param h mesh handle
1689  * @param tunnel_ctx client's tunnel context to associate with the tunnel
1690  * @param connect_handler function to call when peers are actually connected
1691  * @param disconnect_handler function to call when peers are disconnected
1692  * @param handler_cls closure for connect/disconnect handlers
1693  */
1694 struct GNUNET_MESH_Tunnel *
1695 GNUNET_MESH_tunnel_create (struct GNUNET_MESH_Handle *h, void *tunnel_ctx,
1696                            GNUNET_MESH_PeerConnectHandler connect_handler,
1697                            GNUNET_MESH_PeerDisconnectHandler disconnect_handler,
1698                            void *handler_cls)
1699 {
1700   struct GNUNET_MESH_Tunnel *t;
1701   struct GNUNET_MESH_TunnelMessage msg;
1702
1703   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating new tunnel\n");
1704   t = create_tunnel (h, 0);
1705   LOG (GNUNET_ERROR_TYPE_DEBUG, "  at %p\n", t);
1706   LOG (GNUNET_ERROR_TYPE_DEBUG, "  number %X\n", t->tid);
1707   t->connect_handler = connect_handler;
1708   t->disconnect_handler = disconnect_handler;
1709   t->cls = handler_cls;
1710   t->ctx = tunnel_ctx;
1711   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1712   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1713   msg.tunnel_id = htonl (t->tid);
1714   send_packet (h, &msg.header, t);
1715   return t;
1716 }
1717
1718
1719 /**
1720  * Destroy an existing tunnel. The existing callback for the tunnel will NOT
1721  * be called.
1722  *
1723  * @param tunnel tunnel handle
1724  */
1725 void
1726 GNUNET_MESH_tunnel_destroy (struct GNUNET_MESH_Tunnel *tunnel)
1727 {
1728   struct GNUNET_MESH_Handle *h;
1729   struct GNUNET_MESH_TunnelMessage msg;
1730   struct GNUNET_MESH_TransmitHandle *th;
1731
1732   LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying tunnel\n");
1733   h = tunnel->mesh;
1734
1735   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1736   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1737   msg.tunnel_id = htonl (tunnel->tid);
1738   th = h->th_head;
1739   while (th != NULL)
1740   {
1741     struct GNUNET_MESH_TransmitHandle *aux;
1742     if (th->tunnel == tunnel)
1743     {
1744       aux = th->next;
1745       /* FIXME call the handler? */
1746       if (GNUNET_YES == th_is_payload (th))
1747         th->notify (th->notify_cls, 0, NULL);
1748       GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1749       GNUNET_free (th);
1750       th = aux;
1751     }
1752     else
1753       th = th->next;
1754   }
1755
1756   destroy_tunnel (tunnel, GNUNET_NO);
1757   send_packet (h, &msg.header, NULL);
1758 }
1759
1760 /**
1761  * Request that the tunnel data rate is limited to the speed of the slowest
1762  * receiver.
1763  *
1764  * @param tunnel Tunnel affected.
1765  */
1766 void
1767 GNUNET_MESH_tunnel_speed_min (struct GNUNET_MESH_Tunnel *tunnel)
1768 {
1769   struct GNUNET_MESH_TunnelMessage msg;
1770   struct GNUNET_MESH_Handle *h;
1771
1772   h = tunnel->mesh;
1773   tunnel->speed_min = GNUNET_YES;
1774
1775   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN);
1776   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1777   msg.tunnel_id = htonl (tunnel->tid);
1778
1779   send_packet (h, &msg.header, NULL);
1780 }
1781
1782
1783 /**
1784  * Request that the tunnel data rate is limited to the speed of the fastest
1785  * receiver. This is the default behavior.
1786  *
1787  * @param tunnel Tunnel affected.
1788  */
1789 void
1790 GNUNET_MESH_tunnel_speed_max (struct GNUNET_MESH_Tunnel *tunnel)
1791 {
1792   struct GNUNET_MESH_TunnelMessage msg;
1793   struct GNUNET_MESH_Handle *h;
1794
1795   h = tunnel->mesh;
1796   tunnel->speed_min = GNUNET_NO;
1797
1798   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX);
1799   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1800   msg.tunnel_id = htonl (tunnel->tid);
1801
1802   send_packet (h, &msg.header, NULL);
1803 }
1804
1805 /**
1806  * Turn on/off the buffering status of the tunnel.
1807  * 
1808  * @param tunnel Tunnel affected.
1809  * @param buffer GNUNET_YES to turn buffering on (default),
1810  *               GNUNET_NO otherwise.
1811  */
1812 void
1813 GNUNET_MESH_tunnel_buffer (struct GNUNET_MESH_Tunnel *tunnel, int buffer)
1814 {
1815   struct GNUNET_MESH_TunnelMessage msg;
1816   struct GNUNET_MESH_Handle *h;
1817
1818   h = tunnel->mesh;
1819   tunnel->buffering = buffer;
1820
1821   if (GNUNET_YES == buffer)
1822     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER);
1823   else
1824     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER);
1825   msg.header.size = htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1826   msg.tunnel_id = htonl (tunnel->tid);
1827
1828   send_packet (h, &msg.header, NULL);
1829 }
1830
1831 /**
1832  * Request that a peer should be added to the tunnel.  The existing
1833  * connect handler will be called ONCE with either success or failure.
1834  * This function should NOT be called again with the same peer before the
1835  * connect handler is called.
1836  *
1837  * @param tunnel handle to existing tunnel
1838  * @param peer peer to add
1839  */
1840 void
1841 GNUNET_MESH_peer_request_connect_add (struct GNUNET_MESH_Tunnel *tunnel,
1842                                       const struct GNUNET_PeerIdentity *peer)
1843 {
1844   struct GNUNET_MESH_PeerControl msg;
1845   GNUNET_PEER_Id peer_id;
1846   unsigned int i;
1847
1848   peer_id = GNUNET_PEER_intern (peer);
1849   for (i = 0; i < tunnel->npeers; i++)
1850   {
1851     if (tunnel->peers[i]->id == peer_id)
1852     {
1853       /* Peer already exists in tunnel */
1854       GNUNET_PEER_change_rc (peer_id, -1);
1855       GNUNET_break (0);
1856       return;
1857     }
1858   }
1859   if (NULL == add_peer_to_tunnel (tunnel, peer))
1860     return;
1861
1862   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1863   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1864   msg.tunnel_id = htonl (tunnel->tid);
1865   msg.peer = *peer;
1866   send_packet (tunnel->mesh, &msg.header, tunnel);
1867
1868   return;
1869 }
1870
1871
1872 /**
1873  * Request that a peer should be removed from the tunnel.  The existing
1874  * disconnect handler will be called ONCE if we were connected.
1875  *
1876  * @param tunnel handle to existing tunnel
1877  * @param peer peer to remove
1878  */
1879 void
1880 GNUNET_MESH_peer_request_connect_del (struct GNUNET_MESH_Tunnel *tunnel,
1881                                       const struct GNUNET_PeerIdentity *peer)
1882 {
1883   struct GNUNET_MESH_PeerControl msg;
1884   GNUNET_PEER_Id peer_id;
1885   unsigned int i;
1886
1887   peer_id = GNUNET_PEER_search (peer);
1888   if (0 == peer_id)
1889   {
1890     GNUNET_break (0);
1891     return;
1892   }
1893   for (i = 0; i < tunnel->npeers; i++)
1894     if (tunnel->peers[i]->id == peer_id)
1895       break;
1896   if (i == tunnel->npeers)
1897   {
1898     GNUNET_break (0);
1899     return;
1900   }
1901   if (NULL != tunnel->disconnect_handler && tunnel->peers[i]->connected == 1)
1902     tunnel->disconnect_handler (tunnel->cls, peer);
1903   GNUNET_PEER_change_rc (peer_id, -1);
1904   GNUNET_free (tunnel->peers[i]);
1905   tunnel->peers[i] = tunnel->peers[tunnel->npeers - 1];
1906   GNUNET_array_grow (tunnel->peers, tunnel->npeers, tunnel->npeers - 1);
1907
1908   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1909   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1910   msg.tunnel_id = htonl (tunnel->tid);
1911   memcpy (&msg.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1912   send_packet (tunnel->mesh, &msg.header, tunnel);
1913 }
1914
1915
1916 /**
1917  * Request that the mesh should try to connect to a peer supporting the given
1918  * message type.
1919  *
1920  * @param tunnel handle to existing tunnel
1921  * @param app_type application type that must be supported by the peer (MESH
1922  *                 should discover peer in proximity handling this type)
1923  */
1924 void
1925 GNUNET_MESH_peer_request_connect_by_type (struct GNUNET_MESH_Tunnel *tunnel,
1926                                           GNUNET_MESH_ApplicationType app_type)
1927 {
1928   struct GNUNET_MESH_ConnectPeerByType msg;
1929
1930   GNUNET_array_append (tunnel->apps, tunnel->napps, app_type);
1931
1932   LOG (GNUNET_ERROR_TYPE_DEBUG, "* CONNECT BY TYPE *\n");
1933   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectPeerByType));
1934   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE);
1935   msg.tunnel_id = htonl (tunnel->tid);
1936   msg.type = htonl (app_type);
1937   send_packet (tunnel->mesh, &msg.header, tunnel);
1938 }
1939
1940
1941 /**
1942  * Request that the mesh should try to connect to a peer matching the
1943  * description given in the service string.
1944  * 
1945  * FIXME: allow multiple? how to deal with reconnect?
1946  *
1947  * @param tunnel handle to existing tunnel
1948  * @param description string describing the destination node requirements
1949  */
1950 void
1951 GNUNET_MESH_peer_request_connect_by_string (struct GNUNET_MESH_Tunnel *tunnel,
1952                                             const char *description)
1953 {
1954   struct GNUNET_MESH_ConnectPeerByString *m;
1955   size_t len;
1956   size_t msgsize;
1957
1958   len = strlen (description);
1959   msgsize = sizeof(struct GNUNET_MESH_ConnectPeerByString) + len;
1960   GNUNET_assert (UINT16_MAX > msgsize);
1961   {
1962     char buffer[msgsize];
1963
1964     m = (struct GNUNET_MESH_ConnectPeerByString *) buffer;
1965     m->header.size = htons (msgsize);
1966     m->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING);
1967     m->tunnel_id = htonl (tunnel->tid);
1968     memcpy(&m[1], description, len);
1969
1970     send_packet (tunnel->mesh, &m->header, tunnel);
1971   }
1972 }
1973
1974
1975 /**
1976  * Request that the given peer isn't added to this tunnel in calls to
1977  * connect_by_* calls, (due to misbehaviour, bad performance, ...).
1978  *
1979  * @param tunnel handle to existing tunnel.
1980  * @param peer peer identity of the peer which should be blacklisted
1981  *                  for the tunnel.
1982  */
1983 void
1984 GNUNET_MESH_peer_blacklist (struct GNUNET_MESH_Tunnel *tunnel,
1985                             const struct GNUNET_PeerIdentity *peer)
1986 {
1987   struct GNUNET_MESH_PeerControl msg;
1988
1989   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1990   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST);
1991   msg.tunnel_id = htonl (tunnel->tid);
1992   msg.peer = *peer;
1993   send_packet (tunnel->mesh, &msg.header, tunnel);
1994
1995   return;
1996 }
1997
1998
1999 /**
2000  * Request that the given peer isn't blacklisted anymore from this tunnel,
2001  * and therefore can be added in future calls to connect_by_*.
2002  * The peer must have been previously blacklisted for this tunnel.
2003  *
2004  * @param tunnel handle to existing tunnel.
2005  * @param peer peer identity of the peer which shouldn't be blacklisted
2006  *                  for the tunnel anymore.
2007  */
2008 void
2009 GNUNET_MESH_peer_unblacklist (struct GNUNET_MESH_Tunnel *tunnel,
2010                               const struct GNUNET_PeerIdentity *peer)
2011 {
2012   struct GNUNET_MESH_PeerControl msg;
2013
2014   msg.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2015   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST);
2016   msg.tunnel_id = htonl (tunnel->tid);
2017   msg.peer = *peer;
2018   send_packet (tunnel->mesh, &msg.header, tunnel);
2019
2020   return;
2021 }
2022
2023
2024 /**
2025  * Ask the mesh to call "notify" once it is ready to transmit the
2026  * given number of bytes to the specified tunnel or target.
2027  * Only one call can be active at any time, to issue another request,
2028  * wait for the callback or cancel the current request.
2029  *
2030  * @param tunnel tunnel to use for transmission
2031  * @param cork is corking allowed for this transmission?
2032  * @param maxdelay how long can the message wait?
2033  * @param target destination for the message
2034  *               NULL for multicast to all tunnel targets
2035  * @param notify_size how many bytes of buffer space does notify want?
2036  * @param notify function to call when buffer space is available;
2037  *        will be called with NULL on timeout or if the overall queue
2038  *        for this peer is larger than queue_size and this is currently
2039  *        the message with the lowest priority
2040  * @param notify_cls closure for notify
2041  * @return non-NULL if the notify callback was queued,
2042  *         NULL if we can not even queue the request (insufficient
2043  *         memory); if NULL is returned, "notify" will NOT be called.
2044  */
2045 struct GNUNET_MESH_TransmitHandle *
2046 GNUNET_MESH_notify_transmit_ready (struct GNUNET_MESH_Tunnel *tunnel, int cork,
2047                                    struct GNUNET_TIME_Relative maxdelay,
2048                                    const struct GNUNET_PeerIdentity *target,
2049                                    size_t notify_size,
2050                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
2051                                    void *notify_cls)
2052 {
2053   struct GNUNET_MESH_TransmitHandle *th;
2054   size_t overhead;
2055
2056   GNUNET_assert (NULL != tunnel);
2057   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH NOTIFY TRANSMIT READY\n");
2058   LOG (GNUNET_ERROR_TYPE_DEBUG, "    on tunnel %X\n", tunnel->tid);
2059   if (tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2060     LOG (GNUNET_ERROR_TYPE_DEBUG, "    to origin\n");
2061   else if (NULL != target)
2062     LOG (GNUNET_ERROR_TYPE_DEBUG, "    target %s\n", GNUNET_i2s (target));
2063   else
2064     LOG (GNUNET_ERROR_TYPE_DEBUG, "    target multicast\n");
2065   LOG (GNUNET_ERROR_TYPE_DEBUG, "    payload size %u\n", notify_size);
2066   GNUNET_assert (NULL != notify);
2067   GNUNET_assert (0 == tunnel->packet_size); // Only one data packet allowed
2068   th = GNUNET_malloc (sizeof (struct GNUNET_MESH_TransmitHandle));
2069   th->tunnel = tunnel;
2070   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
2071   th->target = GNUNET_PEER_intern (target);
2072   if (tunnel->tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2073     overhead = sizeof (struct GNUNET_MESH_ToOrigin);
2074   else if (NULL == target)
2075     overhead = sizeof (struct GNUNET_MESH_Multicast);
2076   else
2077     overhead = sizeof (struct GNUNET_MESH_Unicast);
2078   tunnel->packet_size = th->size = notify_size + overhead;
2079   LOG (GNUNET_ERROR_TYPE_DEBUG, "    total size %u\n", th->size);
2080   th->notify = notify;
2081   th->notify_cls = notify_cls;
2082   add_to_queue (tunnel->mesh, th);
2083   if (NULL != tunnel->mesh->th)
2084     return th;
2085   if (GMC_is_pid_bigger(tunnel->next_send_pid, tunnel->max_send_pid))
2086     return th;
2087   LOG (GNUNET_ERROR_TYPE_DEBUG, "    call notify tmt rdy\n");
2088   tunnel->mesh->th =
2089       GNUNET_CLIENT_notify_transmit_ready (tunnel->mesh->client, th->size,
2090                                            GNUNET_TIME_UNIT_FOREVER_REL,
2091                                            GNUNET_YES, &send_callback,
2092                                            tunnel->mesh);
2093   LOG (GNUNET_ERROR_TYPE_DEBUG, "MESH NOTIFY TRANSMIT READY END\n");
2094   return th;
2095 }
2096
2097
2098 /**
2099  * Cancel the specified transmission-ready notification.
2100  *
2101  * @param th handle that was returned by "notify_transmit_ready".
2102  */
2103 void
2104 GNUNET_MESH_notify_transmit_ready_cancel (struct GNUNET_MESH_TransmitHandle *th)
2105 {
2106   struct GNUNET_MESH_Handle *mesh;
2107
2108   th->tunnel->packet_size = 0;
2109   mesh = th->tunnel->mesh;
2110   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2111     GNUNET_SCHEDULER_cancel (th->timeout_task);
2112   GNUNET_CONTAINER_DLL_remove (mesh->th_head, mesh->th_tail, th);
2113   GNUNET_free (th);
2114   if ((0 == message_ready_size (mesh)) && (NULL != mesh->th))
2115   {
2116     /* queue empty, no point in asking for transmission */
2117     GNUNET_CLIENT_notify_transmit_ready_cancel (mesh->th);
2118     mesh->th = NULL;
2119   }
2120 }
2121
2122
2123 /**
2124  * Transition API for tunnel ctx management
2125  */
2126 void
2127 GNUNET_MESH_tunnel_set_data (struct GNUNET_MESH_Tunnel *tunnel, void *data)
2128 {
2129   tunnel->ctx = data;
2130 }
2131
2132 /**
2133  * Transition API for tunnel ctx management
2134  */
2135 void *
2136 GNUNET_MESH_tunnel_get_data (struct GNUNET_MESH_Tunnel *tunnel)
2137 {
2138   return tunnel->ctx;
2139 }
2140
2141