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