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