]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
8e94fa1e7cf020cf678e8720c4d826e5b396752a
[meshlink] / src / meshlink.c
1 /*
2     meshlink.c -- Implementation of the MeshLink 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 #include "system.h"
21 #include <pthread.h>
22
23 #include "crypto.h"
24 #include "ecdsagen.h"
25 #include "meshlink_internal.h"
26 #include "node.h"
27 #include "protocol.h"
28 #include "route.h"
29 #include "xalloc.h"
30
31 meshlink_handle_t *mesh;
32
33 static const char *errstr[] = {
34         [MESHLINK_OK] = "No error",
35         [MESHLINK_ENOMEM] = "Out of memory",
36         [MESHLINK_ENOENT] = "No such node",
37 };
38
39 const char *meshlink_strerror(meshlink_errno_t errno) {
40         return errstr[errno];
41 }
42
43 // TODO: hack, remove once all global variables are gone.
44 static void set_mesh(meshlink_handle_t *localmesh) {
45         mesh = localmesh;
46 }
47
48 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
49         ecdsa_t *key;
50         FILE *f;
51         char pubname[PATH_MAX], privname[PATH_MAX];
52
53         fprintf(stderr, "Generating ECDSA keypair:\n");
54
55         if(!(key = ecdsa_generate())) {
56                 fprintf(stderr, "Error during key generation!\n");
57                 return false;
58         } else
59                 fprintf(stderr, "Done.\n");
60
61         snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
62         f = fopen(privname, "w");
63
64         if(!f)
65                 return false;
66
67 #ifdef HAVE_FCHMOD
68         fchmod(fileno(f), 0600);
69 #endif
70
71         if(!ecdsa_write_pem_private_key(key, f)) {
72                 fprintf(stderr, "Error writing private key!\n");
73                 ecdsa_free(key);
74                 fclose(f);
75                 return false;
76         }
77
78         fclose(f);
79
80
81         snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
82         f = fopen(pubname, "a");
83
84         if(!f)
85                 return false;
86
87         char *pubkey = ecdsa_get_base64_public_key(key);
88         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
89         free(pubkey);
90
91         fclose(f);
92         ecdsa_free(key);
93
94         return true;
95 }
96
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,
104         };
105
106         char portstr[16];
107         snprintf(portstr, sizeof portstr, "%d", port);
108
109         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
110                 return false;
111
112         while(ai) {
113                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
114                 if(!fd)
115                         return false;
116                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
117                 closesocket(fd);
118                 if(result)
119                         return false;
120                 ai = ai->ai_next;
121         }
122
123         return true;
124 }
125
126 static int check_port(meshlink_handle_t *mesh) {
127         if(try_bind(655))
128                 return 655;
129
130         fprintf(stderr, "Warning: could not bind to port 655.\n");
131
132         for(int i = 0; i < 100; i++) {
133                 int port = 0x1000 + (rand() & 0x7fff);
134                 if(try_bind(port)) {
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");
138                         if(!f) {
139                                 fprintf(stderr, "Please change MeshLink's Port manually.\n");
140                                 return 0;
141                         }
142
143                         fprintf(f, "Port = %d\n", port);
144                         fclose(f);
145                         fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
146                         return port;
147                 }
148         }
149
150         fprintf(stderr, "Please change MeshLink's Port manually.\n");
151         return 0;
152 }
153
154 static bool meshlink_setup(meshlink_handle_t *mesh) {
155         char meshlink_conf[PATH_MAX];
156         char hosts_dir[PATH_MAX];
157
158         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
159                 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
160                 return false;
161         }
162
163         snprintf(hosts_dir, sizeof hosts_dir, "%s" SLASH "hosts", mesh->confbase);
164
165         if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
166                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
167                 return false;
168         }
169
170         snprintf(meshlink_conf, sizeof meshlink_conf, "%s" SLASH "meshlink.conf", mesh->confbase);
171
172         if(!access(meshlink_conf, F_OK)) {
173                 fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
174                 return false;
175         }
176
177         FILE *f = fopen(meshlink_conf, "w");
178         if(!f) {
179                 fprintf(stderr, "Could not create file %s: %s\n", meshlink_conf, strerror(errno));
180                 return 1;
181         }
182
183         fprintf(f, "Name = %s\n", mesh->name);
184         fclose(f);
185
186         if(!ecdsa_keygen(mesh))
187                 return false;
188
189         check_port(mesh);
190
191         return true;
192 }
193
194 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
195         // Validate arguments provided by the application
196
197         if(!confbase || !*confbase) {
198                 fprintf(stderr, "No confbase given!\n");
199                 return NULL;
200         }
201
202         if(!name || !*name) {
203                 fprintf(stderr, "No name given!\n");
204                 return NULL;
205         }
206
207         if(!check_id(name)) {
208                 fprintf(stderr, "Invalid name given!\n");
209                 return NULL;
210         }
211
212         meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
213         mesh->confbase = xstrdup(confbase);
214         mesh->name = xstrdup(name);
215         event_loop_init(&mesh->loop);
216         mesh->loop.data = mesh;
217         set_mesh(mesh);
218
219         // TODO: should be set by a function.
220         mesh->debug_level = 5;
221
222         // Check whether meshlink.conf already exists
223
224         char filename[PATH_MAX];
225         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
226
227         if(access(filename, R_OK)) {
228                 if(errno == ENOENT) {
229                         // If not, create it
230                         meshlink_setup(mesh);
231                 } else {
232                         fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
233                         return meshlink_close(mesh), NULL;
234                 }
235         }
236
237         // Read the configuration
238
239         init_configuration(&mesh->config);
240
241         if(!read_server_config(mesh))
242                 return meshlink_close(mesh), NULL;
243
244         // Setup up everything
245         // TODO: we should not open listening sockets yet
246
247         if(!setup_network(mesh))
248                 return meshlink_close(mesh), NULL;
249
250         return mesh;
251 }
252
253 void *meshlink_main_loop(void *arg) {
254         meshlink_handle_t *mesh = arg;
255
256         try_outgoing_connections(mesh);
257
258         main_loop(mesh);
259
260         return NULL;
261 }
262
263 bool meshlink_start(meshlink_handle_t *mesh) {
264         // TODO: open listening sockets first
265
266         // Start the main thread
267
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);
271                 return false;
272         }
273
274         return true;
275 }
276
277 void meshlink_stop(meshlink_handle_t *mesh) {
278         // TODO: close the listening sockets to signal the main thread to shut down
279
280         // Wait for the main thread to finish
281
282         pthread_join(mesh->thread, NULL);
283 }
284
285 void meshlink_close(meshlink_handle_t *mesh) {
286         // Close and free all resources used.
287
288         close_network_connections(mesh);
289
290         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
291
292         exit_configuration(&mesh->config);
293         event_loop_exit(&mesh->loop);
294 }
295
296 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
297         mesh->receive_cb = cb;
298 }
299
300 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
301         mesh->node_status_cb = cb;
302 }
303
304 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
305         mesh->log_cb = cb;
306         mesh->log_level = level;
307 }
308
309 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
310         vpn_packet_t packet;
311         meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
312         if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
313                 //log something
314                 return false;
315         }
316
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);
321
322         packet.len = sizeof *hdr + len;
323         memcpy(packet.data + sizeof *hdr, data, len);
324
325         mesh->self->in_packets++;
326         mesh->self->in_bytes += packet.len;
327         route(mesh->self, &packet);
328         return false;
329 }
330
331 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
332         return (meshlink_node_t *)lookup_node(name);
333         return NULL;
334 }
335
336 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
337         return 0;
338 }
339
340 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
341         return NULL;
342 }
343
344 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
345         return false;
346 }
347
348 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
349         return NULL;
350 }
351
352 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
353         return false;
354 }
355
356 char *meshlink_export(meshlink_handle_t *mesh) {
357         return NULL;
358 }
359
360 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
361         return false;
362 }
363
364 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
365 }
366
367 static void __attribute__((constructor)) meshlink_init(void) {
368         crypto_init();
369 }
370
371 static void __attribute__((destructor)) meshlink_exit(void) {
372         crypto_exit();
373 }