]> git.meshlink.io Git - meshlink/blobdiff - src/meshlink++.h
Add meshlink_channel_open_ex().
[meshlink] / src / meshlink++.h
index 8271ab2f4cbfb4814009a81d2f9b61a7c8381f68..6acfe251dfe1be60b2c342221836abf172987e2e 100644 (file)
@@ -59,7 +59,6 @@ namespace meshlink {
        /// A callback for accepting incoming channels.
        /** @param mesh         A handle which represents an instance of MeshLink.
         *  @param channel      A handle for the incoming channel.
-        *  @param node         The node from which this channel is being initiated.
         *  @param port         The port number the peer wishes to connect to.
         *  @param data         A pointer to a buffer containing data already received. (Not yet used.)
         *  @param len          The length of the data. (Not yet used.)
@@ -67,7 +66,7 @@ namespace meshlink {
         *  @return             This function should return true if the application accepts the incoming channel, false otherwise.
         *                      If returning false, the channel is invalid and may not be used anymore.
         */
-       typedef bool (*channel_accept_cb_t)(mesh *mesh, channel *channel, node *node, uint16_t port, const void *data, size_t len);
+       typedef bool (*channel_accept_cb_t)(mesh *mesh, channel *channel, uint16_t port, const void *data, size_t len);
 
        /// A callback for receiving data from a channel.
        /** @param mesh         A handle which represents an instance of MeshLink.
@@ -77,23 +76,93 @@ namespace meshlink {
         */
        typedef void (*channel_receive_cb_t)(mesh *mesh, channel *channel, const void *data, size_t len);
 
+       /// A callback that is called when data can be send on a channel.
+       /** @param mesh         A handle which represents an instance of MeshLink.
+        *  @param channel      A handle for the channel.
+        *  @param len          The maximum length of data that is guaranteed to be accepted by a call to channel_send().
+        */
+       typedef void (*channel_poll_cb_t)(mesh *mesh, channel *channel, size_t len);
+
        /// A class describing a MeshLink node.
        class node: public meshlink_node_t {
        };
 
        /// A class describing a MeshLink channel.
        class channel: public meshlink_channel_t {
+               public:
+               static const uint32_t RELIABLE = MESHLINK_CHANNEL_RELIABLE;
+               static const uint32_t ORDERED = MESHLINK_CHANNEL_ORDERED;
+               static const uint32_t FRAMED = MESHLINK_CHANNEL_FRAMED;
+               static const uint32_t DROP_LATE = MESHLINK_CHANNEL_DROP_LATE;
+               static const uint32_t TCP = MESHLINK_CHANNEL_TCP;
+               static const uint32_t UDP = MESHLINK_CHANNEL_UDP;
        };
 
        /// A class describing a MeshLink mesh.
-       class mesh: public meshlink_handle_t {
+       class mesh {
        public:
-               mesh() {}
-       
+               mesh() : handle(0) {}
+               
                virtual ~mesh() {
-                       meshlink_close(this);
+                       this->close();
+               }
+               
+               bool isOpen() const {
+                       return (handle!=0);
+               }
+               
+// TODO: please enable C++11 in autoconf to enable "move constructors":
+//             mesh(mesh&& other)
+//             : handle(other.handle)
+//             {
+//                     if(handle)
+//                             handle->priv = this;
+//                     other.handle = 0;
+//             }
+
+               /// Initialize MeshLink's configuration directory.
+               /** This function causes MeshLink to initialize its configuration directory,
+                *  if it hasn't already been initialized.
+                *  It only has to be run the first time the application starts,
+                *  but it is not a problem if it is run more than once, as long as
+                *  the arguments given are the same.
+                *
+                *  This function does not start any network I/O yet. The application should
+                *  first set callbacks, and then call meshlink_start().
+                *
+                *  @param confbase The directory in which MeshLink will store its configuration files.
+                *  @param name     The name which this instance of the application will use in the mesh.
+                *  @param appname  The application name which will be used in the mesh.
+                *  @param dclass   The device class which will be used in the mesh.
+                *
+                *  @return         This function will return a pointer to a meshlink::mesh if MeshLink has succesfully set up its configuration files, NULL otherwise.
+                */ 
+               bool open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
+                       handle = meshlink_open(confbase, name, appname, devclass);
+                       if(handle)
+                               handle->priv = this;
+                       
+                       return isOpen();
+               }
+               
+               mesh(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
+                       open(confbase, name, appname, devclass);
                }
                
+               /// Close the MeshLink handle.
+               /** This function calls meshlink_stop() if necessary,
+                *  and frees all memory allocated by MeshLink.
+                *  Afterwards, the handle and any pointers to a struct meshlink_node are invalid.
+                */
+               void close() {
+                       if(handle)
+                       {
+                               handle->priv = 0;
+                               meshlink_close(handle);
+                       }
+                       handle=0;
+               }
+       
                /** instead of registerin callbacks you derive your own class and overwrite the following abstract member functions.
                 *  These functions are run in MeshLink's own thread.
                 *  It is therefore important that these functions use apprioriate methods (queues, pipes, locking, etc.)
@@ -110,6 +179,56 @@ namespace meshlink {
                
                /// This functions is called whenever MeshLink has some information to log.
                virtual void log(log_level_t level, const char* message)            { /* do nothing */ }
+
+               /// This functions is called whenever another node attemps to open a channel to the local node.
+               /** 
+                *  If the channel is accepted, the poll_callback will be set to channel_poll and can be
+                *  changed using set_channel_poll_cb(). Likewise, the receive callback is set to
+                *  channel_receive().
+                *
+                *  The function is run in MeshLink's own thread.
+                *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
+                *  to pass data to or from the application's thread.
+                *  The callback should also not block itself and return as quickly as possible.
+                *
+                *  @param channel      A handle for the incoming channel.
+                *  @param port         The port number the peer wishes to connect to.
+                *  @param data         A pointer to a buffer containing data already received. (Not yet used.)
+                *  @param len          The length of the data. (Not yet used.)
+                *
+                *  @return             This function should return true if the application accepts the incoming channel, false otherwise.
+                *                      If returning false, the channel is invalid and may not be used anymore.
+                */
+               virtual bool channel_accept(channel *channel, uint16_t port, const void *data, size_t len)
+               {
+                       /* by default reject all channels */
+                       return false;
+               }
+
+               /// This function is called by Meshlink for receiving data from a channel.
+               /** 
+                *  The function is run in MeshLink's own thread.
+                *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
+                *  to pass data to or from the application's thread.
+                *  The callback should also not block itself and return as quickly as possible.
+                *
+                *  @param channel      A handle for the channel.
+                *  @param data         A pointer to a buffer containing data sent by the source.
+                *  @param len          The length of the data.
+                */
+               virtual void channel_receive(channel *channel, const void *data, size_t len) { /* do nothing */ }
+
+               /// This function is called by Meshlink when data can be send on a channel.
+               /**
+                *  The function is run in MeshLink's own thread.
+                *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
+                *  to pass data to or from the application's thread.
+                *
+                *  The callback should also not block itself and return as quickly as possible.
+                *  @param channel      A handle for the channel.
+                *  @param len          The maximum length of data that is guaranteed to be accepted by a call to channel_send().
+                */
+               virtual void channel_poll(channel *channel, size_t len) { /* do nothing */ }
                
                /// Start MeshLink.
                /** This function causes MeshLink to open network sockets, make outgoing connections, and
@@ -118,10 +237,11 @@ namespace meshlink {
                 *  @return         This function will return true if MeshLink has succesfully started its thread, false otherwise.
                 */
                bool start() {
-                       meshlink_set_receive_cb    (this, &receive_trampoline);
-                       meshlink_set_node_status_cb(this, &node_status_trampoline);
-                       meshlink_set_log_cb        (this, MESHLINK_DEBUG, &log_trampoline);
-                       return meshlink_start(this);
+                       meshlink_set_receive_cb       (handle, &receive_trampoline);
+                       meshlink_set_node_status_cb   (handle, &node_status_trampoline);
+                       meshlink_set_log_cb           (handle, MESHLINK_DEBUG, &log_trampoline);
+                       meshlink_set_channel_accept_cb(handle, &channel_accept_trampoline);
+                       return meshlink_start         (handle);
                }
 
                /// Stop MeshLink.
@@ -129,7 +249,7 @@ namespace meshlink {
                 *  close all sockets, and shut down its own thread.
                 */
                void stop() {
-                       meshlink_stop(this);
+                       meshlink_stop(handle);
                }
 
                /// Send data to another node.
@@ -146,7 +266,7 @@ namespace meshlink {
                 *                      A return value of true does not guarantee that the message will actually arrive at the destination.
                 */
                bool send(node *destination, const void *data, unsigned int len) {
-                       return meshlink_send(this, destination, data, len);
+                       return meshlink_send(handle, destination, data, len);
                }
 
                /// Get a handle for a specific node.
@@ -158,7 +278,16 @@ namespace meshlink {
                 *                      or NULL if the requested node does not exist.
                 */
                node *get_node(const char *name) {
-                       return (node *)meshlink_get_node(this, name);
+                       return (node *)meshlink_get_node(handle, name);
+               }
+
+               /// Get a handle for our own node.
+               /** This function returns a handle for the local node.
+                *
+                *  @return             A pointer to a meshlink::node which represents the local node.
+                */
+               node *get_self() {
+                       return (node *)meshlink_get_self(handle);
                }
 
                /// Get a list of all nodes.
@@ -171,7 +300,7 @@ namespace meshlink {
                 *                      This can be larger than nmemb, in which case not all nodes were stored in the nodes array.
                 */
                node **get_all_nodes(node **nodes, size_t *nmemb) {
-                       return (node **)meshlink_get_all_nodes(this, (meshlink_node_t **)nodes, nmemb);
+                       return (node **)meshlink_get_all_nodes(handle, (meshlink_node_t **)nodes, nmemb);
                }
 
                /// Sign data using the local node's MeshLink key.
@@ -186,7 +315,7 @@ namespace meshlink {
                 *  @return             This function returns true if the signature is valid, false otherwise.
                 */
                bool sign(const void *data, size_t len, void *signature, size_t *siglen) {
-                       return meshlink_sign(this, data, len, signature, siglen);
+                       return meshlink_sign(handle, data, len, signature, siglen);
                }
 
                /// Verify the signature generated by another node of a piece of data.
@@ -201,7 +330,7 @@ namespace meshlink {
                 *  @return             This function returns true if the signature is valid, false otherwise.
                 */
                bool verify(node *source, const void *data, size_t len, const void *signature, size_t siglen) {
-                       return meshlink_verify(this, source, data, len, signature, siglen);
+                       return meshlink_verify(handle, source, data, len, signature, siglen);
                }
 
                /// Add an Address for the local node.
@@ -212,7 +341,67 @@ namespace meshlink {
                 *  @return             This function returns true if the address was added, false otherwise.
                 */
                bool add_address(const char *address) {
-                       return meshlink_add_address(this, address);
+                       return meshlink_add_address(handle, address);
+               }
+
+               /** This function performs tries to discover the local node's external address
+                *  by contacting the meshlink.io server. If a reverse lookup of the address works,
+                *  the FQDN associated with the address will be returned.
+                *
+                *  Please note that this is function only returns a single address,
+                *  even if the local node might have more than one external address.
+                *  In that case, there is no control over which address will be selected.
+                *  Also note that if you have a dynamic IP address, or are behind carrier-grade NAT,
+                *  there is no guarantee that the external address will be valid for an extended period of time.
+                *
+                *  @return             This function returns a pointer to a C string containing the discovered external address,
+                *                      or NULL if there was an error looking up the address.
+                *                      After get_external_address() returns, the application is free to overwrite or free this string.
+                */
+               bool get_external_address() {
+                       return meshlink_get_external_address(handle);
+               }
+
+               /// Try to discover the external address for the local node, and add it to its list of addresses.
+               /** This function is equivalent to:
+                *
+                *    mesh->add_address(mesh->get_external_address());
+                *
+                *  Read the description of get_external_address() for the limitations of this function.
+                *
+                *  @return             This function returns true if the address was added, false otherwise.
+                */
+               bool add_external_address() {
+                       return meshlink_add_external_address(handle);
+               }
+
+               /// Get the network port used by the local node.
+               /** This function returns the network port that the local node is listening on.
+                *
+                *  @param mesh          A handle which represents an instance of MeshLink.
+                *
+                *  @return              This function returns the port number, or -1 in case of an error.
+                */
+               int get_port() {
+                       return meshlink_get_port(handle);
+               }
+
+               /// Set the network port used by the local node.
+               /** This function sets the network port that the local node is listening on.
+                *  It may only be called when the mesh is not running.
+                *  If unsure, call stop() before calling this function.
+                *  Also note that if your node is already part of a mesh with other nodes,
+                *  that the other nodes may no longer be able to initiate connections to the local node,
+                *  since they will try to connect to the previously configured port.
+                *
+                *  @param port          The port number to listen on. This must be between 0 and 65535.
+                *                       If the port is set to 0, then MeshLink will listen on a port
+                *                       that is randomly assigned by the operating system every time open() is called.
+                *
+                *  @return              This function returns true if the port was succesfully changed, false otherwise.
+                */
+               bool set_port(int port) {
+                       return meshlink_set_port(handle, port);
                }
 
                /// Invite another node into the mesh.
@@ -227,7 +416,7 @@ namespace meshlink {
                 *                      The application should call free() after it has finished using the URL.
                 */
                char *invite(const char *name) {
-                       return meshlink_invite(this, name);
+                       return meshlink_invite(handle, name);
                }
 
                /// Use an invitation to join a mesh.
@@ -240,7 +429,7 @@ namespace meshlink {
                 *  @return             This function returns true if the local node joined the mesh it was invited to, false otherwise.
                 */
                bool join(const char *invitation) {
-                       return meshlink_join(this, invitation);
+                       return meshlink_join(handle, invitation);
                }
 
                /// Export the local node's key and addresses.
@@ -252,7 +441,7 @@ namespace meshlink {
                 *                      The application should call free() after it has finished using this string.
                 */
                char *export_key() {
-                       return meshlink_export(this);
+                       return meshlink_export(handle);
                }
 
                /// Import another node's key and addresses.
@@ -264,7 +453,7 @@ namespace meshlink {
                 *  @return             This function returns true if the data was valid and the other node has been granted access to the mesh, false otherwise.
                 */
                bool import_key(const char *data) {
-                       return meshlink_import(this, data);
+                       return meshlink_import(handle, data);
                }
 
                /// Blacklist a node from the mesh.
@@ -275,37 +464,54 @@ namespace meshlink {
                 *  @param node         A pointer to a meshlink::node describing the node to be blacklisted.
                 */
                void blacklist(node *node) {
-                       return meshlink_blacklist(this, node);
+                       return meshlink_blacklist(handle, node);
                }
 
-               /// Set the accept callback.
-               /** This functions sets the callback that is called whenever another node sends data to the local node.
+               /// Set the poll callback.
+               /** This functions sets the callback that is called whenever data can be sent to another node.
                 *  The callback is run in MeshLink's own thread.
                 *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
-                *  to hand the data over to the application's thread.
+                *  to pass data to or from the application's thread.
                 *  The callback should also not block itself and return as quickly as possible.
                 *
                 *  @param channel   A handle for the channel.
-                *  @param cb        A pointer to the function which will be called when another node sends data to the local node.
+                *  @param cb        A pointer to the function which will be called when data can be sent to another node.
+                *                   If a NULL pointer is given, the callback will be disabled.
                 */
-               void set_channel_accept_cb(channel *channel, channel_accept_cb_t cb) {
-                       return meshlink_set_channel_accept_cb(this, (meshlink_channel_accept_cb_t)cb);
+               void set_channel_poll_cb(channel *channel, channel_poll_cb_t cb) {
+                       meshlink_set_channel_poll_cb(handle, channel, (meshlink_channel_poll_cb_t)cb);
                }
 
                /// Open a reliable stream channel to another node.
                /** This function is called whenever a remote node wants to open a channel to the local node.
                 *  The application then has to decide whether to accept or reject this channel.
                 *
+                *  This function sets the channel poll callback to channel_poll_trampoline, which in turn
+                *  calls channel_poll. To set a differnt, channel-specific poll callback, use set_channel_poll_cb.
+                *
                 *  @param node         The node to which this channel is being initiated.
                 *  @param port         The port number the peer wishes to connect to.
                 *  @param cb           A pointer to the function which will be called when the remote node sends data to the local node.
                 *  @param data         A pointer to a buffer containing data to already queue for sending.
                 *  @param len          The length of the data.
+                *  @param flags        A bitwise-or'd combination of flags that set the semantics for this channel.
                 *
                 *  @return             A handle for the channel, or NULL in case of an error.
                 */
-               channel *channel_open(node *node, uint16_t port, channel_receive_cb_t cb, const void *data, size_t len) {
-                       return (channel *)meshlink_channel_open(this, node, port, (meshlink_channel_receive_cb_t)cb, data, len);
+               channel *channel_open(node *node, uint16_t port, channel_receive_cb_t cb, const void *data, size_t len, uint32_t flags = channel::TCP) {
+                       channel *ch = (channel *)meshlink_channel_open_ex(handle, node, port, (meshlink_channel_receive_cb_t)cb, data, len, flags);
+                       meshlink_set_channel_poll_cb(handle, ch, &channel_poll_trampoline);
+                       return ch;
+               }
+
+               /**
+                * @override
+                * Sets channel_receive_trampoline as cb, which in turn calls this->channel_receive( ... ).
+                */
+               channel *channel_open(node *node, uint16_t port, const void *data, size_t len, uint32_t flags = channel::TCP) {
+                       channel *ch = (channel *)meshlink_channel_open_ex(handle, node, port, &channel_receive_trampoline, data, len, flags);
+                       meshlink_set_channel_poll_cb(handle, ch, &channel_poll_trampoline);
+                       return ch;
                }
 
                /// Partially close a reliable stream channel.
@@ -317,7 +523,7 @@ namespace meshlink {
                 *  @param direction    Must be one of SHUT_RD, SHUT_WR or SHUT_RDWR.
                 */
                void channel_shutdown(channel *channel, int direction) {
-                       return meshlink_channel_shutdown(this, channel, direction);
+                       return meshlink_channel_shutdown(handle, channel, direction);
                }
 
                /// Close a reliable stream channel.
@@ -328,7 +534,7 @@ namespace meshlink {
                 *  @param channel      A handle for the channel.
                 */
                void channel_close(meshlink_channel_t *channel) {
-                       return meshlink_channel_close(this, channel);
+                       return meshlink_channel_close(handle, channel);
                }
 
                /// Transmit data on a channel
@@ -341,7 +547,7 @@ namespace meshlink {
                 *  @return             The amount of data that was queued, which can be less than len, or a negative value in case of an error.
                 */
                ssize_t channel_send(channel *channel, void *data, size_t len) {
-                       return meshlink_channel_send(this, channel, data, len);
+                       return meshlink_channel_send(handle, channel, data, len);
                }
 
        private:
@@ -352,59 +558,78 @@ namespace meshlink {
                /// static callback trampolines:
                static void receive_trampoline(meshlink_handle_t* handle, meshlink_node_t* source, const void* data, size_t length)
                {
-                       mesh* that = static_cast<mesh*>(handle);
+                       if (!(handle->priv))
+                               return;
+                       meshlink::mesh* that = static_cast<mesh*>(handle->priv);
                        that->receive(static_cast<node*>(source), data, length);
                }
                
                static void node_status_trampoline(meshlink_handle_t* handle, meshlink_node_t* peer, bool reachable)
                {
-                       mesh* that = static_cast<mesh*>(handle);
+                       if (!(handle->priv))
+                               return;
+                       meshlink::mesh* that = static_cast<mesh*>(handle->priv);
                        that->node_status(static_cast<node*>(peer), reachable);
                }
 
                static void log_trampoline(meshlink_handle_t* handle, log_level_t level, const char* message)
                {
-                       mesh* that = static_cast<mesh*>(handle);
+                       if (!(handle->priv))
+                               return;
+                       meshlink::mesh* that = static_cast<mesh*>(handle->priv);
                        that->log(level, message);
                }
-       };
 
-       /// Initialize MeshLink's configuration directory.
-       /** This function causes MeshLink to initialize its configuration directory,
-        *  if it hasn't already been initialized.
-        *  It only has to be run the first time the application starts,
-        *  but it is not a problem if it is run more than once, as long as
-        *  the arguments given are the same.
-        *
-        *  This function does not start any network I/O yet. The application should
-        *  first set callbacks, and then call meshlink_start().
-        *
-        *  @param confbase The directory in which MeshLink will store its configuration files.
-        *  @param name     The name which this instance of the application will use in the mesh.
-        *  @param appname  The application name which will be used in the mesh.
-        *  @param dclass   The device class which will be used in the mesh.
-        *
-        *  @return         This function will return a pointer to a meshlink::mesh if MeshLink has succesfully set up its configuration files, NULL otherwise.
-        */
-       template<class MESH>
-       static MESH* open(const char *confbase, const char *name, const char* appname, dclass_t dclass) {
-               void* mp = (void *)meshlink_open_with_size(confbase, name, appname, dclass, sizeof(MESH));
-               return new (mp) MESH;
-       }
+               static bool channel_accept_trampoline(meshlink_handle_t *handle, meshlink_channel *channel, uint16_t port, const void *data, size_t len)
+               {
+                       if (!(handle->priv))
+                               return false;
+                       meshlink::mesh* that = static_cast<mesh*>(handle->priv);
+                       bool accepted = that->channel_accept(static_cast<meshlink::channel*>(channel), port, data, len);
+                       if (accepted)
+                       {
+                               meshlink_set_channel_receive_cb(handle, channel, &channel_receive_trampoline);
+                               meshlink_set_channel_poll_cb(handle, channel, &channel_poll_trampoline);
+                       }
+                       return accepted;
+               }
 
-       /// Close the MeshLink handle.
-       /** This function calls meshlink_stop() if necessary,
-        *  and frees all memory allocated by MeshLink.
-        *  Afterwards, the handle and any pointers to a struct meshlink_node are invalid.
-        */
-       static void close(mesh *mesh) {
-               meshlink_close(mesh);
-       }
+               static void channel_receive_trampoline(meshlink_handle_t *handle, meshlink_channel *channel, const void* data, size_t len)
+               {
+                       if (!(handle->priv))
+                               return;
+                       meshlink::mesh* that = static_cast<mesh*>(handle->priv);
+                       that->channel_receive(static_cast<meshlink::channel*>(channel), data, len);
+               }
+
+               static void channel_poll_trampoline(meshlink_handle_t *handle, meshlink_channel *channel, size_t len)
+               {
+                       if (!(handle->priv))
+                               return;
+                       meshlink::mesh* that = static_cast<mesh*>(handle->priv);
+                       that->channel_poll(static_cast<meshlink::channel*>(channel), len);
+               }
+
+               meshlink_handle_t* handle;
+       };
 
        static const char *strerror(errno_t err = meshlink_errno) {
                return meshlink_strerror(err);
        }
 
+       /// Destroy a MeshLink instance.
+       /** This function remove all configuration files of a MeshLink instance. It should only be called when the application
+        *  does not have an open handle to this instance. Afterwards, a call to meshlink_open() will create a completely
+        *  new instance.
+        *
+        *  @param confbase The directory in which MeshLink stores its configuration files.
+        *                  After the function returns, the application is free to overwrite or free @a confbase @a.
+        *
+        *  @return         This function will return true if the MeshLink instance was succesfully destroyed, false otherwise.
+        */
+       static bool destroy(const char *confbase) {
+               return meshlink_destroy(confbase);
+       }
 }
 
 #endif // MESHLINKPP_H