From: Saverio Proto Date: Wed, 11 Jun 2014 17:58:53 +0000 (+0200) Subject: Merge branch 'master' into testing/invitations X-Git-Url: http://git.meshlink.io/?a=commitdiff_plain;h=e9ea74ec1b656ba663d94fb3cf99a5837f170be7;hp=1bad176f8d6be0bf8890b5efeaae0d1b4bdb1281;p=meshlink Merge branch 'master' into testing/invitations --- diff --git a/configure.ac b/configure.ac index f668719c..2f1caa68 100644 --- a/configure.ac +++ b/configure.ac @@ -15,6 +15,7 @@ AC_DEFINE([__USE_BSD], 1, [Enable BSD extensions]) dnl Checks for programs. AC_PROG_CC_C99 +AC_PROG_CXX AC_PROG_CPP AC_PROG_INSTALL AC_PROG_LN_S diff --git a/examples/Makefile.am b/examples/Makefile.am index baa03715..af8f0f45 100644 --- a/examples/Makefile.am +++ b/examples/Makefile.am @@ -1,4 +1,4 @@ -bin_PROGRAMS = meshlinkapp chat +bin_PROGRAMS = meshlinkapp chat chatpp AM_CPPFLAGS = -I../src @@ -7,3 +7,6 @@ meshlinkapp_LDADD = ../src/libmeshlink.la chat_SOURCES = chat.c chat_LDADD = ../src/libmeshlink.la + +chatpp_SOURCES = chatpp.cc +chatpp_LDADD = ../src/libmeshlink.la diff --git a/examples/chatpp.cc b/examples/chatpp.cc new file mode 100644 index 00000000..864a3e80 --- /dev/null +++ b/examples/chatpp.cc @@ -0,0 +1,211 @@ +#include +#include +#include +#include +#include "../src/meshlink++.h" + +static void log_message(meshlink::mesh *mesh, meshlink::log_level_t level, const char *text) { + const char *levelstr[] = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}; + fprintf(stderr, "%s: %s\n", levelstr[level], text); +} + +static void receive(meshlink::mesh *mesh, meshlink::node *source, const void *data, size_t len) { + const char *msg = (const char *)data; + + if(!len || msg[len - 1]) { + fprintf(stderr, "Received invalid data from %s\n", source->name); + return; + } + + printf("%s says: %s\n", source->name, msg); +} + +static void node_status(meshlink::mesh *mesh, meshlink::node *node, bool reachable) { + if(reachable) + printf("%s joined.\n", node->name); + else + printf("%s left.\n", node->name); +} + +static void parse_command(meshlink::mesh *mesh, char *buf) { + char *arg = strchr(buf, ' '); + if(arg) + *arg++ = 0; + + if(!strcasecmp(buf, "invite")) { + char *invitation; + + if(!arg) { + fprintf(stderr, "/invite requires an argument!\n"); + return; + } + + invitation = mesh->invite(arg); + if(!invitation) { + fprintf(stderr, "Could not invite '%s': %s\n", arg, mesh->errstr); + return; + } + + printf("Invitation for %s: %s\n", arg, invitation); + free(invitation); + } else if(!strcasecmp(buf, "join")) { + if(!arg) { + fprintf(stderr, "/join requires an argument!\n"); + return; + } + + if(!mesh->join(arg)) + fprintf(stderr, "Could not join using invitation: %s\n", mesh->errstr); + else + fprintf(stderr, "Invitation accepted!\n"); + } else if(!strcasecmp(buf, "kick")) { + if(!arg) { + fprintf(stderr, "/kick requires an argument!\n"); + return; + } + + meshlink::node *node = mesh->get_node(arg); + if(!node) { + fprintf(stderr, "Unknown node '%s'\n", arg); + return; + } + + mesh->blacklist(node); + + printf("Node '%s' blacklisted.\n", arg); + } else if(!strcasecmp(buf, "who")) { + if(!arg) { + meshlink::node *nodes[100]; + size_t n = mesh->get_all_nodes(nodes, 100); + if(!n) { + fprintf(stderr, "No nodes known!\n"); + } else { + printf("Known nodes:"); + for(int i = 0; i < n && i < 100; i++) + printf(" %s", nodes[i]->name); + if(n > 100) + printf(" (and %zu more)", n - 100); + printf("\n"); + } + } else { + meshlink::node *node = mesh->get_node(arg); + if(!node) { + fprintf(stderr, "Unknown node '%s'\n", arg); + } else { + printf("Node %s found\n", arg); + } + } + } else if(!strcasecmp(buf, "quit")) { + printf("Bye!\n"); + fclose(stdin); + } else if(!strcasecmp(buf, "help")) { + printf( + ": Send a message to the given node.\n" + " Subsequent messages don't need the : prefix.\n" + "/invite Create an invitation for a new node.\n" + "/join Join an existing mesh using an invitation.\n" + "/kick Blacklist the given node.\n" + "/who [] List all nodes or show information about the given node.\n" + "/quit Exit this program.\n" + ); + } else { + fprintf(stderr, "Unknown command '/%s'\n", buf); + } +} + +static void parse_input(meshlink::mesh *mesh, char *buf) { + static meshlink::node *destination; + size_t len; + + if(!buf) + return; + + // Remove newline. + + len = strlen(buf); + + if(len && buf[len - 1] == '\n') + buf[--len] = 0; + + if(len && buf[len - 1] == '\r') + buf[--len] = 0; + + // Ignore empty lines. + + if(!len) + return; + + // Commands start with '/' + + if(*buf == '/') + return parse_command(mesh, buf + 1); + + // Lines in the form "name: message..." set the destination node. + + char *msg = buf; + char *colon = strchr(buf, ':'); + + if(colon) { + *colon = 0; + msg = colon + 1; + if(*msg == ' ') + msg++; + + destination = mesh->get_node(buf); + if(!destination) { + fprintf(stderr, "Unknown node '%s'\n", buf); + return; + } + } + + if(!destination) { + fprintf(stderr, "Who are you talking to? Write 'name: message...'\n"); + return; + } + + if(!mesh->send(destination, msg, strlen(msg) + 1)) { + fprintf(stderr, "Could not send message to '%s': %s\n", destination->name, mesh->errstr); + return; + } + + printf("Message sent to '%s'.\n", destination->name); +} + +int main(int argc, char *argv[]) { + const char *confbase = ".chat"; + const char *nick = NULL; + char buf[1024]; + + if(argc > 1) + confbase = argv[1]; + + if(argc > 2) + nick = argv[2]; + + meshlink::mesh *mesh = meshlink::open(confbase, nick); + if(!mesh) { + fprintf(stderr, "Could not open MeshLink!\n"); + return 1; + } + + mesh->set_receive_cb(receive); + mesh->set_node_status_cb(node_status); + mesh->set_log_cb(MESHLINK_INFO, log_message); + + if(!mesh->start()) { + fprintf(stderr, "Could not start MeshLink: %s\n", mesh->errstr); + return 1; + } + + printf("Chat started.\nType /help for a list of commands.\n"); + + while(fgets(buf, sizeof buf, stdin)) + parse_input(mesh, buf); + + printf("Chat stopping.\n"); + + mesh->stop(); + meshlink::close(mesh); + + return 0; +} diff --git a/src/event.c b/src/event.c index 63657a5f..aa451801 100644 --- a/src/event.c +++ b/src/event.c @@ -246,9 +246,9 @@ void event_loop_init(event_loop_t *loop) { void event_loop_exit(event_loop_t *loop) { for splay_each(io_t, io, &loop->ios) - splay_free_node(&loop->ios, node); + splay_unlink_node(&loop->ios, node); for splay_each(timeout_t, timeout, &loop->timeouts) - splay_free_node(&loop->timeouts, node); + splay_unlink_node(&loop->timeouts, node); for splay_each(signal_t, signal, &loop->signals) - splay_free_node(&loop->signals, node); + splay_unlink_node(&loop->signals, node); } diff --git a/src/meshlink++.h b/src/meshlink++.h new file mode 100644 index 00000000..3fa7774e --- /dev/null +++ b/src/meshlink++.h @@ -0,0 +1,297 @@ +/* + meshlink++.h -- MeshLink C++ API + Copyright (C) 2014 Guus Sliepen + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MESHLINKPP_H +#define MESHLINKPP_H + +#include + +namespace meshlink { + class mesh; + class node; + + /// Severity of log messages generated by MeshLink. + typedef meshlink_log_level_t log_level_t; + + /// Code of most recent error encountered. + typedef meshlink_errno_t errno_t; + + /// A callback for receiving data from the mesh. + /** @param mesh A handle which represents an instance of MeshLink. + * @param source A pointer to a meshlink::node describing the source of the data. + * @param data A pointer to a buffer containing the data sent by the source. + * @param len The length of the received data. + */ + typedef void (*receive_cb_t)(mesh *mesh, node *source, const void *data, size_t len); + + /// A callback reporting node status changes. + /** @param mesh A handle which represents an instance of MeshLink. + * @param node A pointer to a meshlink::node describing the node whose status changed. + * @param reachable True if the node is reachable, false otherwise. + */ + typedef void (*node_status_cb_t)(mesh *mesh, node *node, bool reachable); + + /// A callback for receiving log messages generated by MeshLink. + /** @param mesh A handle which represents an instance of MeshLink. + * @param level An enum describing the severity level of the message. + * @param text A pointer to a string containing the textual log message. + */ + typedef void (*log_cb_t)(mesh *mesh, log_level_t level, const char *text); + + /// A class describing a MeshLink node. + class node: public meshlink_node_t { + }; + + /// A class describing a MeshLink mesh. + class mesh: public meshlink_handle_t { + public: + // TODO: delete constructor, add a destructor. + + /// Start MeshLink. + /** This function causes MeshLink to open network sockets, make outgoing connections, and + * create a new thread, which will handle all network I/O. + * + * @return This function will return true if MeshLink has succesfully started its thread, false otherwise. + */ + bool start() { + return meshlink_start(this); + } + + /// Stop MeshLink. + /** This function causes MeshLink to disconnect from all other nodes, + * close all sockets, and shut down its own thread. + */ + void stop() { + meshlink_stop(this); + } + + /// Set the receive callback. + /** This functions sets the callback that is called whenever another node sends data to the local node. + * The callback is run in MeshLink's own thread. + * It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.) + * to hand the data over to the application's thread. + * The callback should also not block itself and return as quickly as possible. + * + * @param cb A pointer to the function which will be called when another node sends data to the local node. + */ + void set_receive_cb(receive_cb_t cb) { + meshlink_set_receive_cb(this, (meshlink_receive_cb_t)cb); + } + + /// Set the node status callback. + /** This functions sets the callback that is called whenever another node's status changed. + * The callback is run in MeshLink's own thread. + * It is therefore important that the callback uses apprioriate methods (queues, pipes, locking, etc.) + * to hand the data over to the application's thread. + * The callback should also not block itself and return as quickly as possible. + * + * @param cb A pointer to the function which will be called when another node's status changes. + */ + void set_node_status_cb(node_status_cb_t cb) { + meshlink_set_node_status_cb(this, (meshlink_node_status_cb_t)cb); + } + + /// Set the log callback. + /** This functions sets the callback that is called whenever MeshLink has some information to log. + * The callback is run in MeshLink's own thread. + * It is important that the callback uses apprioriate methods (queues, pipes, locking, etc.) + * to hand the data over to the application's thread. + * The callback should also not block itself and return as quickly as possible. + * + * @param level An enum describing the minimum severity level. Debugging information with a lower level will not trigger the callback. + * @param cb A pointer to the function which will be called when another node sends data to the local node. + */ + void set_log_cb(meshlink_log_level_t level, log_cb_t cb) { + meshlink_set_log_cb(this, level, (meshlink_log_cb_t)cb); + } + + /// Send data to another node. + /** This functions sends one packet of data to another node in the mesh. + * The packet is sent using UDP semantics, which means that + * the packet is sent as one unit and is received as one unit, + * and that there is no guarantee that the packet will arrive at the destination. + * The application should take care of getting an acknowledgement and retransmission if necessary. + * + * @param destination A pointer to a meshlink::node describing the destination for the data. + * @param data A pointer to a buffer containing the data to be sent to the source. + * @param len The length of the data. + * @return This function will return true if MeshLink has queued the message for transmission, and false otherwise. + * A return value of true does not guarantee that the message will actually arrive at the destination. + */ + bool send(node *destination, const void *data, unsigned int len) { + return meshlink_send(this, destination, data, len); + } + + /// Get a handle for a specific node. + /** This function returns a handle for the node with the given name. + * + * @param name The name of the node for which a handle is requested. + * + * @return A pointer to a meshlink::node which represents the requested node, + * or NULL if the requested node does not exist. + */ + node *get_node(const char *name) { + return (node *)meshlink_get_node(this, name); + } + + /// Get a list of all nodes. + /** This function returns a list with handles for all known nodes. + * + * @param nodes A pointer to an array of pointers to meshlink::node, which should be allocated by the application. + * @param nmemb The maximum number of pointers that can be stored in the nodes array. + * + * @param return The number of known nodes. This can be larger than nmemb, in which case not all nodes were stored in the nodes array. + */ + size_t get_all_nodes(node **nodes, size_t nmemb) { + return meshlink_get_all_nodes(this, (meshlink_node_t **)nodes, nmemb); + } + + /// Sign data using the local node's MeshLink key. + /** This function signs data using the local node's MeshLink key. + * The generated signature can be securely verified by other nodes. + * + * @param data A pointer to a buffer containing the data to be signed. + * @param len The length of the data to be signed. + * + * @return This function returns a pointer to a string containing the signature, or NULL in case of an error. + * The application should call free() after it has finished using the signature. + */ + char *sign(const char *data, size_t len) { + return meshlink_sign(this, data, len); + } + + /// Verify the signature generated by another node of a piece of data. + /** This function verifies the signature that another node generated for a piece of data. + * + * @param source A pointer to a meshlink_node_t describing the source of the signature. + * @param data A pointer to a buffer containing the data to be verified. + * @param len The length of the data to be verified. + * @param signature A pointer to a string containing the signature. + * + * @return This function returns true if the signature is valid, false otherwise. + */ + bool verify(node *source, const char *data, size_t len, const char *signature) { + return meshlink_verify(this, source, data, len, signature); + } + + /// Add an Address for the local node. + /** This function adds an Address for the local node, which will be used for invitation URLs. + * + * @param address A string containing the address, which can be either in numeric format or a hostname. + * + * @return This function returns true if the address was added, false otherwise. + */ + bool add_address(const char *address) { + return meshlink_add_address(this, address); + } + + /// Invite another node into the mesh. + /** This function generates an invitation that can be used by another node to join the same mesh as the local node. + * The generated invitation is a string containing a URL. + * This URL should be passed by the application to the invitee in a way that no eavesdroppers can see the URL. + * The URL can only be used once, after the user has joined the mesh the URL is no longer valid. + * + * @param name The name that the invitee will use in the mesh. + * + * @return This function returns a string that contains the invitation URL. + * The application should call free() after it has finished using the URL. + */ + char *invite(const char *name) { + return meshlink_invite(this, name); + } + + /// Use an invitation to join a mesh. + /** This function allows the local node to join an existing mesh using an invitation URL generated by another node. + * An invitation can only be used if the local node has never connected to other nodes before. + * After a succesfully accepted invitation, the name of the local node may have changed. + * + * @param invitation A string containing the invitation URL. + * + * @return This function returns true if the local node joined the mesh it was invited to, false otherwise. + */ + bool join(const char *invitation) { + return meshlink_join(this, invitation); + } + + /// Export the local node's key and addresses. + /** This function generates a string that contains the local node's public key and one or more IP addresses. + * The application can pass it in some way to another node, which can then import it, + * granting the local node access to the other node's mesh. + * + * @return This function returns a string that contains the exported key and addresses. + * The application should call free() after it has finished using this string. + */ + char *export_key() { + return meshlink_export(this); + } + + /// Import another node's key and addresses. + /** This function accepts a string containing the exported public key and addresses of another node. + * By importing this data, the local node grants the other node access to its mesh. + * + * @param data A string containing the other node's exported key and addresses. + * + * @return This function returns true if the data was valid and the other node has been granted access to the mesh, false otherwise. + */ + bool import_key(const char *data) { + return meshlink_import(this, data); + } + + /// Blacklist a node from the mesh. + /** This function causes the local node to blacklist another node. + * The local node will drop any existing connections to that node, + * and will not send data to it nor accept any data received from it any more. + * + * @param node A pointer to a meshlink::node describing the node to be blacklisted. + */ + void blacklist(node *node) { + return meshlink_blacklist(this, node); + } + }; + + /// Initialize MeshLink's configuration directory. + /** This function causes MeshLink to initialize its configuration directory, + * if it hasn't already been initialized. + * It only has to be run the first time the application starts, + * but it is not a problem if it is run more than once, as long as + * the arguments given are the same. + * + * This function does not start any network I/O yet. The application should + * first set callbacks, and then call meshlink_start(). + * + * @param confbase The directory in which MeshLink will store its configuration files. + * @param name The name which this instance of the application will use in the mesh. + * + * @return This function will return a pointer to a meshlink::mesh if MeshLink has succesfully set up its configuration files, NULL otherwise. + */ + static mesh *open(const char *confbase, const char *name) { + return (mesh *)meshlink_open(confbase, name); + } + + /// Close the MeshLink handle. + /** This function calls meshlink_stop() if necessary, + * and frees all memory allocated by MeshLink. + * Afterwards, the handle and any pointers to a struct meshlink_node are invalid. + */ + static void close(mesh *mesh) { + meshlink_close(mesh); + } +}; + +#endif // MESHLINKPP_H diff --git a/src/meshlink.c b/src/meshlink.c index b57eb21b..c703ddbe 100644 --- a/src/meshlink.c +++ b/src/meshlink.c @@ -836,6 +836,8 @@ void meshlink_close(meshlink_handle_t *mesh) { exit_configuration(&mesh->config); event_loop_exit(&mesh->loop); + free(mesh); + #ifdef HAVE_MINGW WSACleanup(); #endif diff --git a/src/meshlink.h b/src/meshlink.h index f7b3f948..19fd4336 100644 --- a/src/meshlink.h +++ b/src/meshlink.h @@ -22,7 +22,6 @@ #include #include -#include "event.h" #ifdef __cplusplus extern "C" { @@ -197,8 +196,6 @@ extern void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t le */ extern bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len); -extern void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh); - /// Get a handle for a specific node. /** This function returns a handle for the node with the given name. * diff --git a/src/meshlink_internal.h b/src/meshlink_internal.h index 72cf638e..8604acb6 100644 --- a/src/meshlink_internal.h +++ b/src/meshlink_internal.h @@ -129,4 +129,7 @@ typedef struct meshlink_packethdr { uint8_t source[16]; } __attribute__ ((__packed__)) meshlink_packethdr_t; +extern void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh); + + #endif // MESHLINK_INTERNAL_H