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