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