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