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