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>
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;
84 static const char *bgtag = 0;
89 #define f_spawnopts 8u
96 /*----- Main code ---------------------------------------------------------*/
98 static void reap(int sig)
101 while (waitpid(-1, 0, WNOHANG) > 0)
106 static void writelog(const char *cat, const char *msg)
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);
115 static void checkbg(char **p)
117 char *q = str_getword(p);
119 die(EXIT_FAILURE, "missing background tag");
120 if (!bgtag || strcmp(bgtag, q) != 0)
121 die(EXIT_FAILURE, "unexpected background tag `%s'", q);
124 static void dolog(int prio, const char *msg, ...)
131 dstr_vputf(&d, msg, &ap);
133 if (f & f_syslog) syslog(prio, "%s", d.buf);
136 case LOG_WARNING: cat = "warning"; break;
137 case LOG_DEBUG: cat = "debug"; break;
138 case LOG_ERR: cat = "error"; break;
139 default: cat = "message"; break;
141 writelog(cat, d.buf);
143 if (prio == LOG_WARNING && (f & f_warn))
144 fprintf(stderr, "Warning: %s\n", d.buf);
148 static void checkfg(void)
149 { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
151 static void cline(char *p, size_t len, void *b)
156 die(EXIT_FAILURE, "server dropped the connection");
162 if (strcmp(q, "WARN") == 0)
163 dolog(LOG_WARNING, p);
164 else if (strcmp(q, "TRACE") == 0)
166 else if (!(f & f_command))
167 dolog(LOG_ERR, "unexpected output `%s %s'", q, p);
168 else if (strcmp(q, "FAIL") == 0) {
170 die(EXIT_FAILURE, "%s", p);
171 } else if (strcmp(q, "INFO") == 0) {
175 } else if (strcmp(q, "OK") == 0) {
178 } else if (strcmp(q, "BGDETACH") == 0) {
180 die(EXIT_FAILURE, "repeat detach");
182 } else if (strcmp(q, "BGOK") == 0) {
185 } else if (strcmp(q, "BGINFO") == 0) {
189 } else if (strcmp(q, "BGFAIL") == 0) {
191 die(EXIT_FAILURE, "%s", p);
193 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
196 static void sline(char *p, size_t len, void *b)
200 moan("server closed the connection");
207 static void uline(char *p, size_t len, void *b)
216 if (write(fd, p, len + 1) != len + 1)
217 moan("write failed: %s", strerror(errno));
221 static void eline(char *p, size_t len, void *b)
224 dolog(LOG_WARNING, "(stderr): %s", p);
231 static void setup(const char *cmd)
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));
247 n = read(fd, &ch, 1);
249 die(EXIT_FAILURE, "unexpected EOF during setup");
251 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
252 cmd, strerror(errno));
261 else if (strcmp(q, "OK") == 0)
263 else if (strcmp(q, "FAIL") == 0)
264 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
270 static void logfile(const char *name)
274 if ((fp = fopen(name, "a")) != 0) {
278 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
281 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
283 writelog("error", d.buf);
285 die(EXIT_FAILURE, d.buf);
287 syslog(LOG_ERR, "%s", d.buf);
292 static void sighup(int sig, void *v) { logfile(logname); }
294 static void cleanup(void) { if (pidfile) unlink(pidfile); }
296 static void sigdie(int sig)
297 { cleanup(); signal(sig, SIG_DFL); raise(sig); }
299 static void putarg(string_v *av, const char *fmt, ...)
305 dstr_vputf(&d, fmt, &ap);
308 DA_UNSHIFT(av, xstrdup(d.buf));
312 static void version(FILE *fp)
313 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
315 static void usage(FILE *fp)
319 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
320 $ [-Dl] [-f FILE] [-OPTIONS]\n\
322 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
323 [-p PROGRAM] [-S ARG,ARG,...]\n\
327 static void help(FILE *fp)
336 -h, --help Show this help text.\n\
337 -v, --version Show version number.\n\
338 -u, --usage Show brief usage message.\n\
340 -D, --daemon Become a background task after connecting.\n\
341 -d, --directory=DIR Select current directory [default " CONFIGDIR "].\n\
342 -U, --setuid=USER Set uid to USER after initialization.\n\
343 -G, --setgid=GROUP Set gid to GROUP after initialization.\n\
344 -a, --admin-socket=FILE Select socket to connect to\n\
345 [default " SOCKETDIR "/tripesock].\n\
346 -P, --pidfile=FILE Write process-id to FILE.\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\
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\
358 int main(int argc, char *argv[])
360 const char *dir = CONFIGDIR;
361 const char *sock = SOCKETDIR "/tripesock";
362 const char *spawnpath = "tripe";
363 string_v spawnopts = DA_INIT;
374 sigset_t newmask, oldmask;
375 struct sockaddr_un sun;
382 if ((p = getenv("TRIPEDIR")) != 0)
384 if ((p = getenv("TRIPESOCK")) != 0)
387 /* --- Parse the arguments --- */
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' },
395 { "uid", OPTF_ARGREQ, 0, 'U' },
396 { "setuid", OPTF_ARGREQ, 0, 'U' },
397 { "gid", OPTF_ARGREQ, 0, 'G' },
398 { "setgid", OPTF_ARGREQ, 0, 'G' },
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' },
407 { "pidfile", OPTF_ARGREQ, 0, 'P' },
411 i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:", opts, 0, 0, 0);
425 f |= f_daemon | f_noinput;
428 u = u_getuser(optarg, &g);
431 g = u_getgroup(optarg);
447 f |= f_spawn | f_spawnopts;
448 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
449 DA_PUSH(&spawnopts, p);
452 f |= f_syslog | f_noinput;
469 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
474 /* --- Set various things up --- */
477 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
478 dir, strerror(errno));
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));
490 signal(SIGINT, sigdie);
491 signal(SIGQUIT, sigdie);
492 signal(SIGTERM, sigdie);
495 /* --- Connect to the server --- */
498 sa.sa_handler = reap;
499 sigemptyset(&sa.sa_mask);
500 sa.sa_flags = SA_NOCLDSTOP;
502 sa.sa_flags |= SA_RESTART;
504 sigaction(SIGCHLD, &sa, 0);
506 DA_PUSH(&spawnopts, 0);
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);
509 putarg(&spawnopts, "-a%s", sock);
510 putarg(&spawnopts, "-d.");
511 putarg(&spawnopts, "-F");
512 putarg(&spawnopts, "%s", spawnpath);
513 if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd) || pipe(efd))
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));
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;
526 if (logfp) fclose(logfp);
527 if (pidfp) fclose(pidfp);
529 if (f & f_daemon) detachtty();
530 execvp(DA(&spawnopts)[0], DA(&spawnopts));
531 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
533 sigprocmask(SIG_SETMASK, &oldmask, 0);
535 close(pfd[1]); close(efd[1]);
536 selbuf_init(&be, &sel, efd[0], eline, &be);
538 sz = strlen(sock) + 1;
539 if (sz > sizeof(sun.sun_path))
540 die(EXIT_FAILURE, "socket name `%s' too long", sock);
541 memset(&sun, 0, sizeof(sun));
542 sun.sun_family = AF_UNIX;
543 memcpy(sun.sun_path, sock, sz);
544 sz = sz + offsetof(struct sockaddr_un, sun_path);
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",
549 sun.sun_path, strerror(errno));
556 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
559 fprintf(pidfp, "%li\n", (long)getpid());
562 signal(SIGPIPE, SIG_IGN);
564 /* --- If we're meant to be interactive, do that --- */
567 setup("WATCH -A+tw");
568 if (!(f & f_noinput) && optind == argc) {
569 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
570 selbuf_init(&bs, &sel, fd, sline, &bs);
572 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
573 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
577 /* --- If there's a command, submit it --- */
580 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
581 while (optind < argc)
582 u_quotify(&d, argv[optind++]);
585 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
586 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
591 /* --- Pull everything else out of the box --- */
593 selbuf_init(&bs, &sel, fd, cline, 0);
596 openlog(QUIS, 0, LOG_DAEMON);
598 sig_add(&hup, SIGHUP, sighup, 0);
600 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
601 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
607 /*----- That's all, folks -------------------------------------------------*/