chiark / gitweb /
client/tripectl: Flush output after each line.
[tripe] / client / tripectl.c
... / ...
CommitLineData
1/* -*-c-*-
2 *
3 * $Id$
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
29/*----- Header files ------------------------------------------------------*/
30
31#include "config.h"
32
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>
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>
61#include <mLib/sig.h>
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
77static const char *pidfile = 0;
78static const char *logname = 0;
79static FILE *logfp = 0;
80static unsigned f = 0;
81static int fd;
82static const char *bgtag = 0;
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{
98 int e = errno;
99 while (waitpid(-1, 0, WNOHANG) > 0)
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
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
128static void cline(char *p, size_t len, void *b)
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 }
160 } else if (strcmp(q, "FAIL") == 0) {
161 checkfg();
162 die(EXIT_FAILURE, "%s", p);
163 } else if (strcmp(q, "INFO") == 0) {
164 checkfg();
165 puts(p);
166 fflush(stdout);
167 } else if (strcmp(q, "OK") == 0) {
168 checkfg();
169 exit(0);
170 } else if (strcmp(q, "BGDETACH") == 0) {
171 if (bgtag)
172 die(EXIT_FAILURE, "repeat detach");
173 bgtag = xstrdup(p);
174 } else if (strcmp(q, "BGOK") == 0) {
175 checkbg(&p);
176 exit(0);
177 } else if (strcmp(q, "BGINFO") == 0) {
178 checkbg(&p);
179 puts(p);
180 fflush(stdout);
181 } else if (strcmp(q, "BGFAIL") == 0) {
182 checkbg(&p);
183 die(EXIT_FAILURE, "%s", p);
184 } else
185 die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
186}
187
188static void sline(char *p, size_t len, void *b)
189{
190 if (!p) {
191 if (!(f & f_uclose))
192 moan("server closed the connection");
193 exit(0);
194 }
195 puts(p);
196 fflush(stdout);
197}
198
199static void uline(char *p, size_t len, void *b)
200{
201 if (!p) {
202 selbuf_destroy(b);
203 shutdown(fd, 1);
204 f |= f_uclose;
205 } else {
206 p[len] = '\n';
207 errno = EIO;
208 if (write(fd, p, len + 1) != len + 1)
209 moan("write failed: %s", strerror(errno));
210 }
211}
212
213static void setup(const char *cmd)
214{
215 dstr d = DSTR_INIT;
216 char ch;
217 char *p, *q;
218 int n;
219
220 dstr_puts(&d, cmd);
221 dstr_putc(&d, '\n');
222 errno = EIO; /* Relax: be vague */
223 if (write(fd, d.buf, d.len) != d.len) {
224 die(EXIT_FAILURE, "error sending setup command `%s': %s",
225 cmd, strerror(errno));
226 }
227 dstr_reset(&d);
228 for (;;) {
229 n = read(fd, &ch, 1);
230 if (!n)
231 die(EXIT_FAILURE, "unexpected EOF during setup");
232 if (n < 0) {
233 die(EXIT_FAILURE, "error receiving reply to `%s': %s",
234 cmd, strerror(errno));
235 }
236 if (d.len < 256)
237 dstr_putc(&d, ch);
238 if (ch == '\n') {
239 p = d.buf;
240 q = str_getword(&p);
241 if (!q)
242 ;
243 else if (strcmp(q, "OK") == 0)
244 return;
245 else if (strcmp(q, "FAIL") == 0)
246 die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
247 dstr_reset(&d);
248 }
249 }
250}
251
252static void logfile(const char *name)
253{
254 FILE *fp;
255
256 if ((fp = fopen(name, "a")) != 0) {
257 if (logfp)
258 fclose(logfp);
259 logfp = fp;
260 setvbuf(logfp, 0, _IOLBF, BUFSIZ);
261 } else {
262 dstr d = DSTR_INIT;
263 dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
264 if (logfp)
265 writelog("error", d.buf);
266 else if (logname)
267 die(EXIT_FAILURE, d.buf);
268 if (f & f_syslog)
269 syslog(LOG_ERR, d.buf);
270 dstr_destroy(&d);
271 }
272}
273
274static void sighup(int sig, void *v) { logfile(logname); }
275
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
289static void version(FILE *fp)
290 { pquis(fp, "$, TrIPE version " VERSION "\n"); }
291
292static void usage(FILE *fp)
293{
294 pquis(fp, "\
295Usage:\n\
296 $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
297 $ [-Dl] [-f FILE] [-OPTIONS]\n\
298Options:\n\
299 [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
300 [-p PROGRAM] [-S ARG,ARG,...]\n\
301");
302}
303
304static void help(FILE *fp)
305{
306 version(fp);
307 fputc('\n', fp);
308 usage(fp);
309 fputs("\
310\n\
311Options in full:\n\
312\n\
313-h, --help Show this help text.\n\
314-v, --version Show version number.\n\
315-u, --usage Show brief usage message.\n\
316\n\
317-D, --daemon Become a background task after connecting.\n\
318-d, --directory=DIR Select current directory [default " CONFIGDIR "].\n\
319-a, --admin-socket=FILE Select socket to connect to\n\
320 [default " SOCKETDIR "/tripesock].\n\
321-P, --pidfile=FILE Write process-id to FILE.\n\
322\n\
323-s, --spawn Start server rather than connecting.\n\
324-p, --spawn-path=PATH Specify path to executable.\n\
325-S, --spawn-args=ARGS Specify comma-separated arguments.\n\
326\n\
327-l, --syslog Log messages to system log.\n\
328-f, --logfile=FILE Log messages to FILE.\n\
329-w, --warnings Show warnings when running commands.\n\
330", fp);
331}
332
333int main(int argc, char *argv[])
334{
335 const char *dir = CONFIGDIR;
336 const char *sock = SOCKETDIR "/tripesock";
337 const char *spawnpath = "tripe";
338 string_v spawnopts = DA_INIT;
339 char *p;
340 FILE *pidfp = 0;
341
342 ego(argv[0]);
343
344 if ((p = getenv("TRIPEDIR")) != 0)
345 dir = p;
346
347 /* --- Parse the arguments --- */
348
349 for (;;) {
350 static const struct option opts[] = {
351 { "help", 0, 0, 'h' },
352 { "version", 0, 0, 'v' },
353 { "usage", 0, 0, 'u' },
354 { "daemon", 0, 0, 'D' },
355 { "directory", OPTF_ARGREQ, 0, 'd' },
356 { "admin-socket", OPTF_ARGREQ, 0, 'a' },
357 { "spawn", 0, 0, 's' },
358 { "spawn-path", OPTF_ARGREQ, 0, 'p' },
359 { "spawn-args", OPTF_ARGREQ, 0, 'S' },
360 { "syslog", 0, 0, 'l' },
361 { "logfile", OPTF_ARGREQ, 0, 'f' },
362 { "warnings", 0, 0, 'w' },
363 { "pidfile", OPTF_ARGREQ, 0, 'P' },
364 { 0, 0, 0, 0 }
365 };
366
367 int i = mdwopt(argc, argv, "+hvuDd:a:sp:S:lwf:nP:", opts, 0, 0, 0);
368 if (i < 0)
369 break;
370 switch (i) {
371 case 'h':
372 help(stdout);
373 exit(0);
374 case 'v':
375 version(stdout);
376 exit(0);
377 case 'u':
378 usage(stdout);
379 exit(0);
380 case 'D':
381 f |= f_daemon | f_noinput;
382 break;
383 case 'd':
384 dir = optarg;
385 break;
386 case 'a':
387 sock = optarg;
388 break;
389 case 's':
390 f |= f_spawn;
391 break;
392 case 'p':
393 f |= f_spawn;
394 spawnpath = optarg;
395 break;
396 case 'S':
397 f |= f_spawn | f_spawnopts;
398 for (p = strtok(optarg, ","); p; p = strtok(0, ","))
399 DA_PUSH(&spawnopts, p);
400 break;
401 case 'l':
402 f |= f_syslog | f_noinput;
403 break;
404 case 'w':
405 f |= f_warn;
406 break;
407 case 'f':
408 logname = optarg;
409 f |= f_noinput;
410 break;
411 case 'P':
412 pidfile = optarg;
413 break;
414 default:
415 f |= f_bogus;
416 break;
417 }
418 }
419 if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
420 usage(stderr);
421 exit(EXIT_FAILURE);
422 }
423
424 /* --- Set various things up --- */
425
426 if (chdir(dir)) {
427 die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
428 dir, strerror(errno));
429 }
430 if (logname)
431 logfile(logname);
432 if (!pidfile && (f & f_daemon) && ((f & f_syslog) || logname))
433 pidfile = "tripectl.pid";
434 if (pidfile && (pidfp = fopen(pidfile, "w")) == 0) {
435 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
436 pidfile, strerror(errno));
437 }
438 signal(SIGINT, sigdie);
439 signal(SIGQUIT, sigdie);
440 signal(SIGTERM, sigdie);
441 atexit(cleanup);
442
443 /* --- Connect to the server --- */
444
445 if (f & f_spawn) {
446 int pfd[2];
447 pid_t kid;
448 struct sigaction sa;
449 sigset_t newmask, oldmask;
450
451 sa.sa_handler = reap;
452 sigemptyset(&sa.sa_mask);
453 sa.sa_flags = SA_NOCLDSTOP;
454#ifdef SA_RESTART
455 sa.sa_flags |= SA_RESTART;
456#endif
457 sigaction(SIGCHLD, &sa, 0);
458
459 DA_UNSHIFT(&spawnopts, (char *)sock);
460 DA_UNSHIFT(&spawnopts, "-a");
461 DA_UNSHIFT(&spawnopts, "-d.");
462 DA_UNSHIFT(&spawnopts, (char *)spawnpath);
463 DA_PUSH(&spawnopts, 0);
464 if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd))
465 die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
466 sigemptyset(&newmask);
467 sigaddset(&newmask, SIGCHLD);
468 sigprocmask(SIG_BLOCK, &newmask, &oldmask);
469 if ((kid = fork()) < 0)
470 die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
471 if (!kid) {
472 dup2(pfd[1], STDIN_FILENO);
473 dup2(pfd[1], STDOUT_FILENO);
474 close(pfd[1]);
475 close(pfd[0]);
476 if (logfp)
477 fclose(logfp);
478 if (pidfp)
479 fclose(pidfp);
480 closelog();
481 if (f & f_daemon)
482 u_detach();
483 execvp(DA(&spawnopts)[0], DA(&spawnopts));
484 die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
485 }
486 sigprocmask(SIG_SETMASK, &oldmask, 0);
487 fd = pfd[0];
488 close(pfd[1]);
489 } else {
490 struct sockaddr_un sun;
491 size_t sz = strlen(sock) + 1;
492 if (sz > sizeof(sun.sun_path))
493 die(EXIT_FAILURE, "socket name `%s' too long", sock);
494 memset(&sun, 0, sizeof(sun));
495 sun.sun_family = AF_UNIX;
496 memcpy(sun.sun_path, sock, sz);
497 sz = sz + offsetof(struct sockaddr_un, sun_path);
498 if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
499 die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
500 if (connect(fd, (struct sockaddr *)&sun, sz)) {
501 die(EXIT_FAILURE, "error connecting to `%s': %s",
502 sun.sun_path, strerror(errno));
503 }
504 }
505
506 if (f & f_daemon) {
507 if (u_daemon())
508 die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
509 }
510 if (pidfp) {
511 fprintf(pidfp, "%li\n", (long)getpid());
512 fclose(pidfp);
513 }
514 signal(SIGPIPE, SIG_IGN);
515
516 /* --- If we're meant to be interactive, do that --- */
517
518 if (optind == argc)
519 setup("WATCH -A+tw");
520 if (!(f & f_noinput) && optind == argc) {
521 sel_state sel;
522 selbuf bu, bs;
523
524 sel_init(&sel);
525 selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
526 selbuf_init(&bs, &sel, fd, sline, &bs);
527 for (;;) {
528 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
529 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
530 }
531 }
532
533 /* --- If there's a command, submit it --- */
534
535 if (optind < argc) {
536 dstr d = DSTR_INIT;
537 setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
538 while (optind < argc)
539 u_quotify(&d, argv[optind++]);
540 dstr_putc(&d, '\n');
541 errno = EIO;
542 if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
543 die(EXIT_FAILURE, "write failed: %s", strerror(errno));
544 dstr_destroy(&d);
545 f |= f_command;
546 }
547
548 /* --- Pull everything else out of the box --- */
549
550 {
551 sel_state sel;
552 selbuf b;
553 sig hup;
554
555 sel_init(&sel);
556 selbuf_init(&b, &sel, fd, cline, 0);
557
558 if (f & f_syslog)
559 openlog(QUIS, 0, LOG_DAEMON);
560 if (logfp) {
561 sig_init(&sel);
562 sig_add(&hup, SIGHUP, sighup, 0);
563 }
564 for (;;) {
565 if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
566 die(EXIT_FAILURE, "select failed: %s", strerror(errno));
567 }
568 }
569
570 return (0);
571}
572
573/*----- That's all, folks -------------------------------------------------*/