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) {
49 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
52 char pubname[PATH_MAX], privname[PATH_MAX];
54 fprintf(stderr, "Generating ECDSA keypair:\n");
56 if(!(key = ecdsa_generate())) {
57 fprintf(stderr, "Error during key generation!\n");
60 fprintf(stderr, "Done.\n");
62 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
63 f = fopen(privname, "w");
69 fchmod(fileno(f), 0600);
72 if(!ecdsa_write_pem_private_key(key, f)) {
73 fprintf(stderr, "Error writing private key!\n");
82 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
83 f = fopen(pubname, "a");
88 char *pubkey = ecdsa_get_base64_public_key(key);
89 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
98 static bool try_bind(int port) {
99 struct addrinfo *ai = NULL;
100 struct addrinfo hint = {
101 .ai_flags = AI_PASSIVE,
102 .ai_family = AF_UNSPEC,
103 .ai_socktype = SOCK_STREAM,
104 .ai_protocol = IPPROTO_TCP,
108 snprintf(portstr, sizeof portstr, "%d", port);
110 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
114 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
117 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
127 static int check_port(meshlink_handle_t *mesh) {
131 fprintf(stderr, "Warning: could not bind to port 655.\n");
133 for(int i = 0; i < 100; i++) {
134 int port = 0x1000 + (rand() & 0x7fff);
136 char filename[PATH_MAX];
137 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
138 FILE *f = fopen(filename, "a");
140 fprintf(stderr, "Please change MeshLink's Port manually.\n");
144 fprintf(f, "Port = %d\n", port);
146 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
151 fprintf(stderr, "Please change MeshLink's Port manually.\n");
155 static bool meshlink_setup(meshlink_handle_t *mesh) {
156 char meshlink_conf[PATH_MAX];
157 char hosts_dir[PATH_MAX];
159 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
160 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
164 snprintf(hosts_dir, sizeof hosts_dir, "%s" SLASH "hosts", mesh->confbase);
166 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
167 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
171 snprintf(meshlink_conf, sizeof meshlink_conf, "%s" SLASH "meshlink.conf", mesh->confbase);
173 if(!access(meshlink_conf, F_OK)) {
174 fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
178 FILE *f = fopen(meshlink_conf, "w");
180 fprintf(stderr, "Could not create file %s: %s\n", meshlink_conf, strerror(errno));
184 fprintf(f, "Name = %s\n", mesh->name);
187 if(!ecdsa_keygen(mesh))
195 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
196 // Validate arguments provided by the application
198 if(!confbase || !*confbase) {
199 fprintf(stderr, "No confbase given!\n");
203 if(!name || !*name) {
204 fprintf(stderr, "No name given!\n");
208 if(!check_id(name)) {
209 fprintf(stderr, "Invalid name given!\n");
213 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
214 mesh->confbase = xstrdup(confbase);
215 mesh->name = xstrdup(name);
216 event_loop_init(&mesh->loop);
219 // TODO: should be set by a function.
220 mesh->debug_level = 5;
222 // Check whether meshlink.conf already exists
224 char filename[PATH_MAX];
225 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
227 if(access(filename, R_OK)) {
228 if(errno == ENOENT) {
230 meshlink_setup(mesh);
232 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
233 return meshlink_close(mesh), NULL;
237 // Read the configuration
239 init_configuration(&mesh->config);
241 if(!read_server_config())
242 return meshlink_close(mesh), NULL;
244 // Setup up everything
245 // TODO: we should not open listening sockets yet
248 return meshlink_close(mesh), NULL;
253 void *meshlink_main_loop(void *arg) {
254 meshlink_handle_t *mesh = arg;
256 try_outgoing_connections();
263 bool meshlink_start(meshlink_handle_t *mesh) {
264 // TODO: open listening sockets first
266 // Start the main thread
268 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
269 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
270 memset(&mesh->thread, 0, sizeof mesh->thread);
277 void meshlink_stop(meshlink_handle_t *mesh) {
278 // TODO: close the listening sockets to signal the main thread to shut down
280 // Wait for the main thread to finish
282 pthread_join(mesh->thread, NULL);
285 void meshlink_close(meshlink_handle_t *mesh) {
286 // Close and free all resources used.
288 close_network_connections();
290 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
292 exit_configuration(&mesh->config);
293 event_loop_exit(&mesh->loop);
296 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
297 mesh->receive_cb = cb;
300 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
301 mesh->node_status_cb = cb;
304 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
306 mesh->log_level = level;
309 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
311 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
312 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
317 packet.probe = false;
318 memset(hdr, 0, sizeof *hdr);
319 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
320 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
322 packet.len = sizeof *hdr + len;
323 memcpy(packet.data + sizeof *hdr, data, len);
325 mesh->self->in_packets++;
326 mesh->self->in_bytes += packet.len;
327 route(mesh->self, &packet);
331 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
332 return (meshlink_node_t *)lookup_node(name);
336 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
340 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
344 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
348 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
352 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
356 char *meshlink_export(meshlink_handle_t *mesh) {
360 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
364 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
367 static void __attribute__((constructor)) meshlink_init(void) {
371 static void __attribute__((destructor)) meshlink_exit(void) {