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_WARNING: 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_WARNING && (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 eline(char *p, size_t len, void *b)
223 dolog(LOG_WARNING, "(stderr): %s", p);
230 static void setup(const char *cmd)
239 errno = EIO; /* Relax: be vague */
240 if (write(fd, d.buf, d.len) != d.len) {
241 die(EXIT_FAILURE, "error sending setup command `%s': %s",
242 cmd, strerror(errno));
246 n = read(fd, &ch, 1);
248 die(EXIT_FAILURE, "unexpected EOF during setup");
250 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
251 cmd, strerror(errno));
260 else if (strcmp(q, "OK") == 0)
262 else if (strcmp(q, "FAIL") == 0)
263 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
269 static void logfile(const char *name)
273 if ((fp = fopen(name, "a")) != 0) {
277 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
280 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
282 writelog("error", d.buf);
284 die(EXIT_FAILURE, d.buf);
286 syslog(LOG_ERR, "%s", d.buf);
291 static void sighup(int sig, void *v) { logfile(logname); }
293 static void cleanup(void) { if (pidfile) unlink(pidfile); }
295 static void sigdie(int sig)
296 { cleanup(); signal(sig, SIG_DFL); raise(sig); }
298 static void putarg(string_v *av, const char *fmt, ...)
304 dstr_vputf(&d, fmt, &ap);
307 DA_UNSHIFT(av, xstrdup(d.buf));
311 static void version(FILE *fp)
312 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
314 static void usage(FILE *fp)
318 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
319 $ [-Dl] [-f FILE] [-OPTIONS]\n\
321 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
322 [-p PROGRAM] [-S ARG,ARG,...]\n\
326 static void help(FILE *fp)
335 -h, --help Show this help text.\n\
336 -v, --version Show version number.\n\
337 -u, --usage Show brief usage message.\n\
339 -D, --daemon Become a background task after connecting.\n\
340 -d, --directory=DIR Select current directory [default " CONFIGDIR "].\n\
341 -U, --setuid=USER Set uid to USER after initialization.\n\
342 -G, --setgid=GROUP Set gid to GROUP after initialization.\n\
343 -a, --admin-socket=FILE Select socket to connect to\n\
344 [default " SOCKETDIR "/tripesock].\n\
345 -P, --pidfile=FILE Write process-id to FILE.\n\
347 -s, --spawn Start server rather than connecting.\n\
348 -p, --spawn-path=PATH Specify path to executable.\n\
349 -S, --spawn-args=ARGS Specify comma-separated arguments.\n\
351 -l, --syslog Log messages to system log.\n\
352 -f, --logfile=FILE Log messages to FILE.\n\
353 -w, --warnings Show warnings when running commands.\n\
357 int main(int argc, char *argv[])
359 const char *dir = CONFIGDIR;
360 const char *sock = SOCKETDIR "/tripesock";
361 const char *spawnpath = "tripe";
362 string_v spawnopts = DA_INIT;
372 sigset_t newmask, oldmask;
373 struct sockaddr_un sun;
380 if ((p = getenv("TRIPEDIR")) != 0)
382 if ((p = getenv("TRIPESOCK")) != 0)
385 /* --- Parse the arguments --- */
388 static const struct option opts[] = {
389 { "help", 0, 0, 'h' },
390 { "version", 0, 0, 'v' },
391 { "usage", 0, 0, 'u' },
392 { "daemon", 0, 0, 'D' },
393 { "uid", OPTF_ARGREQ, 0, 'U' },
394 { "setuid", OPTF_ARGREQ, 0, 'U' },
395 { "gid", OPTF_ARGREQ, 0, 'G' },
396 { "setgid", OPTF_ARGREQ, 0, 'G' },
397 { "directory", OPTF_ARGREQ, 0, 'd' },
398 { "admin-socket", OPTF_ARGREQ, 0, 'a' },
399 { "spawn", 0, 0, 's' },
400 { "spawn-path", OPTF_ARGREQ, 0, 'p' },
401 { "spawn-args", OPTF_ARGREQ, 0, 'S' },
402 { "syslog", 0, 0, 'l' },
403 { "logfile", OPTF_ARGREQ, 0, 'f' },
404 { "warnings", 0, 0, 'w' },
405 { "pidfile", OPTF_ARGREQ, 0, 'P' },
409 i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:", opts, 0, 0, 0);
423 f |= f_daemon | f_noinput;
426 u = u_getuser(optarg, &g);
429 g = u_getgroup(optarg);
445 f |= f_spawn | f_spawnopts;
446 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
447 DA_PUSH(&spawnopts, p);
450 f |= f_syslog | f_noinput;
467 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
472 /* --- Set various things up --- */
475 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
476 dir, strerror(errno));
480 if (!pidfile && (f & f_daemon) && ((f & f_syslog) || logname))
481 pidfile = "tripectl.pid";
482 if (pidfile && (pidfp = fopen(pidfile, "w")) == 0) {
483 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
484 pidfile, strerror(errno));
488 signal(SIGINT, sigdie);
489 signal(SIGQUIT, sigdie);
490 signal(SIGTERM, sigdie);
493 /* --- Connect to the server --- */
496 sa.sa_handler = reap;
497 sigemptyset(&sa.sa_mask);
498 sa.sa_flags = SA_NOCLDSTOP;
500 sa.sa_flags |= SA_RESTART;
502 sigaction(SIGCHLD, &sa, 0);
504 DA_PUSH(&spawnopts, 0);
505 if (g != (gid_t)-1) putarg(&spawnopts, "-G%lu", (unsigned long)g);
506 if (u != (uid_t)-1) putarg(&spawnopts, "-U%lu", (unsigned long)u);
507 putarg(&spawnopts, "-a%s", sock);
508 putarg(&spawnopts, "-d.");
509 putarg(&spawnopts, "-F");
510 putarg(&spawnopts, "%s", spawnpath);
511 if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd) || pipe(efd))
512 die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
513 sigemptyset(&newmask);
514 sigaddset(&newmask, SIGCHLD);
515 sigprocmask(SIG_BLOCK, &newmask, &oldmask);
516 if ((kid = fork()) < 0)
517 die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
519 dup2(pfd[1], STDIN_FILENO);
520 dup2(pfd[1], STDOUT_FILENO);
521 dup2(efd[1], STDERR_FILENO);
522 close(pfd[0]); close(pfd[1]);
523 close(efd[0]); close(efd[1]);
524 if (logfp) fclose(logfp);
525 if (pidfp) fclose(pidfp);
527 if (f & f_daemon) detachtty();
528 execvp(DA(&spawnopts)[0], DA(&spawnopts));
529 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
531 sigprocmask(SIG_SETMASK, &oldmask, 0);
533 close(pfd[1]); close(efd[1]);
534 selbuf_init(&be, &sel, efd[0], eline, &be);
536 sz = strlen(sock) + 1;
537 if (sz > sizeof(sun.sun_path))
538 die(EXIT_FAILURE, "socket name `%s' too long", sock);
539 memset(&sun, 0, sizeof(sun));
540 sun.sun_family = AF_UNIX;
541 memcpy(sun.sun_path, sock, sz);
542 sz = sz + offsetof(struct sockaddr_un, sun_path);
543 if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
544 die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
545 if (connect(fd, (struct sockaddr *)&sun, sz)) {
546 die(EXIT_FAILURE, "error connecting to `%s': %s",
547 sun.sun_path, strerror(errno));
554 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
557 fprintf(pidfp, "%li\n", (long)getpid());
560 signal(SIGPIPE, SIG_IGN);
562 /* --- If we're meant to be interactive, do that --- */
565 setup("WATCH -A+tw");
566 if (!(f & f_noinput) && optind == argc) {
567 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
568 selbuf_init(&bs, &sel, fd, sline, &bs);
570 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
571 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
575 /* --- If there's a command, submit it --- */
578 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
579 while (optind < argc)
580 u_quotify(&d, argv[optind++]);
583 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
584 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
589 /* --- Pull everything else out of the box --- */
591 selbuf_init(&bs, &sel, fd, cline, 0);
594 openlog(QUIS, 0, LOG_DAEMON);
596 sig_add(&hup, SIGHUP, sighup, 0);
598 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
599 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
605 /*----- That's all, folks -------------------------------------------------*/