]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Remove global variables from the event loop 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 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         loop = &mesh->loop;
47 }
48
49 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
50         ecdsa_t *key;
51         FILE *f;
52         char pubname[PATH_MAX], privname[PATH_MAX];
53
54         fprintf(stderr, "Generating ECDSA keypair:\n");
55
56         if(!(key = ecdsa_generate())) {
57                 fprintf(stderr, "Error during key generation!\n");
58                 return false;
59         } else
60                 fprintf(stderr, "Done.\n");
61
62         snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
63         f = fopen(privname, "w");
64
65         if(!f)
66                 return false;
67
68 #ifdef HAVE_FCHMOD
69         fchmod(fileno(f), 0600);
70 #endif
71
72         if(!ecdsa_write_pem_private_key(key, f)) {
73                 fprintf(stderr, "Error writing private key!\n");
74                 ecdsa_free(key);
75                 fclose(f);
76                 return false;
77         }
78
79         fclose(f);
80
81
82         snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
83         f = fopen(pubname, "a");
84
85         if(!f)
86                 return false;
87
88         char *pubkey = ecdsa_get_base64_public_key(key);
89         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
90         free(pubkey);
91
92         fclose(f);
93         ecdsa_free(key);
94
95         return true;
96 }
97
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,
105         };
106
107         char portstr[16];
108         snprintf(portstr, sizeof portstr, "%d", port);
109
110         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
111                 return false;
112
113         while(ai) {
114                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
115                 if(!fd)
116                         return false;
117                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
118                 closesocket(fd);
119                 if(result)
120                         return false;
121                 ai = ai->ai_next;
122         }
123
124         return true;
125 }
126
127 static int check_port(meshlink_handle_t *mesh) {
128         if(try_bind(655))
129                 return 655;
130
131         fprintf(stderr, "Warning: could not bind to port 655.\n");
132
133         for(int i = 0; i < 100; i++) {
134                 int port = 0x1000 + (rand() & 0x7fff);
135                 if(try_bind(port)) {
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");
139                         if(!f) {
140                                 fprintf(stderr, "Please change MeshLink's Port manually.\n");
141                                 return 0;
142                         }
143
144                         fprintf(f, "Port = %d\n", port);
145                         fclose(f);
146                         fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
147                         return port;
148                 }
149         }
150
151         fprintf(stderr, "Please change MeshLink's Port manually.\n");
152         return 0;
153 }
154
155 static bool meshlink_setup(meshlink_handle_t *mesh) {
156         char meshlink_conf[PATH_MAX];
157         char hosts_dir[PATH_MAX];
158
159         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
160                 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
161                 return false;
162         }
163
164         snprintf(hosts_dir, sizeof hosts_dir, "%s" SLASH "hosts", mesh->confbase);
165
166         if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
167                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
168                 return false;
169         }
170
171         snprintf(meshlink_conf, sizeof meshlink_conf, "%s" SLASH "meshlink.conf", mesh->confbase);
172
173         if(!access(meshlink_conf, F_OK)) {
174                 fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
175                 return false;
176         }
177
178         FILE *f = fopen(meshlink_conf, "w");
179         if(!f) {
180                 fprintf(stderr, "Could not create file %s: %s\n", meshlink_conf, strerror(errno));
181                 return 1;
182         }
183
184         fprintf(f, "Name = %s\n", mesh->name);
185         fclose(f);
186
187         if(!ecdsa_keygen(mesh))
188                 return false;
189
190         check_port(mesh);
191
192         return true;
193 }
194
195 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
196         // Validate arguments provided by the application
197
198         if(!confbase || !*confbase) {
199                 fprintf(stderr, "No confbase given!\n");
200                 return NULL;
201         }
202
203         if(!name || !*name) {
204                 fprintf(stderr, "No name given!\n");
205                 return NULL;
206         }
207
208         if(!check_id(name)) {
209                 fprintf(stderr, "Invalid name given!\n");
210                 return NULL;
211         }
212
213         meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
214         mesh->confbase = xstrdup(confbase);
215         mesh->name = xstrdup(name);
216         event_loop_init(&mesh->loop);
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())
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())
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();
257
258         main_loop();
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();
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         gettimeofday(&now, NULL);
369         srand(now.tv_sec + now.tv_usec);
370         crypto_init();
371 }
372
373 static void __attribute__((destructor)) meshlink_exit(void) {
374         crypto_exit();
375 }