2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014 Guus Sliepen <guus@meshlink.io>
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.
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.
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.
25 #include "meshlink_internal.h"
31 meshlink_handle_t *mesh;
33 static const char *errstr[] = {
34 [MESHLINK_OK] = "No error",
35 [MESHLINK_ENOMEM] = "Out of memory",
36 [MESHLINK_ENOENT] = "No such node",
39 const char *meshlink_strerror(meshlink_errno_t errno) {
43 // TODO: hack, remove once all global variables are gone.
44 static void set_mesh(meshlink_handle_t *localmesh) {
48 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
51 char pubname[PATH_MAX], privname[PATH_MAX];
53 fprintf(stderr, "Generating ECDSA keypair:\n");
55 if(!(key = ecdsa_generate())) {
56 fprintf(stderr, "Error during key generation!\n");
59 fprintf(stderr, "Done.\n");
61 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
62 f = fopen(privname, "w");
68 fchmod(fileno(f), 0600);
71 if(!ecdsa_write_pem_private_key(key, f)) {
72 fprintf(stderr, "Error writing private key!\n");
81 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
82 f = fopen(pubname, "a");
87 char *pubkey = ecdsa_get_base64_public_key(key);
88 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
97 static bool try_bind(int port) {
98 struct addrinfo *ai = NULL;
99 struct addrinfo hint = {
100 .ai_flags = AI_PASSIVE,
101 .ai_family = AF_UNSPEC,
102 .ai_socktype = SOCK_STREAM,
103 .ai_protocol = IPPROTO_TCP,
107 snprintf(portstr, sizeof portstr, "%d", port);
109 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
113 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
116 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
126 static int check_port(meshlink_handle_t *mesh) {
130 fprintf(stderr, "Warning: could not bind to port 655.\n");
132 for(int i = 0; i < 100; i++) {
133 int port = 0x1000 + (rand() & 0x7fff);
135 char filename[PATH_MAX];
136 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
137 FILE *f = fopen(filename, "a");
139 fprintf(stderr, "Please change MeshLink's Port manually.\n");
143 fprintf(f, "Port = %d\n", port);
145 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
150 fprintf(stderr, "Please change MeshLink's Port manually.\n");
154 static bool meshlink_setup(meshlink_handle_t *mesh) {
155 char meshlink_conf[PATH_MAX];
156 char hosts_dir[PATH_MAX];
158 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
159 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
163 snprintf(hosts_dir, sizeof hosts_dir, "%s" SLASH "hosts", mesh->confbase);
165 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
166 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
170 snprintf(meshlink_conf, sizeof meshlink_conf, "%s" SLASH "meshlink.conf", mesh->confbase);
172 if(!access(meshlink_conf, F_OK)) {
173 fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
177 FILE *f = fopen(meshlink_conf, "w");
179 fprintf(stderr, "Could not create file %s: %s\n", meshlink_conf, strerror(errno));
183 fprintf(f, "Name = %s\n", mesh->name);
186 if(!ecdsa_keygen(mesh))
194 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
195 // Validate arguments provided by the application
197 if(!confbase || !*confbase) {
198 fprintf(stderr, "No confbase given!\n");
202 if(!name || !*name) {
203 fprintf(stderr, "No name given!\n");
207 if(!check_id(name)) {
208 fprintf(stderr, "Invalid name given!\n");
212 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
213 mesh->confbase = xstrdup(confbase);
214 mesh->name = xstrdup(name);
215 event_loop_init(&mesh->loop);
218 // TODO: should be set by a function.
219 mesh->debug_level = 5;
221 // Check whether meshlink.conf already exists
223 char filename[PATH_MAX];
224 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
226 if(access(filename, R_OK)) {
227 if(errno == ENOENT) {
229 meshlink_setup(mesh);
231 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
232 return meshlink_close(mesh), NULL;
236 // Read the configuration
238 init_configuration(&mesh->config);
240 if(!read_server_config())
241 return meshlink_close(mesh), NULL;
243 // Setup up everything
244 // TODO: we should not open listening sockets yet
247 return meshlink_close(mesh), NULL;
252 void *meshlink_main_loop(void *arg) {
253 meshlink_handle_t *mesh = arg;
255 try_outgoing_connections();
262 bool meshlink_start(meshlink_handle_t *mesh) {
263 // TODO: open listening sockets first
265 // Start the main thread
267 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
268 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
269 memset(&mesh->thread, 0, sizeof mesh->thread);
276 void meshlink_stop(meshlink_handle_t *mesh) {
277 // TODO: close the listening sockets to signal the main thread to shut down
279 // Wait for the main thread to finish
281 pthread_join(mesh->thread, NULL);
284 void meshlink_close(meshlink_handle_t *mesh) {
285 // Close and free all resources used.
287 close_network_connections();
289 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
291 exit_configuration(&mesh->config);
292 event_loop_exit(&mesh->loop);
295 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
296 mesh->receive_cb = cb;
299 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
300 mesh->node_status_cb = cb;
303 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
305 mesh->log_level = level;
308 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
310 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
311 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
316 packet.probe = false;
317 memset(hdr, 0, sizeof *hdr);
318 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
319 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
321 packet.len = sizeof *hdr + len;
322 memcpy(packet.data + sizeof *hdr, data, len);
324 mesh->self->in_packets++;
325 mesh->self->in_bytes += packet.len;
326 route(mesh->self, &packet);
330 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
331 return (meshlink_node_t *)lookup_node(name);
335 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
339 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
343 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
347 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
351 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
355 char *meshlink_export(meshlink_handle_t *mesh) {
359 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
363 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
366 static void __attribute__((constructor)) meshlink_init(void) {
370 static void __attribute__((destructor)) meshlink_exit(void) {