]> git.meshlink.io Git - meshlink/blob - src/meshlink.h
Lock meshlink.conf to ensure only one instance can run at a time.
[meshlink] / src / meshlink.h
1 #ifndef MESHLINK_H
2 #define MESHLINK_H
3
4 /*
5     meshlink.h -- MeshLink API
6     Copyright (C) 2014-2018 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 <stdint.h>
24 #include <stdbool.h>
25 #include <stddef.h>
26 #include <unistd.h>
27
28 #if defined(_WIN32)
29 #include <winsock2.h>
30 #else
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #endif
34
35 #ifdef __cplusplus
36 extern "C" {
37 #endif
38
39 /// The length in bytes of a signature made with meshlink_sign()
40 #define MESHLINK_SIGLEN (64ul)
41
42 // The maximum length of fingerprints
43 #define MESHLINK_FINGERPRINTLEN (64ul)
44
45 /// A handle for an instance of MeshLink.
46 typedef struct meshlink_handle meshlink_handle_t;
47
48 /// A handle for a MeshLink node.
49 typedef struct meshlink_node meshlink_node_t;
50
51 /// A handle for a MeshLink channel.
52 typedef struct meshlink_channel meshlink_channel_t;
53
54 /// Code of most recent error encountered.
55 typedef enum {
56         MESHLINK_OK,        ///< Everything is fine
57         MESHLINK_EINVAL,    ///< Invalid parameter(s) to function call
58         MESHLINK_ENOMEM,    ///< Out of memory
59         MESHLINK_ENOENT,    ///< Node is not known
60         MESHLINK_EEXIST,    ///< Node already exists
61         MESHLINK_EINTERNAL, ///< MeshLink internal error
62         MESHLINK_ERESOLV,   ///< MeshLink could not resolve a hostname
63         MESHLINK_ESTORAGE,  ///< MeshLink coud not load or write data from/to disk
64         MESHLINK_ENETWORK,  ///< MeshLink encountered a network error
65         MESHLINK_EPEER,     ///< A peer caused an error
66         MESHLINK_ENOTSUP,   ///< The operation is not supported in the current configuration of MeshLink
67         MESHLINK_EBUSY,     ///< The MeshLink instance is already in use by another process
68 } meshlink_errno_t;
69
70 /// Device class
71 typedef enum {
72         DEV_CLASS_BACKBONE = 0,
73         DEV_CLASS_STATIONARY = 1,
74         DEV_CLASS_PORTABLE = 2,
75         DEV_CLASS_UNKNOWN = 3,
76         _DEV_CLASS_MAX = 3
77 } dev_class_t;
78
79 /// Channel flags
80 static const uint32_t MESHLINK_CHANNEL_RELIABLE = 1;   // Data is retransmitted when packets are lost.
81 static const uint32_t MESHLINK_CHANNEL_ORDERED = 2;    // Data is delivered in-order to the application.
82 static const uint32_t MESHLINK_CHANNEL_FRAMED = 4;     // Data is delivered in chunks of the same length as data was originally sent.
83 static const uint32_t MESHLINK_CHANNEL_DROP_LATE = 8;  // When packets are reordered, late packets are ignored.
84 static const uint32_t MESHLINK_CHANNEL_TCP = 3;        // Select TCP semantics.
85 static const uint32_t MESHLINK_CHANNEL_UDP = 0;        // Select UDP semantics.
86
87 /// A variable holding the last encountered error from MeshLink.
88 /** This is a thread local variable that contains the error code of the most recent error
89  *  encountered by a MeshLink API function called in the current thread.
90  *  The variable is only updated when an error is encountered, and is not reset to MESHLINK_OK
91  *  if a function returned succesfully.
92  */
93 extern __thread meshlink_errno_t meshlink_errno;
94
95 #ifndef MESHLINK_INTERNAL_H
96
97 struct meshlink_handle {
98         const char *const name; ///< Textual name of ourself. It is stored in a nul-terminated C string, which is allocated by MeshLink.
99         void *priv;             ///< Private pointer which may be set freely by the application, and is never used or modified by MeshLink.
100 };
101
102 struct meshlink_node {
103         const char *const name; ///< Textual name of this node. It is stored in a nul-terminated C string, which is allocated by MeshLink.
104         void *priv;             ///< Private pointer which may be set freely by the application, and is never used or modified by MeshLink.
105 };
106
107 struct meshlink_channel {
108         struct meshlink_node *const node; ///< Pointer to the peer of this channel.
109         void *priv;                       ///< Private pointer which may be set freely by the application, and is never used or modified by MeshLink.
110 };
111
112 #endif // MESHLINK_INTERNAL_H
113
114 /// Get the text for the given MeshLink error code.
115 /** This function returns a pointer to the string containing the description of the given error code.
116  *
117  *  @param err      An error code returned by MeshLink.
118  *
119  *  @return         A pointer to a string containing the description of the error code.
120  *                  The pointer is to static storage that is valid for the lifetime of the application.
121  *                  This function will always return a valid pointer, even if an invalid error code has been passed.
122  */
123 extern const char *meshlink_strerror(meshlink_errno_t err);
124
125 /// Open or create a MeshLink instance.
126 /** This function opens or creates a MeshLink instance.
127  *  The state is stored in the configuration directory passed in the variable @a confbase @a.
128  *  If the configuration directory does not exist yet, for example when it is the first time
129  *  this instance is opened, the configuration directory will be automatically created and initialized.
130  *  However, the parent directory should already exist, otherwise an error will be returned.
131  *
132  *  The name given should be a unique identifier for this instance.
133  *
134  *  This function returns a pointer to a struct meshlink_handle that will be allocated by MeshLink.
135  *  When the application does no longer need to use this handle, it must call meshlink_close() to
136  *  free its resources.
137  *
138  *  This function does not start any network I/O yet. The application should
139  *  first set callbacks, and then call meshlink_start().
140  *
141  *  @param confbase The directory in which MeshLink will store its configuration files.
142  *                  After the function returns, the application is free to overwrite or free @a confbase @a.
143  *  @param name     The name which this instance of the application will use in the mesh.
144  *                  After the function returns, the application is free to overwrite or free @a name @a.
145  *  @param appname  The application name which will be used in the mesh.
146  *                  After the function returns, the application is free to overwrite or free @a name @a.
147  *  @param devclass The device class which will be used in the mesh.
148  *
149  *  @return         A pointer to a meshlink_handle_t which represents this instance of MeshLink, or NULL in case of an error.
150  *                  The pointer is valid until meshlink_close() is called.
151  */
152 extern meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass);
153
154 /// Start MeshLink.
155 /** This function causes MeshLink to open network sockets, make outgoing connections, and
156  *  create a new thread, which will handle all network I/O.
157  *
158  *  It is allowed to call this function even if MeshLink is already started, in which case it will return true.
159  *
160  *  @param mesh     A handle which represents an instance of MeshLink.
161  *
162  *  @return         This function will return true if MeshLink has succesfully started, false otherwise.
163  */
164 extern bool meshlink_start(meshlink_handle_t *mesh);
165
166 /// Stop MeshLink.
167 /** This function causes MeshLink to disconnect from all other nodes,
168  *  close all sockets, and shut down its own thread.
169  *
170  *  This function always succeeds. It is allowed to call meshlink_stop() even if MeshLink is already stopped or has never been started.
171  *  Channels that are still open will remain valid, but any communication via channels will stop as well.
172  *
173  *  @param mesh     A handle which represents an instance of MeshLink.
174  */
175 extern void meshlink_stop(meshlink_handle_t *mesh);
176
177 /// Close the MeshLink handle.
178 /** This function calls meshlink_stop() if necessary,
179  *  and frees the struct meshlink_handle and all associacted memory allocated by MeshLink, including all channels.
180  *  Afterwards, the handle and any pointers to a struct meshlink_node or struct meshlink_channel are invalid.
181  *
182  *  It is allowed to call this function at any time on a valid handle, except inside callback functions.
183  *  If called at a proper time with a valid handle, this function always succeeds.
184  *  If called within a callback or with an invalid handle, the result is undefined.
185  *
186  *  @param mesh     A handle which represents an instance of MeshLink.
187  */
188 extern void meshlink_close(meshlink_handle_t *mesh);
189
190 /// Destroy a MeshLink instance.
191 /** This function remove all configuration files of a MeshLink instance. It should only be called when the application
192  *  does not have an open handle to this instance. Afterwards, a call to meshlink_open() will create a completely
193  *  new instance.
194  *
195  *  @param confbase The directory in which MeshLink stores its configuration files.
196  *                  After the function returns, the application is free to overwrite or free @a confbase @a.
197  *
198  *  @return         This function will return true if the MeshLink instance was succesfully destroyed, false otherwise.
199  */
200 extern bool meshlink_destroy(const char *confbase);
201
202 /// A callback for receiving data from the mesh.
203 /** @param mesh      A handle which represents an instance of MeshLink.
204  *  @param source    A pointer to a meshlink_node_t describing the source of the data.
205  *  @param data      A pointer to a buffer containing the data sent by the source, or NULL in case there is no data (an empty packet was received).
206  *                   The pointer is only valid during the lifetime of the callback.
207  *                   The callback should mempcy() the data if it needs to be available outside the callback.
208  *  @param len       The length of the received data, or 0 in case there is no data.
209  */
210 typedef void (*meshlink_receive_cb_t)(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len);
211
212 /// Set the receive callback.
213 /** This functions sets the callback that is called whenever another node sends data to the local node.
214  *  The callback is run in MeshLink's own thread.
215  *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
216  *  to hand the data over to the application's thread.
217  *  The callback should also not block itself and return as quickly as possible.
218  *
219  *  @param mesh      A handle which represents an instance of MeshLink.
220  *  @param cb        A pointer to the function which will be called when another node sends data to the local node.
221  *                   If a NULL pointer is given, the callback will be disabled.
222  */
223 extern void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb);
224
225 /// A callback reporting node status changes.
226 /** @param mesh       A handle which represents an instance of MeshLink.
227  *  @param node       A pointer to a meshlink_node_t describing the node whose status changed.
228  *                    This pointer is valid until meshlink_close() is called.
229  *  @param reachable  True if the node is reachable, false otherwise.
230  */
231 typedef void (*meshlink_node_status_cb_t)(meshlink_handle_t *mesh, meshlink_node_t *node, bool reachable);
232
233 /// Set the node status callback.
234 /** This functions sets the callback that is called whenever another node's status changed.
235  *  The callback is run in MeshLink's own thread.
236  *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
237  *  to hand the data over to the application's thread.
238  *  The callback should also not block itself and return as quickly as possible.
239  *
240  *  @param mesh      A handle which represents an instance of MeshLink.
241  *  @param cb        A pointer to the function which will be called when another node's status changes.
242  *                   If a NULL pointer is given, the callback will be disabled.
243  */
244 extern void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb);
245
246 /// A callback reporting duplicate node detection.
247 /** @param mesh       A handle which represents an instance of MeshLink.
248  *  @param node       A pointer to a meshlink_node_t describing the node which is duplicate.
249  *                    This pointer is valid until meshlink_close() is called.
250  */
251 typedef void (*meshlink_node_duplicate_cb_t)(meshlink_handle_t *mesh, meshlink_node_t *node);
252
253 /// Set the node duplicate callback.
254 /** This functions sets the callback that is called whenever a duplicate node is detected.
255  *  The callback is run in MeshLink's own thread.
256  *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
257  *  to hand the data over to the application's thread.
258  *  The callback should also not block itself and return as quickly as possible.
259  *
260  *  @param mesh      A handle which represents an instance of MeshLink.
261  *  @param cb        A pointer to the function which will be called when a duplicate node is detected.
262  *                   If a NULL pointer is given, the callback will be disabled.
263  */
264 extern void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb);
265
266 /// Severity of log messages generated by MeshLink.
267 typedef enum {
268         MESHLINK_DEBUG,    ///< Internal debugging messages. Only useful during application development.
269         MESHLINK_INFO,     ///< Informational messages.
270         MESHLINK_WARNING,  ///< Warnings which might indicate problems, but which are not real errors.
271         MESHLINK_ERROR,    ///< Errors which hamper correct functioning of MeshLink, without causing it to fail completely.
272         MESHLINK_CRITICAL, ///< Critical errors which cause MeshLink to fail completely.
273 } meshlink_log_level_t;
274
275 /// A callback for receiving log messages generated by MeshLink.
276 /** @param mesh      A handle which represents an instance of MeshLink, or NULL.
277  *  @param level     An enum describing the severity level of the message.
278  *  @param text      A pointer to a nul-terminated C string containing the textual log message.
279  *                   This pointer is only valid for the duration of the callback.
280  *                   The application must not free() this pointer.
281  *                   The application should strdup() the text if it has to be available outside the callback.
282  */
283 typedef void (*meshlink_log_cb_t)(meshlink_handle_t *mesh, meshlink_log_level_t level, const char *text);
284
285 /// Set the log callback.
286 /** This functions sets the callback that is called whenever MeshLink has some information to log.
287  *
288  *  The @a mesh @a parameter can either be a valid MeshLink handle, or NULL.
289  *  In case it is NULL, the callback will be called for errors that happen outside the context of a valid mesh instance.
290  *  Otherwise, it will be called for errors that happen in the context of the given mesh instance.
291  *
292  *  If @a mesh @a is not NULL, then the callback is run in MeshLink's own thread.
293  *  It is important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
294  *  to hand the data over to the application's thread.
295  *  The callback should also not block itself and return as quickly as possible.
296  *
297  *  The @a mesh @a parameter can either be a valid MeshLink handle, or NULL.
298  *  In case it is NULL, the callback will be called for errors that happen outside the context of a valid mesh instance.
299  *  Otherwise, it will be called for errors that happen in the context of the given mesh instance.
300  *
301  *  @param mesh      A handle which represents an instance of MeshLink, or NULL.
302  *  @param level     An enum describing the minimum severity level. Debugging information with a lower level will not trigger the callback.
303  *  @param cb        A pointer to the function which will be called when another node sends data to the local node.
304  *                   If a NULL pointer is given, the callback will be disabled.
305  */
306 extern void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb);
307
308 /// Send data to another node.
309 /** This functions sends one packet of data to another node in the mesh.
310  *  The packet is sent using UDP semantics, which means that
311  *  the packet is sent as one unit and is received as one unit,
312  *  and that there is no guarantee that the packet will arrive at the destination.
313  *  Packets that are too big to be sent over the network as one unit might be dropped, and this function may return an error if this situation can be detected beforehand.
314  *  The application should not send packets that are larger than the path MTU, which can be queried with meshlink_get_pmtu().
315  *  The application should take care of getting an acknowledgement and retransmission if necessary.
316  *
317  *  @param mesh         A handle which represents an instance of MeshLink.
318  *  @param destination  A pointer to a meshlink_node_t describing the destination for the data.
319  *  @param data         A pointer to a buffer containing the data to be sent to the source.
320  *                      After meshlink_send() returns, the application is free to overwrite or free this buffer.
321  *                      It is valid to specify a NULL pointer, but only if @a len @a is also 0.
322  *  @param len          The length of the data.
323  *  @return             This function will return true if MeshLink has queued the message for transmission, and false otherwise.
324  *                      A return value of true does not guarantee that the message will actually arrive at the destination.
325  */
326 extern bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len);
327
328 /// Query the maximum packet size that can be sent to a node.
329 /** This functions returns the maximum size of packets (path MTU) that can be sent to a specific node with meshlink_send().
330  *  The path MTU is a property of the path packets will take to the destination node over the Internet.
331  *  It can be different for different destination nodes.
332  *  and the path MTU can change at any point in time due to changes in the Internet.
333  *  Therefore, although this should only occur rarely, it can still happen that packets that do not exceed this size get dropped.
334  *
335  *  @param mesh         A handle which represents an instance of MeshLink.
336  *  @param destination  A pointer to a meshlink_node_t describing the destination for the data.
337  *
338  *  @return             The recommended maximum size of packets that are to be sent to the destination node, 0 if the node is unreachable,
339  *                      or a negative value in case of an error.
340  */
341 extern ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination);
342
343 /// Get a handle for our own node.
344 /** This function returns a handle for the local node.
345  *
346  *  @param mesh         A handle which represents an instance of MeshLink.
347  *
348  *  @return             A pointer to a meshlink_node_t which represents the local node.
349  *                      The pointer is guaranteed to be valid until meshlink_close() is called.
350  */
351 extern meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh);
352
353 /// Get a handle for a specific node.
354 /** This function returns a handle for the node with the given name.
355  *
356  *  @param mesh         A handle which represents an instance of MeshLink.
357  *  @param name         The name of the node for which a handle is requested.
358  *                      After this function returns, the application is free to overwrite or free @a name @a.
359  *
360  *  @return             A pointer to a meshlink_node_t which represents the requested node,
361  *                      or NULL if the requested node does not exist.
362  *                      The pointer is guaranteed to be valid until meshlink_close() is called.
363  */
364 extern meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name);
365
366 /// Get the fingerprint of a node's public key.
367 /** This function returns a fingerprint of the node's public key.
368  *  It should be treated as an opaque blob.
369  *
370  *  @param mesh         A handle which represents an instance of MeshLink.
371  *  @param node         A pointer to a meshlink_node_t describing the node.
372  *
373  *  @return             A nul-terminated C string containing the fingerprint of the node's public key in a printable ASCII format.
374  *                      The application should call free() after it is done using this string.
375  */
376 extern char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node);
377
378 /// Get a list of all nodes.
379 /** This function returns a list with handles for all known nodes.
380  *
381  *  @param mesh         A handle which represents an instance of MeshLink.
382  *  @param nodes        A pointer to a previously allocated array of pointers to meshlink_node_t, or NULL in which case MeshLink will allocate a new array.
383  *                      The application can supply an array it allocated itself with malloc, or the return value from the previous call to this function (which is the preferred way).
384  *                      The application is allowed to call free() on the array whenever it wishes.
385  *                      The pointers in the array are valid until meshlink_close() is called.
386  *  @param nmemb        A pointer to a variable holding the number of nodes that are stored in the array.
387  *                      In case the @a nodes @a argument is not NULL, MeshLink might call realloc() on the array to change its size.
388  *                      The contents of this variable will be changed to reflect the new size of the array.
389  *
390  *  @return             A pointer to an array containing pointers to all known nodes, or NULL in case of an error.
391  *                      If the @a nodes @a argument was not NULL, then the return value can either be the same value or a different value.
392  *                      If it is a new value, the old value of @a nodes @a should not be used anymore.
393  *                      If the new value is NULL, then the old array will have been freed by MeshLink.
394  */
395 extern meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb);
396
397 /// Sign data using the local node's MeshLink key.
398 /** This function signs data using the local node's MeshLink key.
399  *  The generated signature can be securely verified by other nodes.
400  *
401  *  @param mesh         A handle which represents an instance of MeshLink.
402  *  @param data         A pointer to a buffer containing the data to be signed.
403  *  @param len          The length of the data to be signed.
404  *  @param signature    A pointer to a buffer where the signature will be stored.
405  *                      The buffer must be allocated by the application, and should be at least MESHLINK_SIGLEN bytes big.
406  *                      The signature is a binary blob, and is not nul-terminated.
407  *  @param siglen       The size of the signature buffer. Will be changed after the call to match the size of the signature itself.
408  *
409  *  @return             This function returns true if the signature was correctly generated, false otherwise.
410  */
411 extern bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen);
412
413 /// Verify the signature generated by another node of a piece of data.
414 /** This function verifies the signature that another node generated for a piece of data.
415  *
416  *  @param mesh         A handle which represents an instance of MeshLink.
417  *  @param source       A pointer to a meshlink_node_t describing the source of the signature.
418  *  @param data         A pointer to a buffer containing the data to be verified.
419  *  @param len          The length of the data to be verified.
420  *  @param signature    A pointer to a buffer where the signature is stored.
421  *  @param siglen       A pointer to a variable holding the size of the signature buffer.
422  *                      The contents of the variable will be changed by meshlink_sign() to reflect the actual size of the signature.
423  *
424  *  @return             This function returns true if the signature is valid, false otherwise.
425  */
426 extern bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen);
427
428 /// Set the canonical Address for a node.
429 /** This function sets the canonical Address for a node.
430  *  This address is stored permanently until it is changed by another call to this function,
431  *  unlike other addresses associated with a node,
432  *  such as those added with meshlink_hint_address() or addresses discovered at runtime.
433  *
434  *  If a canonical Address is set for the local node,
435  *  it will be used for the hostname part of generated invitation URLs.
436  *
437  *  @param mesh         A handle which represents an instance of MeshLink.
438  *  @param node         A pointer to a meshlink_node_t describing the node.
439  *  @param address      A nul-terminated C string containing the address, which can be either in numeric format or a hostname.
440  *  @param port         A nul-terminated C string containing the port, which can be either in numeric or symbolic format.
441  *                      If it is NULL, the listening port's number will be used.
442  *
443  *  @return             This function returns true if the address was added, false otherwise.
444  */
445 extern bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port);
446
447 /// Add an Address for the local node.
448 /** This function adds an Address for the local node, which will be used for invitation URLs.
449  *
450  *  @param mesh         A handle which represents an instance of MeshLink.
451  *  @param address      A nul-terminated C string containing the address, which can be either in numeric format or a hostname.
452  *
453  *  @return             This function returns true if the address was added, false otherwise.
454  */
455 extern bool meshlink_add_address(meshlink_handle_t *mesh, const char *address);
456
457 /// Try to discover the external address for the local node.
458 /** This function performs tries to discover the local node's external address
459  *  by contacting the meshlink.io server. If a reverse lookup of the address works,
460  *  the FQDN associated with the address will be returned.
461  *
462  *  Please note that this is function only returns a single address,
463  *  even if the local node might have more than one external address.
464  *  In that case, there is no control over which address will be selected.
465  *  Also note that if you have a dynamic IP address, or are behind carrier-grade NAT,
466  *  there is no guarantee that the external address will be valid for an extended period of time.
467  *
468  *  This function is blocking. It can take several seconds before it returns.
469  *  There is no guarantee it will be able to resolve the external address.
470  *  Failures might be because by temporary network outages.
471  *
472  *  @param mesh         A handle which represents an instance of MeshLink.
473  *
474  *  @return             This function returns a pointer to a C string containing the discovered external address,
475  *                      or NULL if there was an error looking up the address.
476  *                      After meshlink_get_external_address() returns, the application is free to overwrite or free this string.
477  */
478 extern char *meshlink_get_external_address(meshlink_handle_t *mesh);
479
480 /// Try to discover the external address for the local node.
481 /** This function performs tries to discover the local node's external address
482  *  by contacting the meshlink.io server. If a reverse lookup of the address works,
483  *  the FQDN associated with the address will be returned.
484  *
485  *  Please note that this is function only returns a single address,
486  *  even if the local node might have more than one external address.
487  *  In that case, there is no control over which address will be selected.
488  *  Also note that if you have a dynamic IP address, or are behind carrier-grade NAT,
489  *  there is no guarantee that the external address will be valid for an extended period of time.
490  *
491  *  This function is blocking. It can take several seconds before it returns.
492  *  There is no guarantee it will be able to resolve the external address.
493  *  Failures might be because by temporary network outages.
494  *
495  *  @param mesh         A handle which represents an instance of MeshLink.
496  *  @param family       The address family to check, for example AF_INET or AF_INET6. If AF_UNSPEC is given,
497  *                      this might return the external address for any working address family.
498  *
499  *  @return             This function returns a pointer to a C string containing the discovered external address,
500  *                      or NULL if there was an error looking up the address.
501  *                      After meshlink_get_external_address() returns, the application is free to overwrite or free this string.
502  */
503 extern char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int address_family);
504
505 /// Try to discover the external address for the local node, and add it to its list of addresses.
506 /** This function is equivalent to:
507  *
508  *    meshlink_add_address(mesh, meshlink_get_external_address(mesh));
509  *
510  *  Read the description of meshlink_get_external_address() for the limitations of this function.
511  *
512  *  @param mesh         A handle which represents an instance of MeshLink.
513  *
514  *  @return             This function returns true if the address was added, false otherwise.
515  */
516 extern bool meshlink_add_external_address(meshlink_handle_t *mesh);
517
518 /// Get the network port used by the local node.
519 /** This function returns the network port that the local node is listening on.
520  *
521  *  @param mesh          A handle which represents an instance of MeshLink.
522  *
523  *  @return              This function returns the port number, or -1 in case of an error.
524  */
525 extern int meshlink_get_port(meshlink_handle_t *mesh);
526
527 /// Set the network port used by the local node.
528 /** This function sets the network port that the local node is listening on.
529  *  It may only be called when the mesh is not running.
530  *  If unsure, call meshlink_stop() before calling this function.
531  *  Also note that if your node is already part of a mesh with other nodes,
532  *  that the other nodes may no longer be able to initiate connections to the local node,
533  *  since they will try to connect to the previously configured port.
534  *
535  *  @param mesh          A handle which represents an instance of MeshLink.
536  *  @param port          The port number to listen on. This must be between 0 and 65535.
537  *                       If the port is set to 0, then MeshLink will listen on a port
538  *                       that is randomly assigned by the operating system every time meshlink_open() is called.
539  *
540  *  @return              This function returns true if the port was succesfully changed, false otherwise.
541  */
542
543 extern bool meshlink_set_port(meshlink_handle_t *mesh, int port);
544
545 /// Set the timeout for invitations.
546 /** This function sets the timeout for invitations.
547  *  Note that timeouts are only checked at the time a node tries to join using an invitation.
548  *  The default timeout for invitations is 1 week.
549  *
550  *  @param mesh         A handle which represents an instance of MeshLink.
551  *  @param timeout      The timeout for invitations in seconds.
552  */
553 extern void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout);
554
555 /// Invite another node into the mesh.
556 /** This function generates an invitation that can be used by another node to join the same mesh as the local node.
557  *  The generated invitation is a string containing a URL.
558  *  This URL should be passed by the application to the invitee in a way that no eavesdroppers can see the URL.
559  *  The URL can only be used once, after the user has joined the mesh the URL is no longer valid.
560  *
561  *  @param mesh         A handle which represents an instance of MeshLink.
562  *  @param name         A nul-terminated C string containing the name that the invitee will be allowed to use in the mesh.
563  *                      After this function returns, the application is free to overwrite or free @a name @a.
564  *
565  *  @return             This function returns a nul-terminated C string that contains the invitation URL, or NULL in case of an error.
566  *                      The application should call free() after it has finished using the URL.
567  */
568 extern char *meshlink_invite(meshlink_handle_t *mesh, const char *name);
569
570 /// Use an invitation to join a mesh.
571 /** This function allows the local node to join an existing mesh using an invitation URL generated by another node.
572  *  An invitation can only be used if the local node has never connected to other nodes before.
573  *  After a succesfully accepted invitation, the name of the local node may have changed.
574  *
575  *  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.
576  *
577  *  This function is blocking. It can take several seconds before it returns.
578  *  There is no guarantee it will perform a successful join.
579  *  Failures might be caused by temporary network outages, or by the invitation having expired.
580  *
581  *  @param mesh         A handle which represents an instance of MeshLink.
582  *  @param invitation   A nul-terminated C string containing the invitation URL.
583  *                      After this function returns, the application is free to overwrite or free @a invitation @a.
584  *
585  *  @return             This function returns true if the local node joined the mesh it was invited to, false otherwise.
586  */
587 extern bool meshlink_join(meshlink_handle_t *mesh, const char *invitation);
588
589 /// Export the local node's key and addresses.
590 /** This function generates a string that contains the local node's public key and one or more IP addresses.
591  *  The application can pass it in some way to another node, which can then import it,
592  *  granting the local node access to the other node's mesh.
593  *  The exported data does not contain any secret keys, it is therefore safe to transmit this data unencrypted over public networks.
594  *
595  *  Note that to create a working connection between two nodes, both must call meshink_export() and both must meshlink_import() each other's data.
596  *
597  *  @param mesh         A handle which represents an instance of MeshLink.
598  *
599  *  @return             This function returns a nul-terminated C string that contains the exported key and addresses, or NULL in case of an error.
600  *                      The application should call free() after it has finished using this string.
601  */
602 extern char *meshlink_export(meshlink_handle_t *mesh);
603
604 /// Import another node's key and addresses.
605 /** This function accepts a string containing the exported public key and addresses of another node.
606  *  By importing this data, the local node grants the other node access to its mesh.
607  *  The application should make sure that the data it imports is really coming from the node it wants to import,
608  *
609  *  Note that to create a working connection between two nodes, both must call meshink_export() and both must meshlink_import() each other's data.
610  *
611  *  @param mesh         A handle which represents an instance of MeshLink.
612  *  @param data         A nul-terminated C string containing the other node's exported key and addresses.
613  *                      After this function returns, the application is free to overwrite or free @a data @a.
614  *
615  *  @return             This function returns true if the data was valid and the other node has been granted access to the mesh, false otherwise.
616  */
617 extern bool meshlink_import(meshlink_handle_t *mesh, const char *data);
618
619 /// Blacklist a node from the mesh.
620 /** This function causes the local node to blacklist another node.
621  *  The local node will drop any existing connections to that node,
622  *  and will not send data to it nor accept any data received from it any more.
623  *
624  *  @param mesh         A handle which represents an instance of MeshLink.
625  *  @param node         A pointer to a meshlink_node_t describing the node to be blacklisted.
626  */
627 extern void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node);
628
629 /// Whitelist a node on the mesh.
630 /** This function causes the local node to whitelist a previously blacklisted node.
631  *  The local node will allow connections to and from that node,
632  *  and will send data to it and accept any data received from it.
633  *
634  *  @param mesh         A handle which represents an instance of MeshLink.
635  *  @param node         A pointer to a meshlink_node_t describing the node to be whitelisted.
636  */
637 extern void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node);
638
639 /// Set whether new nodes are blacklisted by default.
640 /** This function sets the blacklist behaviour for newly discovered nodes.
641  *  If set to true, new nodes will be automatically blacklisted.
642  *  If set to false, which is the default, new nodes are automatically whitelisted.
643  *  The whitelist/blacklist status of a node may be changed afterwards with the
644  *  meshlink_whitelist() and meshlink_blacklist() functions.
645  *
646  *  @param mesh         A handle which represents an instance of MeshLink.
647  *  @param blacklist    True if new nodes are to be blacklisted, false if whitelisted.
648  */
649 extern void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist);
650
651 /// A callback for accepting incoming channels.
652 /** This function is called whenever a remote node wants to open a channel to the local node.
653  *  The application then has to decide whether to accept or reject this channel.
654  *
655  *  The callback is run in MeshLink's own thread.
656  *  It is therefore important that the callback return quickly and uses apprioriate methods (queues, pipes, locking, etc.)
657  *  to hand any data over to the application's thread.
658  *
659  *  @param mesh         A handle which represents an instance of MeshLink.
660  *  @param channel      A handle for the incoming channel.
661  *                      If the application accepts the incoming channel by returning true,
662  *                      then this handle is valid until meshlink_channel_close() is called on it.
663  *                      If the application rejects the incoming channel by returning false,
664  *                      then this handle is invalid after the callback returns
665  *                      (the callback does not need to call meshlink_channel_close() itself in this case).
666  *  @param port         The port number the peer wishes to connect to.
667  *  @param data         A pointer to a buffer containing data already received, or NULL in case no data has been received yet. (Not yet used.)
668  *                      The pointer is only valid during the lifetime of the callback.
669  *                      The callback should mempcy() the data if it needs to be available outside the callback.
670  *  @param len          The length of the data, or 0 in case no data has been received yet. (Not yet used.)
671  *
672  *  @return             This function should return true if the application accepts the incoming channel, false otherwise.
673  *                      If returning false, the channel is invalid and may not be used anymore.
674  */
675 typedef bool (*meshlink_channel_accept_cb_t)(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint16_t port, const void *data, size_t len);
676
677 /// A callback for receiving data from a channel.
678 /** This function is called whenever data is received from a remote node on a channel.
679  *
680  *  This function is also called in case the channel has been closed by the remote node, or when the channel is terminated abnormally.
681  *  In both cases, @a data @a will be NULL and @a len @a will be 0, and meshlink_errno will be set.
682  *  In any case, the @a channel @a handle will still be valid until the application calls meshlink_close().
683  *
684  *  @param mesh         A handle which represents an instance of MeshLink.
685  *  @param channel      A handle for the channel.
686  *  @param data         A pointer to a buffer containing data sent by the source, or NULL in case of an error.
687  *                      The pointer is only valid during the lifetime of the callback.
688  *                      The callback should mempcy() the data if it needs to be available outside the callback.
689  *  @param len          The length of the data, or 0 in case of an error.
690  */
691 typedef void (*meshlink_channel_receive_cb_t)(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len);
692
693 /// A callback informing the application when data can be sent on a channel.
694 /** This function is called whenever there is enough free buffer space so a call to meshlink_channel_send() will succeed.
695  *
696  *  @param mesh         A handle which represents an instance of MeshLink.
697  *  @param channel      A handle for the channel.
698  *  @param len          The maximum amount of data that is guaranteed to be accepted by meshlink_channel_send(),
699  *                      or 0 in case of an error.
700  */
701 typedef void (*meshlink_channel_poll_cb_t)(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t len);
702
703 /// Set the accept callback.
704 /** This functions sets the callback that is called whenever another node sends data to the local node.
705  *  The callback is run in MeshLink's own thread.
706  *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
707  *  to hand the data over to the application's thread.
708  *  The callback should also not block itself and return as quickly as possible.
709  *
710  *  If no accept callback is set, incoming channels are rejected.
711  *
712  *  @param mesh      A handle which represents an instance of MeshLink.
713  *  @param cb        A pointer to the function which will be called when another node sends data to the local node.
714  *                   If a NULL pointer is given, the callback will be disabled.
715  */
716 extern void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb);
717
718 /// Set the receive callback.
719 /** This functions sets the callback that is called whenever another node sends data to the local node.
720  *  The callback is run in MeshLink's own thread.
721  *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
722  *  to hand the data over to the application's thread.
723  *  The callback should also not block itself and return as quickly as possible.
724  *
725  *  @param mesh      A handle which represents an instance of MeshLink.
726  *  @param channel   A handle for the channel.
727  *  @param cb        A pointer to the function which will be called when another node sends data to the local node.
728  *                   If a NULL pointer is given, the callback will be disabled and incoming data is ignored.
729  */
730 extern void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb);
731
732 /// Set the poll callback.
733 /** This functions sets the callback that is called whenever data can be sent to another node.
734  *  The callback is run in MeshLink's own thread.
735  *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
736  *  to pass data to or from the application's thread.
737  *  The callback should also not block itself and return as quickly as possible.
738  *
739  *  @param mesh      A handle which represents an instance of MeshLink.
740  *  @param channel   A handle for the channel.
741  *  @param cb        A pointer to the function which will be called when data can be sent to another node.
742  *                   If a NULL pointer is given, the callback will be disabled.
743  */
744 extern void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb);
745
746 /// Open a reliable stream channel to another node.
747 /** This function is called whenever a remote node wants to open a channel to the local node.
748  *  The application then has to decide whether to accept or reject this channel.
749  *
750  *  This function returns a pointer to a struct meshlink_channel that will be allocated by MeshLink.
751  *  When the application does no longer need to use this channel, it must call meshlink_close()
752  *  to free its resources.
753  *
754  *  @param mesh         A handle which represents an instance of MeshLink.
755  *  @param node         The node to which this channel is being initiated.
756  *  @param port         The port number the peer wishes to connect to.
757  *  @param cb           A pointer to the function which will be called when the remote node sends data to the local node.
758  *                      The pointer may be NULL, in which case incoming data is ignored.
759  *  @param data         A pointer to a buffer containing data to already queue for sending, or NULL if there is no data to send.
760  *                      After meshlink_send() returns, the application is free to overwrite or free this buffer.
761  *  @param len          The length of the data, or 0 if there is no data to send.
762  *  @param flags        A bitwise-or'd combination of flags that set the semantics for this channel.
763  *
764  *  @return             A handle for the channel, or NULL in case of an error.
765  *                      The handle is valid until meshlink_channel_close() is called.
766  */
767 extern meshlink_channel_t *meshlink_channel_open_ex(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len, uint32_t flags);
768
769 /// Open a reliable stream channel to another node.
770 /** This function is called whenever a remote node wants to open a channel to the local node.
771  *  The application then has to decide whether to accept or reject this channel.
772  *
773  *  This function returns a pointer to a struct meshlink_channel that will be allocated by MeshLink.
774  *  When the application does no longer need to use this channel, it must call meshlink_close()
775  *  to free its resources.
776  *
777  *  @param mesh         A handle which represents an instance of MeshLink.
778  *  @param node         The node to which this channel is being initiated.
779  *  @param port         The port number the peer wishes to connect to.
780  *  @param cb           A pointer to the function which will be called when the remote node sends data to the local node.
781  *                      The pointer may be NULL, in which case incoming data is ignored.
782  *  @param data         A pointer to a buffer containing data to already queue for sending, or NULL if there is no data to send.
783  *                      After meshlink_send() returns, the application is free to overwrite or free this buffer.
784  *  @param len          The length of the data, or 0 if there is no data to send.
785  *
786  *  @return             A handle for the channel, or NULL in case of an error.
787  *                      The handle is valid until meshlink_channel_close() is called.
788  */
789 extern meshlink_channel_t *meshlink_channel_open(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len);
790
791 /// Partially close a reliable stream channel.
792 /** This shuts down the read or write side of a channel, or both, without closing the handle.
793  *  It can be used to inform the remote node that the local node has finished sending all data on the channel,
794  *  but still allows waiting for incoming data from the remote node.
795  *
796  *  Shutting down the receive direction is also possible, and is equivalent to setting the receive callback to NULL.
797  *
798  *  @param mesh         A handle which represents an instance of MeshLink.
799  *  @param channel      A handle for the channel.
800  *  @param direction    Must be one of SHUT_RD, SHUT_WR or SHUT_RDWR, otherwise this call will not have any affect.
801  */
802 extern void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction);
803
804 /// Close a reliable stream channel.
805 /** This informs the remote node that the local node has finished sending all data on the channel.
806  *  It also causes the local node to stop accepting incoming data from the remote node.
807  *  It will free the struct meshlink_channel and all associated resources.
808  *  Afterwards, the channel handle is invalid and must not be used any more.
809  *
810  *  It is allowed to call this function at any time on a valid handle, even inside callback functions.
811  *  If called with a valid handle, this function always succeeds, otherwise the result is undefined.
812  *
813  *  @param mesh         A handle which represents an instance of MeshLink.
814  *  @param channel      A handle for the channel.
815  */
816 extern void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel);
817
818 /// Transmit data on a channel
819 /** This queues data to send to the remote node.
820  *
821  *  @param mesh         A handle which represents an instance of MeshLink.
822  *  @param channel      A handle for the channel.
823  *  @param data         A pointer to a buffer containing data sent by the source, or NULL if there is no data to send.
824  *                      After meshlink_send() returns, the application is free to overwrite or free this buffer.
825  *  @param len          The length of the data, or 0 if there is no data to send.
826  *
827  *  @return             The amount of data that was queued, which can be less than len, or a negative value in case of an error.
828  */
829 extern ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len);
830
831 /// Get channel flags.
832 /** This returns the flags used when opening this channel.
833  *
834  *  @param mesh         A handle which represents an instance of MeshLink.
835  *  @param channel      A handle for the channel.
836  *
837  *  @return             The flags set for this channel.
838  */
839 extern uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel);
840
841 /// Hint that a hostname may be found at an address
842 /** This function indicates to meshlink that the given hostname is likely found
843  *  at the given IP address and port.
844  *
845  *  @param mesh     A handle which represents an instance of MeshLink.
846  *  @param hostname The hostname which can be found at the given address.
847  *                  The caller is free to overwrite or free this string
848  *                  once meshlink returns.
849  *  @param addr     The IP address and port which should be tried for the
850  *                  given hostname. The caller is free to overwrite or free
851  *                  this memory once meshlink returns.
852  */
853 extern void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr);
854
855 /// Enable or disable zeroconf discovery of local peers
856
857 /** This controls whether zeroconf discovery using the Catta library will be
858  *  enabled to search for peers on the local network. By default, it is enabled.
859  *
860  *  @param mesh    A handle which represents an instance of MeshLink.
861  *  @param enable  Set to true to enable discovery, false to disable.
862  */
863 extern void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable);
864
865 #ifdef __cplusplus
866 }
867 #endif
868
869 #endif