5 meshlink-tiny++.h -- MeshLink C++ API
6 Copyright (C) 2014, 2017 Guus Sliepen <guus@meshlink.io>
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <meshlink-tiny.h>
24 #include <new> // for 'placement new'
30 /// Severity of log messages generated by MeshLink.
31 typedef meshlink_log_level_t log_level_t;
33 /// Code of most recent error encountered.
34 typedef meshlink_errno_t errno_t;
36 /// A callback for receiving data from the mesh.
37 /** @param mesh A handle which represents an instance of MeshLink.
38 * @param source A pointer to a meshlink::node describing the source of the data.
39 * @param data A pointer to a buffer containing the data sent by the source.
40 * @param len The length of the received data.
42 typedef void (*receive_cb_t)(mesh *mesh, node *source, const void *data, size_t len);
44 /// A callback reporting the meta-connection attempt made by the host node to an another node.
45 /** @param mesh A handle which represents an instance of MeshLink.
46 * @param node A pointer to a meshlink_node_t describing the node to whom meta-connection is being tried.
47 * This pointer is valid until meshlink_close() is called.
49 typedef void (*connection_try_cb_t)(mesh *mesh, node *node);
51 /// A callback reporting node status changes.
52 /** @param mesh A handle which represents an instance of MeshLink.
53 * @param node A pointer to a meshlink::node describing the node whose status changed.
54 * @param reachable True if the node is reachable, false otherwise.
56 typedef void (*node_status_cb_t)(mesh *mesh, node *node, bool reachable);
58 /// A callback reporting duplicate node detection.
59 /** @param mesh A handle which represents an instance of MeshLink.
60 * @param node A pointer to a meshlink_node_t describing the node which is duplicate.
61 * This pointer is valid until meshlink_close() is called.
63 typedef void (*duplicate_cb_t)(mesh *mesh, node *node);
65 /// A callback for receiving log messages generated by MeshLink.
66 /** @param mesh A handle which represents an instance of MeshLink.
67 * @param level An enum describing the severity level of the message.
68 * @param text A pointer to a string containing the textual log message.
70 typedef void (*log_cb_t)(mesh *mesh, log_level_t level, const char *text);
72 /// A class describing a MeshLink node.
73 class node: public meshlink_node_t {
76 /// A class describing a MeshLink mesh.
89 // TODO: please enable C++11 in autoconf to enable "move constructors":
91 // : handle(other.handle)
94 // handle->priv = this;
98 /// Initialize MeshLink's configuration directory.
99 /** This function causes MeshLink to initialize its configuration directory,
100 * if it hasn't already been initialized.
101 * It only has to be run the first time the application starts,
102 * but it is not a problem if it is run more than once, as long as
103 * the arguments given are the same.
105 * This function does not start any network I/O yet. The application should
106 * first set callbacks, and then call meshlink_start().
108 * @param confbase The directory in which MeshLink will store its configuration files.
109 * @param name The name which this instance of the application will use in the mesh.
110 * @param appname The application name which will be used in the mesh.
111 * @param devclass The device class which will be used in the mesh.
113 * @return This function will return a pointer to a meshlink::mesh if MeshLink has successfully set up its configuration files, NULL otherwise.
115 bool open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
116 handle = meshlink_open(confbase, name, appname, devclass);
125 mesh(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
126 open(confbase, name, appname, devclass);
129 /// Close the MeshLink handle.
130 /** This function calls meshlink_stop() if necessary,
131 * and frees all memory allocated by MeshLink.
132 * Afterwards, the handle and any pointers to a struct meshlink_node are invalid.
137 meshlink_close(handle);
143 /** instead of registerin callbacks you derive your own class and overwrite the following abstract member functions.
144 * These functions are run in MeshLink's own thread.
145 * It is therefore important that these functions use apprioriate methods (queues, pipes, locking, etc.)
146 * to hand the data over to the application's thread.
147 * These functions should also not block itself and return as quickly as possible.
148 * The default member functions are no-ops, so you are not required to overwrite all these member functions
151 /// This function is called whenever another node sends data to the local node.
152 virtual void receive(node *source, const void *data, size_t length) {
159 /// This functions is called whenever another node's status changed.
160 virtual void node_status(node *peer, bool reachable) {
166 /// This functions is called whenever a duplicate node is detected.
167 virtual void node_duplicate(node *peer) {
172 /// This functions is called whenever MeshLink has some information to log.
173 virtual void log(log_level_t level, const char *message) {
179 /// This functions is called whenever MeshLink has encountered a serious error.
180 virtual void error(meshlink_errno_t meshlink_errno) {
182 (void)meshlink_errno;
185 /// This functions is called whenever MeshLink a meta-connection attempt is made.
186 virtual void connection_try(node *peer) {
192 /** This function causes MeshLink to open network sockets, make outgoing connections, and
193 * create a new thread, which will handle all network I/O.
195 * @return This function will return true if MeshLink has successfully started its thread, false otherwise.
198 meshlink_set_receive_cb(handle, &receive_trampoline);
199 meshlink_set_node_status_cb(handle, &node_status_trampoline);
200 meshlink_set_node_duplicate_cb(handle, &node_duplicate_trampoline);
201 meshlink_set_log_cb(handle, MESHLINK_DEBUG, &log_trampoline);
202 meshlink_set_error_cb(handle, &error_trampoline);
203 meshlink_set_connection_try_cb(handle, &connection_try_trampoline);
204 return meshlink_start(handle);
208 /** This function causes MeshLink to disconnect from all other nodes,
209 * close all sockets, and shut down its own thread.
212 meshlink_stop(handle);
215 /// Send data to another node.
216 /** This functions sends one packet of data to another node in the mesh.
217 * The packet is sent using UDP semantics, which means that
218 * the packet is sent as one unit and is received as one unit,
219 * and that there is no guarantee that the packet will arrive at the destination.
220 * The application should take care of getting an acknowledgement and retransmission if necessary.
222 * @param destination A pointer to a meshlink::node describing the destination for the data.
223 * @param data A pointer to a buffer containing the data to be sent to the source.
224 * @param len The length of the data.
225 * @return This function will return true if MeshLink has queued the message for transmission, and false otherwise.
226 * A return value of true does not guarantee that the message will actually arrive at the destination.
228 bool send(node *destination, const void *data, unsigned int len) {
229 return meshlink_send(handle, destination, data, len);
232 /// Get a handle for a specific node.
233 /** This function returns a handle for the node with the given name.
235 * @param name The name of the node for which a handle is requested.
237 * @return A pointer to a meshlink::node which represents the requested node,
238 * or NULL if the requested node does not exist.
240 node *get_node(const char *name) {
241 return (node *)meshlink_get_node(handle, name);
244 /// Get a node's reachability status.
245 /** This function returns the current reachability of a given node, and the times of the last state changes.
246 * If a given state change never happened, the time returned will be 0.
248 * @param node A pointer to a meshlink::node describing the node.
249 * @param last_reachable A pointer to a time_t variable that will be filled in with the last time the node became reachable.
250 * @param last_unreachable A pointer to a time_t variable that will be filled in with the last time the node became unreachable.
252 * @return This function returns true if the node is currently reachable, false otherwise.
254 bool get_node_reachability(node *node, time_t *last_reachable = NULL, time_t *last_unreachable = NULL) {
255 return meshlink_get_node_reachability(handle, node, last_reachable, last_unreachable);
258 /// Get a handle for our own node.
259 /** This function returns a handle for the local node.
261 * @return A pointer to a meshlink::node which represents the local node.
264 return (node *)meshlink_get_self(handle);
267 /// Get a list of all nodes.
268 /** This function returns a list with handles for all known nodes.
270 * @param nodes A pointer to an array of pointers to meshlink::node, which should be allocated by the application.
271 * @param nmemb The maximum number of pointers that can be stored in the nodes array.
273 * @return The number of known nodes, or -1 in case of an error.
274 * This can be larger than nmemb, in which case not all nodes were stored in the nodes array.
276 node **get_all_nodes(node **nodes, size_t *nmemb) {
277 return (node **)meshlink_get_all_nodes(handle, (meshlink_node_t **)nodes, nmemb);
280 /// Sign data using the local node's MeshLink key.
281 /** This function signs data using the local node's MeshLink key.
282 * The generated signature can be securely verified by other nodes.
284 * @param data A pointer to a buffer containing the data to be signed.
285 * @param len The length of the data to be signed.
286 * @param signature A pointer to a buffer where the signature will be stored.
287 * @param siglen The size of the signature buffer. Will be changed after the call to match the size of the signature itself.
289 * @return This function returns true if the signature is valid, false otherwise.
291 bool sign(const void *data, size_t len, void *signature, size_t *siglen) {
292 return meshlink_sign(handle, data, len, signature, siglen);
295 /// Verify the signature generated by another node of a piece of data.
296 /** This function verifies the signature that another node generated for a piece of data.
298 * @param source A pointer to a meshlink_node_t describing the source of the signature.
299 * @param data A pointer to a buffer containing the data to be verified.
300 * @param len The length of the data to be verified.
301 * @param signature A pointer to a string containing the signature.
302 * @param siglen The size of the signature.
304 * @return This function returns true if the signature is valid, false otherwise.
306 bool verify(node *source, const void *data, size_t len, const void *signature, size_t siglen) {
307 return meshlink_verify(handle, source, data, len, signature, siglen);
310 /// Set the canonical Address for a node.
311 /** This function sets the canonical Address for a node.
312 * This address is stored permanently until it is changed by another call to this function,
313 * unlike other addresses associated with a node,
314 * such as those added with meshlink_hint_address() or addresses discovered at runtime.
316 * If a canonical Address is set for the local node,
317 * it will be used for the hostname part of generated invitation URLs.
319 * @param node A pointer to a meshlink_node_t describing the node.
320 * @param address A nul-terminated C string containing the address, which can be either in numeric format or a hostname.
321 * @param port A nul-terminated C string containing the port, which can be either in numeric or symbolic format.
322 * If it is NULL, the listening port's number will be used.
324 * @return This function returns true if the address was added, false otherwise.
326 bool set_canonical_address(node *node, const char *address, const char *port = NULL) {
327 return meshlink_set_canonical_address(handle, node, address, port);
330 /// Clear the canonical Address for a node.
331 /** This function clears the canonical Address for a node.
333 * @param node A pointer to a struct meshlink_node describing the node.
335 * @return This function returns true if the address was removed, false otherwise.
337 bool clear_canonical_address(node *node) {
338 return meshlink_clear_canonical_address(handle, node);
341 /// Set the scheduling granularity of the application
342 /** This should be set to the effective scheduling granularity for the application.
343 * This depends on the scheduling granularity of the operating system, the application's
344 * process priority and whether it is running as realtime or not.
345 * The default value is 10000 (10 milliseconds).
347 * @param granularity The scheduling granularity of the application in microseconds.
349 void set_granularity(long granularity) {
350 meshlink_set_scheduling_granularity(handle, granularity);
353 /// Sets the storage policy used by MeshLink
354 /** This sets the policy MeshLink uses when it has new information about nodes.
355 * By default, all udpates will be stored to disk (unless an ephemeral instance has been opened).
356 * Setting the policy to MESHLINK_STORAGE_KEYS_ONLY, only updates that contain new keys for nodes
358 * By setting the policy to MESHLINK_STORAGE_DISABLED, no updates will be stored.
360 * @param policy The storage policy to use.
362 void set_storage_policy(meshlink_storage_policy_t policy) {
363 meshlink_set_storage_policy(handle, policy);
366 /// Use an invitation to join a mesh.
367 /** This function allows the local node to join an existing mesh using an invitation URL generated by another node.
368 * An invitation can only be used if the local node has never connected to other nodes before.
369 * After a successfully accepted invitation, the name of the local node may have changed.
371 * This function may only be called on a mesh that has not been started yet and which is not already part of an existing mesh.
373 * This function is blocking. It can take several seconds before it returns.
374 * There is no guarantee it will perform a successful join.
375 * Failures might be caused by temporary network outages, or by the invitation having expired.
377 * @param invitation A string containing the invitation URL.
379 * @return This function returns true if the local node joined the mesh it was invited to, false otherwise.
381 bool join(const char *invitation) {
382 return meshlink_join(handle, invitation);
385 /// Export the local node's key and addresses.
386 /** This function generates a string that contains the local node's public key and one or more IP addresses.
387 * The application can pass it in some way to another node, which can then import it,
388 * granting the local node access to the other node's mesh.
390 * @return This function returns a string that contains the exported key and addresses.
391 * The application should call free() after it has finished using this string.
394 return meshlink_export(handle);
397 /// Import another node's key and addresses.
398 /** This function accepts a string containing the exported public key and addresses of another node.
399 * By importing this data, the local node grants the other node access to its mesh.
401 * @param data A string containing the other node's exported key and addresses.
403 * @return This function returns true if the data was valid and the other node has been granted access to the mesh, false otherwise.
405 bool import_key(const char *data) {
406 return meshlink_import(handle, data);
409 /// Forget any information about a node.
410 /** This function allows the local node to forget any information it has about a node,
411 * and if possible will remove any data it has stored on disk about the node.
413 * After this call returns, the node handle is invalid and may no longer be used, regardless
414 * of the return value of this call.
416 * Note that this function does not prevent MeshLink from actually forgetting about a node,
417 * or re-learning information about a node at a later point in time. It is merely a hint that
418 * the application does not care about this node anymore and that any resources kept could be
421 * \memberof meshlink_node
422 * @param node A pointer to a struct meshlink_node describing the node to be forgotten.
424 * @return This function returns true if all currently known data about the node has been forgotten, false otherwise.
426 bool forget_node(node *node) {
427 return meshlink_forget_node(handle, node);
430 /// Inform MeshLink that the local network configuration might have changed
431 /** This is intended to be used when there is no way for MeshLink to get notifications of local network changes.
432 * It forces MeshLink to scan all network interfaces for changes in up/down status and new/removed addresses,
433 * and will immediately check if all connections to other nodes are still alive.
435 void hint_network_change() {
436 meshlink_hint_network_change(handle);
439 /// Set device class timeouts
440 /** This sets the ping interval and timeout for a given device class.
442 * @param devclass The device class to update
443 * @param pinginterval The interval between keepalive packets, in seconds. The default is 60.
444 * @param pingtimeout The required time within which a peer should respond, in seconds. The default is 5.
445 * The timeout must be smaller than the interval.
447 void set_dev_class_timeouts(dev_class_t devclass, int pinginterval, int pingtimeout) {
448 meshlink_set_dev_class_timeouts(handle, devclass, pinginterval, pingtimeout);
451 /// Set device class fast retry period
452 /** This sets the fast retry period for a given device class.
453 * During this period after the last time the mesh becomes unreachable, connections are tried once a second.
455 * @param devclass The device class to update
456 * @param fast_retry_period The period during which fast connection retries are done. The default is 0.
458 void set_dev_class_fast_retry_period(dev_class_t devclass, int fast_retry_period) {
459 meshlink_set_dev_class_fast_retry_period(handle, devclass, fast_retry_period);
462 /// Set device class maximum timeout
463 /** This sets the maximum timeout for outgoing connection retries for a given device class.
465 * @param devclass The device class to update
466 * @param maxtimeout The maximum timeout between reconnection attempts, in seconds. The default is 900.
468 void set_dev_class_maxtimeout(dev_class_t devclass, int maxtimeout) {
469 meshlink_set_dev_class_maxtimeout(handle, devclass, maxtimeout);
472 /// Set which order invitations are committed
473 /** This determines in which order configuration files are written to disk during an invitation.
474 * By default, the invitee saves the configuration to disk first, then the inviter.
475 * By calling this function with @a inviter_commits_first set to true, the order is reversed.
477 * @param inviter_commits_first If true, then the node that invited a peer will commit data to disk first.
479 void set_inviter_commits_first(bool inviter_commits_first) {
480 meshlink_set_inviter_commits_first(handle, inviter_commits_first);
485 mesh(const mesh &) /* TODO: C++11: = delete */;
486 void operator=(const mesh &) /* TODO: C++11: = delete */;
488 /// static callback trampolines:
489 static void receive_trampoline(meshlink_handle_t *handle, meshlink_node_t *source, const void *data, size_t length) {
490 if(!(handle->priv)) {
494 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
495 that->receive(static_cast<node *>(source), data, length);
498 static void node_status_trampoline(meshlink_handle_t *handle, meshlink_node_t *peer, bool reachable) {
499 if(!(handle->priv)) {
503 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
504 that->node_status(static_cast<node *>(peer), reachable);
507 static void node_duplicate_trampoline(meshlink_handle_t *handle, meshlink_node_t *peer) {
508 if(!(handle->priv)) {
512 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
513 that->node_duplicate(static_cast<node *>(peer));
516 static void log_trampoline(meshlink_handle_t *handle, log_level_t level, const char *message) {
517 if(!(handle->priv)) {
521 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
522 that->log(level, message);
525 static void error_trampoline(meshlink_handle_t *handle, meshlink_errno_t meshlink_errno) {
526 if(!(handle->priv)) {
530 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
531 that->error(meshlink_errno);
534 static void connection_try_trampoline(meshlink_handle_t *handle, meshlink_node_t *peer) {
535 if(!(handle->priv)) {
539 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
540 that->connection_try(static_cast<node *>(peer));
543 meshlink_handle_t *handle;
546 static inline const char *strerror(errno_t err = meshlink_errno) {
547 return meshlink_strerror(err);
550 /// Destroy a MeshLink instance.
551 /** This function remove all configuration files of a MeshLink instance. It should only be called when the application
552 * does not have an open handle to this instance. Afterwards, a call to meshlink_open() will create a completely
555 * @param confbase The directory in which MeshLink stores its configuration files.
556 * After the function returns, the application is free to overwrite or free @a confbase @a.
558 * @return This function will return true if the MeshLink instance was successfully destroyed, false otherwise.
560 static inline bool destroy(const char *confbase) {
561 return meshlink_destroy(confbase);