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