]> git.meshlink.io Git - meshlink-tiny/blob - src/meshlink-tiny++.h
Remove all support for channels.
[meshlink-tiny] / src / meshlink-tiny++.h
1 #ifndef MESHLINKPP_H
2 #define MESHLINKPP_H
3
4 /*
5     meshlink-tiny++.h -- MeshLink C++ API
6     Copyright (C) 2014, 2017 Guus Sliepen <guus@meshlink.io>
7
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.
12
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.
17
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.
21 */
22
23 #include <meshlink-tiny.h>
24 #include <new> // for 'placement new'
25
26 namespace meshlink {
27 class mesh;
28 class node;
29
30 /// Severity of log messages generated by MeshLink.
31 typedef meshlink_log_level_t log_level_t;
32
33 /// Code of most recent error encountered.
34 typedef meshlink_errno_t errno_t;
35
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.
41  */
42 typedef void (*receive_cb_t)(mesh *mesh, node *source, const void *data, size_t len);
43
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.
48  */
49 typedef void (*connection_try_cb_t)(mesh *mesh, node *node);
50
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.
55  */
56 typedef void (*node_status_cb_t)(mesh *mesh, node *node, bool reachable);
57
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.
62  */
63 typedef void (*duplicate_cb_t)(mesh *mesh, node *node);
64
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.
69  */
70 typedef void (*log_cb_t)(mesh *mesh, log_level_t level, const char *text);
71
72 /// A class describing a MeshLink node.
73 class node: public meshlink_node_t {
74 };
75
76 /// A class describing a MeshLink mesh.
77 class mesh {
78 public:
79         mesh() : handle(0) {}
80
81         virtual ~mesh() {
82                 this->close();
83         }
84
85         bool isOpen() const {
86                 return (handle != 0);
87         }
88
89 // TODO: please enable C++11 in autoconf to enable "move constructors":
90 //              mesh(mesh&& other)
91 //              : handle(other.handle)
92 //              {
93 //                      if(handle)
94 //                              handle->priv = this;
95 //                      other.handle = 0;
96 //              }
97
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.
104          *
105          *  This function does not start any network I/O yet. The application should
106          *  first set callbacks, and then call meshlink_start().
107          *
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.
112          *
113          *  @return         This function will return a pointer to a meshlink::mesh if MeshLink has successfully set up its configuration files, NULL otherwise.
114          */
115         bool open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
116                 handle = meshlink_open(confbase, name, appname, devclass);
117
118                 if(handle) {
119                         handle->priv = this;
120                 }
121
122                 return isOpen();
123         }
124
125         mesh(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
126                 open(confbase, name, appname, devclass);
127         }
128
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.
133          */
134         void close() {
135                 if(handle) {
136                         handle->priv = 0;
137                         meshlink_close(handle);
138                 }
139
140                 handle = 0;
141         }
142
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
149          */
150
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) {
153                 /* do nothing */
154                 (void)source;
155                 (void)data;
156                 (void) length;
157         }
158
159         /// This functions is called whenever another node's status changed.
160         virtual void node_status(node *peer, bool reachable) {
161                 /* do nothing */
162                 (void)peer;
163                 (void)reachable;
164         }
165
166         /// This functions is called whenever a duplicate node is detected.
167         virtual void node_duplicate(node *peer) {
168                 /* do nothing */
169                 (void)peer;
170         }
171
172         /// This functions is called whenever MeshLink has some information to log.
173         virtual void log(log_level_t level, const char *message) {
174                 /* do nothing */
175                 (void)level;
176                 (void)message;
177         }
178
179         /// This functions is called whenever MeshLink has encountered a serious error.
180         virtual void error(meshlink_errno_t meshlink_errno) {
181                 /* do nothing */
182                 (void)meshlink_errno;
183         }
184
185         /// This functions is called whenever MeshLink a meta-connection attempt is made.
186         virtual void connection_try(node *peer) {
187                 /* do nothing */
188                 (void)peer;
189         }
190
191         /// Start MeshLink.
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.
194          *
195          *  @return         This function will return true if MeshLink has successfully started its thread, false otherwise.
196          */
197         bool start() {
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);
205         }
206
207         /// Stop MeshLink.
208         /** This function causes MeshLink to disconnect from all other nodes,
209          *  close all sockets, and shut down its own thread.
210          */
211         void stop() {
212                 meshlink_stop(handle);
213         }
214
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.
221          *
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.
227          */
228         bool send(node *destination, const void *data, unsigned int len) {
229                 return meshlink_send(handle, destination, data, len);
230         }
231
232         /// Get a handle for a specific node.
233         /** This function returns a handle for the node with the given name.
234          *
235          *  @param name         The name of the node for which a handle is requested.
236          *
237          *  @return             A pointer to a meshlink::node which represents the requested node,
238          *                      or NULL if the requested node does not exist.
239          */
240         node *get_node(const char *name) {
241                 return (node *)meshlink_get_node(handle, name);
242         }
243
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.
247          *
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.
251          *
252          *  @return                  This function returns true if the node is currently reachable, false otherwise.
253          */
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);
256         }
257
258         /// Get a handle for our own node.
259         /** This function returns a handle for the local node.
260          *
261          *  @return             A pointer to a meshlink::node which represents the local node.
262          */
263         node *get_self() {
264                 return (node *)meshlink_get_self(handle);
265         }
266
267         /// Get a list of all nodes.
268         /** This function returns a list with handles for all known nodes.
269          *
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.
272          *
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.
275          */
276         node **get_all_nodes(node **nodes, size_t *nmemb) {
277                 return (node **)meshlink_get_all_nodes(handle, (meshlink_node_t **)nodes, nmemb);
278         }
279
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.
283          *
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.
288          *
289          *  @return             This function returns true if the signature is valid, false otherwise.
290          */
291         bool sign(const void *data, size_t len, void *signature, size_t *siglen) {
292                 return meshlink_sign(handle, data, len, signature, siglen);
293         }
294
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.
297          *
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.
303          *
304          *  @return             This function returns true if the signature is valid, false otherwise.
305          */
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);
308         }
309
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.
315          *
316          *  If a canonical Address is set for the local node,
317          *  it will be used for the hostname part of generated invitation URLs.
318          *
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.
323          *
324          *  @return             This function returns true if the address was added, false otherwise.
325          */
326         bool set_canonical_address(node *node, const char *address, const char *port = NULL) {
327                 return meshlink_set_canonical_address(handle, node, address, port);
328         }
329
330         /// Clear the canonical Address for a node.
331         /** This function clears the canonical Address for a node.
332          *
333          *  @param node         A pointer to a struct meshlink_node describing the node.
334          *
335          *  @return             This function returns true if the address was removed, false otherwise.
336          */
337         bool clear_canonical_address(node *node) {
338                 return meshlink_clear_canonical_address(handle, node);
339         }
340
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).
346          *
347          *  @param granularity  The scheduling granularity of the application in microseconds.
348          */
349         void set_granularity(long granularity) {
350                 meshlink_set_scheduling_granularity(handle, granularity);
351         }
352
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
357          *  are stored.
358          *  By setting the policy to MESHLINK_STORAGE_DISABLED, no updates will be stored.
359          *
360          *  @param policy  The storage policy to use.
361          */
362         void set_storage_policy(meshlink_storage_policy_t policy) {
363                 meshlink_set_storage_policy(handle, policy);
364         }
365
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.
370          *
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.
372          *
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.
376          *
377          *  @param invitation   A string containing the invitation URL.
378          *
379          *  @return             This function returns true if the local node joined the mesh it was invited to, false otherwise.
380          */
381         bool join(const char *invitation) {
382                 return meshlink_join(handle, invitation);
383         }
384
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.
389          *
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.
392          */
393         char *export_key() {
394                 return meshlink_export(handle);
395         }
396
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.
400          *
401          *  @param data         A string containing the other node's exported key and addresses.
402          *
403          *  @return             This function returns true if the data was valid and the other node has been granted access to the mesh, false otherwise.
404          */
405         bool import_key(const char *data) {
406                 return meshlink_import(handle, data);
407         }
408
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.
412          *
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.
415          *
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
419          *  cleaned up.
420          *
421          *  \memberof meshlink_node
422          *  @param node         A pointer to a struct meshlink_node describing the node to be forgotten.
423          *
424          *  @return             This function returns true if all currently known data about the node has been forgotten, false otherwise.
425          */
426         bool forget_node(node *node) {
427                 return meshlink_forget_node(handle, node);
428         }
429
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.
434          */
435         void hint_network_change() {
436                 meshlink_hint_network_change(handle);
437         }
438
439         /// Set device class timeouts
440         /** This sets the ping interval and timeout for a given device class.
441          *
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.
446          */
447         void set_dev_class_timeouts(dev_class_t devclass, int pinginterval, int pingtimeout) {
448                 meshlink_set_dev_class_timeouts(handle, devclass, pinginterval, pingtimeout);
449         }
450
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.
454          *
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.
457          */
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);
460         }
461
462         /// Set device class maximum timeout
463         /** This sets the maximum timeout for outgoing connection retries for a given device class.
464          *
465          *  @param devclass      The device class to update
466          *  @param maxtimeout    The maximum timeout between reconnection attempts, in seconds. The default is 900.
467          */
468         void set_dev_class_maxtimeout(dev_class_t devclass, int maxtimeout) {
469                 meshlink_set_dev_class_maxtimeout(handle, devclass, maxtimeout);
470         }
471
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.
476          *
477          *  @param inviter_commits_first  If true, then the node that invited a peer will commit data to disk first.
478          */
479         void set_inviter_commits_first(bool inviter_commits_first) {
480                 meshlink_set_inviter_commits_first(handle, inviter_commits_first);
481         }
482
483 private:
484         // non-copyable:
485         mesh(const mesh &) /* TODO: C++11: = delete */;
486         void operator=(const mesh &) /* TODO: C++11: = delete */;
487
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)) {
491                         return;
492                 }
493
494                 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
495                 that->receive(static_cast<node *>(source), data, length);
496         }
497
498         static void node_status_trampoline(meshlink_handle_t *handle, meshlink_node_t *peer, bool reachable) {
499                 if(!(handle->priv)) {
500                         return;
501                 }
502
503                 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
504                 that->node_status(static_cast<node *>(peer), reachable);
505         }
506
507         static void node_duplicate_trampoline(meshlink_handle_t *handle, meshlink_node_t *peer) {
508                 if(!(handle->priv)) {
509                         return;
510                 }
511
512                 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
513                 that->node_duplicate(static_cast<node *>(peer));
514         }
515
516         static void log_trampoline(meshlink_handle_t *handle, log_level_t level, const char *message) {
517                 if(!(handle->priv)) {
518                         return;
519                 }
520
521                 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
522                 that->log(level, message);
523         }
524
525         static void error_trampoline(meshlink_handle_t *handle, meshlink_errno_t meshlink_errno) {
526                 if(!(handle->priv)) {
527                         return;
528                 }
529
530                 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
531                 that->error(meshlink_errno);
532         }
533
534         static void connection_try_trampoline(meshlink_handle_t *handle, meshlink_node_t *peer) {
535                 if(!(handle->priv)) {
536                         return;
537                 }
538
539                 meshlink::mesh *that = static_cast<mesh *>(handle->priv);
540                 that->connection_try(static_cast<node *>(peer));
541         }
542
543         meshlink_handle_t *handle;
544 };
545
546 static inline const char *strerror(errno_t err = meshlink_errno) {
547         return meshlink_strerror(err);
548 }
549
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
553  *  new instance.
554  *
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.
557  *
558  *  @return         This function will return true if the MeshLink instance was successfully destroyed, false otherwise.
559  */
560 static inline bool destroy(const char *confbase) {
561         return meshlink_destroy(confbase);
562 }
563 }
564
565 #endif