]> git.meshlink.io Git - meshlink/blob - src/libmeshlink.c
cd9e8a745f496ecdbe3e38a19aec652e364acfdc
[meshlink] / src / libmeshlink.c
1 /*
2     libmeshlink.h -- Tincd Library
3     Copyright (C) 2014 Guus Sliepen <guus@meshlink.io> Saverio Proto <zioproto@gmail.com>
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
22 #include <pthread.h>
23
24 #include "connection.h"
25 #include "crypto.h"
26 #include "ecdsagen.h"
27 #include "edge.h"
28 #include "libmeshlink.h"
29 #include "net.h"
30 #include "node.h"
31 #include "protocol.h"
32
33 char *hosts_dir = NULL;
34 recvdata_cb_t recv_callback;
35 static char *name = NULL;
36 char *tinc_conf = NULL;
37 static bool tty = false;
38
39 #ifdef HAVE_MLOCKALL
40 /* If nonzero, disable swapping for this process. */
41 static bool do_mlock = false;
42 #endif
43
44 /* Open a file with the desired permissions, minus the umask.
45    Also, if we want to create an executable file, we call fchmod()
46    to set the executable bits. */
47
48 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
49         mode_t mask = umask(0);
50         perms &= ~mask;
51         umask(~perms);
52         FILE *f = fopen(filename, mode);
53 #ifdef HAVE_FCHMOD
54         if((perms & 0444) && f)
55                 fchmod(fileno(f), perms);
56 #endif
57         umask(mask);
58         return f;
59 }
60
61 static void disable_old_keys(const char *filename, const char *what) {
62         char tmpfile[PATH_MAX] = "";
63         char buf[1024];
64         bool disabled = false;
65         bool block = false;
66         bool error = false;
67         FILE *r, *w;
68
69         r = fopen(filename, "r");
70         if(!r)
71                 return;
72
73         snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
74
75         struct stat st = {.st_mode = 0600};
76         fstat(fileno(r), &st);
77         w = fopenmask(tmpfile, "w", st.st_mode);
78
79         while(fgets(buf, sizeof buf, r)) {
80                 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
81                         if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
82                                 disabled = true;
83                                 block = true;
84                         }
85                 }
86
87                 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
88
89                 if(ecdsapubkey)
90                         disabled = true;
91
92                 if(w) {
93                         if(block || ecdsapubkey)
94                                 fputc('#', w);
95                         if(fputs(buf, w) < 0) {
96                                 error = true;
97                                 break;
98                         }
99                 }
100
101                 if(block && !strncmp(buf, "-----END ", 9))
102                         block = false;
103         }
104
105         if(w)
106                 if(fclose(w) < 0)
107                         error = true;
108         if(ferror(r) || fclose(r) < 0)
109                 error = true;
110
111         if(disabled) {
112                 if(!w || error) {
113                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
114                         if(w)
115                                 unlink(tmpfile);
116                         return;
117                 }
118
119 #ifdef HAVE_MINGW
120                 // We cannot atomically replace files on Windows.
121                 char bakfile[PATH_MAX] = "";
122                 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
123                 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
124                         rename(bakfile, filename);
125 #else
126                 if(rename(tmpfile, filename)) {
127 #endif
128                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
129                 } else  {
130 #ifdef HAVE_MINGW
131                         unlink(bakfile);
132 #endif
133                         fprintf(stderr, "Warning: old key(s) found and disabled.\n");
134                 }
135         }
136
137         unlink(tmpfile);
138 }
139
140 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
141         FILE *r;
142         char *directory;
143         char buf[PATH_MAX];
144         char buf2[PATH_MAX];
145
146         /* Check stdin and stdout */
147         if(ask && tty) {
148                 /* Ask for a file and/or directory name. */
149                 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
150
151                 if(fgets(buf, sizeof buf, stdin) == NULL) {
152                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
153                         return NULL;
154                 }
155
156                 size_t len = strlen(buf);
157                 if(len)
158                         buf[--len] = 0;
159
160                 if(len)
161                         filename = buf;
162         }
163
164 #ifdef HAVE_MINGW
165         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
166 #else
167         if(filename[0] != '/') {
168 #endif
169                 /* The directory is a relative path or a filename. */
170                 directory = get_current_dir_name();
171                 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
172                 filename = buf2;
173         }
174
175         disable_old_keys(filename, what);
176
177         /* Open it first to keep the inode busy */
178
179         r = fopenmask(filename, mode, perms);
180
181         if(!r) {
182                 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
183                 return NULL;
184         }
185
186         return r;
187 }
188
189 /*
190   Generate a public/private ECDSA keypair, and ask for a file to store
191   them in.
192 */
193 bool ecdsa_keygen(bool ask) {
194         ecdsa_t *key;
195         FILE *f;
196         char *pubname, *privname;
197
198         fprintf(stderr, "Generating ECDSA keypair:\n");
199
200         if(!(key = ecdsa_generate())) {
201                 fprintf(stderr, "Error during key generation!\n");
202                 return false;
203         } else
204                 fprintf(stderr, "Done.\n");
205
206         xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
207         f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
208         free(privname);
209
210         if(!f)
211                 return false;
212
213         if(!ecdsa_write_pem_private_key(key, f)) {
214                 fprintf(stderr, "Error writing private key!\n");
215                 ecdsa_free(key);
216                 fclose(f);
217                 return false;
218         }
219
220         fclose(f);
221
222         if(name)
223                 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
224         else
225                 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
226
227         f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
228         free(pubname);
229
230         if(!f)
231                 return false;
232
233         char *pubkey = ecdsa_get_base64_public_key(key);
234         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
235         free(pubkey);
236
237         fclose(f);
238         ecdsa_free(key);
239
240         return true;
241 }
242
243 static bool try_bind(int port) {
244         struct addrinfo *ai = NULL;
245         struct addrinfo hint = {
246                 .ai_flags = AI_PASSIVE,
247                 .ai_family = AF_UNSPEC,
248                 .ai_socktype = SOCK_STREAM,
249                 .ai_protocol = IPPROTO_TCP,
250         };
251
252         char portstr[16];
253         snprintf(portstr, sizeof portstr, "%d", port);
254
255         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
256                 return false;
257
258         while(ai) {
259                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
260                 if(!fd)
261                         return false;
262                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
263                 closesocket(fd);
264                 if(result)
265                         return false;
266                 ai = ai->ai_next;
267         }
268
269         return true;
270 }
271
272 int check_port(const char *name) {
273         if(try_bind(655))
274                 return 655;
275
276         fprintf(stderr, "Warning: could not bind to port 655. ");
277
278         for(int i = 0; i < 100; i++) {
279                 int port = 0x1000 + (rand() & 0x7fff);
280                 if(try_bind(port)) {
281                         char *filename;
282                         xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
283                         FILE *f = fopen(filename, "a");
284                         free(filename);
285                         if(!f) {
286                                 fprintf(stderr, "Please change tinc's Port manually.\n");
287                                 return 0;
288                         }
289
290                         fprintf(f, "Port = %d\n", port);
291                         fclose(f);
292                         fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
293                         return port;
294                 }
295         }
296
297         fprintf(stderr, "Please change tinc's Port manually.\n");
298         return 0;
299 }
300 //tinc_setup() should basically do what cmd_init() from src/tincctl.c does, except it doesn't have to generate a tinc-up script.
301 bool tinc_setup(const char* confbaseapi, const char* name) {
302         confbase = xstrdup(confbaseapi);
303         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
304         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
305         if(!access(tinc_conf, F_OK)) {
306                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
307                 return false;
308         }
309
310         if(!check_id(name)) {
311                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
312                 return false;
313         }
314
315         if(mkdir(confbase, 0777) && errno != EEXIST) {
316                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
317                 return false;
318         }
319
320         if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
321                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
322                 return false;
323         }
324
325         FILE *f = fopen(tinc_conf, "w");
326         if(!f) {
327                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
328                 return 1;
329         }
330
331         fprintf(f, "Name = %s\n", name);
332         fclose(f);
333
334         if(!ecdsa_keygen(false))
335                 return false;
336
337         check_port(name);
338
339         return true;
340
341 }
342
343
344 bool tinc_start(const char* confbaseapi) {
345         pthread_t tincThread;
346         confbase = xstrdup(confbaseapi);
347         pthread_create(&tincThread,NULL,tinc_main_thread,confbase);
348         pthread_detach(tincThread);
349 return true;
350 }
351
352 __attribute__((constructor)) static void meshlink_init(void) {
353         /* Slllluuuuuuurrrrp! */
354
355         gettimeofday(&now, NULL);
356         srand(now.tv_sec + now.tv_usec);
357         crypto_init();
358 }
359
360 __attribute__((destructor)) static void meshlink_exit(void) {
361         crypto_exit();
362 }
363
364
365 void *tinc_main_thread(void * in) {
366         static bool status = false;
367         /* If nonzero, write log entries to a separate file. */
368         bool use_logfile = false;
369
370         confbase = (char*) in;
371
372         openlogger("tinc", LOGMODE_STDERR);
373
374         init_configuration(&config_tree);
375
376         if(!read_server_config())
377                 return false;
378
379         //char *priority = NULL; //shoud be not needed in libmeshlink
380
381         /* Setup sockets and open device. */
382
383         if(!setup_network())
384                 goto end;
385
386         /* Start main loop. It only exits when tinc is killed. */
387
388         logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
389
390         try_outgoing_connections();
391
392         status = main_loop();
393
394         /* Shutdown properly. */
395
396 end:
397         close_network_connections();
398
399         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
400
401         //free(priority);
402
403         exit_configuration(&config_tree);
404
405         return (void *)status;
406 }
407
408 bool tinc_stop();
409
410 // can be called from any thread
411 bool tinc_send_packet(node_t *receiver, const char* buf, unsigned int len) {
412
413         vpn_packet_t packet;
414         tincpackethdr* hdr = (tincpackethdr *)packet.data;
415         if (sizeof(tincpackethdr) + len > MAXSIZE) {
416
417         //log something
418         return false;
419         }
420
421         packet.probe = false;
422         memset(hdr, 0, sizeof *hdr);
423         memcpy(hdr->destination,receiver->name,sizeof(hdr->destination));
424         memcpy(hdr->source,mesh->self->name,sizeof(hdr->source));
425
426         packet.len = sizeof(tincpackethdr) + len;
427         memcpy(packet.data+sizeof(tincpackethdr),buf,len);
428
429         mesh->self->in_packets++;
430         mesh->self->in_bytes += packet.len;
431         route(mesh->self, &packet);
432
433 return true;
434 }
435
436 // handler runs in tinc thread and should return immediately
437 bool tinc_set_packet_receive_handler(void (*handler)(const char* sender, const char* buf, unsigned int len));
438
439
440 //It might also be a good idea to add the option of looking up hosts by public
441 //key (fingerprints) instead of names.
442
443 node_t *tinc_get_host(const char *name) {
444
445
446
447 };
448
449 bool tinc_get_hosts(node_t** hosts);
450
451 bool tinc_sign(const char* payload, unsigned int len, const char** signature);
452
453 int tinc_verify(const char* sender, const char* payload, unsigned int plen, const char* signature, unsigned int slen);
454
455 /*
456 TODO: It would be good to add a void pointer here that will be passed on to the
457 handler function whenever it is called, or have a void pointer in node_t
458 that can be filled in by the application. That way, you can easily link an
459 application-specific data structure to a node_t.
460 */
461 void channel_set_packet_send_handler(int (*handler)(const char* receiver, const char* buf, unsigned int len));
462 void channel_packet_receive_handler(const char* sender, const char* buf, unsigned int len);
463
464 bool channel_open(const char* partner, void(*read)(int id, const char* buf, unsigned int len), void(*result)(int result, int id));
465 void channel_close(int id);
466 bool channel_write(int id, const char* buf, unsigned int len, void(*result)(int result, int id, unsigned int written));
467
468
469 //We do need some more functions. First of all, we need to be able to add nodes
470 //to a VPN. To do that, either an invitation protocol should be used:
471
472 bool tinc_join_network(const char *invitation);
473 const char *tinc_generate_invitation(const char *name);
474
475 /*
476 Or two nodes should exchange some information (their name, address, public
477 key). If the application provides a way to exchange some data with another
478 node, then:
479 */
480
481 bool tinc_export(char *buf, size_t *len);
482 node_t *tinc_import(const char *buf, size_t len);
483 /*
484 Last but not least, some way to get rid of unwanted nodes. Simplest is a
485 function that just blacklists a node.
486 Which should immediately cause the local tincd to ignore any data from that
487 host from that point on. Of course, a somewhat centrally managed,
488 automatically distributed blacklist or whitelist would be the next step.
489 */
490 bool tinc_blacklist(node_t *host);
491
492 void recvdata_register_cb(recvdata_cb_t cb) {
493 recv_callback = cb;
494 };
495
496