]> git.meshlink.io Git - meshlink/blob - src/meshlink++.h
2nd approach again: class meshlink::mesh has the handle as member, not as base class.
[meshlink] / src / meshlink++.h
1 /*
2     meshlink++.h -- MeshLink C++ 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 MESHLINKPP_H
21 #define MESHLINKPP_H
22
23 #include <meshlink.h>
24 #include <new> // for 'placement new'
25
26 namespace meshlink {
27         class mesh;
28         class node;
29         class channel;
30
31         /// Severity of log messages generated by MeshLink.
32         typedef meshlink_log_level_t log_level_t;
33
34         /// Code of most recent error encountered.
35         typedef meshlink_errno_t errno_t;
36
37         /// A callback for receiving data from the mesh.
38         /** @param mesh      A handle which represents an instance of MeshLink.
39          *  @param source    A pointer to a meshlink::node describing the source of the data.
40          *  @param data      A pointer to a buffer containing the data sent by the source.
41          *  @param len       The length of the received data.
42          */
43         typedef void (*receive_cb_t)(mesh *mesh, node *source, const void *data, size_t len);
44
45         /// A callback reporting node status changes.
46         /** @param mesh       A handle which represents an instance of MeshLink.
47          *  @param node       A pointer to a meshlink::node describing the node whose status changed.
48          *  @param reachable  True if the node is reachable, false otherwise.
49          */
50         typedef void (*node_status_cb_t)(mesh *mesh, node *node, bool reachable);
51
52         /// A callback for receiving log messages generated by MeshLink.
53         /** @param mesh      A handle which represents an instance of MeshLink.
54          *  @param level     An enum describing the severity level of the message.
55          *  @param text      A pointer to a string containing the textual log message.
56          */
57         typedef void (*log_cb_t)(mesh *mesh, log_level_t level, const char *text);
58
59         /// A callback for accepting incoming channels.
60         /** @param mesh         A handle which represents an instance of MeshLink.
61          *  @param channel      A handle for the incoming channel.
62          *  @param node         The node from which this channel is being initiated.
63          *  @param port         The port number the peer wishes to connect to.
64          *  @param data         A pointer to a buffer containing data already received. (Not yet used.)
65          *  @param len          The length of the data. (Not yet used.)
66          *
67          *  @return             This function should return true if the application accepts the incoming channel, false otherwise.
68          *                      If returning false, the channel is invalid and may not be used anymore.
69          */
70         typedef bool (*channel_accept_cb_t)(mesh *mesh, channel *channel, node *node, uint16_t port, const void *data, size_t len);
71
72         /// A callback for receiving data from a channel.
73         /** @param mesh         A handle which represents an instance of MeshLink.
74          *  @param channel      A handle for the channel.
75          *  @param data         A pointer to a buffer containing data sent by the source.
76          *  @param len          The length of the data.
77          */
78         typedef void (*channel_receive_cb_t)(mesh *mesh, channel *channel, const void *data, size_t len);
79
80         /// A callback that is called when data can be send on a channel.
81         /** @param mesh         A handle which represents an instance of MeshLink.
82          *  @param channel      A handle for the channel.
83          *  @param len          The maximum length of data that is guaranteed to be accepted by a call to channel_send().
84          */
85         typedef void (*channel_poll_cb_t)(mesh *mesh, channel *channel, size_t len);
86
87         /// A class describing a MeshLink node.
88         class node: public meshlink_node_t {
89         };
90
91         /// A class describing a MeshLink channel.
92         class channel: public meshlink_channel_t {
93         };
94
95         /// A class describing a MeshLink mesh.
96         class mesh {
97         public:
98                 mesh() : handle(0) {}
99                 
100                 virtual ~mesh() {
101                         this->close();
102                 }
103                 
104                 bool isOpen() const {
105                         return (handle!=0);
106                 }
107                 
108 // TODO: please enable C++11 in autoconf to enable "move constructors":
109 //              mesh(mesh&& other)
110 //              : handle(other.handle)
111 //              {
112 //                      if(handle)
113 //                              handle->priv = this;
114 //                      other.handle = 0;
115 //              }
116
117                 /// Initialize MeshLink's configuration directory.
118                 /** This function causes MeshLink to initialize its configuration directory,
119                  *  if it hasn't already been initialized.
120                  *  It only has to be run the first time the application starts,
121                  *  but it is not a problem if it is run more than once, as long as
122                  *  the arguments given are the same.
123                  *
124                  *  This function does not start any network I/O yet. The application should
125                  *  first set callbacks, and then call meshlink_start().
126                  *
127                  *  @param confbase The directory in which MeshLink will store its configuration files.
128                  *  @param name     The name which this instance of the application will use in the mesh.
129                  *  @param appname  The application name which will be used in the mesh.
130                  *  @param dclass   The device class which will be used in the mesh.
131                  *
132                  *  @return         This function will return a pointer to a meshlink::mesh if MeshLink has succesfully set up its configuration files, NULL otherwise.
133                  */ 
134                 bool open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
135                         handle = meshlink_open(confbase, name, appname, devclass);
136                         if(handle)
137                                 handle->priv = this;
138                         
139                         return isOpen();
140                 }
141                 
142                 mesh(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
143                         open(confbase, name, appname, devclass);
144                 }
145                 
146                 /// Close the MeshLink handle.
147                 /** This function calls meshlink_stop() if necessary,
148                  *  and frees all memory allocated by MeshLink.
149                  *  Afterwards, the handle and any pointers to a struct meshlink_node are invalid.
150                  */
151                 void close() {
152                         if(handle)
153                                 meshlink_close(handle);
154                         handle=0;
155                 }
156         
157                 /** instead of registerin callbacks you derive your own class and overwrite the following abstract member functions.
158                  *  These functions are run in MeshLink's own thread.
159                  *  It is therefore important that these functions use apprioriate methods (queues, pipes, locking, etc.)
160                  *  to hand the data over to the application's thread.
161                  *  These functions should also not block itself and return as quickly as possible.
162                  * The default member functions are no-ops, so you are not required to overwrite all these member functions
163                  */
164                 
165                 /// This function is called whenever another node sends data to the local node.
166                 virtual void receive(node* source, const void* data, size_t length) { /* do nothing */ }
167                 
168                 /// This functions is called  whenever another node's status changed.
169                 virtual void node_status(node* peer, bool reachable)                { /* do nothing */ }
170                 
171                 /// This functions is called whenever MeshLink has some information to log.
172                 virtual void log(log_level_t level, const char* message)            { /* do nothing */ }
173                 
174                 /// Start MeshLink.
175                 /** This function causes MeshLink to open network sockets, make outgoing connections, and
176                  *  create a new thread, which will handle all network I/O.
177                  *
178                  *  @return         This function will return true if MeshLink has succesfully started its thread, false otherwise.
179                  */
180                 bool start() {
181                         meshlink_set_receive_cb    (handle, &receive_trampoline);
182                         meshlink_set_node_status_cb(handle, &node_status_trampoline);
183                         meshlink_set_log_cb        (handle, MESHLINK_DEBUG, &log_trampoline);
184                         return meshlink_start      (handle);
185                 }
186
187                 /// Stop MeshLink.
188                 /** This function causes MeshLink to disconnect from all other nodes,
189                  *  close all sockets, and shut down its own thread.
190                  */
191                 void stop() {
192                         meshlink_stop(handle);
193                 }
194
195                 /// Send data to another node.
196                 /** This functions sends one packet of data to another node in the mesh.
197                  *  The packet is sent using UDP semantics, which means that
198                  *  the packet is sent as one unit and is received as one unit,
199                  *  and that there is no guarantee that the packet will arrive at the destination.
200                  *  The application should take care of getting an acknowledgement and retransmission if necessary.
201                  *
202                  *  @param destination  A pointer to a meshlink::node describing the destination for the data.
203                  *  @param data         A pointer to a buffer containing the data to be sent to the source.
204                  *  @param len          The length of the data.
205                  *  @return             This function will return true if MeshLink has queued the message for transmission, and false otherwise.
206                  *                      A return value of true does not guarantee that the message will actually arrive at the destination.
207                  */
208                 bool send(node *destination, const void *data, unsigned int len) {
209                         return meshlink_send(handle, destination, data, len);
210                 }
211
212                 /// Get a handle for a specific node.
213                 /** This function returns a handle for the node with the given name.
214                  *
215                  *  @param name         The name of the node for which a handle is requested.
216                  *
217                  *  @return             A pointer to a meshlink::node which represents the requested node,
218                  *                      or NULL if the requested node does not exist.
219                  */
220                 node *get_node(const char *name) {
221                         return (node *)meshlink_get_node(handle, name);
222                 }
223
224                 /// Get a list of all nodes.
225                 /** This function returns a list with handles for all known nodes.
226                  *
227                  *  @param nodes        A pointer to an array of pointers to meshlink::node, which should be allocated by the application.
228                  *  @param nmemb        The maximum number of pointers that can be stored in the nodes array.
229                  *
230                  *  @return             The number of known nodes, or -1 in case of an error.
231                  *                      This can be larger than nmemb, in which case not all nodes were stored in the nodes array.
232                  */
233                 node **get_all_nodes(node **nodes, size_t *nmemb) {
234                         return (node **)meshlink_get_all_nodes(handle, (meshlink_node_t **)nodes, nmemb);
235                 }
236
237                 /// Sign data using the local node's MeshLink key.
238                 /** This function signs data using the local node's MeshLink key.
239                  *  The generated signature can be securely verified by other nodes.
240                  *
241                  *  @param data         A pointer to a buffer containing the data to be signed.
242                  *  @param len          The length of the data to be signed.
243                  *  @param signature    A pointer to a buffer where the signature will be stored.
244                  *  @param siglen       The size of the signature buffer. Will be changed after the call to match the size of the signature itself.
245                  *
246                  *  @return             This function returns true if the signature is valid, false otherwise.
247                  */
248                 bool sign(const void *data, size_t len, void *signature, size_t *siglen) {
249                         return meshlink_sign(handle, data, len, signature, siglen);
250                 }
251
252                 /// Verify the signature generated by another node of a piece of data.
253                 /** This function verifies the signature that another node generated for a piece of data.
254                  *
255                  *  @param source       A pointer to a meshlink_node_t describing the source of the signature.
256                  *  @param data         A pointer to a buffer containing the data to be verified.
257                  *  @param len          The length of the data to be verified.
258                  *  @param signature    A pointer to a string containing the signature.
259                  *  @param siglen       The size of the signature.
260                  *
261                  *  @return             This function returns true if the signature is valid, false otherwise.
262                  */
263                 bool verify(node *source, const void *data, size_t len, const void *signature, size_t siglen) {
264                         return meshlink_verify(handle, source, data, len, signature, siglen);
265                 }
266
267                 /// Add an Address for the local node.
268                 /** This function adds an Address for the local node, which will be used for invitation URLs.
269                  *
270                  *  @param address      A string containing the address, which can be either in numeric format or a hostname.
271                  *
272                  *  @return             This function returns true if the address was added, false otherwise.
273                  */
274                 bool add_address(const char *address) {
275                         return meshlink_add_address(handle, address);
276                 }
277
278                 /// Invite another node into the mesh.
279                 /** This function generates an invitation that can be used by another node to join the same mesh as the local node.
280                  *  The generated invitation is a string containing a URL.
281                  *  This URL should be passed by the application to the invitee in a way that no eavesdroppers can see the URL.
282                  *  The URL can only be used once, after the user has joined the mesh the URL is no longer valid.
283                  *
284                  *  @param name         The name that the invitee will use in the mesh.
285                  *
286                  *  @return             This function returns a string that contains the invitation URL.
287                  *                      The application should call free() after it has finished using the URL.
288                  */
289                 char *invite(const char *name) {
290                         return meshlink_invite(handle, name);
291                 }
292
293                 /// Use an invitation to join a mesh.
294                 /** This function allows the local node to join an existing mesh using an invitation URL generated by another node.
295                  *  An invitation can only be used if the local node has never connected to other nodes before.
296                  *  After a succesfully accepted invitation, the name of the local node may have changed.
297                  *
298                  *  @param invitation   A string containing the invitation URL.
299                  *
300                  *  @return             This function returns true if the local node joined the mesh it was invited to, false otherwise.
301                  */
302                 bool join(const char *invitation) {
303                         return meshlink_join(handle, invitation);
304                 }
305
306                 /// Export the local node's key and addresses.
307                 /** This function generates a string that contains the local node's public key and one or more IP addresses.
308                  *  The application can pass it in some way to another node, which can then import it,
309                  *  granting the local node access to the other node's mesh.
310                  *
311                  *  @return             This function returns a string that contains the exported key and addresses.
312                  *                      The application should call free() after it has finished using this string.
313                  */
314                 char *export_key() {
315                         return meshlink_export(handle);
316                 }
317
318                 /// Import another node's key and addresses.
319                 /** This function accepts a string containing the exported public key and addresses of another node.
320                  *  By importing this data, the local node grants the other node access to its mesh.
321                  *
322                  *  @param data         A string containing the other node's exported key and addresses.
323                  *
324                  *  @return             This function returns true if the data was valid and the other node has been granted access to the mesh, false otherwise.
325                  */
326                 bool import_key(const char *data) {
327                         return meshlink_import(handle, data);
328                 }
329
330                 /// Blacklist a node from the mesh.
331                 /** This function causes the local node to blacklist another node.
332                  *  The local node will drop any existing connections to that node,
333                  *  and will not send data to it nor accept any data received from it any more.
334                  *
335                  *  @param node         A pointer to a meshlink::node describing the node to be blacklisted.
336                  */
337                 void blacklist(node *node) {
338                         return meshlink_blacklist(handle, node);
339                 }
340
341                 /// Set the accept callback.
342                 /** This functions sets the callback that is called whenever another node sends data to the local node.
343                  *  The callback is run in MeshLink's own thread.
344                  *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
345                  *  to hand the data over to the application's thread.
346                  *  The callback should also not block itself and return as quickly as possible.
347                  *
348                  *  @param channel   A handle for the channel.
349                  *  @param cb        A pointer to the function which will be called when another node sends data to the local node.
350                  */
351                 void set_channel_accept_cb(channel *channel, channel_accept_cb_t cb) {
352                         return meshlink_set_channel_accept_cb(handle, (meshlink_channel_accept_cb_t)cb);
353                 }
354
355                 /// Set the poll callback.
356                 /** This functions sets the callback that is called whenever data can be sent to another node.
357                  *  The callback is run in MeshLink's own thread.
358                  *  It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.)
359                  *  to pass data to or from the application's thread.
360                  *  The callback should also not block itself and return as quickly as possible.
361                  *
362                  *  @param channel   A handle for the channel.
363                  *  @param cb        A pointer to the function which will be called when data can be sent to another node.
364                  *                   If a NULL pointer is given, the callback will be disabled.
365                  */
366                 void set_channel_poll_cb(channel *channel, channel_poll_cb_t cb) {
367                         return meshlink_set_channel_poll_cb(handle, channel, (meshlink_channel_poll_cb_t)cb);
368                 }
369
370                 /// Open a reliable stream channel to another node.
371                 /** This function is called whenever a remote node wants to open a channel to the local node.
372                  *  The application then has to decide whether to accept or reject this channel.
373                  *
374                  *  @param node         The node to which this channel is being initiated.
375                  *  @param port         The port number the peer wishes to connect to.
376                  *  @param cb           A pointer to the function which will be called when the remote node sends data to the local node.
377                  *  @param data         A pointer to a buffer containing data to already queue for sending.
378                  *  @param len          The length of the data.
379                  *
380                  *  @return             A handle for the channel, or NULL in case of an error.
381                  */
382                 channel *channel_open(node *node, uint16_t port, channel_receive_cb_t cb, const void *data, size_t len) {
383                         return (channel *)meshlink_channel_open(handle, node, port, (meshlink_channel_receive_cb_t)cb, data, len);
384                 }
385
386                 /// Partially close a reliable stream channel.
387                 /** This shuts down the read or write side of a channel, or both, without closing the handle.
388                  *  It can be used to inform the remote node that the local node has finished sending all data on the channel,
389                  *  but still allows waiting for incoming data from the remote node.
390                  *
391                  *  @param channel      A handle for the channel.
392                  *  @param direction    Must be one of SHUT_RD, SHUT_WR or SHUT_RDWR.
393                  */
394                 void channel_shutdown(channel *channel, int direction) {
395                         return meshlink_channel_shutdown(handle, channel, direction);
396                 }
397
398                 /// Close a reliable stream channel.
399                 /** This informs the remote node that the local node has finished sending all data on the channel.
400                  *  It also causes the local node to stop accepting incoming data from the remote node.
401                  *  Afterwards, the channel handle is invalid and must not be used any more.
402                  *
403                  *  @param channel      A handle for the channel.
404                  */
405                 void channel_close(meshlink_channel_t *channel) {
406                         return meshlink_channel_close(handle, channel);
407                 }
408
409                 /// Transmit data on a channel
410                 /** This queues data to send to the remote node.
411                  *
412                  *  @param channel      A handle for the channel.
413                  *  @param data         A pointer to a buffer containing data sent by the source.
414                  *  @param len          The length of the data.
415                  *
416                  *  @return             The amount of data that was queued, which can be less than len, or a negative value in case of an error.
417                  */
418                 ssize_t channel_send(channel *channel, void *data, size_t len) {
419                         return meshlink_channel_send(handle, channel, data, len);
420                 }
421
422         private:
423                 // non-copyable:
424                 mesh(const mesh&) /* TODO: C++11: = delete */;
425                 void operator=(const mesh&) /* TODO: C++11: = delete */ ;
426                 
427                 /// static callback trampolines:
428                 static void receive_trampoline(meshlink_handle_t* handle, meshlink_node_t* source, const void* data, size_t length)
429                 {
430                         mesh* that = static_cast<mesh*>(handle->priv);
431                         that->receive(static_cast<node*>(source), data, length);
432                 }
433                 
434                 static void node_status_trampoline(meshlink_handle_t* handle, meshlink_node_t* peer, bool reachable)
435                 {
436                         mesh* that = static_cast<mesh*>(handle->priv);
437                         that->node_status(static_cast<node*>(peer), reachable);
438                 }
439
440                 static void log_trampoline(meshlink_handle_t* handle, log_level_t level, const char* message)
441                 {
442                         mesh* that = static_cast<mesh*>(handle->priv);
443                         that->log(level, message);
444                 }
445                 
446                 meshlink_handle_t*  handle;
447         };
448
449         static const char *strerror(errno_t err = meshlink_errno) {
450                 return meshlink_strerror(err);
451         }
452
453 }
454
455 #endif // MESHLINKPP_H