chiark / gitweb /
pathmtu: Reset the timeout on each packet.
[tripe] / client / tripectl.c
CommitLineData
410c8acf 1/* -*-c-*-
2 *
410c8acf 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
8efdf64b 77static sel_state sel;
06b2a088 78static const char *pidfile = 0;
79static const char *logname = 0;
410c8acf 80static FILE *logfp = 0;
81static unsigned f = 0;
82static int fd;
de014da6 83static const char *bgtag = 0;
410c8acf 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
97static void reap(int sig)
98{
410c8acf 99 int e = errno;
06b2a088 100 while (waitpid(-1, 0, WNOHANG) > 0)
410c8acf 101 ;
102 errno = e;
103}
104
105static 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
de014da6 114static 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
2b3ef395
MW
123static 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) {
155a970a 135 case LOG_WARNING: cat = "warning"; break;
2b3ef395
MW
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 }
155a970a 142 if (prio == LOG_WARNING && (f & f_warn))
2b3ef395
MW
143 fprintf(stderr, "Warning: %s\n", d.buf);
144 dstr_destroy(&d);
145}
146
de014da6 147static void checkfg(void)
6047fbac 148 { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
de014da6 149
6be88c14 150static void cline(char *p, size_t len, void *b)
410c8acf 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;
2b3ef395
MW
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) {
de014da6 168 checkfg();
410c8acf 169 die(EXIT_FAILURE, "%s", p);
de014da6 170 } else if (strcmp(q, "INFO") == 0) {
171 checkfg();
410c8acf 172 puts(p);
5136c31e 173 fflush(stdout);
de014da6 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);
410c8acf 183 exit(0);
de014da6 184 } else if (strcmp(q, "BGINFO") == 0) {
185 checkbg(&p);
186 puts(p);
5136c31e 187 fflush(stdout);
de014da6 188 } else if (strcmp(q, "BGFAIL") == 0) {
189 checkbg(&p);
190 die(EXIT_FAILURE, "%s", p);
191 } else
e04c2d50 192 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
410c8acf 193}
194
6be88c14 195static void sline(char *p, size_t len, void *b)
410c8acf 196{
197 if (!p) {
198 if (!(f & f_uclose))
199 moan("server closed the connection");
200 exit(0);
201 }
202 puts(p);
5136c31e 203 fflush(stdout);
410c8acf 204}
205
6be88c14 206static void uline(char *p, size_t len, void *b)
410c8acf 207{
410c8acf 208 if (!p) {
209 selbuf_destroy(b);
210 shutdown(fd, 1);
211 f |= f_uclose;
212 } else {
6be88c14 213 p[len] = '\n';
3cdc3f3a 214 errno = EIO;
215 if (write(fd, p, len + 1) != len + 1)
216 moan("write failed: %s", strerror(errno));
217 }
218}
219
155a970a
MW
220static void eline(char *p, size_t len, void *b)
221{
222 if (p)
223 dolog(LOG_WARNING, "(stderr): %s", p);
224 else {
225 selbuf_destroy(b);
226 close(fd);
227 }
228}
229
3cdc3f3a 230static void setup(const char *cmd)
231{
232 dstr d = DSTR_INIT;
233 char ch;
234 char *p, *q;
235 int n;
236
237 dstr_puts(&d, cmd);
238 dstr_putc(&d, '\n');
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));
243 }
244 dstr_reset(&d);
245 for (;;) {
246 n = read(fd, &ch, 1);
247 if (!n)
248 die(EXIT_FAILURE, "unexpected EOF during setup");
249 if (n < 0) {
250 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
251 cmd, strerror(errno));
252 }
253 if (d.len < 256)
254 dstr_putc(&d, ch);
255 if (ch == '\n') {
256 p = d.buf;
257 q = str_getword(&p);
258 if (!q)
259 ;
260 else if (strcmp(q, "OK") == 0)
261 return;
262 else if (strcmp(q, "FAIL") == 0)
263 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
264 dstr_reset(&d);
265 }
410c8acf 266 }
267}
268
9dd01bc6 269static void logfile(const char *name)
270{
fa4bef80 271 FILE *fp;
272
273 if ((fp = fopen(name, "a")) != 0) {
274 if (logfp)
275 fclose(logfp);
276 logfp = fp;
277 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
278 } else {
279 dstr d = DSTR_INIT;
280 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
281 if (logfp)
282 writelog("error", d.buf);
283 else if (logname)
284 die(EXIT_FAILURE, d.buf);
285 if (f & f_syslog)
92e57abc 286 syslog(LOG_ERR, "%s", d.buf);
fa4bef80 287 dstr_destroy(&d);
9dd01bc6 288 }
9dd01bc6 289}
290
f98df549 291static void sighup(int sig, void *v) { logfile(logname); }
5f5150b1 292
6047fbac 293static void cleanup(void) { if (pidfile) unlink(pidfile); }
06b2a088 294
295static void sigdie(int sig)
6047fbac 296 { cleanup(); signal(sig, SIG_DFL); raise(sig); }
06b2a088 297
f685e692
MW
298static void putarg(string_v *av, const char *fmt, ...)
299{
300 va_list ap;
301 dstr d = DSTR_INIT;
302
303 va_start(ap, fmt);
304 dstr_vputf(&d, fmt, &ap);
305 dstr_putz(&d);
306 va_end(ap);
307 DA_UNSHIFT(av, xstrdup(d.buf));
308 dstr_destroy(&d);
309}
310
410c8acf 311static void version(FILE *fp)
f98df549 312 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
410c8acf 313
314static void usage(FILE *fp)
315{
316 pquis(fp, "\
317Usage:\n\
2d752320 318 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
319 $ [-Dl] [-f FILE] [-OPTIONS]\n\
410c8acf 320Options:\n\
2d752320 321 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
322 [-p PROGRAM] [-S ARG,ARG,...]\n\
410c8acf 323");
324}
325
326static void help(FILE *fp)
327{
328 version(fp);
329 fputc('\n', fp);
330 usage(fp);
331 fputs("\
332\n\
333Options in full:\n\
334\n\
335-h, --help Show this help text.\n\
336-v, --version Show version number.\n\
337-u, --usage Show brief usage message.\n\
338\n\
339-D, --daemon Become a background task after connecting.\n\
ef4a1ab7 340-d, --directory=DIR Select current directory [default " CONFIGDIR "].\n\
ab46a787
MW
341-U, --setuid=USER Set uid to USER after initialization.\n\
342-G, --setgid=GROUP Set gid to GROUP after initialization.\n\
3cdc3f3a 343-a, --admin-socket=FILE Select socket to connect to\n\
e04c2d50 344 [default " SOCKETDIR "/tripesock].\n\
06b2a088 345-P, --pidfile=FILE Write process-id to FILE.\n\
410c8acf 346\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\
350\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\
354", fp);
355}
356
357int main(int argc, char *argv[])
358{
ef4a1ab7 359 const char *dir = CONFIGDIR;
360 const char *sock = SOCKETDIR "/tripesock";
410c8acf 361 const char *spawnpath = "tripe";
362 string_v spawnopts = DA_INIT;
363 char *p;
06b2a088 364 FILE *pidfp = 0;
8efdf64b
MW
365 int i;
366 size_t sz;
ab46a787
MW
367 uid_t u = -1;
368 gid_t g = -1;
155a970a 369 int pfd[2], efd[2];
8efdf64b
MW
370 pid_t kid;
371 struct sigaction sa;
372 sigset_t newmask, oldmask;
373 struct sockaddr_un sun;
155a970a 374 selbuf bu, bs, be;
8efdf64b
MW
375 dstr d = DSTR_INIT;
376 sig hup;
410c8acf 377
378 ego(argv[0]);
379
380 if ((p = getenv("TRIPEDIR")) != 0)
381 dir = p;
797cf76b
MW
382 if ((p = getenv("TRIPESOCK")) != 0)
383 sock = p;
410c8acf 384
385 /* --- Parse the arguments --- */
386
387 for (;;) {
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' },
ab46a787
MW
393 { "uid", OPTF_ARGREQ, 0, 'U' },
394 { "setuid", OPTF_ARGREQ, 0, 'U' },
395 { "gid", OPTF_ARGREQ, 0, 'G' },
396 { "setgid", OPTF_ARGREQ, 0, 'G' },
410c8acf 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' },
06b2a088 405 { "pidfile", OPTF_ARGREQ, 0, 'P' },
410c8acf 406 { 0, 0, 0, 0 }
407 };
408
8efdf64b 409 i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:", opts, 0, 0, 0);
410c8acf 410 if (i < 0)
411 break;
412 switch (i) {
413 case 'h':
414 help(stdout);
415 exit(0);
416 case 'v':
417 version(stdout);
418 exit(0);
419 case 'u':
420 usage(stdout);
421 exit(0);
422 case 'D':
423 f |= f_daemon | f_noinput;
424 break;
ab46a787
MW
425 case 'U':
426 u = u_getuser(optarg, &g);
427 break;
428 case 'G':
429 g = u_getgroup(optarg);
430 break;
410c8acf 431 case 'd':
432 dir = optarg;
433 break;
434 case 'a':
435 sock = optarg;
436 break;
437 case 's':
438 f |= f_spawn;
439 break;
440 case 'p':
441 f |= f_spawn;
442 spawnpath = optarg;
443 break;
444 case 'S':
445 f |= f_spawn | f_spawnopts;
446 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
447 DA_PUSH(&spawnopts, p);
448 break;
449 case 'l':
450 f |= f_syslog | f_noinput;
451 break;
452 case 'w':
453 f |= f_warn;
454 break;
455 case 'f':
9dd01bc6 456 logname = optarg;
410c8acf 457 f |= f_noinput;
458 break;
06b2a088 459 case 'P':
460 pidfile = optarg;
461 break;
410c8acf 462 default:
463 f |= f_bogus;
464 break;
465 }
466 }
467 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
468 usage(stderr);
469 exit(EXIT_FAILURE);
470 }
471
06b2a088 472 /* --- Set various things up --- */
473
474 if (chdir(dir)) {
475 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
476 dir, strerror(errno));
477 }
478 if (logname)
479 logfile(logname);
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));
485 }
8efdf64b
MW
486 sel_init(&sel);
487 sig_init(&sel);
06b2a088 488 signal(SIGINT, sigdie);
489 signal(SIGQUIT, sigdie);
490 signal(SIGTERM, sigdie);
491 atexit(cleanup);
492
410c8acf 493 /* --- Connect to the server --- */
494
495 if (f & f_spawn) {
410c8acf 496 sa.sa_handler = reap;
497 sigemptyset(&sa.sa_mask);
498 sa.sa_flags = SA_NOCLDSTOP;
499#ifdef SA_RESTART
500 sa.sa_flags |= SA_RESTART;
501#endif
502 sigaction(SIGCHLD, &sa, 0);
503
410c8acf 504 DA_PUSH(&spawnopts, 0);
ab46a787
MW
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);
f685e692
MW
507 putarg(&spawnopts, "-a%s", sock);
508 putarg(&spawnopts, "-d.");
509 putarg(&spawnopts, "-F");
510 putarg(&spawnopts, "%s", spawnpath);
155a970a 511 if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd) || pipe(efd))
410c8acf 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));
518 if (!kid) {
519 dup2(pfd[1], STDIN_FILENO);
520 dup2(pfd[1], STDOUT_FILENO);
155a970a
MW
521 dup2(efd[1], STDERR_FILENO);
522 close(pfd[0]); close(pfd[1]);
523 close(efd[0]); close(efd[1]);
6047fbac
MW
524 if (logfp) fclose(logfp);
525 if (pidfp) fclose(pidfp);
9dd01bc6 526 closelog();
6047fbac 527 if (f & f_daemon) detachtty();
410c8acf 528 execvp(DA(&spawnopts)[0], DA(&spawnopts));
529 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
530 }
531 sigprocmask(SIG_SETMASK, &oldmask, 0);
532 fd = pfd[0];
155a970a
MW
533 close(pfd[1]); close(efd[1]);
534 selbuf_init(&be, &sel, efd[0], eline, &be);
410c8acf 535 } else {
8efdf64b 536 sz = strlen(sock) + 1;
06b2a088 537 if (sz > sizeof(sun.sun_path))
410c8acf 538 die(EXIT_FAILURE, "socket name `%s' too long", sock);
539 memset(&sun, 0, sizeof(sun));
540 sun.sun_family = AF_UNIX;
06b2a088 541 memcpy(sun.sun_path, sock, sz);
542 sz = sz + offsetof(struct sockaddr_un, sun_path);
410c8acf 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",
9dd01bc6 547 sun.sun_path, strerror(errno));
410c8acf 548 }
549 }
550
ab46a787 551 u_setugid(u, g);
410c8acf 552 if (f & f_daemon) {
19dd2531 553 if (daemonize())
410c8acf 554 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
555 }
06b2a088 556 if (pidfp) {
a803add7 557 fprintf(pidfp, "%li\n", (long)getpid());
06b2a088 558 fclose(pidfp);
559 }
3cdc3f3a 560 signal(SIGPIPE, SIG_IGN);
410c8acf 561
562 /* --- If we're meant to be interactive, do that --- */
563
3cdc3f3a 564 if (optind == argc)
565 setup("WATCH -A+tw");
410c8acf 566 if (!(f & f_noinput) && optind == argc) {
410c8acf 567 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
568 selbuf_init(&bs, &sel, fd, sline, &bs);
569 for (;;) {
5f5150b1 570 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
410c8acf 571 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
572 }
573 }
574
575 /* --- If there's a command, submit it --- */
576
577 if (optind < argc) {
3cdc3f3a 578 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
0ed0735f
MW
579 while (optind < argc)
580 u_quotify(&d, argv[optind++]);
410c8acf 581 dstr_putc(&d, '\n');
3cdc3f3a 582 errno = EIO;
583 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
584 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
410c8acf 585 dstr_destroy(&d);
586 f |= f_command;
587 }
588
589 /* --- Pull everything else out of the box --- */
590
8efdf64b 591 selbuf_init(&bs, &sel, fd, cline, 0);
5f5150b1 592
8efdf64b
MW
593 if (f & f_syslog)
594 openlog(QUIS, 0, LOG_DAEMON);
595 if (logfp)
596 sig_add(&hup, SIGHUP, sighup, 0);
597 for (;;) {
598 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
599 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
410c8acf 600 }
601
602 return (0);
603}
604
605/*----- That's all, folks -------------------------------------------------*/