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