chiark / gitweb /
svc/tripe-ifup.in: Trim prefix length from IPv6 address used as gateway.
[tripe] / client / tripectl.c
CommitLineData
410c8acf 1/* -*-c-*-
410c8acf 2 *
3 * Client for TrIPE
4 *
5 * (c) 2001 Straylight/Edgeware
6 */
7
e04c2d50 8/*----- Licensing notice --------------------------------------------------*
410c8acf 9 *
10 * This file is part of Trivial IP Encryption (TrIPE).
11 *
12 * TrIPE is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
e04c2d50 16 *
410c8acf 17 * TrIPE is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
e04c2d50 21 *
410c8acf 22 * You should have received a copy of the GNU General Public License
23 * along with TrIPE; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 */
26
410c8acf 27/*----- Header files ------------------------------------------------------*/
28
73189848 29#include "config.h"
30
410c8acf 31#include <ctype.h>
32#include <errno.h>
33#include <signal.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37#include <time.h>
38
39#include <sys/types.h>
40#include <sys/time.h>
41#include <unistd.h>
42#include <fcntl.h>
43#include <sys/wait.h>
44#include <syslog.h>
45
46#include <sys/socket.h>
47#include <sys/un.h>
48#include <arpa/inet.h>
49#include <netdb.h>
50
51#include <mLib/alloc.h>
19dd2531 52#include <mLib/daemonize.h>
410c8acf 53#include <mLib/darray.h>
54#include <mLib/dstr.h>
ddb384f1 55#include <mLib/macros.h>
b9537f3b 56#include <mLib/mdup.h>
410c8acf 57#include <mLib/mdwopt.h>
58#include <mLib/quis.h>
59#include <mLib/report.h>
60#include <mLib/sel.h>
61#include <mLib/selbuf.h>
5f5150b1 62#include <mLib/sig.h>
410c8acf 63#include <mLib/str.h>
19dd2531 64#include <mLib/versioncmp.h>
410c8acf 65
66#include "util.h"
67
68#undef sun
69
70/*----- Data structures ---------------------------------------------------*/
71
72#ifndef STRING_V
73# define STRING_V
74 DA_DECL(string_v, char *);
75#endif
76
77/*----- Static variables --------------------------------------------------*/
78
8efdf64b 79static sel_state sel;
06b2a088 80static const char *pidfile = 0;
81static const char *logname = 0;
410c8acf 82static FILE *logfp = 0;
83static unsigned f = 0;
84static int fd;
de014da6 85static const char *bgtag = 0;
410c8acf 86
87#define f_bogus 1u
88#define f_spawn 2u
89#define f_daemon 4u
90#define f_spawnopts 8u
91#define f_syslog 16u
92#define f_command 32u
93#define f_noinput 64u
94#define f_warn 128u
95#define f_uclose 256u
1a372224 96#define f_losing 512u
ae8928d2 97#define f_nostamp 1024u
410c8acf 98
99/*----- Main code ---------------------------------------------------------*/
100
101static void reap(int sig)
102{
410c8acf 103 int e = errno;
06b2a088 104 while (waitpid(-1, 0, WNOHANG) > 0)
410c8acf 105 ;
106 errno = e;
107}
108
109static void writelog(const char *cat, const char *msg)
110{
111 char buf[256];
112 time_t t = time(0);
113 struct tm *tm = localtime(&t);
ae8928d2
MW
114 if (f & f_nostamp) buf[0] = 0;
115 else strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S ", tm);
116 fprintf(logfp, "%s%s: %s\n", buf, cat, msg);
410c8acf 117}
118
de014da6 119static void checkbg(char **p)
120{
121 char *q = str_getword(p);
122 if (!q)
123 die(EXIT_FAILURE, "missing background tag");
124 if (!bgtag || strcmp(bgtag, q) != 0)
125 die(EXIT_FAILURE, "unexpected background tag `%s'", q);
126}
127
ddb384f1 128static void PRINTF_LIKE(2, 3) dolog(int prio, const char *msg, ...)
2b3ef395
MW
129{
130 va_list ap;
131 dstr d = DSTR_INIT;
132 const char *cat;
133
134 va_start(ap, msg);
135 dstr_vputf(&d, msg, &ap);
136 va_end(ap);
137 if (f & f_syslog) syslog(prio, "%s", d.buf);
138 if (logfp) {
139 switch (prio) {
155a970a 140 case LOG_WARNING: cat = "warning"; break;
2b3ef395
MW
141 case LOG_DEBUG: cat = "debug"; break;
142 case LOG_ERR: cat = "error"; break;
143 default: cat = "message"; break;
144 }
145 writelog(cat, d.buf);
146 }
155a970a 147 if (prio == LOG_WARNING && (f & f_warn))
2b3ef395
MW
148 fprintf(stderr, "Warning: %s\n", d.buf);
149 dstr_destroy(&d);
150}
151
de014da6 152static void checkfg(void)
6047fbac 153 { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
de014da6 154
6be88c14 155static void cline(char *p, size_t len, void *b)
410c8acf 156{
157 char *q;
158 if (!p) {
159 if (f & f_command)
160 die(EXIT_FAILURE, "server dropped the connection");
1a372224 161 f &= ~f_losing;
410c8acf 162 exit(0);
163 }
164 q = str_getword(&p);
165 if (!q)
166 return;
2b3ef395 167 if (strcmp(q, "WARN") == 0)
f7a19d39 168 dolog(LOG_WARNING, "%s", p);
2b3ef395 169 else if (strcmp(q, "TRACE") == 0)
f7a19d39 170 dolog(LOG_DEBUG, "%s", p);
2b3ef395
MW
171 else if (!(f & f_command))
172 dolog(LOG_ERR, "unexpected output `%s %s'", q, p);
173 else if (strcmp(q, "FAIL") == 0) {
de014da6 174 checkfg();
410c8acf 175 die(EXIT_FAILURE, "%s", p);
de014da6 176 } else if (strcmp(q, "INFO") == 0) {
177 checkfg();
410c8acf 178 puts(p);
5136c31e 179 fflush(stdout);
de014da6 180 } else if (strcmp(q, "OK") == 0) {
181 checkfg();
182 exit(0);
183 } else if (strcmp(q, "BGDETACH") == 0) {
184 if (bgtag)
185 die(EXIT_FAILURE, "repeat detach");
186 bgtag = xstrdup(p);
187 } else if (strcmp(q, "BGOK") == 0) {
188 checkbg(&p);
410c8acf 189 exit(0);
de014da6 190 } else if (strcmp(q, "BGINFO") == 0) {
191 checkbg(&p);
192 puts(p);
5136c31e 193 fflush(stdout);
de014da6 194 } else if (strcmp(q, "BGFAIL") == 0) {
195 checkbg(&p);
196 die(EXIT_FAILURE, "%s", p);
197 } else
e04c2d50 198 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
410c8acf 199}
200
6be88c14 201static void sline(char *p, size_t len, void *b)
410c8acf 202{
203 if (!p) {
204 if (!(f & f_uclose))
205 moan("server closed the connection");
206 exit(0);
207 }
208 puts(p);
5136c31e 209 fflush(stdout);
410c8acf 210}
211
6be88c14 212static void uline(char *p, size_t len, void *b)
410c8acf 213{
410c8acf 214 if (!p) {
215 selbuf_destroy(b);
216 shutdown(fd, 1);
217 f |= f_uclose;
218 } else {
6be88c14 219 p[len] = '\n';
3cdc3f3a 220 errno = EIO;
221 if (write(fd, p, len + 1) != len + 1)
222 moan("write failed: %s", strerror(errno));
223 }
224}
225
155a970a
MW
226static void eline(char *p, size_t len, void *b)
227{
228 if (p)
229 dolog(LOG_WARNING, "(stderr): %s", p);
230 else {
231 selbuf_destroy(b);
232 close(fd);
233 }
234}
235
3cdc3f3a 236static void setup(const char *cmd)
237{
238 dstr d = DSTR_INIT;
239 char ch;
240 char *p, *q;
241 int n;
242
243 dstr_puts(&d, cmd);
244 dstr_putc(&d, '\n');
245 errno = EIO; /* Relax: be vague */
246 if (write(fd, d.buf, d.len) != d.len) {
247 die(EXIT_FAILURE, "error sending setup command `%s': %s",
248 cmd, strerror(errno));
249 }
250 dstr_reset(&d);
251 for (;;) {
252 n = read(fd, &ch, 1);
253 if (!n)
254 die(EXIT_FAILURE, "unexpected EOF during setup");
255 if (n < 0) {
256 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
257 cmd, strerror(errno));
258 }
259 if (d.len < 256)
260 dstr_putc(&d, ch);
261 if (ch == '\n') {
262 p = d.buf;
263 q = str_getword(&p);
264 if (!q)
265 ;
266 else if (strcmp(q, "OK") == 0)
267 return;
268 else if (strcmp(q, "FAIL") == 0)
269 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
270 dstr_reset(&d);
271 }
410c8acf 272 }
273}
274
9dd01bc6 275static void logfile(const char *name)
276{
fa4bef80 277 FILE *fp;
278
ae8928d2
MW
279 if (strcmp(name, "-") == 0)
280 logfp = stdout;
281 else if (strcmp(name, "!") == 0)
282 logfp = stderr;
283 else if ((fp = fopen(name, "a")) != 0) {
fa4bef80 284 if (logfp)
285 fclose(logfp);
286 logfp = fp;
287 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
288 } else {
289 dstr d = DSTR_INIT;
290 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
291 if (logfp)
292 writelog("error", d.buf);
293 else if (logname)
f7a19d39 294 die(EXIT_FAILURE, "%s", d.buf);
fa4bef80 295 if (f & f_syslog)
92e57abc 296 syslog(LOG_ERR, "%s", d.buf);
fa4bef80 297 dstr_destroy(&d);
9dd01bc6 298 }
9dd01bc6 299}
300
f98df549 301static void sighup(int sig, void *v) { logfile(logname); }
5f5150b1 302
6047fbac 303static void cleanup(void) { if (pidfile) unlink(pidfile); }
06b2a088 304
305static void sigdie(int sig)
6047fbac 306 { cleanup(); signal(sig, SIG_DFL); raise(sig); }
06b2a088 307
ddb384f1 308static void PRINTF_LIKE(2, 3) putarg(string_v *av, const char *fmt, ...)
f685e692
MW
309{
310 va_list ap;
311 dstr d = DSTR_INIT;
312
313 va_start(ap, fmt);
314 dstr_vputf(&d, fmt, &ap);
315 dstr_putz(&d);
316 va_end(ap);
317 DA_UNSHIFT(av, xstrdup(d.buf));
318 dstr_destroy(&d);
319}
320
410c8acf 321static void version(FILE *fp)
f98df549 322 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
410c8acf 323
324static void usage(FILE *fp)
325{
326 pquis(fp, "\
327Usage:\n\
2d752320 328 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
329 $ [-Dl] [-f FILE] [-OPTIONS]\n\
410c8acf 330Options:\n\
2d752320 331 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
332 [-p PROGRAM] [-S ARG,ARG,...]\n\
410c8acf 333");
334}
335
336static void help(FILE *fp)
337{
338 version(fp);
339 fputc('\n', fp);
340 usage(fp);
341 fputs("\
342\n\
343Options in full:\n\
344\n\
345-h, --help Show this help text.\n\
346-v, --version Show version number.\n\
347-u, --usage Show brief usage message.\n\
348\n\
349-D, --daemon Become a background task after connecting.\n\
ef4a1ab7 350-d, --directory=DIR Select current directory [default " CONFIGDIR "].\n\
ab46a787
MW
351-U, --setuid=USER Set uid to USER after initialization.\n\
352-G, --setgid=GROUP Set gid to GROUP after initialization.\n\
3cdc3f3a 353-a, --admin-socket=FILE Select socket to connect to\n\
e04c2d50 354 [default " SOCKETDIR "/tripesock].\n\
06b2a088 355-P, --pidfile=FILE Write process-id to FILE.\n\
410c8acf 356\n\
357-s, --spawn Start server rather than connecting.\n\
358-p, --spawn-path=PATH Specify path to executable.\n\
359-S, --spawn-args=ARGS Specify comma-separated arguments.\n\
360\n\
361-l, --syslog Log messages to system log.\n\
362-f, --logfile=FILE Log messages to FILE.\n\
ae8928d2 363-t, --no-timestamp When logging to a file, don't emit timestamps.\n\
410c8acf 364-w, --warnings Show warnings when running commands.\n\
365", fp);
366}
367
368int main(int argc, char *argv[])
369{
ef4a1ab7 370 const char *dir = CONFIGDIR;
371 const char *sock = SOCKETDIR "/tripesock";
410c8acf 372 const char *spawnpath = "tripe";
373 string_v spawnopts = DA_INIT;
374 char *p;
06b2a088 375 FILE *pidfp = 0;
8efdf64b
MW
376 int i;
377 size_t sz;
ab46a787
MW
378 uid_t u = -1;
379 gid_t g = -1;
155a970a 380 int pfd[2], efd[2];
b9537f3b 381 mdup_fd md[3];
8efdf64b
MW
382 pid_t kid;
383 struct sigaction sa;
384 sigset_t newmask, oldmask;
385 struct sockaddr_un sun;
155a970a 386 selbuf bu, bs, be;
8efdf64b
MW
387 dstr d = DSTR_INIT;
388 sig hup;
410c8acf 389
390 ego(argv[0]);
391
392 if ((p = getenv("TRIPEDIR")) != 0)
393 dir = p;
797cf76b
MW
394 if ((p = getenv("TRIPESOCK")) != 0)
395 sock = p;
410c8acf 396
397 /* --- Parse the arguments --- */
398
399 for (;;) {
400 static const struct option opts[] = {
401 { "help", 0, 0, 'h' },
402 { "version", 0, 0, 'v' },
403 { "usage", 0, 0, 'u' },
404 { "daemon", 0, 0, 'D' },
ab46a787
MW
405 { "uid", OPTF_ARGREQ, 0, 'U' },
406 { "setuid", OPTF_ARGREQ, 0, 'U' },
407 { "gid", OPTF_ARGREQ, 0, 'G' },
408 { "setgid", OPTF_ARGREQ, 0, 'G' },
410c8acf 409 { "directory", OPTF_ARGREQ, 0, 'd' },
410 { "admin-socket", OPTF_ARGREQ, 0, 'a' },
411 { "spawn", 0, 0, 's' },
412 { "spawn-path", OPTF_ARGREQ, 0, 'p' },
413 { "spawn-args", OPTF_ARGREQ, 0, 'S' },
414 { "syslog", 0, 0, 'l' },
415 { "logfile", OPTF_ARGREQ, 0, 'f' },
ae8928d2 416 { "no-timestamp", 0, 0, 't' },
410c8acf 417 { "warnings", 0, 0, 'w' },
06b2a088 418 { "pidfile", OPTF_ARGREQ, 0, 'P' },
410c8acf 419 { 0, 0, 0, 0 }
420 };
421
ae8928d2 422 i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:t", opts, 0, 0, 0);
410c8acf 423 if (i < 0)
424 break;
425 switch (i) {
426 case 'h':
427 help(stdout);
428 exit(0);
429 case 'v':
430 version(stdout);
431 exit(0);
432 case 'u':
433 usage(stdout);
434 exit(0);
435 case 'D':
436 f |= f_daemon | f_noinput;
437 break;
ab46a787
MW
438 case 'U':
439 u = u_getuser(optarg, &g);
440 break;
441 case 'G':
442 g = u_getgroup(optarg);
443 break;
410c8acf 444 case 'd':
445 dir = optarg;
446 break;
447 case 'a':
448 sock = optarg;
449 break;
450 case 's':
451 f |= f_spawn;
452 break;
453 case 'p':
454 f |= f_spawn;
455 spawnpath = optarg;
456 break;
457 case 'S':
458 f |= f_spawn | f_spawnopts;
459 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
460 DA_PUSH(&spawnopts, p);
461 break;
462 case 'l':
463 f |= f_syslog | f_noinput;
464 break;
465 case 'w':
466 f |= f_warn;
467 break;
468 case 'f':
9dd01bc6 469 logname = optarg;
410c8acf 470 f |= f_noinput;
471 break;
ae8928d2
MW
472 case 't':
473 f |= f_nostamp;
474 break;
06b2a088 475 case 'P':
476 pidfile = optarg;
477 break;
410c8acf 478 default:
479 f |= f_bogus;
480 break;
481 }
482 }
483 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
484 usage(stderr);
485 exit(EXIT_FAILURE);
486 }
487
06b2a088 488 /* --- Set various things up --- */
489
490 if (chdir(dir)) {
491 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
492 dir, strerror(errno));
493 }
06b2a088 494 if (!pidfile && (f & f_daemon) && ((f & f_syslog) || logname))
495 pidfile = "tripectl.pid";
496 if (pidfile && (pidfp = fopen(pidfile, "w")) == 0) {
497 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
498 pidfile, strerror(errno));
499 }
8efdf64b
MW
500 sel_init(&sel);
501 sig_init(&sel);
06b2a088 502 signal(SIGINT, sigdie);
503 signal(SIGQUIT, sigdie);
504 signal(SIGTERM, sigdie);
505 atexit(cleanup);
506
410c8acf 507 /* --- Connect to the server --- */
508
509 if (f & f_spawn) {
410c8acf 510 sa.sa_handler = reap;
511 sigemptyset(&sa.sa_mask);
512 sa.sa_flags = SA_NOCLDSTOP;
513#ifdef SA_RESTART
514 sa.sa_flags |= SA_RESTART;
515#endif
516 sigaction(SIGCHLD, &sa, 0);
517
410c8acf 518 DA_PUSH(&spawnopts, 0);
ab46a787
MW
519 if (g != (gid_t)-1) putarg(&spawnopts, "-G%lu", (unsigned long)g);
520 if (u != (uid_t)-1) putarg(&spawnopts, "-U%lu", (unsigned long)u);
f685e692
MW
521 putarg(&spawnopts, "-a%s", sock);
522 putarg(&spawnopts, "-d.");
523 putarg(&spawnopts, "-F");
524 putarg(&spawnopts, "%s", spawnpath);
155a970a 525 if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd) || pipe(efd))
410c8acf 526 die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
527 sigemptyset(&newmask);
528 sigaddset(&newmask, SIGCHLD);
529 sigprocmask(SIG_BLOCK, &newmask, &oldmask);
530 if ((kid = fork()) < 0)
531 die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
532 if (!kid) {
b9537f3b 533 close(pfd[0]); close(efd[0]);
0dba5cb9 534 sigprocmask(SIG_SETMASK, &oldmask, 0);
b9537f3b
MW
535 md[0].cur = pfd[1]; md[0].want = STDIN_FILENO;
536 md[1].cur = pfd[1]; md[1].want = STDOUT_FILENO;
537 md[2].cur = efd[1]; md[2].want = STDERR_FILENO;
538 mdup(md, 3);
6047fbac 539 if (pidfp) fclose(pidfp);
9dd01bc6 540 closelog();
6047fbac 541 if (f & f_daemon) detachtty();
410c8acf 542 execvp(DA(&spawnopts)[0], DA(&spawnopts));
543 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
544 }
545 sigprocmask(SIG_SETMASK, &oldmask, 0);
546 fd = pfd[0];
155a970a
MW
547 close(pfd[1]); close(efd[1]);
548 selbuf_init(&be, &sel, efd[0], eline, &be);
410c8acf 549 } else {
8efdf64b 550 sz = strlen(sock) + 1;
06b2a088 551 if (sz > sizeof(sun.sun_path))
410c8acf 552 die(EXIT_FAILURE, "socket name `%s' too long", sock);
553 memset(&sun, 0, sizeof(sun));
554 sun.sun_family = AF_UNIX;
06b2a088 555 memcpy(sun.sun_path, sock, sz);
556 sz = sz + offsetof(struct sockaddr_un, sun_path);
410c8acf 557 if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
558 die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
559 if (connect(fd, (struct sockaddr *)&sun, sz)) {
560 die(EXIT_FAILURE, "error connecting to `%s': %s",
9dd01bc6 561 sun.sun_path, strerror(errno));
410c8acf 562 }
563 }
564
1a372224 565 f |= f_losing; /* pessimism */
ab46a787 566 u_setugid(u, g);
1a372224
MW
567 if (logname)
568 logfile(logname);
410c8acf 569 if (f & f_daemon) {
19dd2531 570 if (daemonize())
410c8acf 571 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
572 }
06b2a088 573 if (pidfp) {
a803add7 574 fprintf(pidfp, "%li\n", (long)getpid());
06b2a088 575 fclose(pidfp);
576 }
3cdc3f3a 577 signal(SIGPIPE, SIG_IGN);
410c8acf 578
579 /* --- If we're meant to be interactive, do that --- */
580
3cdc3f3a 581 if (optind == argc)
582 setup("WATCH -A+tw");
410c8acf 583 if (!(f & f_noinput) && optind == argc) {
410c8acf 584 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
585 selbuf_init(&bs, &sel, fd, sline, &bs);
586 for (;;) {
5f5150b1 587 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
410c8acf 588 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
589 }
590 }
591
592 /* --- If there's a command, submit it --- */
593
594 if (optind < argc) {
3cdc3f3a 595 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
0ed0735f
MW
596 while (optind < argc)
597 u_quotify(&d, argv[optind++]);
410c8acf 598 dstr_putc(&d, '\n');
3cdc3f3a 599 errno = EIO;
600 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
601 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
410c8acf 602 dstr_destroy(&d);
603 f |= f_command;
604 }
605
606 /* --- Pull everything else out of the box --- */
607
8efdf64b 608 selbuf_init(&bs, &sel, fd, cline, 0);
5f5150b1 609
8efdf64b
MW
610 if (f & f_syslog)
611 openlog(QUIS, 0, LOG_DAEMON);
612 if (logfp)
613 sig_add(&hup, SIGHUP, sighup, 0);
614 for (;;) {
615 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
616 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
410c8acf 617 }
618
619 return (0);
620}
621
622/*----- That's all, folks -------------------------------------------------*/