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/mdwopt.h>
56 #include <mLib/quis.h>
57 #include <mLib/report.h>
59 #include <mLib/selbuf.h>
62 #include <mLib/versioncmp.h>
68 /*----- Data structures ---------------------------------------------------*/
72 DA_DECL(string_v, char *);
75 /*----- Static variables --------------------------------------------------*/
78 static const char *pidfile = 0;
79 static const char *logname = 0;
80 static FILE *logfp = 0;
81 static unsigned f = 0;
83 static const char *bgtag = 0;
88 #define f_spawnopts 8u
95 /*----- Main code ---------------------------------------------------------*/
97 static void reap(int sig)
100 while (waitpid(-1, 0, WNOHANG) > 0)
105 static void writelog(const char *cat, const char *msg)
109 struct tm *tm = localtime(&t);
110 strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
111 fprintf(logfp, "%s %s: %s\n", buf, cat, msg);
114 static void checkbg(char **p)
116 char *q = str_getword(p);
118 die(EXIT_FAILURE, "missing background tag");
119 if (!bgtag || strcmp(bgtag, q) != 0)
120 die(EXIT_FAILURE, "unexpected background tag `%s'", q);
123 static void dolog(int prio, const char *msg, ...)
130 dstr_vputf(&d, msg, &ap);
132 if (f & f_syslog) syslog(prio, "%s", d.buf);
135 case LOG_WARN: cat = "warning"; break;
136 case LOG_DEBUG: cat = "debug"; break;
137 case LOG_ERR: cat = "error"; break;
138 default: cat = "message"; break;
140 writelog(cat, d.buf);
142 if (prio == LOG_WARN && (f & f_warn))
143 fprintf(stderr, "Warning: %s\n", d.buf);
147 static void checkfg(void)
148 { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
150 static void cline(char *p, size_t len, void *b)
155 die(EXIT_FAILURE, "server dropped the connection");
161 if (strcmp(q, "WARN") == 0)
162 dolog(LOG_WARNING, p);
163 else if (strcmp(q, "TRACE") == 0)
165 else if (!(f & f_command))
166 dolog(LOG_ERR, "unexpected output `%s %s'", q, p);
167 else if (strcmp(q, "FAIL") == 0) {
169 die(EXIT_FAILURE, "%s", p);
170 } else if (strcmp(q, "INFO") == 0) {
174 } else if (strcmp(q, "OK") == 0) {
177 } else if (strcmp(q, "BGDETACH") == 0) {
179 die(EXIT_FAILURE, "repeat detach");
181 } else if (strcmp(q, "BGOK") == 0) {
184 } else if (strcmp(q, "BGINFO") == 0) {
188 } else if (strcmp(q, "BGFAIL") == 0) {
190 die(EXIT_FAILURE, "%s", p);
192 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
195 static void sline(char *p, size_t len, void *b)
199 moan("server closed the connection");
206 static void uline(char *p, size_t len, void *b)
215 if (write(fd, p, len + 1) != len + 1)
216 moan("write failed: %s", strerror(errno));
220 static void setup(const char *cmd)
229 errno = EIO; /* Relax: be vague */
230 if (write(fd, d.buf, d.len) != d.len) {
231 die(EXIT_FAILURE, "error sending setup command `%s': %s",
232 cmd, strerror(errno));
236 n = read(fd, &ch, 1);
238 die(EXIT_FAILURE, "unexpected EOF during setup");
240 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
241 cmd, strerror(errno));
250 else if (strcmp(q, "OK") == 0)
252 else if (strcmp(q, "FAIL") == 0)
253 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
259 static void logfile(const char *name)
263 if ((fp = fopen(name, "a")) != 0) {
267 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
270 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
272 writelog("error", d.buf);
274 die(EXIT_FAILURE, d.buf);
276 syslog(LOG_ERR, d.buf);
281 static void sighup(int sig, void *v) { logfile(logname); }
283 static void cleanup(void) { if (pidfile) unlink(pidfile); }
285 static void sigdie(int sig)
286 { cleanup(); signal(sig, SIG_DFL); raise(sig); }
288 static void putarg(string_v *av, const char *fmt, ...)
294 dstr_vputf(&d, fmt, &ap);
297 DA_UNSHIFT(av, xstrdup(d.buf));
301 static void version(FILE *fp)
302 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
304 static void usage(FILE *fp)
308 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
309 $ [-Dl] [-f FILE] [-OPTIONS]\n\
311 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
312 [-p PROGRAM] [-S ARG,ARG,...]\n\
316 static void help(FILE *fp)
325 -h, --help Show this help text.\n\
326 -v, --version Show version number.\n\
327 -u, --usage Show brief usage message.\n\
329 -D, --daemon Become a background task after connecting.\n\
330 -d, --directory=DIR Select current directory [default " CONFIGDIR "].\n\
331 -U, --setuid=USER Set uid to USER after initialization.\n\
332 -G, --setgid=GROUP Set gid to GROUP after initialization.\n\
333 -a, --admin-socket=FILE Select socket to connect to\n\
334 [default " SOCKETDIR "/tripesock].\n\
335 -P, --pidfile=FILE Write process-id to FILE.\n\
337 -s, --spawn Start server rather than connecting.\n\
338 -p, --spawn-path=PATH Specify path to executable.\n\
339 -S, --spawn-args=ARGS Specify comma-separated arguments.\n\
341 -l, --syslog Log messages to system log.\n\
342 -f, --logfile=FILE Log messages to FILE.\n\
343 -w, --warnings Show warnings when running commands.\n\
347 int main(int argc, char *argv[])
349 const char *dir = CONFIGDIR;
350 const char *sock = SOCKETDIR "/tripesock";
351 const char *spawnpath = "tripe";
352 string_v spawnopts = DA_INIT;
362 sigset_t newmask, oldmask;
363 struct sockaddr_un sun;
370 if ((p = getenv("TRIPEDIR")) != 0)
372 if ((p = getenv("TRIPESOCK")) != 0)
375 /* --- Parse the arguments --- */
378 static const struct option opts[] = {
379 { "help", 0, 0, 'h' },
380 { "version", 0, 0, 'v' },
381 { "usage", 0, 0, 'u' },
382 { "daemon", 0, 0, 'D' },
383 { "uid", OPTF_ARGREQ, 0, 'U' },
384 { "setuid", OPTF_ARGREQ, 0, 'U' },
385 { "gid", OPTF_ARGREQ, 0, 'G' },
386 { "setgid", OPTF_ARGREQ, 0, 'G' },
387 { "directory", OPTF_ARGREQ, 0, 'd' },
388 { "admin-socket", OPTF_ARGREQ, 0, 'a' },
389 { "spawn", 0, 0, 's' },
390 { "spawn-path", OPTF_ARGREQ, 0, 'p' },
391 { "spawn-args", OPTF_ARGREQ, 0, 'S' },
392 { "syslog", 0, 0, 'l' },
393 { "logfile", OPTF_ARGREQ, 0, 'f' },
394 { "warnings", 0, 0, 'w' },
395 { "pidfile", OPTF_ARGREQ, 0, 'P' },
399 i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:", opts, 0, 0, 0);
413 f |= f_daemon | f_noinput;
416 u = u_getuser(optarg, &g);
419 g = u_getgroup(optarg);
435 f |= f_spawn | f_spawnopts;
436 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
437 DA_PUSH(&spawnopts, p);
440 f |= f_syslog | f_noinput;
457 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
462 /* --- Set various things up --- */
465 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
466 dir, strerror(errno));
470 if (!pidfile && (f & f_daemon) && ((f & f_syslog) || logname))
471 pidfile = "tripectl.pid";
472 if (pidfile && (pidfp = fopen(pidfile, "w")) == 0) {
473 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
474 pidfile, strerror(errno));
478 signal(SIGINT, sigdie);
479 signal(SIGQUIT, sigdie);
480 signal(SIGTERM, sigdie);
483 /* --- Connect to the server --- */
486 sa.sa_handler = reap;
487 sigemptyset(&sa.sa_mask);
488 sa.sa_flags = SA_NOCLDSTOP;
490 sa.sa_flags |= SA_RESTART;
492 sigaction(SIGCHLD, &sa, 0);
494 DA_PUSH(&spawnopts, 0);
495 if (g != (gid_t)-1) putarg(&spawnopts, "-G%lu", (unsigned long)g);
496 if (u != (uid_t)-1) putarg(&spawnopts, "-U%lu", (unsigned long)u);
497 putarg(&spawnopts, "-a%s", sock);
498 putarg(&spawnopts, "-d.");
499 putarg(&spawnopts, "-F");
500 putarg(&spawnopts, "%s", spawnpath);
501 if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd))
502 die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
503 sigemptyset(&newmask);
504 sigaddset(&newmask, SIGCHLD);
505 sigprocmask(SIG_BLOCK, &newmask, &oldmask);
506 if ((kid = fork()) < 0)
507 die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
509 dup2(pfd[1], STDIN_FILENO);
510 dup2(pfd[1], STDOUT_FILENO);
513 if (logfp) fclose(logfp);
514 if (pidfp) fclose(pidfp);
516 if (f & f_daemon) detachtty();
517 execvp(DA(&spawnopts)[0], DA(&spawnopts));
518 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
520 sigprocmask(SIG_SETMASK, &oldmask, 0);
524 sz = strlen(sock) + 1;
525 if (sz > sizeof(sun.sun_path))
526 die(EXIT_FAILURE, "socket name `%s' too long", sock);
527 memset(&sun, 0, sizeof(sun));
528 sun.sun_family = AF_UNIX;
529 memcpy(sun.sun_path, sock, sz);
530 sz = sz + offsetof(struct sockaddr_un, sun_path);
531 if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
532 die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
533 if (connect(fd, (struct sockaddr *)&sun, sz)) {
534 die(EXIT_FAILURE, "error connecting to `%s': %s",
535 sun.sun_path, strerror(errno));
542 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
545 fprintf(pidfp, "%li\n", (long)getpid());
548 signal(SIGPIPE, SIG_IGN);
550 /* --- If we're meant to be interactive, do that --- */
553 setup("WATCH -A+tw");
554 if (!(f & f_noinput) && optind == argc) {
555 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
556 selbuf_init(&bs, &sel, fd, sline, &bs);
558 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
559 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
563 /* --- If there's a command, submit it --- */
566 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
567 while (optind < argc)
568 u_quotify(&d, argv[optind++]);
571 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
572 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
577 /* --- Pull everything else out of the box --- */
579 selbuf_init(&bs, &sel, fd, cline, 0);
582 openlog(QUIS, 0, LOG_DAEMON);
584 sig_add(&hup, SIGHUP, sighup, 0);
586 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
587 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
593 /*----- That's all, folks -------------------------------------------------*/