Comment out old public/private keys when generating new ones.
[tinc] / src / tincctl.c
1 /*
2     tincctl.c -- Controlling a running tincd
3     Copyright (C) 2007-2012 Guus Sliepen <guus@tinc-vpn.org>
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 <getopt.h>
23
24 #ifdef HAVE_READLINE
25 #include "readline/readline.h"
26 #include "readline/history.h"
27 #endif
28
29 #include "xalloc.h"
30 #include "protocol.h"
31 #include "control_common.h"
32 #include "ecdsagen.h"
33 #include "info.h"
34 #include "rsagen.h"
35 #include "utils.h"
36 #include "tincctl.h"
37 #include "top.h"
38
39 #ifdef HAVE_MINGW
40 #define mkdir(a, b) mkdir(a)
41 #endif
42
43
44 /* The name this program was run with. */
45 static char *program_name = NULL;
46
47 static char **orig_argv;
48 static int orig_argc;
49
50 /* If nonzero, display usage information and exit. */
51 static bool show_help = false;
52
53 /* If nonzero, print the version on standard output and exit.  */
54 static bool show_version = false;
55
56 static char *name = NULL;
57 static char *identname = NULL;                          /* program name for syslog */
58 static char *pidfilename = NULL;                        /* pid file location */
59 static char *confdir = NULL;
60 static char controlcookie[1024];
61 char *netname = NULL;
62 char *confbase = NULL;
63 static char *tinc_conf = NULL;
64 static char *hosts_dir = NULL;
65
66 // Horrible global variables...
67 static int pid = 0;
68 static int fd = -1;
69 static char line[4096];
70 static int code;
71 static int req;
72 static int result;
73 static bool force = false;
74 static bool tty = true;
75
76 #ifdef HAVE_MINGW
77 static struct WSAData wsa_state;
78 #endif
79
80 static struct option const long_options[] = {
81         {"config", required_argument, NULL, 'c'},
82         {"debug", optional_argument, NULL, 0},
83         {"no-detach", no_argument, NULL, 0},
84         {"mlock", no_argument, NULL, 0},
85         {"net", required_argument, NULL, 'n'},
86         {"help", no_argument, NULL, 1},
87         {"version", no_argument, NULL, 2},
88         {"pidfile", required_argument, NULL, 5},
89         {"logfile", required_argument, NULL, 0},
90         {"bypass-security", no_argument, NULL, 0},
91         {"chroot", no_argument, NULL, 0},
92         {"user", required_argument, NULL, 0},
93         {"option", required_argument, NULL, 0},
94         {"force", no_argument, NULL, 6},
95         {NULL, 0, NULL, 0}
96 };
97
98 static void version(void) {
99         printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
100                    VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
101         printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
102                         "See the AUTHORS file for a complete list.\n\n"
103                         "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
104                         "and you are welcome to redistribute it under certain conditions;\n"
105                         "see the file COPYING for details.\n");
106 }
107
108 static void usage(bool status) {
109         if(status)
110                 fprintf(stderr, "Try `%s --help\' for more information.\n",
111                                 program_name);
112         else {
113                 printf("Usage: %s [options] command\n\n", program_name);
114                 printf("Valid options are:\n"
115                                 "  -c, --config=DIR        Read configuration options from DIR.\n"
116                                 "  -n, --net=NETNAME       Connect to net NETNAME.\n"
117                                 "      --pidfile=FILENAME  Read control cookie from FILENAME.\n"
118                                 "      --help              Display this help and exit.\n"
119                                 "      --version           Output version information and exit.\n"
120                                 "\n"
121                                 "Valid commands are:\n"
122                                 "  init [name]                Create initial configuration files.\n"
123                                 "  config                     Change configuration:\n"
124                                 "    [get] VARIABLE           - print current value of VARIABLE\n"
125                                 "    [set] VARIABLE VALUE     - set VARIABLE to VALUE\n"
126                                 "    add VARIABLE VALUE       - add VARIABLE with the given VALUE\n"
127                                 "    del VARIABLE [VALUE]     - remove VARIABLE [only ones with watching VALUE]\n"
128                                 "  start [tincd options]      Start tincd.\n"
129                                 "  stop                       Stop tincd.\n"
130                                 "  restart                    Restart tincd.\n"
131                                 "  reload                     Partially reload configuration of running tincd.\n"
132                                 "  pid                        Show PID of currently running tincd.\n"
133                                 "  generate-keys [bits]       Generate new RSA and ECDSA public/private keypairs.\n"
134                                 "  generate-rsa-keys [bits]   Generate a new RSA public/private keypair.\n"
135                                 "  generate-ecdsa-keys        Generate a new ECDSA public/private keypair.\n"
136                                 "  dump                       Dump a list of one of the following things:\n"
137                                 "    nodes                    - all known nodes in the VPN\n"
138                                 "    edges                    - all known connections in the VPN\n"
139                                 "    subnets                  - all known subnets in the VPN\n"
140                                 "    connections              - all meta connections with ourself\n"
141                                 "    [di]graph                - graph of the VPN in dotty format\n"
142                                 "  info NODE|SUBNET|ADDRESS   Give information about a particular NODE, SUBNET or ADDRESS.\n"
143                                 "  purge                      Purge unreachable nodes\n"
144                                 "  debug N                    Set debug level\n"
145                                 "  retry                      Retry all outgoing connections\n"
146                                 "  disconnect NODE            Close meta connection with NODE\n"
147 #ifdef HAVE_CURSES
148                                 "  top                        Show real-time statistics\n"
149 #endif
150                                 "  pcap [snaplen]             Dump traffic in pcap format [up to snaplen bytes per packet]\n"
151                                 "  log [level]                Dump log output [up to the specified level]\n"
152                                 "  export                     Export host configuration of local node to standard output\n"
153                                 "  export-all                 Export all host configuration files to standard output\n"
154                                 "  import [--force]           Import host configuration file(s) from standard input\n"
155                                 "\n");
156                 printf("Report bugs to tinc@tinc-vpn.org.\n");
157         }
158 }
159
160 static bool parse_options(int argc, char **argv) {
161         int r;
162         int option_index = 0;
163
164         while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
165                 switch (r) {
166                         case 0:                         /* long option */
167                                 break;
168
169                         case 'c':                               /* config file */
170                                 confbase = xstrdup(optarg);
171                                 break;
172
173                         case 'n':                               /* net name given */
174                                 netname = xstrdup(optarg);
175                                 break;
176
177                         case 1:                                 /* show help */
178                                 show_help = true;
179                                 break;
180
181                         case 2:                                 /* show version */
182                                 show_version = true;
183                                 break;
184
185                         case 5:                                 /* open control socket here */
186                                 pidfilename = xstrdup(optarg);
187                                 break;
188
189                         case 6:
190                                 force = true;
191                                 break;
192
193                         case '?':
194                                 usage(true);
195                                 return false;
196
197                         default:
198                                 break;
199                 }
200         }
201
202         if(!netname && (netname = getenv("NETNAME")))
203                 netname = xstrdup(netname);
204
205         /* netname "." is special: a "top-level name" */
206
207         if(netname && (!*netname || !strcmp(netname, "."))) {
208                 free(netname);
209                 netname = NULL;
210         }
211
212         if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
213                 fprintf(stderr, "Invalid character in netname!\n");
214                 return false;
215         }
216
217         return true;
218 }
219
220 static void disable_old_keys(const char *filename, const char *what) {
221         char tmpfile[PATH_MAX] = "";
222         char buf[1024];
223         bool disabled = false;
224         bool block = false;
225         bool error = false;
226         FILE *r, *w;
227
228         r = fopen(filename, "r");
229         if(!r)
230                 return;
231
232         snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
233
234         w = fopen(tmpfile, "w");
235
236         while(fgets(buf, sizeof buf, r)) {
237                 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
238                         if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
239                                 disabled = true;
240                                 block = true;
241                         }
242                 }
243
244                 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
245
246                 if(ecdsapubkey)
247                         disabled = true;
248
249                 if(w) {
250                         if(block || ecdsapubkey)
251                                 fputc('#', w);
252                         if(fputs(buf, w) < 0) {
253                                 error = true;
254                                 break;
255                         }
256                 }
257
258                 if(block && !strncmp(buf, "-----END ", 9))
259                         block = false;
260         }
261
262         if(w)
263                 if(fclose(w) < 0)
264                         error = true;
265         if(ferror(r) || fclose(r) < 0)
266                 error = true;
267
268         if(disabled) {
269                 if(!w || error) {
270                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
271                         if(w)
272                                 unlink(tmpfile);
273                         return;
274                 }
275
276 #ifdef HAVE_MINGW
277                 // We cannot atomically replace files on Windows.
278                 char bakfile[PATH_MAX] = "";
279                 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
280                 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
281                         rename(bakfile, filename);
282 #else
283                 if(rename(tmpfile, filename)) {
284 #endif
285                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
286                 } else  {
287 #ifdef HAVE_MINGW
288                         unlink(bakfile);
289 #endif
290                         fprintf(stderr, "Warning: old key(s) found and disabled.\n");
291                 }
292         }
293
294         unlink(tmpfile);
295 }
296
297 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
298         FILE *r;
299         char *directory;
300         char buf[PATH_MAX];
301         char buf2[PATH_MAX];
302
303         /* Check stdin and stdout */
304         if(ask && tty) {
305                 /* Ask for a file and/or directory name. */
306                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
307                                 what, filename);
308                 fflush(stdout);
309
310                 if(fgets(buf, sizeof buf, stdin) == NULL) {
311                         fprintf(stderr, "Error while reading stdin: %s\n",
312                                         strerror(errno));
313                         return NULL;
314                 }
315
316                 size_t len = strlen(buf);
317                 if(len)
318                         buf[--len] = 0;
319
320                 if(len)
321                         filename = buf;
322         }
323
324 #ifdef HAVE_MINGW
325         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
326 #else
327         if(filename[0] != '/') {
328 #endif
329                 /* The directory is a relative path or a filename. */
330                 directory = get_current_dir_name();
331                 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
332                 filename = buf2;
333         }
334
335         umask(0077);                            /* Disallow everything for group and other */
336
337         disable_old_keys(filename, what);
338
339         /* Open it first to keep the inode busy */
340
341         r = fopen(filename, mode);
342
343         if(!r) {
344                 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
345                 return NULL;
346         }
347
348         return r;
349 }
350
351 /*
352   Generate a public/private ECDSA keypair, and ask for a file to store
353   them in.
354 */
355 static bool ecdsa_keygen(bool ask) {
356         ecdsa_t key;
357         FILE *f;
358         char *filename;
359
360         fprintf(stderr, "Generating ECDSA keypair:\n");
361
362         if(!ecdsa_generate(&key)) {
363                 fprintf(stderr, "Error during key generation!\n");
364                 return false;
365         } else
366                 fprintf(stderr, "Done.\n");
367
368         xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
369         f = ask_and_open(filename, "private ECDSA key", "a", ask);
370
371         if(!f)
372                 return false;
373   
374 #ifdef HAVE_FCHMOD
375         /* Make it unreadable for others. */
376         fchmod(fileno(f), 0600);
377 #endif
378                 
379         ecdsa_write_pem_private_key(&key, f);
380
381         fclose(f);
382         free(filename);
383
384         if(name)
385                 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
386         else
387                 xasprintf(&filename, "%s" SLASH "ecdsa_key.pub", confbase);
388
389         f = ask_and_open(filename, "public ECDSA key", "a", ask);
390
391         if(!f)
392                 return false;
393
394         char *pubkey = ecdsa_get_base64_public_key(&key);
395         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
396         free(pubkey);
397
398         fclose(f);
399         free(filename);
400
401         return true;
402 }
403
404 /*
405   Generate a public/private RSA keypair, and ask for a file to store
406   them in.
407 */
408 static bool rsa_keygen(int bits, bool ask) {
409         rsa_t key;
410         FILE *f;
411         char *filename;
412
413         fprintf(stderr, "Generating %d bits keys:\n", bits);
414
415         if(!rsa_generate(&key, bits, 0x10001)) {
416                 fprintf(stderr, "Error during key generation!\n");
417                 return false;
418         } else
419                 fprintf(stderr, "Done.\n");
420
421         xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
422         f = ask_and_open(filename, "private RSA key", "a", ask);
423
424         if(!f)
425                 return false;
426   
427 #ifdef HAVE_FCHMOD
428         /* Make it unreadable for others. */
429         fchmod(fileno(f), 0600);
430 #endif
431                 
432         rsa_write_pem_private_key(&key, f);
433
434         fclose(f);
435         free(filename);
436
437         if(name)
438                 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
439         else
440                 xasprintf(&filename, "%s" SLASH "rsa_key.pub", confbase);
441
442         f = ask_and_open(filename, "public RSA key", "a", ask);
443
444         if(!f)
445                 return false;
446
447         rsa_write_pem_public_key(&key, f);
448
449         fclose(f);
450         free(filename);
451
452         return true;
453 }
454
455 /*
456   Set all files and paths according to netname
457 */
458 static void make_names(void) {
459 #ifdef HAVE_MINGW
460         HKEY key;
461         char installdir[1024] = "";
462         long len = sizeof installdir;
463 #endif
464
465         if(netname)
466                 xasprintf(&identname, "tinc.%s", netname);
467         else
468                 identname = xstrdup("tinc");
469
470 #ifdef HAVE_MINGW
471         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
472                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
473                         if(!confbase) {
474                                 if(netname)
475                                         xasprintf(&confbase, "%s" SLASH "%s", installdir, netname);
476                                 else
477                                         xasprintf(&confbase, "%s", installdir);
478                         }
479                 }
480                 if(!pidfilename)
481                         xasprintf(&pidfilename, "%s" SLASH "pid", confbase);
482                 RegCloseKey(key);
483         }
484
485         if(!*installdir) {
486 #endif
487         confdir = xstrdup(CONFDIR);
488
489         if(!pidfilename)
490                 xasprintf(&pidfilename, "%s" SLASH "run" SLASH "%s.pid", LOCALSTATEDIR, identname);
491
492         if(netname) {
493                 if(!confbase)
494                         xasprintf(&confbase, CONFDIR SLASH "tinc" SLASH "%s", netname);
495                 else
496                         fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
497         } else {
498                 if(!confbase)
499                         xasprintf(&confbase, CONFDIR SLASH "tinc");
500         }
501
502 #ifdef HAVE_MINGW
503         } else
504                 confdir = xstrdup(installdir);
505 #endif
506
507         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
508         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
509 }
510
511 static char buffer[4096];
512 static size_t blen = 0;
513
514 bool recvline(int fd, char *line, size_t len) {
515         char *newline = NULL;
516
517         while(!(newline = memchr(buffer, '\n', blen))) {
518                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
519                 if(result == -1 && errno == EINTR)
520                         continue;
521                 else if(result <= 0)
522                         return false;
523                 blen += result;
524         }
525
526         if(newline - buffer >= len)
527                 return false;
528
529         len = newline - buffer;
530
531         memcpy(line, buffer, len);
532         line[len] = 0;
533         memmove(buffer, newline + 1, blen - len - 1);
534         blen -= len + 1;
535
536         return true;
537 }
538
539 static bool recvdata(int fd, char *data, size_t len) {
540         while(blen < len) {
541                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
542                 if(result == -1 && errno == EINTR)
543                         continue;
544                 else if(result <= 0)
545                         return false;
546                 blen += result;
547         }
548
549         memcpy(data, buffer, len);
550         memmove(buffer, buffer + len, blen - len);
551         blen -= len;
552
553         return true;
554 }
555
556 bool sendline(int fd, char *format, ...) {
557         static char buffer[4096];
558         char *p = buffer;
559         int blen = 0;
560         va_list ap;
561
562         va_start(ap, format);
563         blen = vsnprintf(buffer, sizeof buffer, format, ap);
564         va_end(ap);
565
566         if(blen < 1 || blen >= sizeof buffer)
567                 return false;
568
569         buffer[blen] = '\n';
570         blen++;
571
572         while(blen) {
573                 int result = send(fd, p, blen, 0);
574                 if(result == -1 && errno == EINTR)
575                         continue;
576                 else if(result <= 0)
577                         return false;
578                 p += result;
579                 blen -= result;
580         }
581
582         return true;    
583 }
584
585 static void pcap(int fd, FILE *out, int snaplen) {
586         sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
587         char data[9018];
588
589         struct {
590                 uint32_t magic;
591                 uint16_t major;
592                 uint16_t minor;
593                 uint32_t tz_offset;
594                 uint32_t tz_accuracy;
595                 uint32_t snaplen;
596                 uint32_t ll_type;
597         } header = {
598                 0xa1b2c3d4,
599                 2, 4,
600                 0, 0,
601                 snaplen ?: sizeof data,
602                 1,
603         };
604
605         struct {
606                 uint32_t tv_sec;
607                 uint32_t tv_usec;
608                 uint32_t len;
609                 uint32_t origlen;
610         } packet;
611
612         struct timeval tv;
613
614         fwrite(&header, sizeof header, 1, out);
615         fflush(out);
616
617         char line[32];
618         while(recvline(fd, line, sizeof line)) {
619                 int code, req, len;
620                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
621                 gettimeofday(&tv, NULL);
622                 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
623                         break;
624                 if(!recvdata(fd, data, len))
625                         break;
626                 packet.tv_sec = tv.tv_sec;
627                 packet.tv_usec = tv.tv_usec;
628                 packet.len = len;
629                 packet.origlen = len;
630                 fwrite(&packet, sizeof packet, 1, out);
631                 fwrite(data, len, 1, out);
632                 fflush(out);
633         }
634 }
635
636 static void logcontrol(int fd, FILE *out, int level) {
637         sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
638         char data[1024];
639         char line[32];
640
641         while(recvline(fd, line, sizeof line)) {
642                 int code, req, len;
643                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
644                 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
645                         break;
646                 if(!recvdata(fd, data, len))
647                         break;
648                 fwrite(data, len, 1, out);
649                 fputc('\n', out);
650                 fflush(out);
651         }
652 }
653
654 #ifdef HAVE_MINGW
655 static bool remove_service(void) {
656         SC_HANDLE manager = NULL;
657         SC_HANDLE service = NULL;
658         SERVICE_STATUS status = {0};
659
660         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
661         if(!manager) {
662                 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
663                 return false;
664         }
665
666         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
667
668         if(!service) {
669                 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
670                 return false;
671         }
672
673         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
674                 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
675         else
676                 fprintf(stderr, "%s service stopped\n", identname);
677
678         if(!DeleteService(service)) {
679                 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
680                 return false;
681         }
682
683         fprintf(stderr, "%s service removed\n", identname);
684
685         return true;
686 }
687 #endif
688
689 static bool connect_tincd(bool verbose) {
690         if(fd >= 0)
691                 return true;
692
693         FILE *f = fopen(pidfilename, "r");
694         if(!f) {
695                 if(verbose)
696                         fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
697                 return false;
698         }
699
700         char host[128];
701         char port[128];
702
703         if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
704                 if(verbose)
705                         fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
706                 fclose(f);
707                 return false;
708         }
709
710         fclose(f);
711
712 #ifdef HAVE_MINGW
713         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
714                 if(verbose)
715                         fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
716                 return false;
717         }
718 #endif
719
720         struct addrinfo hints = {
721                 .ai_family = AF_UNSPEC,
722                 .ai_socktype = SOCK_STREAM,
723                 .ai_protocol = IPPROTO_TCP,
724                 .ai_flags = 0,
725         };
726
727         struct addrinfo *res = NULL;
728
729         if(getaddrinfo(host, port, &hints, &res) || !res) {
730                 if(verbose)
731                         fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
732                 return false;
733         }
734
735         fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
736         if(fd < 0) {
737                 if(verbose)
738                         fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
739                 return false;
740         }
741
742 #ifdef HAVE_MINGW
743         unsigned long arg = 0;
744
745         if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
746                 if(verbose)
747                         fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
748         }
749 #endif
750
751         if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
752                 if(verbose)
753                         fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
754                 return false;
755         }
756
757         freeaddrinfo(res);
758
759         char data[4096];
760         int version;
761
762         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
763                 if(verbose)
764                         fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
765                 return false;
766         }
767
768         sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
769         
770         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
771                 if(verbose)
772                         fprintf(stderr, "Could not fully establish control socket connection\n");
773                 return false;
774         }
775
776         return true;
777 }
778
779
780 static int cmd_start(int argc, char *argv[]) {
781         if(connect_tincd(false)) {
782                 if(netname)
783                         fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
784                 else
785                         fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
786                 return 0;
787         }
788
789         char *c;
790         char *slash = strrchr(program_name, '/');
791
792 #ifdef HAVE_MINGW
793         if ((c = strrchr(program_name, '\\')) > slash)
794                 slash = c;
795 #endif
796
797         if (slash++)
798                 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
799         else
800                 c = "tincd";
801
802         int nargc = 0;
803         char **nargv = xmalloc_and_zero((orig_argc + argc) * sizeof *nargv);
804
805         for(int i = 0; i < orig_argc; i++)
806                 nargv[nargc++] = orig_argv[i];
807         for(int i = 1; i < argc; i++)
808                 nargv[nargc++] = argv[i];
809
810 #ifdef HAVE_MINGW
811         execvp(c, nargv);
812         fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
813         return 1;
814 #else
815         pid_t pid = fork();
816         if(pid == -1) {
817                 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
818                 return 1;
819         }
820
821         if(!pid)
822                 exit(execvp(c, nargv));
823         
824         int status = -1;
825         if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
826                 fprintf(stderr, "Error starting %s\n", c);
827                 return 1;
828         }
829
830         return 0;
831 #endif
832 }
833
834 static int cmd_stop(int argc, char *argv[]) {
835 #ifndef HAVE_MINGW
836         if(!connect_tincd(true)) {
837                 if(pid) {
838                         if(kill(pid, SIGTERM)) 
839                                 return 1;
840                         fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
841                         return 0;
842                 }
843
844                 return 1;
845         }
846
847         sendline(fd, "%d %d", CONTROL, REQ_STOP);
848         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
849                 fprintf(stderr, "Could not stop tinc daemon.\n");
850                 return 1;
851         }
852 #else
853         if(!remove_service())
854                 return 1;
855 #endif
856         close(fd);
857         pid = 0;
858         fd = -1;
859
860         return 0;
861 }
862
863 static int cmd_restart(int argc, char *argv[]) {
864         cmd_stop(argc, argv);
865         return cmd_start(argc, argv);
866 }
867
868 static int cmd_reload(int argc, char *argv[]) {
869         if(!connect_tincd(true))
870                 return 1;
871
872         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
873         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
874                 fprintf(stderr, "Could not reload configuration.\n");
875                 return 1;
876         }
877
878         return 0;
879
880 }
881
882 static int cmd_dump(int argc, char *argv[]) {
883         if(argc != 2) {
884                 fprintf(stderr, "Invalid number of arguments.\n");
885                 usage(true);
886                 return 1;
887         }
888
889         if(!connect_tincd(true))
890                 return 1;
891
892         int do_graph = 0;
893
894         if(!strcasecmp(argv[1], "nodes"))
895                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
896         else if(!strcasecmp(argv[1], "edges"))
897                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
898         else if(!strcasecmp(argv[1], "subnets"))
899                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
900         else if(!strcasecmp(argv[1], "connections"))
901                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
902         else if(!strcasecmp(argv[1], "graph")) {
903                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
904                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
905                 do_graph = 1;
906         } else if(!strcasecmp(argv[1], "digraph")) {
907                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
908                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
909                 do_graph = 2;
910         } else {
911                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
912                 usage(true);
913                 return 1;
914         }
915
916         if(do_graph == 1)
917                 printf("graph {\n");
918         else if(do_graph == 2)
919                 printf("digraph {\n");
920
921         while(recvline(fd, line, sizeof line)) {
922                 char node1[4096], node2[4096];
923                 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
924                 if(n == 2) {
925                         if(do_graph && req == REQ_DUMP_NODES)
926                                 continue;
927                         else {
928                                 if(do_graph)
929                                         printf("}\n");
930                                 return 0;
931                         }
932                 }
933                 if(n < 2)
934                         break;
935
936                 if(!do_graph) {
937                         char node[4096];
938                         char from[4096];
939                         char to[4096];
940                         char subnet[4096];
941                         char host[4096];
942                         char port[4096];
943                         char via[4096];
944                         char nexthop[4096];
945                         int cipher, digest, maclength, compression, distance, socket, weight;
946                         short int pmtu, minmtu, maxmtu;
947                         unsigned int options, status;
948                         long int last_state_change;
949
950                         switch(req) {
951                                 case REQ_DUMP_NODES: {
952                                         int n = sscanf(line, "%*d %*d %s %s port %s %d %d %d %d %x %x %s %s %d %hd %hd %hd %ld", node, host, port, &cipher, &digest, &maclength, &compression, &options, &status, nexthop, via, &distance, &pmtu, &minmtu, &maxmtu, &last_state_change);
953                                         if(n != 16) {
954                                                 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
955                                                 return 1;
956                                         }
957                                         printf("%s at %s port %s cipher %d digest %d maclength %d compression %d options %x status %04x nexthop %s via %s distance %d pmtu %hd (min %hd max %hd)\n",
958                                                         node, host, port, cipher, digest, maclength, compression, options, status, nexthop, via, distance, pmtu, minmtu, maxmtu);
959                                 } break;
960
961                                 case REQ_DUMP_EDGES: {
962                                         int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
963                                         if(n != 6) {
964                                                 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
965                                                 return 1;
966                                         }
967                                         printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
968                                 } break;
969
970                                 case REQ_DUMP_SUBNETS: {
971                                         int n = sscanf(line, "%*d %*d %s %s", subnet, node);
972                                         if(n != 2) {
973                                                 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
974                                                 return 1;
975                                         }
976                                         printf("%s owner %s\n", strip_weight(subnet), node);
977                                 } break;
978
979                                 case REQ_DUMP_CONNECTIONS: {
980                                         int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status);
981                                         if(n != 6) {
982                                                 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
983                                                 return 1;
984                                         }
985                                         printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status);
986                                 } break;
987
988                                 default:
989                                         fprintf(stderr, "Unable to parse dump from tincd.\n");
990                                         return 1;
991                         }
992                 } else {
993                         if(req == REQ_DUMP_NODES)
994                                 printf(" %s [label = \"%s\"];\n", node1, node1);
995                         else {
996                                 if(do_graph == 1 && strcmp(node1, node2) > 0)
997                                         printf(" %s -- %s;\n", node1, node2);
998                                 else if(do_graph == 2)
999                                         printf(" %s -> %s;\n", node1, node2);
1000                         }
1001                 }
1002         }
1003
1004         fprintf(stderr, "Error receiving dump.\n");
1005         return 1;
1006 }
1007
1008 static int cmd_purge(int argc, char *argv[]) {
1009         if(!connect_tincd(true))
1010                 return 1;
1011
1012         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1013         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1014                 fprintf(stderr, "Could not purge old information.\n");
1015                 return 1;
1016         }
1017
1018         return 0;
1019 }
1020
1021 static int cmd_debug(int argc, char *argv[]) {
1022         if(argc != 2) {
1023                 fprintf(stderr, "Invalid number of arguments.\n");
1024                 return 1;
1025         }
1026
1027         if(!connect_tincd(true))
1028                 return 1;
1029
1030         int debuglevel = atoi(argv[1]);
1031         int origlevel;
1032
1033         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1034         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1035                 fprintf(stderr, "Could not set debug level.\n");
1036                 return 1;
1037         }
1038
1039         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1040         return 0;
1041 }
1042
1043 static int cmd_retry(int argc, char *argv[]) {
1044         if(!connect_tincd(true))
1045                 return 1;
1046
1047         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1048         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1049                 fprintf(stderr, "Could not retry outgoing connections.\n");
1050                 return 1;
1051         }
1052
1053         return 0;
1054 }
1055
1056 static int cmd_connect(int argc, char *argv[]) {
1057         if(argc != 2) {
1058                 fprintf(stderr, "Invalid number of arguments.\n");
1059                 return 1;
1060         }
1061
1062         if(!check_id(argv[1])) {
1063                 fprintf(stderr, "Invalid name for node.\n");
1064                 return 1;
1065         }
1066
1067         if(!connect_tincd(true))
1068                 return 1;
1069
1070         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1071         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1072                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1073                 return 1;
1074         }
1075
1076         return 0;
1077 }
1078
1079 static int cmd_disconnect(int argc, char *argv[]) {
1080         if(argc != 2) {
1081                 fprintf(stderr, "Invalid number of arguments.\n");
1082                 return 1;
1083         }
1084
1085         if(!check_id(argv[1])) {
1086                 fprintf(stderr, "Invalid name for node.\n");
1087                 return 1;
1088         }
1089
1090         if(!connect_tincd(true))
1091                 return 1;
1092
1093         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1094         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1095                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1096                 return 1;
1097         }
1098
1099         return 0;
1100 }
1101
1102 static int cmd_top(int argc, char *argv[]) {
1103 #ifdef HAVE_CURSES
1104         if(!connect_tincd(true))
1105                 return 1;
1106
1107         top(fd);
1108         return 0;
1109 #else
1110         fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1111         return 1;
1112 #endif
1113 }
1114
1115 static int cmd_pcap(int argc, char *argv[]) {
1116         if(!connect_tincd(true))
1117                 return 1;
1118
1119         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1120         return 0;
1121 }
1122
1123 static int cmd_log(int argc, char *argv[]) {
1124         if(!connect_tincd(true))
1125                 return 1;
1126
1127         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1128         return 0;
1129 }
1130
1131 static int cmd_pid(int argc, char *argv[]) {
1132         if(!connect_tincd(true) && !pid)
1133                 return 1;
1134
1135         printf("%d\n", pid);
1136         return 0;
1137 }
1138
1139 static int rstrip(char *value) {
1140         int len = strlen(value);
1141         while(len && strchr("\t\r\n ", value[len - 1]))
1142                 value[--len] = 0;
1143         return len;
1144 }
1145
1146 static char *get_my_name() {
1147         FILE *f = fopen(tinc_conf, "r");
1148         if(!f) {
1149                 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1150                 return NULL;
1151         }
1152
1153         char buf[4096];
1154         char *value;
1155         while(fgets(buf, sizeof buf, f)) {
1156                 int len = strcspn(buf, "\t =");
1157                 value = buf + len;
1158                 value += strspn(value, "\t ");
1159                 if(*value == '=') {
1160                         value++;
1161                         value += strspn(value, "\t ");
1162                 }
1163                 if(!rstrip(value))
1164                         continue;
1165                 buf[len] = 0;
1166                 if(strcasecmp(buf, "Name"))
1167                         continue;
1168                 if(*value) {
1169                         fclose(f);
1170                         return strdup(value);
1171                 }
1172         }
1173
1174         fclose(f);
1175         fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1176         return NULL;
1177 }
1178
1179 #define VAR_SERVER 1    /* Should be in tinc.conf */
1180 #define VAR_HOST 2      /* Can be in host config file */
1181 #define VAR_MULTIPLE 4  /* Multiple statements allowed */
1182 #define VAR_OBSOLETE 8  /* Should not be used anymore */
1183
1184 static struct {
1185         const char *name;
1186         int type;
1187 } const variables[] = {
1188         /* Server configuration */
1189         {"AddressFamily", VAR_SERVER},
1190         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1191         {"BindToInterface", VAR_SERVER},
1192         {"Broadcast", VAR_SERVER},
1193         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1194         {"DecrementTTL", VAR_SERVER},
1195         {"Device", VAR_SERVER},
1196         {"DeviceType", VAR_SERVER},
1197         {"DirectOnly", VAR_SERVER},
1198         {"ECDSAPrivateKeyFile", VAR_SERVER},
1199         {"ExperimentalProtocol", VAR_SERVER},
1200         {"Forwarding", VAR_SERVER},
1201         {"GraphDumpFile", VAR_SERVER},
1202         {"Hostnames", VAR_SERVER},
1203         {"IffOneQueue", VAR_SERVER},
1204         {"Interface", VAR_SERVER},
1205         {"KeyExpire", VAR_SERVER},
1206         {"LocalDiscovery", VAR_SERVER},
1207         {"MACExpire", VAR_SERVER},
1208         {"MaxOutputBufferSize", VAR_SERVER},
1209         {"MaxTimeout", VAR_SERVER},
1210         {"Mode", VAR_SERVER},
1211         {"Name", VAR_SERVER},
1212         {"PingInterval", VAR_SERVER},
1213         {"PingTimeout", VAR_SERVER},
1214         {"PriorityInheritance", VAR_SERVER},
1215         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1216         {"PrivateKeyFile", VAR_SERVER},
1217         {"ProcessPriority", VAR_SERVER},
1218         {"Proxy", VAR_SERVER},
1219         {"ReplayWindow", VAR_SERVER},
1220         {"StrictSubnets", VAR_SERVER},
1221         {"TunnelServer", VAR_SERVER},
1222         {"UDPRcvBuf", VAR_SERVER},
1223         {"UDPSndBuf", VAR_SERVER},
1224         {"VDEGroup", VAR_SERVER},
1225         {"VDEPort", VAR_SERVER},
1226         /* Host configuration */
1227         {"Address", VAR_HOST | VAR_MULTIPLE},
1228         {"Cipher", VAR_SERVER | VAR_HOST},
1229         {"ClampMSS", VAR_SERVER | VAR_HOST},
1230         {"Compression", VAR_SERVER | VAR_HOST},
1231         {"Digest", VAR_SERVER | VAR_HOST},
1232         {"ECDSAPublicKey", VAR_HOST},
1233         {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1234         {"IndirectData", VAR_SERVER | VAR_HOST},
1235         {"MACLength", VAR_SERVER | VAR_HOST},
1236         {"PMTU", VAR_SERVER | VAR_HOST},
1237         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1238         {"Port", VAR_HOST},
1239         {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1240         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1241         {"Subnet", VAR_HOST | VAR_MULTIPLE},
1242         {"TCPOnly", VAR_SERVER | VAR_HOST},
1243         {"Weight", VAR_HOST},
1244         {NULL, 0}
1245 };
1246
1247 static int cmd_config(int argc, char *argv[]) {
1248         if(argc < 2) {
1249                 fprintf(stderr, "Invalid number of arguments.\n");
1250                 return 1;
1251         }
1252
1253         int action = -2;
1254         if(!strcasecmp(argv[1], "get")) {
1255                 argv++, argc--;
1256         } else if(!strcasecmp(argv[1], "add")) {
1257                 argv++, argc--, action = 1;
1258         } else if(!strcasecmp(argv[1], "del")) {
1259                 argv++, argc--, action = -1;
1260         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1261                 argv++, argc--, action = 0;
1262         }
1263
1264         if(argc < 2) {
1265                 fprintf(stderr, "Invalid number of arguments.\n");
1266                 return 1;
1267         }
1268
1269         // Concatenate the rest of the command line
1270         strncpy(line, argv[1], sizeof line - 1);
1271         for(int i = 2; i < argc; i++) {
1272                 strncat(line, " ", sizeof line - 1 - strlen(line));
1273                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1274         }
1275
1276         // Liberal parsing into node name, variable name and value.
1277         char *node = NULL;
1278         char *variable;
1279         char *value;
1280         int len;
1281
1282         len = strcspn(line, "\t =");
1283         value = line + len;
1284         value += strspn(value, "\t ");
1285         if(*value == '=') {
1286                 value++;
1287                 value += strspn(value, "\t ");
1288         }
1289         line[len] = '\0';
1290         variable = strchr(line, '.');
1291         if(variable) {
1292                 node = line;
1293                 *variable++ = 0;
1294         } else {
1295                 variable = line;
1296         }
1297
1298         if(!*variable) {
1299                 fprintf(stderr, "No variable given.\n");
1300                 return 1;
1301         }
1302
1303         if(action >= 0 && !*value) {
1304                 fprintf(stderr, "No value for variable given.\n");
1305                 return 1;
1306         }
1307
1308         if(action < -1 && *value)
1309                 action = 0;
1310
1311         /* Some simple checks. */
1312         bool found = false;
1313
1314         for(int i = 0; variables[i].name; i++) {
1315                 if(strcasecmp(variables[i].name, variable))
1316                         continue;
1317
1318                 found = true;
1319                 variable = (char *)variables[i].name;
1320
1321                 /* Discourage use of obsolete variables. */
1322
1323                 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1324                         if(force) {
1325                                 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1326                         } else {
1327                                 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1328                                 return 1;
1329                         }
1330                 }
1331
1332                 /* Don't put server variables in host config files */
1333
1334                 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1335                         if(force) {
1336                                 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1337                         } else {
1338                                 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1339                                 return 1;
1340                         }
1341                 }
1342
1343                 /* Should this go into our own host config file? */
1344
1345                 if(!node && !(variables[i].type & VAR_SERVER)) {
1346                         node = get_my_name();
1347                         if(!node)
1348                                 return 1;
1349                 }
1350
1351                 break;
1352         }
1353
1354         if(node && !check_id(node)) {
1355                 fprintf(stderr, "Invalid name for node.\n");
1356                 return 1;
1357         }
1358
1359         if(!found) {
1360                 if(force || action < 0) {
1361                         fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1362                 } else {
1363                         fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1364                         return 1;
1365                 }
1366         }
1367
1368         // Open the right configuration file.
1369         char *filename;
1370         if(node)
1371                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1372         else
1373                 filename = tinc_conf;
1374
1375         FILE *f = fopen(filename, "r");
1376         if(!f) {
1377                 if(action < 0 || errno != ENOENT) {
1378                         fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1379                         return 1;
1380                 }
1381
1382                 // If it doesn't exist, create it.
1383                 f = fopen(filename, "a+");
1384                 if(!f) {
1385                         fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1386                         return 1;
1387                 } else {
1388                         fprintf(stderr, "Created configuration file %s.\n", filename);
1389                 }
1390         }
1391
1392         char *tmpfile = NULL;
1393         FILE *tf = NULL;
1394
1395         if(action >= -1) {
1396                 xasprintf(&tmpfile, "%s.config.tmp", filename);
1397                 tf = fopen(tmpfile, "w");
1398                 if(!tf) {
1399                         fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1400                         fclose(f);
1401                         return 1;
1402                 }
1403         }
1404
1405         // Copy the file, making modifications on the fly, unless we are just getting a value.
1406         char buf1[4096];
1407         char buf2[4096];
1408         bool set = false;
1409         bool removed = false;
1410         found = false;
1411
1412         while(fgets(buf1, sizeof buf1, f)) {
1413                 buf1[sizeof buf1 - 1] = 0;
1414                 strncpy(buf2, buf1, sizeof buf2);
1415
1416                 // Parse line in a simple way
1417                 char *bvalue;
1418                 int len;
1419
1420                 len = strcspn(buf2, "\t =");
1421                 bvalue = buf2 + len;
1422                 bvalue += strspn(bvalue, "\t ");
1423                 if(*bvalue == '=') {
1424                         bvalue++;
1425                         bvalue += strspn(bvalue, "\t ");
1426                 }
1427                 rstrip(bvalue);
1428                 buf2[len] = '\0';
1429
1430                 // Did it match?
1431                 if(!strcasecmp(buf2, variable)) {
1432                         // Get
1433                         if(action < -1) {
1434                                 found = true;
1435                                 printf("%s\n", bvalue);
1436                         // Del
1437                         } else if(action == -1) {
1438                                 if(!*value || !strcasecmp(bvalue, value)) {
1439                                         removed = true;
1440                                         continue;
1441                                 }
1442                         // Set
1443                         } else if(action == 0) {
1444                                 // Already set? Delete the rest...
1445                                 if(set)
1446                                         continue;
1447                                 // Otherwise, replace.
1448                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1449                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1450                                         return 1;
1451                                 }
1452                                 set = true;
1453                                 continue;
1454                         }
1455                 }
1456
1457                 if(action >= -1) {
1458                         // Copy original line...
1459                         if(fputs(buf1, tf) < 0) {
1460                                 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1461                                 return 1;
1462                         }
1463
1464                         // Add newline if it is missing...
1465                         if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1466                                 if(fputc('\n', tf) < 0) {
1467                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1468                                         return 1;
1469                                 }
1470                         }
1471                 }
1472         }
1473
1474         // Make sure we read everything...
1475         if(ferror(f) || !feof(f)) {
1476                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1477                 return 1;
1478         }
1479
1480         if(fclose(f)) {
1481                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1482                 return 1;
1483         }
1484
1485         // Add new variable if necessary.
1486         if(action > 0 || (action == 0 && !set)) {
1487                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1488                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1489                         return 1;
1490                 }
1491         }
1492
1493         if(action < -1) {
1494                 if(!found)
1495                         fprintf(stderr, "No matching configuration variables found.\n");
1496                 return 0;
1497         }
1498
1499         // Make sure we wrote everything...
1500         if(fclose(tf)) {
1501                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1502                 return 1;
1503         }
1504
1505         // Could we find what we had to remove?
1506         if(action < 0 && !removed) {
1507                 remove(tmpfile);
1508                 fprintf(stderr, "No configuration variables deleted.\n");
1509                 return *value;
1510         }
1511
1512         // Replace the configuration file with the new one
1513 #ifdef HAVE_MINGW
1514         if(remove(filename)) {
1515                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1516                 return 1;
1517         }
1518 #endif
1519         if(rename(tmpfile, filename)) {
1520                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1521                 return 1;
1522         }
1523
1524         // Silently try notifying a running tincd of changes.
1525         if(connect_tincd(false))
1526                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1527
1528         return 0;
1529 }
1530
1531 bool check_id(const char *name) {
1532         if(!name || !*name)
1533                 return false;
1534
1535         for(int i = 0; i < strlen(name); i++) {
1536                 if(!isalnum(name[i]) && name[i] != '_')
1537                         return false;
1538         }
1539
1540         return true;
1541 }
1542
1543 static int cmd_init(int argc, char *argv[]) {
1544         if(!access(tinc_conf, F_OK)) {
1545                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1546                 return 1;
1547         }
1548
1549         if(argc < 2) {
1550                 if(tty) {
1551                         char buf[1024];
1552                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1553                         fflush(stdout);
1554                         if(!fgets(buf, sizeof buf, stdin)) {
1555                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1556                                 return 1;
1557                         }
1558                         int len = rstrip(buf);
1559                         if(!len) {
1560                                 fprintf(stderr, "No name given!\n");
1561                                 return 1;
1562                         }
1563                         name = strdup(buf);
1564                 } else {
1565                         fprintf(stderr, "No Name given!\n");
1566                         return 1;
1567                 }
1568         } else {
1569                 name = strdup(argv[1]);
1570                 if(!*name) {
1571                         fprintf(stderr, "No Name given!\n");
1572                         return 1;
1573                 }
1574         }
1575
1576         if(!check_id(name)) {
1577                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1578                 return 1;
1579         }
1580
1581         if(mkdir(confdir, 0755) && errno != EEXIST) {
1582                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1583                 return 1;
1584         }
1585
1586         if(mkdir(confbase, 0755) && errno != EEXIST) {
1587                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1588                 return 1;
1589         }
1590
1591         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1592                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1593                 return 1;
1594         }
1595
1596         FILE *f = fopen(tinc_conf, "w");
1597         if(!f) {
1598                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1599                 return 1;
1600         }
1601
1602         fprintf(f, "Name = %s\n", name);
1603         fclose(f);
1604
1605         if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1606                 return 1;
1607
1608 #ifndef HAVE_MINGW
1609         char *filename;
1610         xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1611         if(access(filename, F_OK)) {
1612                 FILE *f = fopen(filename, "w");
1613                 if(!f) {
1614                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1615                         return 1;
1616                 }
1617                 fchmod(fileno(f), 0755);
1618                 fprintf(f, "#!/bin/sh\n\necho 'Unconfigured tinc-up script, please edit!'\n\n#ifconfig $INTERFACE <your vpn IP address> netmask <netmask of whole VPN>\n");
1619                 fclose(f);
1620         }
1621 #endif
1622
1623         return 0;
1624
1625 }
1626
1627 static int cmd_generate_keys(int argc, char *argv[]) {
1628         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1629 }
1630
1631 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1632         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1633 }
1634
1635 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1636         return !ecdsa_keygen(true);
1637 }
1638
1639 static int cmd_help(int argc, char *argv[]) {
1640         usage(false);
1641         return 0;
1642 }
1643
1644 static int cmd_version(int argc, char *argv[]) {
1645         version();
1646         return 0;
1647 }
1648
1649 static int cmd_info(int argc, char *argv[]) {
1650         if(argc != 2) {
1651                 fprintf(stderr, "Invalid number of arguments.\n");
1652                 return 1;
1653         }
1654
1655         if(!connect_tincd(true))
1656                 return 1;
1657
1658         return info(fd, argv[1]);
1659 }
1660
1661 static const char *conffiles[] = {
1662         "tinc.conf",
1663         "tinc-up",
1664         "tinc-down",
1665         "subnet-up",
1666         "subnet-down",
1667         "host-up",
1668         "host-down",
1669         NULL,
1670 };
1671
1672 static int cmd_edit(int argc, char *argv[]) {
1673         if(argc != 2) {
1674                 fprintf(stderr, "Invalid number of arguments.\n");
1675                 return 1;
1676         }
1677
1678         char *filename = NULL;
1679
1680         if(strncmp(argv[1], "hosts" SLASH, 6)) {
1681                 for(int i = 0; conffiles[i]; i++) {
1682                         if(!strcmp(argv[1], conffiles[i])) {
1683                                 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1684                                 break;
1685                         }
1686                 }
1687         } else {
1688                 argv[1] += 6;
1689         }
1690
1691         if(!filename) {
1692                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1693                 char *dash = strchr(argv[1], '-');
1694                 if(dash) {
1695                         *dash++ = 0;
1696                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1697                                 fprintf(stderr, "Invalid configuration filename.\n");
1698                                 return 1;
1699                         }
1700                 }
1701         }
1702
1703         char *command;
1704 #ifndef HAVE_MINGW
1705         xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1706 #else
1707         xasprintf(&command, "edit \"%s\"", filename);
1708 #endif
1709         int result = system(command);
1710         if(result)
1711                 return result;
1712
1713         // Silently try notifying a running tincd of changes.
1714         if(connect_tincd(false))
1715                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1716
1717         return 0;
1718 }
1719
1720 static int export(const char *name, FILE *out) {
1721         char *filename;
1722         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1723         FILE *in = fopen(filename, "r");
1724         if(!in) {
1725                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1726                 return 1;
1727         }
1728
1729         fprintf(out, "Name = %s\n", name);
1730         char buf[4096];
1731         while(fgets(buf, sizeof buf, in)) {
1732                 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1733                         fputs(buf, out);
1734         }
1735
1736         if(ferror(in)) {
1737                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1738                 fclose(in);
1739                 return 1;
1740         }
1741
1742         fclose(in);
1743         return 0;
1744 }
1745
1746 static int cmd_export(int argc, char *argv[]) {
1747         char *name = get_my_name();
1748         if(!name)
1749                 return 1;
1750
1751         return export(name, stdout);
1752 }
1753
1754 static int cmd_export_all(int argc, char *argv[]) {
1755         DIR *dir = opendir(hosts_dir);
1756         if(!dir) {
1757                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1758                 return 1;
1759         }
1760
1761         bool first = true;
1762         int result = 0;
1763         struct dirent *ent;
1764
1765         while((ent = readdir(dir))) {
1766                 if(!check_id(ent->d_name))
1767                         continue;
1768
1769                 if(first)
1770                         first = false;
1771                 else
1772                         printf("#---------------------------------------------------------------#\n");
1773
1774                 result |= export(ent->d_name, stdout);
1775         }
1776
1777         closedir(dir);
1778         return result;
1779 }
1780
1781 static int cmd_import(int argc, char *argv[]) {
1782         FILE *in = stdin;
1783         FILE *out = NULL;
1784
1785         char buf[4096];
1786         char name[4096];
1787         char *filename;
1788         int count = 0;
1789         bool firstline = true;
1790
1791         while(fgets(buf, sizeof buf, in)) {
1792                 if(sscanf(buf, "Name = %s", name) == 1) {
1793                         if(!check_id(name)) {
1794                                 fprintf(stderr, "Invalid Name in input!\n");
1795                                 return 1;
1796                         }
1797
1798                         if(out)
1799                                 fclose(out);
1800
1801                         free(filename);
1802                         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1803
1804                         if(!force && !access(filename, F_OK)) {
1805                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1806                                 out = NULL;
1807                                 continue;
1808                         }
1809
1810                         out = fopen(filename, "w");
1811                         if(!out) {
1812                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1813                                 return 1;
1814                         }
1815
1816                         count++;
1817                         firstline = false;
1818                         continue;
1819                 } else if(firstline) {
1820                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1821                         firstline = false;
1822                 }
1823
1824
1825                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1826                         continue;
1827
1828                 if(out) {
1829                         if(fputs(buf, out) < 0) {
1830                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1831                                 return 1;
1832                         }
1833                 }
1834         }
1835
1836         if(out)
1837                 fclose(out);
1838
1839         if(count) {
1840                 fprintf(stderr, "Imported %d host configuration files.\n", count);
1841                 return 0;
1842         } else {
1843                 fprintf(stderr, "No host configuration files imported.\n");
1844                 return 1;
1845         }
1846 }
1847
1848 static const struct {
1849         const char *command;
1850         int (*function)(int argc, char *argv[]);
1851 } commands[] = {
1852         {"start", cmd_start},
1853         {"stop", cmd_stop},
1854         {"restart", cmd_restart},
1855         {"reload", cmd_reload},
1856         {"dump", cmd_dump},
1857         {"purge", cmd_purge},
1858         {"debug", cmd_debug},
1859         {"retry", cmd_retry},
1860         {"connect", cmd_connect},
1861         {"disconnect", cmd_disconnect},
1862         {"top", cmd_top},
1863         {"pcap", cmd_pcap},
1864         {"log", cmd_log},
1865         {"pid", cmd_pid},
1866         {"config", cmd_config},
1867         {"init", cmd_init},
1868         {"generate-keys", cmd_generate_keys},
1869         {"generate-rsa-keys", cmd_generate_rsa_keys},
1870         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1871         {"help", cmd_help},
1872         {"version", cmd_version},
1873         {"info", cmd_info},
1874         {"edit", cmd_edit},
1875         {"export", cmd_export},
1876         {"export-all", cmd_export_all},
1877         {"import", cmd_import},
1878         {NULL, NULL},
1879 };
1880
1881 #ifdef HAVE_READLINE
1882 static char *complete_command(const char *text, int state) {
1883         static int i;
1884
1885         if(!state)
1886                 i = 0;
1887         else
1888                 i++;
1889
1890         while(commands[i].command) {
1891                 if(!strncasecmp(commands[i].command, text, strlen(text)))
1892                         return xstrdup(commands[i].command);
1893                 i++;
1894         }
1895
1896         return NULL;
1897 }
1898
1899 static char *complete_dump(const char *text, int state) {
1900         const char *matches[] = {"nodes", "edges", "subnets", "connections", "graph", NULL};
1901         static int i;
1902
1903         if(!state)
1904                 i = 0;
1905         else
1906                 i++;
1907
1908         while(matches[i]) {
1909                 if(!strncasecmp(matches[i], text, strlen(text)))
1910                         return xstrdup(matches[i]);
1911                 i++;
1912         }
1913
1914         return NULL;
1915 }
1916
1917 static char *complete_config(const char *text, int state) {
1918         const char *sub[] = {"get", "set", "add", "del"};
1919         static int i;
1920         if(!state) {
1921                 i = 0;
1922                 if(!strchr(rl_line_buffer + 7, ' '))
1923                         i = -4;
1924                 else {
1925                         bool found = false;
1926                         for(int i = 0; i < 4; i++) {
1927                                 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
1928                                         found = true;
1929                                         break;
1930                                 }
1931                         }
1932                         if(!found)
1933                                 return NULL;
1934                 }
1935         } else {
1936                 i++;
1937         }
1938
1939         while(i < 0 || variables[i].name) {
1940                 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
1941                         return xstrdup(sub[i + 4]);
1942                 if(i >= 0) {
1943                         char *dot = strchr(text, '.');
1944                         if(dot) {
1945                                 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
1946                                         char *match;
1947                                         xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
1948                                         return match;
1949                                 }
1950                         } else {
1951                                 if(!strncasecmp(variables[i].name, text, strlen(text)))
1952                                         return xstrdup(variables[i].name);
1953                         }
1954                 }
1955                 i++;
1956         }
1957
1958         return NULL;
1959 }
1960
1961 static char *complete_info(const char *text, int state) {
1962         static int i;
1963         if(!state) {
1964                 i = 0;
1965                 if(!connect_tincd(false))
1966                         return NULL;
1967                 // Check the list of nodes
1968                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
1969                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
1970         }
1971
1972         while(recvline(fd, line, sizeof line)) {
1973                 char item[4096];
1974                 int n = sscanf(line, "%d %d %s", &code, &req, item);
1975                 if(n == 2) {
1976                         i++;
1977                         if(i >= 2)
1978                                 break;
1979                         else
1980                                 continue;
1981                 }
1982
1983                 if(n != 3) {
1984                         fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
1985                         break;
1986                 }
1987
1988                 if(!strncmp(item, text, strlen(text)))
1989                         return xstrdup(strip_weight(item));
1990         }
1991
1992         return NULL;
1993 }
1994
1995 static char *complete_nothing(const char *text, int state) {
1996         return NULL;
1997 }
1998
1999 static char **completion (const char *text, int start, int end) {
2000         char **matches = NULL;
2001
2002         if(!start)
2003                 matches = rl_completion_matches(text, complete_command);
2004         else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2005                 matches = rl_completion_matches(text, complete_dump);
2006         else if(!strncasecmp(rl_line_buffer, "config ", 7))
2007                 matches = rl_completion_matches(text, complete_config);
2008         else if(!strncasecmp(rl_line_buffer, "info ", 5))
2009                 matches = rl_completion_matches(text, complete_info);
2010
2011         return matches;
2012 }
2013 #endif
2014
2015 static int cmd_shell(int argc, char *argv[]) {
2016         char *prompt;
2017         xasprintf(&prompt, "%s> ", identname);
2018         int result = 0;
2019         char buf[4096];
2020         char *line = NULL;
2021         int maxargs = argc + 16;
2022         char **nargv = xmalloc(maxargs * sizeof *nargv);
2023         optind = argc;
2024
2025         for(int i = 0; i < argc; i++)
2026                 nargv[i] = argv[i];
2027
2028 #ifdef HAVE_READLINE
2029         rl_readline_name = "tinc";
2030         rl_completion_entry_function = complete_nothing;
2031         rl_attempted_completion_function = completion;
2032         rl_filename_completion_desired = 0;
2033         char *copy = NULL;
2034 #endif
2035
2036         while(true) {
2037 #ifdef HAVE_READLINE
2038                 if(tty) {
2039                         free(copy);
2040                         free(line);
2041                         rl_basic_word_break_characters = "\t\n ";
2042                         line = readline(prompt);
2043                         if(line)
2044                                 copy = xstrdup(line);
2045                 } else {
2046                         line = fgets(buf, sizeof buf, stdin);
2047                 }
2048 #else
2049                 if(tty)
2050                         fputs(prompt, stdout);
2051
2052                 line = fgets(buf, sizeof buf, stdin);
2053 #endif
2054
2055                 if(!line)
2056                         break;
2057
2058                 /* Ignore comments */
2059
2060                 if(*line == '#')
2061                         continue;
2062
2063                 /* Split */
2064
2065                 int nargc = argc;
2066                 char *p = line + strspn(line, " \t\n");
2067                 char *next = strtok(p, " \t\n");
2068
2069                 while(p && *p) {
2070                         if(nargc >= maxargs) {
2071                                 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2072                                 abort();
2073                                 maxargs *= 2;
2074                                 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2075                         }
2076
2077                         nargv[nargc++] = p;
2078                         p = next;
2079                         next = strtok(NULL, " \t\n");
2080                 }
2081
2082                 if(nargc == argc)
2083                         continue;
2084
2085                 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2086                         return result;
2087
2088                 bool found = false;
2089
2090                 for(int i = 0; commands[i].command; i++) {
2091                         if(!strcasecmp(nargv[argc], commands[i].command)) {
2092                                 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2093                                 found = true;
2094                                 break;
2095                         }
2096                 }
2097
2098 #ifdef HAVE_READLINE
2099                 if(tty && found)
2100                         add_history(copy);
2101 #endif
2102
2103                 if(!found) {
2104                         fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2105                         result |= 1;
2106                 }
2107         }
2108
2109         if(tty)
2110                 printf("\n");
2111         return result;
2112 }
2113
2114
2115 int main(int argc, char *argv[]) {
2116         program_name = argv[0];
2117         orig_argv = argv;
2118         orig_argc = argc;
2119
2120         if(!parse_options(argc, argv))
2121                 return 1;
2122         
2123         make_names();
2124
2125         if(show_version) {
2126                 version();
2127                 return 0;
2128         }
2129
2130         if(show_help) {
2131                 usage(false);
2132                 return 0;
2133         }
2134
2135         tty = isatty(0) && isatty(1);
2136
2137         if(optind >= argc)
2138                 return cmd_shell(argc, argv);
2139
2140         for(int i = 0; commands[i].command; i++) {
2141                 if(!strcasecmp(argv[optind], commands[i].command))
2142                         return commands[i].function(argc - optind, argv + optind);
2143         }
2144
2145         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
2146         usage(true);
2147         return 1;
2148 }