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 static const char *errstr[] = {
32 [MESHLINK_OK] = "No error",
33 [MESHLINK_ENOMEM] = "Out of memory",
34 [MESHLINK_ENOENT] = "No such node",
37 const char *meshlink_strerror(meshlink_errno_t errno) {
41 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
44 char pubname[PATH_MAX], privname[PATH_MAX];
46 fprintf(stderr, "Generating ECDSA keypair:\n");
48 if(!(key = ecdsa_generate())) {
49 fprintf(stderr, "Error during key generation!\n");
52 fprintf(stderr, "Done.\n");
54 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
55 f = fopen(privname, "w");
61 fchmod(fileno(f), 0600);
64 if(!ecdsa_write_pem_private_key(key, f)) {
65 fprintf(stderr, "Error writing private key!\n");
74 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
75 f = fopen(pubname, "a");
80 char *pubkey = ecdsa_get_base64_public_key(key);
81 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
90 static bool try_bind(int port) {
91 struct addrinfo *ai = NULL;
92 struct addrinfo hint = {
93 .ai_flags = AI_PASSIVE,
94 .ai_family = AF_UNSPEC,
95 .ai_socktype = SOCK_STREAM,
96 .ai_protocol = IPPROTO_TCP,
100 snprintf(portstr, sizeof portstr, "%d", port);
102 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
106 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
109 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
119 static int check_port(meshlink_handle_t *mesh) {
123 fprintf(stderr, "Warning: could not bind to port 655.\n");
125 for(int i = 0; i < 100; i++) {
126 int port = 0x1000 + (rand() & 0x7fff);
128 char filename[PATH_MAX];
129 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
130 FILE *f = fopen(filename, "a");
132 fprintf(stderr, "Please change MeshLink's Port manually.\n");
136 fprintf(f, "Port = %d\n", port);
138 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
143 fprintf(stderr, "Please change MeshLink's Port manually.\n");
147 static bool meshlink_setup(meshlink_handle_t *mesh) {
148 char meshlink_conf[PATH_MAX];
149 char hosts_dir[PATH_MAX];
151 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
152 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
156 snprintf(hosts_dir, sizeof hosts_dir, "%s" SLASH "hosts", mesh->confbase);
158 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
159 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
163 snprintf(meshlink_conf, sizeof meshlink_conf, "%s" SLASH "meshlink.conf", mesh->confbase);
165 if(!access(meshlink_conf, F_OK)) {
166 fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
170 FILE *f = fopen(meshlink_conf, "w");
172 fprintf(stderr, "Could not create file %s: %s\n", meshlink_conf, strerror(errno));
176 fprintf(f, "Name = %s\n", mesh->name);
179 if(!ecdsa_keygen(mesh))
187 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
188 // Validate arguments provided by the application
190 if(!confbase || !*confbase) {
191 fprintf(stderr, "No confbase given!\n");
195 if(!name || !*name) {
196 fprintf(stderr, "No name given!\n");
200 if(!check_id(name)) {
201 fprintf(stderr, "Invalid name given!\n");
205 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
206 mesh->confbase = xstrdup(confbase);
207 mesh->name = xstrdup(name);
208 event_loop_init(&mesh->loop);
209 mesh->loop.data = mesh;
211 // TODO: should be set by a function.
212 mesh->debug_level = 5;
214 // Check whether meshlink.conf already exists
216 char filename[PATH_MAX];
217 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
219 if(access(filename, R_OK)) {
220 if(errno == ENOENT) {
222 meshlink_setup(mesh);
224 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
225 return meshlink_close(mesh), NULL;
229 // Read the configuration
231 init_configuration(&mesh->config);
233 if(!read_server_config(mesh))
234 return meshlink_close(mesh), NULL;
236 // Setup up everything
237 // TODO: we should not open listening sockets yet
239 if(!setup_network(mesh))
240 return meshlink_close(mesh), NULL;
245 void *meshlink_main_loop(void *arg) {
246 meshlink_handle_t *mesh = arg;
248 try_outgoing_connections(mesh);
255 bool meshlink_start(meshlink_handle_t *mesh) {
256 // TODO: open listening sockets first
258 // Start the main thread
260 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
261 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
262 memset(&mesh->thread, 0, sizeof mesh->thread);
269 void meshlink_stop(meshlink_handle_t *mesh) {
270 // TODO: close the listening sockets to signal the main thread to shut down
272 // Wait for the main thread to finish
274 pthread_join(mesh->thread, NULL);
277 void meshlink_close(meshlink_handle_t *mesh) {
278 // Close and free all resources used.
280 close_network_connections(mesh);
282 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
284 exit_configuration(&mesh->config);
285 event_loop_exit(&mesh->loop);
288 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
289 mesh->receive_cb = cb;
292 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
293 mesh->node_status_cb = cb;
296 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
298 mesh->log_level = level;
301 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
303 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
304 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
309 packet.probe = false;
310 memset(hdr, 0, sizeof *hdr);
311 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
312 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
314 packet.len = sizeof *hdr + len;
315 memcpy(packet.data + sizeof *hdr, data, len);
317 mesh->self->in_packets++;
318 mesh->self->in_bytes += packet.len;
319 route(mesh, mesh->self, &packet);
323 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
324 return (meshlink_node_t *)lookup_node(mesh, name);
328 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
332 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
336 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
340 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
344 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
348 char *meshlink_export(meshlink_handle_t *mesh) {
352 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
356 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
359 static void __attribute__((constructor)) meshlink_init(void) {
363 static void __attribute__((destructor)) meshlink_exit(void) {