]> git.meshlink.io Git - meshlink/blob - src/libmeshlink.c
Remove everything GPL that is not copyright Guus Sliepen, update copyright statements.
[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 /*
267   Generate a public/private RSA keypair, and ask for a file to store
268   them in.
269 */
270 bool rsa_keygen(int bits, bool ask) {
271         rsa_t *key;
272         FILE *f;
273         char *pubname, *privname;
274
275         fprintf(stderr, "Generating %d bits keys:\n", bits);
276
277         if(!(key = rsa_generate(bits, 0x10001))) {
278                 fprintf(stderr, "Error during key generation!\n");
279                 return false;
280         } else
281                 fprintf(stderr, "Done.\n");
282
283         xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
284         f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
285         free(privname);
286
287         if(!f)
288                 return false;
289
290         if(!rsa_write_pem_private_key(key, f)) {
291                 fprintf(stderr, "Error writing private key!\n");
292                 fclose(f);
293                 rsa_free(key);
294                 return false;
295         }
296
297         fclose(f);
298
299         if(name)
300                 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
301         else
302                 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
303
304         f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
305         free(pubname);
306
307         if(!f)
308                 return false;
309
310         if(!rsa_write_pem_public_key(key, f)) {
311                 fprintf(stderr, "Error writing public key!\n");
312                 fclose(f);
313                 rsa_free(key);
314                 return false;
315         }
316
317         fclose(f);
318         rsa_free(key);
319
320         return true;
321 }
322
323 static bool try_bind(int port) {
324         struct addrinfo *ai = NULL;
325         struct addrinfo hint = {
326                 .ai_flags = AI_PASSIVE,
327                 .ai_family = AF_UNSPEC,
328                 .ai_socktype = SOCK_STREAM,
329                 .ai_protocol = IPPROTO_TCP,
330         };
331
332         char portstr[16];
333         snprintf(portstr, sizeof portstr, "%d", port);
334
335         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
336                 return false;
337
338         while(ai) {
339                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
340                 if(!fd)
341                         return false;
342                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
343                 closesocket(fd);
344                 if(result)
345                         return false;
346                 ai = ai->ai_next;
347         }
348
349         return true;
350 }
351
352 int check_port(char *name) {
353         if(try_bind(655))
354                 return 655;
355
356         fprintf(stderr, "Warning: could not bind to port 655. ");
357
358         for(int i = 0; i < 100; i++) {
359                 int port = 0x1000 + (rand() & 0x7fff);
360                 if(try_bind(port)) {
361                         char *filename;
362                         xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
363                         FILE *f = fopen(filename, "a");
364                         free(filename);
365                         if(!f) {
366                                 fprintf(stderr, "Please change tinc's Port manually.\n");
367                                 return 0;
368                         }
369
370                         fprintf(f, "Port = %d\n", port);
371                         fclose(f);
372                         fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
373                         return port;
374                 }
375         }
376
377         fprintf(stderr, "Please change tinc's Port manually.\n");
378         return 0;
379 }
380 //tinc_setup() should basically do what cmd_init() from src/tincctl.c does, except it doesn't have to generate a tinc-up script.
381 bool tinc_setup(const char* confbaseapi, const char* name) {
382         confbase = xstrdup(confbaseapi);
383         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
384         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
385         if(!access(tinc_conf, F_OK)) {
386                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
387                 return false;
388         }
389
390         if(!check_id(name)) {
391                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
392                 return false;
393         }
394
395         if(mkdir(confbase, 0777) && errno != EEXIST) {
396                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
397                 return false;
398         }
399
400         if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
401                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
402                 return false;
403         }
404
405         FILE *f = fopen(tinc_conf, "w");
406         if(!f) {
407                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
408                 return 1;
409         }
410
411         fprintf(f, "Name = %s\n", name);
412         fclose(f);
413
414         if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
415                 return false;
416
417         check_port(name);
418
419         return true;
420
421 }
422
423
424 bool tinc_start(const char* confbaseapi) {
425         pthread_t tincThread;
426         confbase = confbaseapi;
427         pthread_create(&tincThread,NULL,tinc_main_thread,confbaseapi);
428         pthread_detach(tincThread);
429 return true;
430 }
431
432 bool tinc_main_thread(void * in) {
433         static bool status = false;
434
435         /* If nonzero, write log entries to a separate file. */
436         bool use_logfile = false;
437
438         confbase = (char*) in;
439
440         openlogger("tinc", LOGMODE_STDERR);
441
442         init_configuration(&config_tree);
443
444         /* Slllluuuuuuurrrrp! */
445
446         gettimeofday(&now, NULL);
447         srand(now.tv_sec + now.tv_usec);
448         crypto_init();
449
450         if(!read_server_config())
451                 return false;
452
453         //char *priority = NULL; //shoud be not needed in libmeshlink
454
455 #ifdef HAVE_MLOCKALL
456         /* Lock all pages into memory if requested.
457          * This has to be done after daemon()/fork() so it works for child.
458          * No need to do that in parent as it's very short-lived. */
459         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
460                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
461                    strerror(errno));
462                 return 1;
463         }
464 #endif
465
466         /* Setup sockets and open device. */
467
468         if(!setup_meshlink_network())
469                 goto end;
470
471         /* Change process priority */
472         //should be not needed in libmeshlink
473         //if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
474         //      if(!strcasecmp(priority, "Normal")) {
475         //              if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
476         //                      logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
477         //                      goto end;
478         //              }
479         //      } else if(!strcasecmp(priority, "Low")) {
480         //              if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
481         //                             logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
482         //                      goto end;
483         //              }
484         //      } else if(!strcasecmp(priority, "High")) {
485         //              if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
486         //                      logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
487         //                      goto end;
488         //              }
489         //      } else {
490         //              logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
491         //              goto end;
492         //      }
493         //}
494
495         /* drop privileges */
496         //if (!drop_privs())
497         //      goto end;
498
499         /* Start main loop. It only exits when tinc is killed. */
500
501         logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
502
503         try_outgoing_connections();
504
505         status = main_loop();
506
507         /* Shutdown properly. */
508
509 end:
510         close_network_connections();
511
512         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
513
514         //free(priority);
515
516         crypto_exit();
517
518         exit_configuration(&config_tree);
519
520         return status;
521
522 }
523
524 bool tinc_stop();
525
526 bool route_meshlink(node_t *source,vpn_packet_t *packet) {
527
528         printf("data %s\n",packet->data);
529         printf("data 16%s\n",packet->data+16);
530         printf("data 32%s\n",packet->data+32);
531         node_t* owner = NULL;
532
533         tincpackethdr* hdr = (tincpackethdr*)packet->data;
534         owner = lookup_node(hdr->destination);
535
536         if (owner == NULL) {
537         //Lookup failed
538         printf("NULL\n");
539         return false;
540         }
541         printf("lookupnode %s\n",owner->name);
542
543         if(!owner->status.reachable) {
544         //Do some here
545         return false;
546         }
547
548         //TODO: I skipped here a lot of checks !
549
550         send_packet(owner,packet);
551
552 }
553 // can be called from any thread
554 bool tinc_send_packet(node_t *receiver, const char* buf, unsigned int len) {
555
556         vpn_packet_t packet;
557         tincpackethdr* hdr = malloc(sizeof(tincpackethdr));
558
559         if (sizeof(hdr) + len > MAXSIZE) {
560
561         //log something
562         return false;
563         }
564
565         memcpy(hdr->destination,receiver->name,sizeof(hdr->destination));
566         memcpy(hdr->source,myself->name,sizeof(hdr->source));
567
568         packet.priority = 0;
569         packet.len = len + 32;
570
571         memcpy(packet.data,hdr,32);
572         memcpy(packet.data+32,buf,len);
573
574         myself->in_packets++;
575         myself->in_bytes += packet.len;
576         route_meshlink(myself, &packet);
577
578 return true;
579 }
580
581 // handler runs in tinc thread and should return immediately
582 bool tinc_set_packet_receive_handler(void (*handler)(const char* sender, const char* buf, unsigned int len));
583
584
585 //It might also be a good idea to add the option of looking up hosts by public
586 //key (fingerprints) instead of names.
587
588 node_t *tinc_get_host(const char *name) {
589
590
591
592 };
593
594 bool tinc_get_hosts(node_t** hosts);
595
596 bool tinc_sign(const char* payload, unsigned int len, const char** signature);
597
598 int tinc_verify(const char* sender, const char* payload, unsigned int plen, const char* signature, unsigned int slen);
599
600 /*
601 TODO: It would be good to add a void pointer here that will be passed on to the
602 handler function whenever it is called, or have a void pointer in node_t
603 that can be filled in by the application. That way, you can easily link an
604 application-specific data structure to a node_t.
605 */
606 void channel_set_packet_send_handler(int (*handler)(const char* receiver, const char* buf, unsigned int len));
607 void channel_packet_receive_handler(const char* sender, const char* buf, unsigned int len);
608
609 bool channel_open(const char* partner, void(*read)(int id, const char* buf, unsigned int len), void(*result)(int result, int id));
610 void channel_close(int id);
611 bool channel_write(int id, const char* buf, unsigned int len, void(*result)(int result, int id, unsigned int written));
612
613
614 //We do need some more functions. First of all, we need to be able to add nodes
615 //to a VPN. To do that, either an invitation protocol should be used:
616
617 bool tinc_join_network(const char *invitation);
618 const char *tinc_generate_invitation(const char *name);
619
620 /*
621 Or two nodes should exchange some information (their name, address, public
622 key). If the application provides a way to exchange some data with another
623 node, then:
624 */
625
626 bool tinc_export(char *buf, size_t *len);
627 node_t *tinc_import(const char *buf, size_t len);
628 /*
629 Last but not least, some way to get rid of unwanted nodes. Simplest is a
630 function that just blacklists a node.
631 Which should immediately cause the local tincd to ignore any data from that
632 host from that point on. Of course, a somewhat centrally managed,
633 automatically distributed blacklist or whitelist would be the next step.
634 */
635 bool tinc_blacklist(node_t *host);
636
637
638
639