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
97 /*----- Main code ---------------------------------------------------------*/
99 static void reap(int sig)
102 while (waitpid(-1, 0, WNOHANG) > 0)
107 static void writelog(const char *cat, const char *msg)
111 struct tm *tm = localtime(&t);
112 strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
113 fprintf(logfp, "%s %s: %s\n", buf, cat, msg);
116 static void checkbg(char **p)
118 char *q = str_getword(p);
120 die(EXIT_FAILURE, "missing background tag");
121 if (!bgtag || strcmp(bgtag, q) != 0)
122 die(EXIT_FAILURE, "unexpected background tag `%s'", q);
125 static void dolog(int prio, const char *msg, ...)
132 dstr_vputf(&d, msg, &ap);
134 if (f & f_syslog) syslog(prio, "%s", d.buf);
137 case LOG_WARNING: cat = "warning"; break;
138 case LOG_DEBUG: cat = "debug"; break;
139 case LOG_ERR: cat = "error"; break;
140 default: cat = "message"; break;
142 writelog(cat, d.buf);
144 if (prio == LOG_WARNING && (f & f_warn))
145 fprintf(stderr, "Warning: %s\n", d.buf);
149 static void checkfg(void)
150 { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
152 static void cline(char *p, size_t len, void *b)
157 die(EXIT_FAILURE, "server dropped the connection");
164 if (strcmp(q, "WARN") == 0)
165 dolog(LOG_WARNING, p);
166 else if (strcmp(q, "TRACE") == 0)
168 else if (!(f & f_command))
169 dolog(LOG_ERR, "unexpected output `%s %s'", q, p);
170 else if (strcmp(q, "FAIL") == 0) {
172 die(EXIT_FAILURE, "%s", p);
173 } else if (strcmp(q, "INFO") == 0) {
177 } else if (strcmp(q, "OK") == 0) {
180 } else if (strcmp(q, "BGDETACH") == 0) {
182 die(EXIT_FAILURE, "repeat detach");
184 } else if (strcmp(q, "BGOK") == 0) {
187 } else if (strcmp(q, "BGINFO") == 0) {
191 } else if (strcmp(q, "BGFAIL") == 0) {
193 die(EXIT_FAILURE, "%s", p);
195 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
198 static void sline(char *p, size_t len, void *b)
202 moan("server closed the connection");
209 static void uline(char *p, size_t len, void *b)
218 if (write(fd, p, len + 1) != len + 1)
219 moan("write failed: %s", strerror(errno));
223 static void eline(char *p, size_t len, void *b)
226 dolog(LOG_WARNING, "(stderr): %s", p);
233 static void setup(const char *cmd)
242 errno = EIO; /* Relax: be vague */
243 if (write(fd, d.buf, d.len) != d.len) {
244 die(EXIT_FAILURE, "error sending setup command `%s': %s",
245 cmd, strerror(errno));
249 n = read(fd, &ch, 1);
251 die(EXIT_FAILURE, "unexpected EOF during setup");
253 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
254 cmd, strerror(errno));
263 else if (strcmp(q, "OK") == 0)
265 else if (strcmp(q, "FAIL") == 0)
266 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
272 static void logfile(const char *name)
276 if ((fp = fopen(name, "a")) != 0) {
280 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
283 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
285 writelog("error", d.buf);
287 die(EXIT_FAILURE, d.buf);
289 syslog(LOG_ERR, "%s", d.buf);
294 static void sighup(int sig, void *v) { logfile(logname); }
296 static void cleanup(void) { if (pidfile) unlink(pidfile); }
298 static void sigdie(int sig)
299 { cleanup(); signal(sig, SIG_DFL); raise(sig); }
301 static void putarg(string_v *av, const char *fmt, ...)
307 dstr_vputf(&d, fmt, &ap);
310 DA_UNSHIFT(av, xstrdup(d.buf));
314 static void version(FILE *fp)
315 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
317 static void usage(FILE *fp)
321 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
322 $ [-Dl] [-f FILE] [-OPTIONS]\n\
324 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
325 [-p PROGRAM] [-S ARG,ARG,...]\n\
329 static void help(FILE *fp)
338 -h, --help Show this help text.\n\
339 -v, --version Show version number.\n\
340 -u, --usage Show brief usage message.\n\
342 -D, --daemon Become a background task after connecting.\n\
343 -d, --directory=DIR Select current directory [default " CONFIGDIR "].\n\
344 -U, --setuid=USER Set uid to USER after initialization.\n\
345 -G, --setgid=GROUP Set gid to GROUP after initialization.\n\
346 -a, --admin-socket=FILE Select socket to connect to\n\
347 [default " SOCKETDIR "/tripesock].\n\
348 -P, --pidfile=FILE Write process-id to FILE.\n\
350 -s, --spawn Start server rather than connecting.\n\
351 -p, --spawn-path=PATH Specify path to executable.\n\
352 -S, --spawn-args=ARGS Specify comma-separated arguments.\n\
354 -l, --syslog Log messages to system log.\n\
355 -f, --logfile=FILE Log messages to FILE.\n\
356 -w, --warnings Show warnings when running commands.\n\
360 int main(int argc, char *argv[])
362 const char *dir = CONFIGDIR;
363 const char *sock = SOCKETDIR "/tripesock";
364 const char *spawnpath = "tripe";
365 string_v spawnopts = DA_INIT;
376 sigset_t newmask, oldmask;
377 struct sockaddr_un sun;
384 if ((p = getenv("TRIPEDIR")) != 0)
386 if ((p = getenv("TRIPESOCK")) != 0)
389 /* --- Parse the arguments --- */
392 static const struct option opts[] = {
393 { "help", 0, 0, 'h' },
394 { "version", 0, 0, 'v' },
395 { "usage", 0, 0, 'u' },
396 { "daemon", 0, 0, 'D' },
397 { "uid", OPTF_ARGREQ, 0, 'U' },
398 { "setuid", OPTF_ARGREQ, 0, 'U' },
399 { "gid", OPTF_ARGREQ, 0, 'G' },
400 { "setgid", OPTF_ARGREQ, 0, 'G' },
401 { "directory", OPTF_ARGREQ, 0, 'd' },
402 { "admin-socket", OPTF_ARGREQ, 0, 'a' },
403 { "spawn", 0, 0, 's' },
404 { "spawn-path", OPTF_ARGREQ, 0, 'p' },
405 { "spawn-args", OPTF_ARGREQ, 0, 'S' },
406 { "syslog", 0, 0, 'l' },
407 { "logfile", OPTF_ARGREQ, 0, 'f' },
408 { "warnings", 0, 0, 'w' },
409 { "pidfile", OPTF_ARGREQ, 0, 'P' },
413 i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:", opts, 0, 0, 0);
427 f |= f_daemon | f_noinput;
430 u = u_getuser(optarg, &g);
433 g = u_getgroup(optarg);
449 f |= f_spawn | f_spawnopts;
450 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
451 DA_PUSH(&spawnopts, p);
454 f |= f_syslog | f_noinput;
471 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
476 /* --- Set various things up --- */
479 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
480 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 sigprocmask(SIG_SETMASK, &oldmask, 0);
523 md[0].cur = pfd[1]; md[0].want = STDIN_FILENO;
524 md[1].cur = pfd[1]; md[1].want = STDOUT_FILENO;
525 md[2].cur = efd[1]; md[2].want = STDERR_FILENO;
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));
553 f |= f_losing; /* pessimism */
559 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
562 fprintf(pidfp, "%li\n", (long)getpid());
565 signal(SIGPIPE, SIG_IGN);
567 /* --- If we're meant to be interactive, do that --- */
570 setup("WATCH -A+tw");
571 if (!(f & f_noinput) && optind == argc) {
572 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
573 selbuf_init(&bs, &sel, fd, sline, &bs);
575 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
576 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
580 /* --- If there's a command, submit it --- */
583 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
584 while (optind < argc)
585 u_quotify(&d, argv[optind++]);
588 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
589 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
594 /* --- Pull everything else out of the box --- */
596 selbuf_init(&bs, &sel, fd, cline, 0);
599 openlog(QUIS, 0, LOG_DAEMON);
601 sig_add(&hup, SIGHUP, sighup, 0);
603 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
604 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
610 /*----- That's all, folks -------------------------------------------------*/