chiark / gitweb /
client: New options for setting user and group identities.
[tripe] / client / tripectl.c
CommitLineData
410c8acf 1/* -*-c-*-
410c8acf 2 *
3 * Client for TrIPE
4 *
5 * (c) 2001 Straylight/Edgeware
6 */
7
e04c2d50 8/*----- Licensing notice --------------------------------------------------*
410c8acf 9 *
10 * This file is part of Trivial IP Encryption (TrIPE).
11 *
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.
e04c2d50 16 *
410c8acf 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.
e04c2d50 21 *
410c8acf 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.
25 */
26
410c8acf 27/*----- Header files ------------------------------------------------------*/
28
73189848 29#include "config.h"
30
410c8acf 31#include <ctype.h>
32#include <errno.h>
33#include <signal.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37#include <time.h>
38
39#include <sys/types.h>
40#include <sys/time.h>
41#include <unistd.h>
42#include <fcntl.h>
43#include <sys/wait.h>
44#include <syslog.h>
45
46#include <sys/socket.h>
47#include <sys/un.h>
48#include <arpa/inet.h>
49#include <netdb.h>
50
51#include <mLib/alloc.h>
19dd2531 52#include <mLib/daemonize.h>
410c8acf 53#include <mLib/darray.h>
54#include <mLib/dstr.h>
410c8acf 55#include <mLib/mdwopt.h>
56#include <mLib/quis.h>
57#include <mLib/report.h>
58#include <mLib/sel.h>
59#include <mLib/selbuf.h>
5f5150b1 60#include <mLib/sig.h>
410c8acf 61#include <mLib/str.h>
19dd2531 62#include <mLib/versioncmp.h>
410c8acf 63
64#include "util.h"
65
66#undef sun
67
68/*----- Data structures ---------------------------------------------------*/
69
70#ifndef STRING_V
71# define STRING_V
72 DA_DECL(string_v, char *);
73#endif
74
75/*----- Static variables --------------------------------------------------*/
76
06b2a088 77static const char *pidfile = 0;
78static const char *logname = 0;
410c8acf 79static FILE *logfp = 0;
80static unsigned f = 0;
81static int fd;
de014da6 82static const char *bgtag = 0;
410c8acf 83
84#define f_bogus 1u
85#define f_spawn 2u
86#define f_daemon 4u
87#define f_spawnopts 8u
88#define f_syslog 16u
89#define f_command 32u
90#define f_noinput 64u
91#define f_warn 128u
92#define f_uclose 256u
93
94/*----- Main code ---------------------------------------------------------*/
95
96static void reap(int sig)
97{
410c8acf 98 int e = errno;
06b2a088 99 while (waitpid(-1, 0, WNOHANG) > 0)
410c8acf 100 ;
101 errno = e;
102}
103
104static void writelog(const char *cat, const char *msg)
105{
106 char buf[256];
107 time_t t = time(0);
108 struct tm *tm = localtime(&t);
109 strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
110 fprintf(logfp, "%s %s: %s\n", buf, cat, msg);
111}
112
de014da6 113static void checkbg(char **p)
114{
115 char *q = str_getword(p);
116 if (!q)
117 die(EXIT_FAILURE, "missing background tag");
118 if (!bgtag || strcmp(bgtag, q) != 0)
119 die(EXIT_FAILURE, "unexpected background tag `%s'", q);
120}
121
122static void checkfg(void)
6047fbac 123 { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
de014da6 124
6be88c14 125static void cline(char *p, size_t len, void *b)
410c8acf 126{
127 char *q;
128 if (!p) {
129 if (f & f_command)
130 die(EXIT_FAILURE, "server dropped the connection");
131 exit(0);
132 }
133 q = str_getword(&p);
134 if (!q)
135 return;
136 if (strcmp(q, "WARN") == 0) {
137 if (f & f_syslog)
138 syslog(LOG_WARNING, "%s", p);
139 if (logfp)
140 writelog("warning", p);
141 if (f & f_warn)
142 fprintf(stderr, "Warning: %s\n", p);
143 } else if (strcmp(q, "TRACE") == 0) {
144 if (f & f_syslog)
145 syslog(LOG_DEBUG, "%s", p);
146 if (logfp)
147 writelog("debug", p);
148 } else if (!(f & f_command)) {
149 if (f & f_syslog)
150 syslog(LOG_ERR, "unexpected output `%s %s'", q, p);
151 if (logfp) {
152 dstr d = DSTR_INIT;
153 dstr_putf(&d, "unexpected output `%s %s'", q, p);
154 writelog("error", d.buf);
155 dstr_destroy(&d);
156 }
de014da6 157 } else if (strcmp(q, "FAIL") == 0) {
158 checkfg();
410c8acf 159 die(EXIT_FAILURE, "%s", p);
de014da6 160 } else if (strcmp(q, "INFO") == 0) {
161 checkfg();
410c8acf 162 puts(p);
5136c31e 163 fflush(stdout);
de014da6 164 } else if (strcmp(q, "OK") == 0) {
165 checkfg();
166 exit(0);
167 } else if (strcmp(q, "BGDETACH") == 0) {
168 if (bgtag)
169 die(EXIT_FAILURE, "repeat detach");
170 bgtag = xstrdup(p);
171 } else if (strcmp(q, "BGOK") == 0) {
172 checkbg(&p);
410c8acf 173 exit(0);
de014da6 174 } else if (strcmp(q, "BGINFO") == 0) {
175 checkbg(&p);
176 puts(p);
5136c31e 177 fflush(stdout);
de014da6 178 } else if (strcmp(q, "BGFAIL") == 0) {
179 checkbg(&p);
180 die(EXIT_FAILURE, "%s", p);
181 } else
e04c2d50 182 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
410c8acf 183}
184
6be88c14 185static void sline(char *p, size_t len, void *b)
410c8acf 186{
187 if (!p) {
188 if (!(f & f_uclose))
189 moan("server closed the connection");
190 exit(0);
191 }
192 puts(p);
5136c31e 193 fflush(stdout);
410c8acf 194}
195
6be88c14 196static void uline(char *p, size_t len, void *b)
410c8acf 197{
410c8acf 198 if (!p) {
199 selbuf_destroy(b);
200 shutdown(fd, 1);
201 f |= f_uclose;
202 } else {
6be88c14 203 p[len] = '\n';
3cdc3f3a 204 errno = EIO;
205 if (write(fd, p, len + 1) != len + 1)
206 moan("write failed: %s", strerror(errno));
207 }
208}
209
210static void setup(const char *cmd)
211{
212 dstr d = DSTR_INIT;
213 char ch;
214 char *p, *q;
215 int n;
216
217 dstr_puts(&d, cmd);
218 dstr_putc(&d, '\n');
219 errno = EIO; /* Relax: be vague */
220 if (write(fd, d.buf, d.len) != d.len) {
221 die(EXIT_FAILURE, "error sending setup command `%s': %s",
222 cmd, strerror(errno));
223 }
224 dstr_reset(&d);
225 for (;;) {
226 n = read(fd, &ch, 1);
227 if (!n)
228 die(EXIT_FAILURE, "unexpected EOF during setup");
229 if (n < 0) {
230 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
231 cmd, strerror(errno));
232 }
233 if (d.len < 256)
234 dstr_putc(&d, ch);
235 if (ch == '\n') {
236 p = d.buf;
237 q = str_getword(&p);
238 if (!q)
239 ;
240 else if (strcmp(q, "OK") == 0)
241 return;
242 else if (strcmp(q, "FAIL") == 0)
243 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
244 dstr_reset(&d);
245 }
410c8acf 246 }
247}
248
9dd01bc6 249static void logfile(const char *name)
250{
fa4bef80 251 FILE *fp;
252
253 if ((fp = fopen(name, "a")) != 0) {
254 if (logfp)
255 fclose(logfp);
256 logfp = fp;
257 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
258 } else {
259 dstr d = DSTR_INIT;
260 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
261 if (logfp)
262 writelog("error", d.buf);
263 else if (logname)
264 die(EXIT_FAILURE, d.buf);
265 if (f & f_syslog)
266 syslog(LOG_ERR, d.buf);
267 dstr_destroy(&d);
9dd01bc6 268 }
9dd01bc6 269}
270
f98df549 271static void sighup(int sig, void *v) { logfile(logname); }
5f5150b1 272
6047fbac 273static void cleanup(void) { if (pidfile) unlink(pidfile); }
06b2a088 274
275static void sigdie(int sig)
6047fbac 276 { cleanup(); signal(sig, SIG_DFL); raise(sig); }
06b2a088 277
f685e692
MW
278static void putarg(string_v *av, const char *fmt, ...)
279{
280 va_list ap;
281 dstr d = DSTR_INIT;
282
283 va_start(ap, fmt);
284 dstr_vputf(&d, fmt, &ap);
285 dstr_putz(&d);
286 va_end(ap);
287 DA_UNSHIFT(av, xstrdup(d.buf));
288 dstr_destroy(&d);
289}
290
410c8acf 291static void version(FILE *fp)
f98df549 292 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
410c8acf 293
294static void usage(FILE *fp)
295{
296 pquis(fp, "\
297Usage:\n\
2d752320 298 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
299 $ [-Dl] [-f FILE] [-OPTIONS]\n\
410c8acf 300Options:\n\
2d752320 301 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
302 [-p PROGRAM] [-S ARG,ARG,...]\n\
410c8acf 303");
304}
305
306static void help(FILE *fp)
307{
308 version(fp);
309 fputc('\n', fp);
310 usage(fp);
311 fputs("\
312\n\
313Options in full:\n\
314\n\
315-h, --help Show this help text.\n\
316-v, --version Show version number.\n\
317-u, --usage Show brief usage message.\n\
318\n\
319-D, --daemon Become a background task after connecting.\n\
ef4a1ab7 320-d, --directory=DIR Select current directory [default " CONFIGDIR "].\n\
ab46a787
MW
321-U, --setuid=USER Set uid to USER after initialization.\n\
322-G, --setgid=GROUP Set gid to GROUP after initialization.\n\
3cdc3f3a 323-a, --admin-socket=FILE Select socket to connect to\n\
e04c2d50 324 [default " SOCKETDIR "/tripesock].\n\
06b2a088 325-P, --pidfile=FILE Write process-id to FILE.\n\
410c8acf 326\n\
327-s, --spawn Start server rather than connecting.\n\
328-p, --spawn-path=PATH Specify path to executable.\n\
329-S, --spawn-args=ARGS Specify comma-separated arguments.\n\
330\n\
331-l, --syslog Log messages to system log.\n\
332-f, --logfile=FILE Log messages to FILE.\n\
333-w, --warnings Show warnings when running commands.\n\
334", fp);
335}
336
337int main(int argc, char *argv[])
338{
ef4a1ab7 339 const char *dir = CONFIGDIR;
340 const char *sock = SOCKETDIR "/tripesock";
410c8acf 341 const char *spawnpath = "tripe";
342 string_v spawnopts = DA_INIT;
343 char *p;
06b2a088 344 FILE *pidfp = 0;
ab46a787
MW
345 uid_t u = -1;
346 gid_t g = -1;
410c8acf 347
348 ego(argv[0]);
349
350 if ((p = getenv("TRIPEDIR")) != 0)
351 dir = p;
797cf76b
MW
352 if ((p = getenv("TRIPESOCK")) != 0)
353 sock = p;
410c8acf 354
355 /* --- Parse the arguments --- */
356
357 for (;;) {
358 static const struct option opts[] = {
359 { "help", 0, 0, 'h' },
360 { "version", 0, 0, 'v' },
361 { "usage", 0, 0, 'u' },
362 { "daemon", 0, 0, 'D' },
ab46a787
MW
363 { "uid", OPTF_ARGREQ, 0, 'U' },
364 { "setuid", OPTF_ARGREQ, 0, 'U' },
365 { "gid", OPTF_ARGREQ, 0, 'G' },
366 { "setgid", OPTF_ARGREQ, 0, 'G' },
410c8acf 367 { "directory", OPTF_ARGREQ, 0, 'd' },
368 { "admin-socket", OPTF_ARGREQ, 0, 'a' },
369 { "spawn", 0, 0, 's' },
370 { "spawn-path", OPTF_ARGREQ, 0, 'p' },
371 { "spawn-args", OPTF_ARGREQ, 0, 'S' },
372 { "syslog", 0, 0, 'l' },
373 { "logfile", OPTF_ARGREQ, 0, 'f' },
374 { "warnings", 0, 0, 'w' },
06b2a088 375 { "pidfile", OPTF_ARGREQ, 0, 'P' },
410c8acf 376 { 0, 0, 0, 0 }
377 };
378
ab46a787 379 int i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:", opts, 0, 0, 0);
410c8acf 380 if (i < 0)
381 break;
382 switch (i) {
383 case 'h':
384 help(stdout);
385 exit(0);
386 case 'v':
387 version(stdout);
388 exit(0);
389 case 'u':
390 usage(stdout);
391 exit(0);
392 case 'D':
393 f |= f_daemon | f_noinput;
394 break;
ab46a787
MW
395 case 'U':
396 u = u_getuser(optarg, &g);
397 break;
398 case 'G':
399 g = u_getgroup(optarg);
400 break;
410c8acf 401 case 'd':
402 dir = optarg;
403 break;
404 case 'a':
405 sock = optarg;
406 break;
407 case 's':
408 f |= f_spawn;
409 break;
410 case 'p':
411 f |= f_spawn;
412 spawnpath = optarg;
413 break;
414 case 'S':
415 f |= f_spawn | f_spawnopts;
416 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
417 DA_PUSH(&spawnopts, p);
418 break;
419 case 'l':
420 f |= f_syslog | f_noinput;
421 break;
422 case 'w':
423 f |= f_warn;
424 break;
425 case 'f':
9dd01bc6 426 logname = optarg;
410c8acf 427 f |= f_noinput;
428 break;
06b2a088 429 case 'P':
430 pidfile = optarg;
431 break;
410c8acf 432 default:
433 f |= f_bogus;
434 break;
435 }
436 }
437 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
438 usage(stderr);
439 exit(EXIT_FAILURE);
440 }
441
06b2a088 442 /* --- Set various things up --- */
443
444 if (chdir(dir)) {
445 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
446 dir, strerror(errno));
447 }
448 if (logname)
449 logfile(logname);
450 if (!pidfile && (f & f_daemon) && ((f & f_syslog) || logname))
451 pidfile = "tripectl.pid";
452 if (pidfile && (pidfp = fopen(pidfile, "w")) == 0) {
453 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
454 pidfile, strerror(errno));
455 }
456 signal(SIGINT, sigdie);
457 signal(SIGQUIT, sigdie);
458 signal(SIGTERM, sigdie);
459 atexit(cleanup);
460
410c8acf 461 /* --- Connect to the server --- */
462
463 if (f & f_spawn) {
464 int pfd[2];
465 pid_t kid;
466 struct sigaction sa;
467 sigset_t newmask, oldmask;
468
469 sa.sa_handler = reap;
470 sigemptyset(&sa.sa_mask);
471 sa.sa_flags = SA_NOCLDSTOP;
472#ifdef SA_RESTART
473 sa.sa_flags |= SA_RESTART;
474#endif
475 sigaction(SIGCHLD, &sa, 0);
476
410c8acf 477 DA_PUSH(&spawnopts, 0);
ab46a787
MW
478 if (g != (gid_t)-1) putarg(&spawnopts, "-G%lu", (unsigned long)g);
479 if (u != (uid_t)-1) putarg(&spawnopts, "-U%lu", (unsigned long)u);
f685e692
MW
480 putarg(&spawnopts, "-a%s", sock);
481 putarg(&spawnopts, "-d.");
482 putarg(&spawnopts, "-F");
483 putarg(&spawnopts, "%s", spawnpath);
410c8acf 484 if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd))
485 die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
486 sigemptyset(&newmask);
487 sigaddset(&newmask, SIGCHLD);
488 sigprocmask(SIG_BLOCK, &newmask, &oldmask);
489 if ((kid = fork()) < 0)
490 die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
491 if (!kid) {
492 dup2(pfd[1], STDIN_FILENO);
493 dup2(pfd[1], STDOUT_FILENO);
410c8acf 494 close(pfd[0]);
6047fbac
MW
495 close(pfd[1]);
496 if (logfp) fclose(logfp);
497 if (pidfp) fclose(pidfp);
9dd01bc6 498 closelog();
6047fbac 499 if (f & f_daemon) detachtty();
410c8acf 500 execvp(DA(&spawnopts)[0], DA(&spawnopts));
501 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
502 }
503 sigprocmask(SIG_SETMASK, &oldmask, 0);
504 fd = pfd[0];
505 close(pfd[1]);
506 } else {
507 struct sockaddr_un sun;
508 size_t sz = strlen(sock) + 1;
06b2a088 509 if (sz > sizeof(sun.sun_path))
410c8acf 510 die(EXIT_FAILURE, "socket name `%s' too long", sock);
511 memset(&sun, 0, sizeof(sun));
512 sun.sun_family = AF_UNIX;
06b2a088 513 memcpy(sun.sun_path, sock, sz);
514 sz = sz + offsetof(struct sockaddr_un, sun_path);
410c8acf 515 if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
516 die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
517 if (connect(fd, (struct sockaddr *)&sun, sz)) {
518 die(EXIT_FAILURE, "error connecting to `%s': %s",
9dd01bc6 519 sun.sun_path, strerror(errno));
410c8acf 520 }
521 }
522
ab46a787 523 u_setugid(u, g);
410c8acf 524 if (f & f_daemon) {
19dd2531 525 if (daemonize())
410c8acf 526 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
527 }
06b2a088 528 if (pidfp) {
a803add7 529 fprintf(pidfp, "%li\n", (long)getpid());
06b2a088 530 fclose(pidfp);
531 }
3cdc3f3a 532 signal(SIGPIPE, SIG_IGN);
410c8acf 533
534 /* --- If we're meant to be interactive, do that --- */
535
3cdc3f3a 536 if (optind == argc)
537 setup("WATCH -A+tw");
410c8acf 538 if (!(f & f_noinput) && optind == argc) {
539 sel_state sel;
540 selbuf bu, bs;
541
542 sel_init(&sel);
543 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
544 selbuf_init(&bs, &sel, fd, sline, &bs);
545 for (;;) {
5f5150b1 546 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
410c8acf 547 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
548 }
549 }
550
551 /* --- If there's a command, submit it --- */
552
553 if (optind < argc) {
554 dstr d = DSTR_INIT;
3cdc3f3a 555 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
0ed0735f
MW
556 while (optind < argc)
557 u_quotify(&d, argv[optind++]);
410c8acf 558 dstr_putc(&d, '\n');
3cdc3f3a 559 errno = EIO;
560 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
561 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
410c8acf 562 dstr_destroy(&d);
563 f |= f_command;
564 }
565
566 /* --- Pull everything else out of the box --- */
567
568 {
5f5150b1 569 sel_state sel;
570 selbuf b;
571 sig hup;
572
573 sel_init(&sel);
574 selbuf_init(&b, &sel, fd, cline, 0);
575
410c8acf 576 if (f & f_syslog)
577 openlog(QUIS, 0, LOG_DAEMON);
9dd01bc6 578 if (logfp) {
5f5150b1 579 sig_init(&sel);
580 sig_add(&hup, SIGHUP, sighup, 0);
9dd01bc6 581 }
410c8acf 582 for (;;) {
5f5150b1 583 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
584 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
410c8acf 585 }
410c8acf 586 }
587
588 return (0);
589}
590
591/*----- That's all, folks -------------------------------------------------*/