chiark / gitweb /
One that got away.
[tripe] / client.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>
54#include <mLib/darray.h>
55#include <mLib/dstr.h>
410c8acf 56#include <mLib/mdwopt.h>
57#include <mLib/quis.h>
58#include <mLib/report.h>
59#include <mLib/sel.h>
60#include <mLib/selbuf.h>
5f5150b1 61#include <mLib/sig.h>
410c8acf 62#include <mLib/str.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
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)
123{
124 if (bgtag)
125 die(EXIT_FAILURE, "unexpected foreground response");
126}
127
6be88c14 128static void cline(char *p, size_t len, void *b)
410c8acf 129{
130 char *q;
131 if (!p) {
132 if (f & f_command)
133 die(EXIT_FAILURE, "server dropped the connection");
134 exit(0);
135 }
136 q = str_getword(&p);
137 if (!q)
138 return;
139 if (strcmp(q, "WARN") == 0) {
140 if (f & f_syslog)
141 syslog(LOG_WARNING, "%s", p);
142 if (logfp)
143 writelog("warning", p);
144 if (f & f_warn)
145 fprintf(stderr, "Warning: %s\n", p);
146 } else if (strcmp(q, "TRACE") == 0) {
147 if (f & f_syslog)
148 syslog(LOG_DEBUG, "%s", p);
149 if (logfp)
150 writelog("debug", p);
151 } else if (!(f & f_command)) {
152 if (f & f_syslog)
153 syslog(LOG_ERR, "unexpected output `%s %s'", q, p);
154 if (logfp) {
155 dstr d = DSTR_INIT;
156 dstr_putf(&d, "unexpected output `%s %s'", q, p);
157 writelog("error", d.buf);
158 dstr_destroy(&d);
159 }
de014da6 160 } else if (strcmp(q, "FAIL") == 0) {
161 checkfg();
410c8acf 162 die(EXIT_FAILURE, "%s", p);
de014da6 163 } else if (strcmp(q, "INFO") == 0) {
164 checkfg();
410c8acf 165 puts(p);
de014da6 166 } else if (strcmp(q, "OK") == 0) {
167 checkfg();
168 exit(0);
169 } else if (strcmp(q, "BGDETACH") == 0) {
170 if (bgtag)
171 die(EXIT_FAILURE, "repeat detach");
172 bgtag = xstrdup(p);
173 } else if (strcmp(q, "BGOK") == 0) {
174 checkbg(&p);
410c8acf 175 exit(0);
de014da6 176 } else if (strcmp(q, "BGINFO") == 0) {
177 checkbg(&p);
178 puts(p);
179 } else if (strcmp(q, "BGFAIL") == 0) {
180 checkbg(&p);
181 die(EXIT_FAILURE, "%s", p);
182 } else
410c8acf 183 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
184}
185
6be88c14 186static void sline(char *p, size_t len, void *b)
410c8acf 187{
188 if (!p) {
189 if (!(f & f_uclose))
190 moan("server closed the connection");
191 exit(0);
192 }
193 puts(p);
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
5f5150b1 271static void sighup(int sig, void *v)
272{
273 logfile(logname);
274}
275
06b2a088 276static void cleanup(void)
277{
278 if (pidfile)
279 unlink(pidfile);
280}
281
282static void sigdie(int sig)
283{
284 cleanup();
285 signal(sig, SIG_DFL);
286 raise(sig);
287}
288
410c8acf 289static void version(FILE *fp)
290{
291 pquis(fp, "$, TrIPE version " VERSION "\n");
292}
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;
348
349 /* --- Parse the arguments --- */
350
351 for (;;) {
352 static const struct option opts[] = {
353 { "help", 0, 0, 'h' },
354 { "version", 0, 0, 'v' },
355 { "usage", 0, 0, 'u' },
356 { "daemon", 0, 0, 'D' },
357 { "directory", OPTF_ARGREQ, 0, 'd' },
358 { "admin-socket", OPTF_ARGREQ, 0, 'a' },
359 { "spawn", 0, 0, 's' },
360 { "spawn-path", OPTF_ARGREQ, 0, 'p' },
361 { "spawn-args", OPTF_ARGREQ, 0, 'S' },
362 { "syslog", 0, 0, 'l' },
363 { "logfile", OPTF_ARGREQ, 0, 'f' },
364 { "warnings", 0, 0, 'w' },
06b2a088 365 { "pidfile", OPTF_ARGREQ, 0, 'P' },
410c8acf 366 { 0, 0, 0, 0 }
367 };
368
06b2a088 369 int i = mdwopt(argc, argv, "+hvuDd:a:sp:S:lwf:nP:", opts, 0, 0, 0);
410c8acf 370 if (i < 0)
371 break;
372 switch (i) {
373 case 'h':
374 help(stdout);
375 exit(0);
376 case 'v':
377 version(stdout);
378 exit(0);
379 case 'u':
380 usage(stdout);
381 exit(0);
382 case 'D':
383 f |= f_daemon | f_noinput;
384 break;
385 case 'd':
386 dir = optarg;
387 break;
388 case 'a':
389 sock = optarg;
390 break;
391 case 's':
392 f |= f_spawn;
393 break;
394 case 'p':
395 f |= f_spawn;
396 spawnpath = optarg;
397 break;
398 case 'S':
399 f |= f_spawn | f_spawnopts;
400 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
401 DA_PUSH(&spawnopts, p);
402 break;
403 case 'l':
404 f |= f_syslog | f_noinput;
405 break;
406 case 'w':
407 f |= f_warn;
408 break;
409 case 'f':
9dd01bc6 410 logname = optarg;
410c8acf 411 f |= f_noinput;
412 break;
06b2a088 413 case 'P':
414 pidfile = optarg;
415 break;
410c8acf 416 default:
417 f |= f_bogus;
418 break;
419 }
420 }
421 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
422 usage(stderr);
423 exit(EXIT_FAILURE);
424 }
425
06b2a088 426 /* --- Set various things up --- */
427
428 if (chdir(dir)) {
429 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
430 dir, strerror(errno));
431 }
432 if (logname)
433 logfile(logname);
434 if (!pidfile && (f & f_daemon) && ((f & f_syslog) || logname))
435 pidfile = "tripectl.pid";
436 if (pidfile && (pidfp = fopen(pidfile, "w")) == 0) {
437 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
438 pidfile, strerror(errno));
439 }
440 signal(SIGINT, sigdie);
441 signal(SIGQUIT, sigdie);
442 signal(SIGTERM, sigdie);
443 atexit(cleanup);
444
410c8acf 445 /* --- Connect to the server --- */
446
447 if (f & f_spawn) {
448 int pfd[2];
449 pid_t kid;
450 struct sigaction sa;
451 sigset_t newmask, oldmask;
452
453 sa.sa_handler = reap;
454 sigemptyset(&sa.sa_mask);
455 sa.sa_flags = SA_NOCLDSTOP;
456#ifdef SA_RESTART
457 sa.sa_flags |= SA_RESTART;
458#endif
459 sigaction(SIGCHLD, &sa, 0);
460
06b2a088 461 DA_UNSHIFT(&spawnopts, (char *)sock);
462 DA_UNSHIFT(&spawnopts, "-a");
463 DA_UNSHIFT(&spawnopts, "-d.");
d071d798 464 DA_UNSHIFT(&spawnopts, (char *)spawnpath);
410c8acf 465 DA_PUSH(&spawnopts, 0);
466 if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd))
467 die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
468 sigemptyset(&newmask);
469 sigaddset(&newmask, SIGCHLD);
470 sigprocmask(SIG_BLOCK, &newmask, &oldmask);
471 if ((kid = fork()) < 0)
472 die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
473 if (!kid) {
474 dup2(pfd[1], STDIN_FILENO);
475 dup2(pfd[1], STDOUT_FILENO);
476 close(pfd[1]);
477 close(pfd[0]);
9dd01bc6 478 if (logfp)
479 fclose(logfp);
7ed14135 480 if (pidfp)
481 fclose(pidfp);
9dd01bc6 482 closelog();
06b2a088 483 if (f & f_daemon)
484 u_detach();
410c8acf 485 execvp(DA(&spawnopts)[0], DA(&spawnopts));
486 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
487 }
488 sigprocmask(SIG_SETMASK, &oldmask, 0);
489 fd = pfd[0];
490 close(pfd[1]);
491 } else {
492 struct sockaddr_un sun;
493 size_t sz = strlen(sock) + 1;
06b2a088 494 if (sz > sizeof(sun.sun_path))
410c8acf 495 die(EXIT_FAILURE, "socket name `%s' too long", sock);
496 memset(&sun, 0, sizeof(sun));
497 sun.sun_family = AF_UNIX;
06b2a088 498 memcpy(sun.sun_path, sock, sz);
499 sz = sz + offsetof(struct sockaddr_un, sun_path);
410c8acf 500 if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
501 die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
502 if (connect(fd, (struct sockaddr *)&sun, sz)) {
503 die(EXIT_FAILURE, "error connecting to `%s': %s",
9dd01bc6 504 sun.sun_path, strerror(errno));
410c8acf 505 }
506 }
507
508 if (f & f_daemon) {
509 if (u_daemon())
510 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
511 }
06b2a088 512 if (pidfp) {
a803add7 513 fprintf(pidfp, "%li\n", (long)getpid());
06b2a088 514 fclose(pidfp);
515 }
3cdc3f3a 516 signal(SIGPIPE, SIG_IGN);
410c8acf 517
518 /* --- If we're meant to be interactive, do that --- */
519
3cdc3f3a 520 if (optind == argc)
521 setup("WATCH -A+tw");
410c8acf 522 if (!(f & f_noinput) && optind == argc) {
523 sel_state sel;
524 selbuf bu, bs;
525
526 sel_init(&sel);
527 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
528 selbuf_init(&bs, &sel, fd, sline, &bs);
529 for (;;) {
5f5150b1 530 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
410c8acf 531 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
532 }
533 }
534
535 /* --- If there's a command, submit it --- */
536
537 if (optind < argc) {
538 dstr d = DSTR_INIT;
3cdc3f3a 539 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
410c8acf 540 dstr_puts(&d, argv[optind++]);
541 while (optind < argc) {
542 dstr_putc(&d, ' ');
543 dstr_puts(&d, argv[optind++]);
544 }
545 dstr_putc(&d, '\n');
3cdc3f3a 546 errno = EIO;
547 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
548 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
410c8acf 549 dstr_destroy(&d);
550 f |= f_command;
551 }
552
553 /* --- Pull everything else out of the box --- */
554
555 {
5f5150b1 556 sel_state sel;
557 selbuf b;
558 sig hup;
559
560 sel_init(&sel);
561 selbuf_init(&b, &sel, fd, cline, 0);
562
410c8acf 563 if (f & f_syslog)
564 openlog(QUIS, 0, LOG_DAEMON);
9dd01bc6 565 if (logfp) {
5f5150b1 566 sig_init(&sel);
567 sig_add(&hup, SIGHUP, sighup, 0);
9dd01bc6 568 }
410c8acf 569 for (;;) {
5f5150b1 570 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
571 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
410c8acf 572 }
410c8acf 573 }
574
575 return (0);
576}
577
578/*----- That's all, folks -------------------------------------------------*/