5 * (c) 2001 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Trivial IP Encryption (TrIPE).
12 * TrIPE is free software: you can redistribute it and/or modify it under
13 * the terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your
15 * option) any later version.
17 * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * You should have received a copy of the GNU General Public License
23 * along with TrIPE. If not, see <https://www.gnu.org/licenses/>.
26 /*----- Header files ------------------------------------------------------*/
38 #include <sys/types.h>
45 #include <sys/socket.h>
47 #include <arpa/inet.h>
50 #include <mLib/alloc.h>
51 #include <mLib/daemonize.h>
52 #include <mLib/darray.h>
53 #include <mLib/dstr.h>
54 #include <mLib/macros.h>
55 #include <mLib/mdup.h>
56 #include <mLib/mdwopt.h>
57 #include <mLib/quis.h>
58 #include <mLib/report.h>
60 #include <mLib/selbuf.h>
63 #include <mLib/versioncmp.h>
69 /*----- Data structures ---------------------------------------------------*/
73 DA_DECL(string_v, char *);
76 /*----- Static variables --------------------------------------------------*/
79 static const char *pidfile = 0;
80 static const char *logname = 0;
81 static FILE *logfp = 0;
82 static unsigned f = 0;
83 static const char *watch = 0;
85 static const char *bgtag = 0;
90 #define f_spawnopts 8u
97 #define f_nostamp 1024u
99 /*----- Main code ---------------------------------------------------------*/
101 static void reap(int sig)
104 while (waitpid(-1, 0, WNOHANG) > 0)
109 static void writelog(const char *cat, const char *msg)
113 struct tm *tm = localtime(&t);
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);
119 static void checkbg(char **p)
121 char *q = str_getword(p);
123 die(EXIT_FAILURE, "missing background tag");
124 if (!bgtag || strcmp(bgtag, q) != 0)
125 die(EXIT_FAILURE, "unexpected background tag `%s'", q);
128 static void PRINTF_LIKE(2, 3) dolog(int prio, const char *msg, ...)
135 dstr_vputf(&d, msg, &ap);
137 if (f & f_syslog) syslog(prio, "%s", d.buf);
140 case LOG_WARNING: cat = "warning"; break;
141 case LOG_DEBUG: cat = "debug"; break;
142 case LOG_ERR: cat = "error"; break;
143 default: cat = "message"; break;
145 writelog(cat, d.buf);
147 if (prio == LOG_WARNING && (f & f_warn))
148 fprintf(stderr, "Warning: %s\n", d.buf);
152 static void checkfg(void)
153 { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
155 static void cline(char *p, size_t len, void *b)
160 die(EXIT_FAILURE, "server dropped the connection");
167 if (strcmp(q, "WARN") == 0)
168 dolog(LOG_WARNING, "%s", p);
169 else if (strcmp(q, "TRACE") == 0)
170 dolog(LOG_DEBUG, "%s", p);
171 else if (!(f & f_command))
172 dolog(LOG_ERR, "unexpected output `%s %s'", q, p);
173 else if (strcmp(q, "FAIL") == 0) {
175 die(EXIT_FAILURE, "%s", p);
176 } else if (strcmp(q, "INFO") == 0) {
180 } else if (strcmp(q, "OK") == 0) {
183 } else if (strcmp(q, "BGDETACH") == 0) {
185 die(EXIT_FAILURE, "repeat detach");
187 } else if (strcmp(q, "BGOK") == 0) {
190 } else if (strcmp(q, "BGINFO") == 0) {
194 } else if (strcmp(q, "BGFAIL") == 0) {
196 die(EXIT_FAILURE, "%s", p);
198 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
201 static void sline(char *p, size_t len, void *b)
205 moan("server closed the connection");
212 static void uline(char *p, size_t len, void *b)
221 if (write(fd, p, len + 1) != len + 1)
222 moan("write failed: %s", strerror(errno));
226 static void eline(char *p, size_t len, void *b)
229 dolog(LOG_WARNING, "(stderr): %s", p);
236 static void setup(const char *cmd)
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));
252 n = read(fd, &ch, 1);
254 die(EXIT_FAILURE, "unexpected EOF during setup");
256 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
257 cmd, strerror(errno));
266 else if (strcmp(q, "OK") == 0)
268 else if (strcmp(q, "FAIL") == 0)
269 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
275 static void logfile(const char *name)
279 if (strcmp(name, "-") == 0)
281 else if (strcmp(name, "!") == 0)
283 else if ((fp = fopen(name, "a")) != 0) {
287 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
290 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
292 writelog("error", d.buf);
294 die(EXIT_FAILURE, "%s", d.buf);
296 syslog(LOG_ERR, "%s", d.buf);
301 static void sighup(int sig, void *v) { logfile(logname); }
303 static void cleanup(void) { if (pidfile) unlink(pidfile); }
305 static void sigdie(int sig)
306 { cleanup(); signal(sig, SIG_DFL); raise(sig); }
308 static void PRINTF_LIKE(2, 3) putarg(string_v *av, const char *fmt, ...)
314 dstr_vputf(&d, fmt, &ap);
317 DA_UNSHIFT(av, xstrdup(d.buf));
321 static void version(FILE *fp)
322 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
324 static void usage(FILE *fp)
328 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
329 $ [-Dl] [-f FILE] [-OPTIONS]\n\
331 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
332 [-p PROGRAM] [-S ARG,ARG,...]\n\
336 static void help(FILE *fp)
345 -h, --help Show this help text.\n\
346 -v, --version Show version number.\n\
347 -u, --usage Show brief usage message.\n\
349 -D, --daemon Become a background task after connecting.\n\
350 -d, --directory=DIR Select current directory [default " CONFIGDIR "].\n\
351 -U, --setuid=USER Set uid to USER after initialization.\n\
352 -G, --setgid=GROUP Set gid to GROUP after initialization.\n\
353 -a, --admin-socket=FILE Select socket to connect to\n\
354 [default " SOCKETDIR "/tripesock].\n\
355 -P, --pidfile=FILE Write process-id to FILE.\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\
361 -l, --syslog Log messages to system log.\n\
362 -f, --logfile=FILE Log messages to FILE.\n\
363 -t, --no-timestamp When logging to a file, don't emit timestamps.\n\
364 -w, --warnings Show warnings when running commands.\n\
365 -W, --watch=THINGS Watch for THINGS after connecting.\n\
369 int main(int argc, char *argv[])
371 const char *dir = CONFIGDIR;
372 const char *sock = SOCKETDIR "/tripesock";
373 const char *spawnpath = "tripe";
374 string_v spawnopts = DA_INIT;
385 sigset_t newmask, oldmask;
386 struct sockaddr_un sun;
393 if ((p = getenv("TRIPEDIR")) != 0)
395 if ((p = getenv("TRIPESOCK")) != 0)
398 /* --- Parse the arguments --- */
401 static const struct option opts[] = {
402 { "help", 0, 0, 'h' },
403 { "version", 0, 0, 'v' },
404 { "usage", 0, 0, 'u' },
405 { "daemon", 0, 0, 'D' },
406 { "uid", OPTF_ARGREQ, 0, 'U' },
407 { "setuid", OPTF_ARGREQ, 0, 'U' },
408 { "gid", OPTF_ARGREQ, 0, 'G' },
409 { "setgid", OPTF_ARGREQ, 0, 'G' },
410 { "directory", OPTF_ARGREQ, 0, 'd' },
411 { "admin-socket", OPTF_ARGREQ, 0, 'a' },
412 { "spawn", 0, 0, 's' },
413 { "spawn-path", OPTF_ARGREQ, 0, 'p' },
414 { "spawn-args", OPTF_ARGREQ, 0, 'S' },
415 { "syslog", 0, 0, 'l' },
416 { "logfile", OPTF_ARGREQ, 0, 'f' },
417 { "no-timestamp", 0, 0, 't' },
418 { "warnings", 0, 0, 'w' },
419 { "watch", OPTF_ARGREQ, 0, 'W' },
420 { "pidfile", OPTF_ARGREQ, 0, 'P' },
424 i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwW:f:nP:t", opts, 0, 0, 0);
438 f |= f_daemon | f_noinput;
441 u = u_getuser(optarg, &g);
444 g = u_getgroup(optarg);
460 f |= f_spawn | f_spawnopts;
461 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
462 DA_PUSH(&spawnopts, p);
465 f |= f_syslog | f_noinput;
488 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
493 /* --- Set various things up --- */
496 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
497 dir, strerror(errno));
499 if (!pidfile && (f & f_daemon) && ((f & f_syslog) || logname))
500 pidfile = "tripectl.pid";
501 if (pidfile && (pidfp = fopen(pidfile, "w")) == 0) {
502 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
503 pidfile, strerror(errno));
507 signal(SIGINT, sigdie);
508 signal(SIGQUIT, sigdie);
509 signal(SIGTERM, sigdie);
512 /* --- Connect to the server --- */
515 sa.sa_handler = reap;
516 sigemptyset(&sa.sa_mask);
517 sa.sa_flags = SA_NOCLDSTOP;
519 sa.sa_flags |= SA_RESTART;
521 sigaction(SIGCHLD, &sa, 0);
523 DA_PUSH(&spawnopts, 0);
524 if (g != (gid_t)-1) putarg(&spawnopts, "-G%lu", (unsigned long)g);
525 if (u != (uid_t)-1) putarg(&spawnopts, "-U%lu", (unsigned long)u);
526 putarg(&spawnopts, "-a%s", sock);
527 putarg(&spawnopts, "-d.");
528 putarg(&spawnopts, "-F");
529 putarg(&spawnopts, "%s", spawnpath);
530 if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd) || pipe(efd))
531 die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
532 sigemptyset(&newmask);
533 sigaddset(&newmask, SIGCHLD);
534 sigprocmask(SIG_BLOCK, &newmask, &oldmask);
535 if ((kid = fork()) < 0)
536 die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
538 close(pfd[0]); close(efd[0]);
539 sigprocmask(SIG_SETMASK, &oldmask, 0);
540 md[0].cur = pfd[1]; md[0].want = STDIN_FILENO;
541 md[1].cur = pfd[1]; md[1].want = STDOUT_FILENO;
542 md[2].cur = efd[1]; md[2].want = STDERR_FILENO;
544 if (pidfp) fclose(pidfp);
546 if (f & f_daemon) detachtty();
547 execvp(DA(&spawnopts)[0], DA(&spawnopts));
548 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
550 sigprocmask(SIG_SETMASK, &oldmask, 0);
552 close(pfd[1]); close(efd[1]);
553 selbuf_init(&be, &sel, efd[0], eline, &be);
555 sz = strlen(sock) + 1;
556 if (sz > sizeof(sun.sun_path))
557 die(EXIT_FAILURE, "socket name `%s' too long", sock);
558 memset(&sun, 0, sizeof(sun));
559 sun.sun_family = AF_UNIX;
560 memcpy(sun.sun_path, sock, sz);
561 sz = sz + offsetof(struct sockaddr_un, sun_path);
562 if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
563 die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
564 if (connect(fd, (struct sockaddr *)&sun, sz)) {
565 die(EXIT_FAILURE, "error connecting to `%s': %s",
566 sun.sun_path, strerror(errno));
570 f |= f_losing; /* pessimism */
576 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
579 fprintf(pidfp, "%li\n", (long)getpid());
582 signal(SIGPIPE, SIG_IGN);
584 /* --- If we're meant to be interactive, do that --- */
586 if (optind == argc) {
588 dstr_puts(&d, "watch");
589 u_quotify(&d, watch ? watch : "-A+tw");
592 if (!(f & f_noinput) && optind == argc) {
593 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
594 selbuf_init(&bs, &sel, fd, sline, &bs);
596 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
597 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
601 /* --- If there's a command, submit it --- */
605 dstr_puts(&d, "watch");
606 u_quotify(&d, watch ? watch : (f & f_warn) ? "-A+w" : "-A");
609 while (optind < argc)
610 u_quotify(&d, argv[optind++]);
613 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
614 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
619 /* --- Pull everything else out of the box --- */
621 selbuf_init(&bs, &sel, fd, cline, 0);
624 openlog(QUIS, 0, LOG_DAEMON);
626 sig_add(&hup, SIGHUP, sighup, 0);
628 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
629 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
635 /*----- That's all, folks -------------------------------------------------*/