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