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