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