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