4c8dde5a5a246f8375f54417981b4a066ecc9dfb
[tripe] / client / tripectl.c
1 /* -*-c-*-
2 *
3 * Client for TrIPE
4 *
5 * (c) 2001 Straylight/Edgeware
6 */
7
8 /*----- Licensing notice --------------------------------------------------*
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.
16 *
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.
21 *
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
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "config.h"
30
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>
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>
58 #include <mLib/sel.h>
59 #include <mLib/selbuf.h>
60 #include <mLib/sig.h>
61 #include <mLib/str.h>
62 #include <mLib/versioncmp.h>
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
77 static sel_state sel;
78 static const char *pidfile = 0;
79 static const char *logname = 0;
80 static FILE *logfp = 0;
81 static unsigned f = 0;
82 static int fd;
83 static const char *bgtag = 0;
84
85 #define f_bogus 1u
86 #define f_spawn 2u
87 #define f_daemon 4u
88 #define f_spawnopts 8u
89 #define f_syslog 16u
90 #define f_command 32u
91 #define f_noinput 64u
92 #define f_warn 128u
93 #define f_uclose 256u
94
95 /*----- Main code ---------------------------------------------------------*/
96
97 static void reap(int sig)
98 {
99 int e = errno;
100 while (waitpid(-1, 0, WNOHANG) > 0)
101 ;
102 errno = e;
103 }
104
105 static void writelog(const char *cat, const char *msg)
106 {
107 char buf[256];
108 time_t t = time(0);
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);
112 }
113
114 static void checkbg(char **p)
115 {
116 char *q = str_getword(p);
117 if (!q)
118 die(EXIT_FAILURE, "missing background tag");
119 if (!bgtag || strcmp(bgtag, q) != 0)
120 die(EXIT_FAILURE, "unexpected background tag `%s'", q);
121 }
122
123 static void dolog(int prio, const char *msg, ...)
124 {
125 va_list ap;
126 dstr d = DSTR_INIT;
127 const char *cat;
128
129 va_start(ap, msg);
130 dstr_vputf(&d, msg, &ap);
131 va_end(ap);
132 if (f & f_syslog) syslog(prio, "%s", d.buf);
133 if (logfp) {
134 switch (prio) {
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;
139 }
140 writelog(cat, d.buf);
141 }
142 if (prio == LOG_WARN && (f & f_warn))
143 fprintf(stderr, "Warning: %s\n", d.buf);
144 dstr_destroy(&d);
145 }
146
147 static void checkfg(void)
148 { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
149
150 static void cline(char *p, size_t len, void *b)
151 {
152 char *q;
153 if (!p) {
154 if (f & f_command)
155 die(EXIT_FAILURE, "server dropped the connection");
156 exit(0);
157 }
158 q = str_getword(&p);
159 if (!q)
160 return;
161 if (strcmp(q, "WARN") == 0)
162 dolog(LOG_WARNING, p);
163 else if (strcmp(q, "TRACE") == 0)
164 dolog(LOG_DEBUG, p);
165 else if (!(f & f_command))
166 dolog(LOG_ERR, "unexpected output `%s %s'", q, p);
167 else if (strcmp(q, "FAIL") == 0) {
168 checkfg();
169 die(EXIT_FAILURE, "%s", p);
170 } else if (strcmp(q, "INFO") == 0) {
171 checkfg();
172 puts(p);
173 fflush(stdout);
174 } else if (strcmp(q, "OK") == 0) {
175 checkfg();
176 exit(0);
177 } else if (strcmp(q, "BGDETACH") == 0) {
178 if (bgtag)
179 die(EXIT_FAILURE, "repeat detach");
180 bgtag = xstrdup(p);
181 } else if (strcmp(q, "BGOK") == 0) {
182 checkbg(&p);
183 exit(0);
184 } else if (strcmp(q, "BGINFO") == 0) {
185 checkbg(&p);
186 puts(p);
187 fflush(stdout);
188 } else if (strcmp(q, "BGFAIL") == 0) {
189 checkbg(&p);
190 die(EXIT_FAILURE, "%s", p);
191 } else
192 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
193 }
194
195 static void sline(char *p, size_t len, void *b)
196 {
197 if (!p) {
198 if (!(f & f_uclose))
199 moan("server closed the connection");
200 exit(0);
201 }
202 puts(p);
203 fflush(stdout);
204 }
205
206 static void uline(char *p, size_t len, void *b)
207 {
208 if (!p) {
209 selbuf_destroy(b);
210 shutdown(fd, 1);
211 f |= f_uclose;
212 } else {
213 p[len] = '\n';
214 errno = EIO;
215 if (write(fd, p, len + 1) != len + 1)
216 moan("write failed: %s", strerror(errno));
217 }
218 }
219
220 static void setup(const char *cmd)
221 {
222 dstr d = DSTR_INIT;
223 char ch;
224 char *p, *q;
225 int n;
226
227 dstr_puts(&d, cmd);
228 dstr_putc(&d, '\n');
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));
233 }
234 dstr_reset(&d);
235 for (;;) {
236 n = read(fd, &ch, 1);
237 if (!n)
238 die(EXIT_FAILURE, "unexpected EOF during setup");
239 if (n < 0) {
240 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
241 cmd, strerror(errno));
242 }
243 if (d.len < 256)
244 dstr_putc(&d, ch);
245 if (ch == '\n') {
246 p = d.buf;
247 q = str_getword(&p);
248 if (!q)
249 ;
250 else if (strcmp(q, "OK") == 0)
251 return;
252 else if (strcmp(q, "FAIL") == 0)
253 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
254 dstr_reset(&d);
255 }
256 }
257 }
258
259 static void logfile(const char *name)
260 {
261 FILE *fp;
262
263 if ((fp = fopen(name, "a")) != 0) {
264 if (logfp)
265 fclose(logfp);
266 logfp = fp;
267 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
268 } else {
269 dstr d = DSTR_INIT;
270 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
271 if (logfp)
272 writelog("error", d.buf);
273 else if (logname)
274 die(EXIT_FAILURE, d.buf);
275 if (f & f_syslog)
276 syslog(LOG_ERR, d.buf);
277 dstr_destroy(&d);
278 }
279 }
280
281 static void sighup(int sig, void *v) { logfile(logname); }
282
283 static void cleanup(void) { if (pidfile) unlink(pidfile); }
284
285 static void sigdie(int sig)
286 { cleanup(); signal(sig, SIG_DFL); raise(sig); }
287
288 static void putarg(string_v *av, const char *fmt, ...)
289 {
290 va_list ap;
291 dstr d = DSTR_INIT;
292
293 va_start(ap, fmt);
294 dstr_vputf(&d, fmt, &ap);
295 dstr_putz(&d);
296 va_end(ap);
297 DA_UNSHIFT(av, xstrdup(d.buf));
298 dstr_destroy(&d);
299 }
300
301 static void version(FILE *fp)
302 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
303
304 static void usage(FILE *fp)
305 {
306 pquis(fp, "\
307 Usage:\n\
308 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
309 $ [-Dl] [-f FILE] [-OPTIONS]\n\
310 Options:\n\
311 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
312 [-p PROGRAM] [-S ARG,ARG,...]\n\
313 ");
314 }
315
316 static void help(FILE *fp)
317 {
318 version(fp);
319 fputc('\n', fp);
320 usage(fp);
321 fputs("\
322 \n\
323 Options in full:\n\
324 \n\
325 -h, --help Show this help text.\n\
326 -v, --version Show version number.\n\
327 -u, --usage Show brief usage message.\n\
328 \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\
336 \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\
340 \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\
344 ", fp);
345 }
346
347 int main(int argc, char *argv[])
348 {
349 const char *dir = CONFIGDIR;
350 const char *sock = SOCKETDIR "/tripesock";
351 const char *spawnpath = "tripe";
352 string_v spawnopts = DA_INIT;
353 char *p;
354 FILE *pidfp = 0;
355 int i;
356 size_t sz;
357 uid_t u = -1;
358 gid_t g = -1;
359 int pfd[2];
360 pid_t kid;
361 struct sigaction sa;
362 sigset_t newmask, oldmask;
363 struct sockaddr_un sun;
364 selbuf bu, bs;
365 dstr d = DSTR_INIT;
366 sig hup;
367
368 ego(argv[0]);
369
370 if ((p = getenv("TRIPEDIR")) != 0)
371 dir = p;
372 if ((p = getenv("TRIPESOCK")) != 0)
373 sock = p;
374
375 /* --- Parse the arguments --- */
376
377 for (;;) {
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' },
396 { 0, 0, 0, 0 }
397 };
398
399 i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:", opts, 0, 0, 0);
400 if (i < 0)
401 break;
402 switch (i) {
403 case 'h':
404 help(stdout);
405 exit(0);
406 case 'v':
407 version(stdout);
408 exit(0);
409 case 'u':
410 usage(stdout);
411 exit(0);
412 case 'D':
413 f |= f_daemon | f_noinput;
414 break;
415 case 'U':
416 u = u_getuser(optarg, &g);
417 break;
418 case 'G':
419 g = u_getgroup(optarg);
420 break;
421 case 'd':
422 dir = optarg;
423 break;
424 case 'a':
425 sock = optarg;
426 break;
427 case 's':
428 f |= f_spawn;
429 break;
430 case 'p':
431 f |= f_spawn;
432 spawnpath = optarg;
433 break;
434 case 'S':
435 f |= f_spawn | f_spawnopts;
436 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
437 DA_PUSH(&spawnopts, p);
438 break;
439 case 'l':
440 f |= f_syslog | f_noinput;
441 break;
442 case 'w':
443 f |= f_warn;
444 break;
445 case 'f':
446 logname = optarg;
447 f |= f_noinput;
448 break;
449 case 'P':
450 pidfile = optarg;
451 break;
452 default:
453 f |= f_bogus;
454 break;
455 }
456 }
457 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
458 usage(stderr);
459 exit(EXIT_FAILURE);
460 }
461
462 /* --- Set various things up --- */
463
464 if (chdir(dir)) {
465 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
466 dir, strerror(errno));
467 }
468 if (logname)
469 logfile(logname);
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));
475 }
476 sel_init(&sel);
477 sig_init(&sel);
478 signal(SIGINT, sigdie);
479 signal(SIGQUIT, sigdie);
480 signal(SIGTERM, sigdie);
481 atexit(cleanup);
482
483 /* --- Connect to the server --- */
484
485 if (f & f_spawn) {
486 sa.sa_handler = reap;
487 sigemptyset(&sa.sa_mask);
488 sa.sa_flags = SA_NOCLDSTOP;
489 #ifdef SA_RESTART
490 sa.sa_flags |= SA_RESTART;
491 #endif
492 sigaction(SIGCHLD, &sa, 0);
493
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));
508 if (!kid) {
509 dup2(pfd[1], STDIN_FILENO);
510 dup2(pfd[1], STDOUT_FILENO);
511 close(pfd[0]);
512 close(pfd[1]);
513 if (logfp) fclose(logfp);
514 if (pidfp) fclose(pidfp);
515 closelog();
516 if (f & f_daemon) detachtty();
517 execvp(DA(&spawnopts)[0], DA(&spawnopts));
518 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
519 }
520 sigprocmask(SIG_SETMASK, &oldmask, 0);
521 fd = pfd[0];
522 close(pfd[1]);
523 } else {
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));
536 }
537 }
538
539 u_setugid(u, g);
540 if (f & f_daemon) {
541 if (daemonize())
542 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
543 }
544 if (pidfp) {
545 fprintf(pidfp, "%li\n", (long)getpid());
546 fclose(pidfp);
547 }
548 signal(SIGPIPE, SIG_IGN);
549
550 /* --- If we're meant to be interactive, do that --- */
551
552 if (optind == argc)
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);
557 for (;;) {
558 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
559 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
560 }
561 }
562
563 /* --- If there's a command, submit it --- */
564
565 if (optind < argc) {
566 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
567 while (optind < argc)
568 u_quotify(&d, argv[optind++]);
569 dstr_putc(&d, '\n');
570 errno = EIO;
571 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
572 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
573 dstr_destroy(&d);
574 f |= f_command;
575 }
576
577 /* --- Pull everything else out of the box --- */
578
579 selbuf_init(&bs, &sel, fd, cline, 0);
580
581 if (f & f_syslog)
582 openlog(QUIS, 0, LOG_DAEMON);
583 if (logfp)
584 sig_add(&hup, SIGHUP, sighup, 0);
585 for (;;) {
586 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
587 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
588 }
589
590 return (0);
591 }
592
593 /*----- That's all, folks -------------------------------------------------*/