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