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 handle for our own node.
245 /** This function returns a handle for the local node.
247 * @return A pointer to a meshlink::node which represents the local node.
250 return (node *)meshlink_get_self(handle);
253 /// Get a list of all nodes.
254 /** This function returns a list with handles for all known nodes.
256 * @param nodes A pointer to an array of pointers to meshlink::node, which should be allocated by the application.
257 * @param nmemb The maximum number of pointers that can be stored in the nodes array.
259 * @return The number of known nodes, or -1 in case of an error.
260 * This can be larger than nmemb, in which case not all nodes were stored in the nodes array.
262 node **get_all_nodes(node **nodes, size_t *nmemb) {
263 return (node **)meshlink_get_all_nodes(handle, (meshlink_node_t **)nodes, nmemb);
266 /// Sign data using the local node's MeshLink key.
267 /** This function signs data using the local node's MeshLink key.
268 * The generated signature can be securely verified by other nodes.
270 * @param data A pointer to a buffer containing the data to be signed.
271 * @param len The length of the data to be signed.
272 * @param signature A pointer to a buffer where the signature will be stored.
273 * @param siglen The size of the signature buffer. Will be changed after the call to match the size of the signature itself.
275 * @return This function returns true if the signature is valid, false otherwise.
277 bool sign(const void *data, size_t len, void *signature, size_t *siglen) {
278 return meshlink_sign(handle, data, len, signature, siglen);
281 /// Verify the signature generated by another node of a piece of data.
282 /** This function verifies the signature that another node generated for a piece of data.
284 * @param source A pointer to a meshlink_node_t describing the source of the signature.
285 * @param data A pointer to a buffer containing the data to be verified.
286 * @param len The length of the data to be verified.
287 * @param signature A pointer to a string containing the signature.
288 * @param siglen The size of the signature.
290 * @return This function returns true if the signature is valid, false otherwise.
292 bool verify(node *source, const void *data, size_t len, const void *signature, size_t siglen) {
293 return meshlink_verify(handle, source, data, len, signature, siglen);
296 /// Set the canonical Address for a node.
297 /** This function sets the canonical Address for a node.
298 * This address is stored permanently until it is changed by another call to this function,
299 * unlike other addresses associated with a node,
300 * such as those added with meshlink_hint_address() or addresses discovered at runtime.
302 * If a canonical Address is set for the local node,
303 * it will be used for the hostname part of generated invitation URLs.
305 * @param node A pointer to a meshlink_node_t describing the node.
306 * @param address A nul-terminated C string containing the address, which can be either in numeric format or a hostname.
307 * @param port A nul-terminated C string containing the port, which can be either in numeric or symbolic format.
308 * If it is NULL, the listening port's number will be used.
310 * @return This function returns true if the address was added, false otherwise.
312 bool set_canonical_address(node *node, const char *address, const char *port = NULL) {
313 return meshlink_set_canonical_address(handle, node, address, port);
316 /// Clear the canonical Address for a node.
317 /** This function clears the canonical Address for a node.
319 * @param node A pointer to a struct meshlink_node describing the node.
321 * @return This function returns true if the address was removed, false otherwise.
323 bool clear_canonical_address(node *node) {
324 return meshlink_clear_canonical_address(handle, node);
327 /// Set the scheduling granularity of the application
328 /** This should be set to the effective scheduling granularity for the application.
329 * This depends on the scheduling granularity of the operating system, the application's
330 * process priority and whether it is running as realtime or not.
331 * The default value is 10000 (10 milliseconds).
333 * @param granularity The scheduling granularity of the application in microseconds.
335 void set_granularity(long granularity) {
336 meshlink_set_scheduling_granularity(handle, granularity);
339 /// Sets the storage policy used by MeshLink
340 /** This sets the policy MeshLink uses when it has new information about nodes.
341 * By default, all udpates will be stored to disk (unless an ephemeral instance has been opened).
342 * Setting the policy to MESHLINK_STORAGE_KEYS_ONLY, only updates that contain new keys for nodes
344 * By setting the policy to MESHLINK_STORAGE_DISABLED, no updates will be stored.
346 * @param policy The storage policy to use.
348 void set_storage_policy(meshlink_storage_policy_t policy) {
349 meshlink_set_storage_policy(handle, policy);
352 /// Use an invitation to join a mesh.
353 /** This function allows the local node to join an existing mesh using an invitation URL generated by another node.
354 * An invitation can only be used if the local node has never connected to other nodes before.
355 * After a successfully accepted invitation, the name of the local node may have changed.
357 * 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.
359 * This function is blocking. It can take several seconds before it returns.
360 * There is no guarantee it will perform a successful join.
361 * Failures might be caused by temporary network outages, or by the invitation having expired.
363 * @param invitation A string containing the invitation URL.
365 * @return This function returns true if the local node joined the mesh it was invited to, false otherwise.
367 bool join(const char *invitation) {
368 return meshlink_join(handle, invitation);
371 /// Export the local node's key and addresses.
372 /** This function generates a string that contains the local node's public key and one or more IP addresses.
373 * The application can pass it in some way to another node, which can then import it,
374 * granting the local node access to the other node's mesh.
376 * @return This function returns a string that contains the exported key and addresses.
377 * The application should call free() after it has finished using this string.
380 return meshlink_export(handle);
383 /// Import another node's key and addresses.
384 /** This function accepts a string containing the exported public key and addresses of another node.
385 * By importing this data, the local node grants the other node access to its mesh.
387 * @param data A string containing the other node's exported key and addresses.
389 * @return This function returns true if the data was valid and the other node has been granted access to the mesh, false otherwise.
391 bool import_key(const char *data) {
392 return meshlink_import(handle, data);
395 /// Forget any information about a node.
396 /** This function allows the local node to forget any information it has about a node,
397 * and if possible will remove any data it has stored on disk about the node.
399 * After this call returns, the node handle is invalid and may no longer be used, regardless
400 * of the return value of this call.
402 * Note that this function does not prevent MeshLink from actually forgetting about a node,
403 * or re-learning information about a node at a later point in time. It is merely a hint that
404 * the application does not care about this node anymore and that any resources kept could be
407 * \memberof meshlink_node
408 * @param node A pointer to a struct meshlink_node describing the node to be forgotten.
410 * @return This function returns true if all currently known data about the node has been forgotten, false otherwise.
412 bool forget_node(node *node) {
413 return meshlink_forget_node(handle, node);
416 /// Inform MeshLink that the local network configuration might have changed
417 /** This is intended to be used when there is no way for MeshLink to get notifications of local network changes.
418 * It forces MeshLink to scan all network interfaces for changes in up/down status and new/removed addresses,
419 * and will immediately check if all connections to other nodes are still alive.
421 void hint_network_change() {
422 meshlink_hint_network_change(handle);
425 /// Set device class timeouts
426 /** This sets the ping interval and timeout for a given device class.
428 * @param devclass The device class to update
429 * @param pinginterval The interval between keepalive packets, in seconds. The default is 60.
430 * @param pingtimeout The required time within which a peer should respond, in seconds. The default is 5.
431 * The timeout must be smaller than the interval.
433 void set_dev_class_timeouts(dev_class_t devclass, int pinginterval, int pingtimeout) {
434 meshlink_set_dev_class_timeouts(handle, devclass, pinginterval, pingtimeout);
437 /// Set device class fast retry period
438 /** This sets the fast retry period for a given device class.
439 * During this period after the last time the mesh becomes unreachable, connections are tried once a second.
441 * @param devclass The device class to update
442 * @param fast_retry_period The period during which fast connection retries are done. The default is 0.
444 void set_dev_class_fast_retry_period(dev_class_t devclass, int fast_retry_period) {
445 meshlink_set_dev_class_fast_retry_period(handle, devclass, fast_retry_period);
448 /// Set device class maximum timeout
449 /** This sets the maximum timeout for outgoing connection retries for a given device class.
451 * @param devclass The device class to update
452 * @param maxtimeout The maximum timeout between reconnection attempts, in seconds. The default is 900.
454 void set_dev_class_maxtimeout(dev_class_t devclass, int maxtimeout) {
455 meshlink_set_dev_class_maxtimeout(handle, devclass, maxtimeout);
458 /// Set which order invitations are committed
459 /** This determines in which order configuration files are written to disk during an invitation.
460 * By default, the invitee saves the configuration to disk first, then the inviter.
461 * By calling this function with @a inviter_commits_first set to true, the order is reversed.
463 * @param inviter_commits_first If true, then the node that invited a peer will commit data to disk first.
465 void set_inviter_commits_first(bool inviter_commits_first) {
466 meshlink_set_inviter_commits_first(handle, inviter_commits_first);
471 mesh(const mesh &) /* TODO: C++11: = delete */;
472 void operator=(const mesh &) /* TODO: C++11: = delete */;
474 /// static callback trampolines:
475 static void receive_trampoline(meshlink_handle_t *handle, meshlink_node_t *source, const void *data, size_t length) {
476 if(!(handle->priv)) {
480 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
481 that->receive(static_cast<node *>(source), data, length);
484 static void node_status_trampoline(meshlink_handle_t *handle, meshlink_node_t *peer, bool reachable) {
485 if(!(handle->priv)) {
489 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
490 that->node_status(static_cast<node *>(peer), reachable);
493 static void node_duplicate_trampoline(meshlink_handle_t *handle, meshlink_node_t *peer) {
494 if(!(handle->priv)) {
498 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
499 that->node_duplicate(static_cast<node *>(peer));
502 static void log_trampoline(meshlink_handle_t *handle, log_level_t level, const char *message) {
503 if(!(handle->priv)) {
507 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
508 that->log(level, message);
511 static void error_trampoline(meshlink_handle_t *handle, meshlink_errno_t meshlink_errno) {
512 if(!(handle->priv)) {
516 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
517 that->error(meshlink_errno);
520 static void connection_try_trampoline(meshlink_handle_t *handle, meshlink_node_t *peer) {
521 if(!(handle->priv)) {
525 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
526 that->connection_try(static_cast<node *>(peer));
529 meshlink_handle_t *handle;
532 static inline const char *strerror(errno_t err = meshlink_errno) {
533 return meshlink_strerror(err);
536 /// Destroy a MeshLink instance.
537 /** This function remove all configuration files of a MeshLink instance. It should only be called when the application
538 * does not have an open handle to this instance. Afterwards, a call to meshlink_open() will create a completely
541 * @param confbase The directory in which MeshLink stores its configuration files.
542 * After the function returns, the application is free to overwrite or free @a confbase @a.
544 * @return This function will return true if the MeshLink instance was successfully destroyed, false otherwise.
546 static inline bool destroy(const char *confbase) {
547 return meshlink_destroy(confbase);