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