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
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.
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.
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.
27 /*----- Header files ------------------------------------------------------*/
39 #include <sys/types.h>
46 #include <sys/socket.h>
48 #include <arpa/inet.h>
51 #include <mLib/alloc.h>
52 #include <mLib/daemonize.h>
53 #include <mLib/darray.h>
54 #include <mLib/dstr.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>
68 #define IGNORE(x) do if (x); while (0)
70 /*----- Data structures ---------------------------------------------------*/
74 DA_DECL(string_v, char *);
77 /*----- Static variables --------------------------------------------------*/
80 static const char *pidfile = 0;
81 static const char *logname = 0;
82 static FILE *logfp = 0;
83 static unsigned f = 0;
85 static const char *bgtag = 0;
90 #define f_spawnopts 8u
98 /*----- Main code ---------------------------------------------------------*/
100 static void reap(int sig)
103 while (waitpid(-1, 0, WNOHANG) > 0)
108 static void writelog(const char *cat, const char *msg)
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);
117 static void checkbg(char **p)
119 char *q = str_getword(p);
121 die(EXIT_FAILURE, "missing background tag");
122 if (!bgtag || strcmp(bgtag, q) != 0)
123 die(EXIT_FAILURE, "unexpected background tag `%s'", q);
126 static void dolog(int prio, const char *msg, ...)
133 dstr_vputf(&d, msg, &ap);
135 if (f & f_syslog) syslog(prio, "%s", d.buf);
138 case LOG_WARNING: cat = "warning"; break;
139 case LOG_DEBUG: cat = "debug"; break;
140 case LOG_ERR: cat = "error"; break;
141 default: cat = "message"; break;
143 writelog(cat, d.buf);
145 if (prio == LOG_WARNING && (f & f_warn))
146 fprintf(stderr, "Warning: %s\n", d.buf);
150 static void checkfg(void)
151 { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
153 static void cline(char *p, size_t len, void *b)
158 die(EXIT_FAILURE, "server dropped the connection");
165 if (strcmp(q, "WARN") == 0)
166 dolog(LOG_WARNING, p);
167 else if (strcmp(q, "TRACE") == 0)
169 else if (!(f & f_command))
170 dolog(LOG_ERR, "unexpected output `%s %s'", q, p);
171 else if (strcmp(q, "FAIL") == 0) {
173 die(EXIT_FAILURE, "%s", p);
174 } else if (strcmp(q, "INFO") == 0) {
178 } else if (strcmp(q, "OK") == 0) {
181 } else if (strcmp(q, "BGDETACH") == 0) {
183 die(EXIT_FAILURE, "repeat detach");
185 } else if (strcmp(q, "BGOK") == 0) {
188 } else if (strcmp(q, "BGINFO") == 0) {
192 } else if (strcmp(q, "BGFAIL") == 0) {
194 die(EXIT_FAILURE, "%s", p);
196 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
199 static void sline(char *p, size_t len, void *b)
203 moan("server closed the connection");
210 static void uline(char *p, size_t len, void *b)
219 if (write(fd, p, len + 1) != len + 1)
220 moan("write failed: %s", strerror(errno));
224 static void eline(char *p, size_t len, void *b)
227 dolog(LOG_WARNING, "(stderr): %s", p);
234 static void setup(const char *cmd)
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));
250 n = read(fd, &ch, 1);
252 die(EXIT_FAILURE, "unexpected EOF during setup");
254 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
255 cmd, strerror(errno));
264 else if (strcmp(q, "OK") == 0)
266 else if (strcmp(q, "FAIL") == 0)
267 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
273 static void logfile(const char *name)
277 if ((fp = fopen(name, "a")) != 0) {
281 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
284 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
286 writelog("error", d.buf);
288 die(EXIT_FAILURE, d.buf);
290 syslog(LOG_ERR, "%s", d.buf);
295 static void sighup(int sig, void *v) { logfile(logname); }
297 static void cleanup(void) { if (pidfile) unlink(pidfile); }
299 static void sigdie(int sig)
300 { cleanup(); signal(sig, SIG_DFL); raise(sig); }
302 static void putarg(string_v *av, const char *fmt, ...)
308 dstr_vputf(&d, fmt, &ap);
311 DA_UNSHIFT(av, xstrdup(d.buf));
315 static void version(FILE *fp)
316 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
318 static void usage(FILE *fp)
322 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
323 $ [-Dl] [-f FILE] [-OPTIONS]\n\
325 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
326 [-p PROGRAM] [-S ARG,ARG,...]\n\
330 static void help(FILE *fp)
339 -h, --help Show this help text.\n\
340 -v, --version Show version number.\n\
341 -u, --usage Show brief usage message.\n\
343 -D, --daemon Become a background task after connecting.\n\
344 -d, --directory=DIR Select current directory [default " CONFIGDIR "].\n\
345 -U, --setuid=USER Set uid to USER after initialization.\n\
346 -G, --setgid=GROUP Set gid to GROUP after initialization.\n\
347 -a, --admin-socket=FILE Select socket to connect to\n\
348 [default " SOCKETDIR "/tripesock].\n\
349 -P, --pidfile=FILE Write process-id to FILE.\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\
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\
361 int main(int argc, char *argv[])
363 const char *dir = CONFIGDIR;
364 const char *sock = SOCKETDIR "/tripesock";
365 const char *spawnpath = "tripe";
366 string_v spawnopts = DA_INIT;
377 sigset_t newmask, oldmask;
378 struct sockaddr_un sun;
385 if ((p = getenv("TRIPEDIR")) != 0)
387 if ((p = getenv("TRIPESOCK")) != 0)
390 /* --- Parse the arguments --- */
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' },
398 { "uid", OPTF_ARGREQ, 0, 'U' },
399 { "setuid", OPTF_ARGREQ, 0, 'U' },
400 { "gid", OPTF_ARGREQ, 0, 'G' },
401 { "setgid", OPTF_ARGREQ, 0, 'G' },
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' },
410 { "pidfile", OPTF_ARGREQ, 0, 'P' },
414 i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:", opts, 0, 0, 0);
428 f |= f_daemon | f_noinput;
431 u = u_getuser(optarg, &g);
434 g = u_getgroup(optarg);
450 f |= f_spawn | f_spawnopts;
451 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
452 DA_PUSH(&spawnopts, p);
455 f |= f_syslog | f_noinput;
472 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
477 /* --- Set various things up --- */
480 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
481 dir, strerror(errno));
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));
491 signal(SIGINT, sigdie);
492 signal(SIGQUIT, sigdie);
493 signal(SIGTERM, sigdie);
496 /* --- Connect to the server --- */
499 sa.sa_handler = reap;
500 sigemptyset(&sa.sa_mask);
501 sa.sa_flags = SA_NOCLDSTOP;
503 sa.sa_flags |= SA_RESTART;
505 sigaction(SIGCHLD, &sa, 0);
507 DA_PUSH(&spawnopts, 0);
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);
510 putarg(&spawnopts, "-a%s", sock);
511 putarg(&spawnopts, "-d.");
512 putarg(&spawnopts, "-F");
513 putarg(&spawnopts, "%s", spawnpath);
514 if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd) || pipe(efd))
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));
522 close(pfd[0]); close(efd[0]);
523 sigprocmask(SIG_SETMASK, &oldmask, 0);
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;
528 if (pidfp) fclose(pidfp);
530 if (f & f_daemon) detachtty();
531 execvp(DA(&spawnopts)[0], DA(&spawnopts));
532 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
534 sigprocmask(SIG_SETMASK, &oldmask, 0);
536 close(pfd[1]); close(efd[1]);
537 selbuf_init(&be, &sel, efd[0], eline, &be);
539 sz = strlen(sock) + 1;
540 if (sz > sizeof(sun.sun_path))
541 die(EXIT_FAILURE, "socket name `%s' too long", sock);
542 memset(&sun, 0, sizeof(sun));
543 sun.sun_family = AF_UNIX;
544 memcpy(sun.sun_path, sock, sz);
545 sz = sz + offsetof(struct sockaddr_un, sun_path);
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",
550 sun.sun_path, strerror(errno));
554 f |= f_losing; /* pessimism */
560 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
563 fprintf(pidfp, "%li\n", (long)getpid());
566 signal(SIGPIPE, SIG_IGN);
568 /* --- If we're meant to be interactive, do that --- */
571 setup("WATCH -A+tw");
572 if (!(f & f_noinput) && optind == argc) {
573 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
574 selbuf_init(&bs, &sel, fd, sline, &bs);
576 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
577 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
581 /* --- If there's a command, submit it --- */
584 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
585 while (optind < argc)
586 u_quotify(&d, argv[optind++]);
589 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
590 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
595 /* --- Pull everything else out of the box --- */
597 selbuf_init(&bs, &sel, fd, cline, 0);
600 openlog(QUIS, 0, LOG_DAEMON);
602 sig_add(&hup, SIGHUP, sighup, 0);
604 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
605 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
611 /*----- That's all, folks -------------------------------------------------*/