chiark / gitweb /
Merge branch 'public'
[tripe] / client / tripectl.c
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/mdwopt.h>
56 #include <mLib/quis.h>
57 #include <mLib/report.h>
58 #include <mLib/sel.h>
59 #include <mLib/selbuf.h>
60 #include <mLib/sig.h>
61 #include <mLib/str.h>
62 #include <mLib/versioncmp.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
77 static const char *pidfile = 0;
78 static const char *logname = 0;
79 static FILE *logfp = 0;
80 static unsigned f = 0;
81 static int fd;
82 static 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
96 static void reap(int sig)
97 {
98   int e = errno;
99   while (waitpid(-1, 0, WNOHANG) > 0)
100     ;
101   errno = e;
102 }
103
104 static 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
113 static 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
122 static void checkfg(void)
123   { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
124
125 static void cline(char *p, size_t len, void *b)
126 {
127   char *q;
128   if (!p) {
129     if (f & f_command)
130       die(EXIT_FAILURE, "server dropped the connection");
131     exit(0);
132   }
133   q = str_getword(&p);
134   if (!q)
135     return;
136   if (strcmp(q, "WARN") == 0) {
137     if (f & f_syslog)
138       syslog(LOG_WARNING, "%s", p);
139     if (logfp)
140       writelog("warning", p);
141     if (f & f_warn)
142       fprintf(stderr, "Warning: %s\n", p);
143   } else if (strcmp(q, "TRACE") == 0) {
144     if (f & f_syslog)
145       syslog(LOG_DEBUG, "%s", p);
146     if (logfp)
147       writelog("debug", p);
148   } else if (!(f & f_command)) {
149     if (f & f_syslog)
150       syslog(LOG_ERR, "unexpected output `%s %s'", q, p);
151     if (logfp) {
152       dstr d = DSTR_INIT;
153       dstr_putf(&d, "unexpected output `%s %s'", q, p);
154       writelog("error", d.buf);
155       dstr_destroy(&d);
156     }
157   } else if (strcmp(q, "FAIL") == 0) {
158     checkfg();
159     die(EXIT_FAILURE, "%s", p);
160   } else if (strcmp(q, "INFO") == 0) {
161     checkfg();
162     puts(p);
163     fflush(stdout);
164   } else if (strcmp(q, "OK") == 0) {
165     checkfg();
166     exit(0);
167   } else if (strcmp(q, "BGDETACH") == 0) {
168     if (bgtag)
169       die(EXIT_FAILURE, "repeat detach");
170     bgtag = xstrdup(p);
171   } else if (strcmp(q, "BGOK") == 0) {
172     checkbg(&p);
173     exit(0);
174   } else if (strcmp(q, "BGINFO") == 0) {
175     checkbg(&p);
176     puts(p);
177     fflush(stdout);
178   } else if (strcmp(q, "BGFAIL") == 0) {
179     checkbg(&p);
180     die(EXIT_FAILURE, "%s", p);
181   } else
182     die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
183 }
184
185 static void sline(char *p, size_t len, void *b)
186 {
187   if (!p) {
188     if (!(f & f_uclose))
189       moan("server closed the connection");
190     exit(0);
191   }
192   puts(p);
193   fflush(stdout);
194 }
195
196 static void uline(char *p, size_t len, void *b)
197 {
198   if (!p) {
199     selbuf_destroy(b);
200     shutdown(fd, 1);
201     f |= f_uclose;
202   } else {
203     p[len] = '\n';
204     errno = EIO;
205     if (write(fd, p, len + 1) != len + 1)
206       moan("write failed: %s", strerror(errno));
207   }
208 }
209
210 static 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     }
246   }
247 }
248
249 static void logfile(const char *name)
250 {
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, "%s", d.buf);
267     dstr_destroy(&d);
268   }
269 }
270
271 static void sighup(int sig, void *v) { logfile(logname); }
272
273 static void cleanup(void) { if (pidfile) unlink(pidfile); }
274
275 static void sigdie(int sig)
276   { cleanup(); signal(sig, SIG_DFL); raise(sig); }
277
278 static void version(FILE *fp)
279   { pquis(fp, "$, TrIPE version " VERSION "\n"); }
280
281 static void usage(FILE *fp)
282 {
283   pquis(fp, "\
284 Usage:\n\
285         $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
286         $ [-Dl] [-f FILE] [-OPTIONS]\n\
287 Options:\n\
288         [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
289         [-p PROGRAM] [-S ARG,ARG,...]\n\
290 ");
291 }
292
293 static void help(FILE *fp)
294 {
295   version(fp);
296   fputc('\n', fp);
297   usage(fp);
298   fputs("\
299 \n\
300 Options in full:\n\
301 \n\
302 -h, --help              Show this help text.\n\
303 -v, --version           Show version number.\n\
304 -u, --usage             Show brief usage message.\n\
305 \n\
306 -D, --daemon            Become a background task after connecting.\n\
307 -d, --directory=DIR     Select current directory [default " CONFIGDIR "].\n\
308 -a, --admin-socket=FILE Select socket to connect to\n\
309                           [default " SOCKETDIR "/tripesock].\n\
310 -P, --pidfile=FILE      Write process-id to FILE.\n\
311 \n\
312 -s, --spawn             Start server rather than connecting.\n\
313 -p, --spawn-path=PATH   Specify path to executable.\n\
314 -S, --spawn-args=ARGS   Specify comma-separated arguments.\n\
315 \n\
316 -l, --syslog            Log messages to system log.\n\
317 -f, --logfile=FILE      Log messages to FILE.\n\
318 -w, --warnings          Show warnings when running commands.\n\
319 ", fp);
320 }
321
322 int main(int argc, char *argv[])
323 {
324   const char *dir = CONFIGDIR;
325   const char *sock = SOCKETDIR "/tripesock";
326   const char *spawnpath = "tripe";
327   string_v spawnopts = DA_INIT;
328   char *p;
329   FILE *pidfp = 0;
330
331   ego(argv[0]);
332
333   if ((p = getenv("TRIPEDIR")) != 0)
334     dir = p;
335   if ((p = getenv("TRIPESOCK")) != 0)
336     sock = p;
337
338   /* --- Parse the arguments --- */
339
340   for (;;) {
341     static const struct option opts[] = {
342       { "help",         0,              0,      'h' },
343       { "version",      0,              0,      'v' },
344       { "usage",        0,              0,      'u' },
345       { "daemon",       0,              0,      'D' },
346       { "directory",    OPTF_ARGREQ,    0,      'd' },
347       { "admin-socket", OPTF_ARGREQ,    0,      'a' },
348       { "spawn",        0,              0,      's' },
349       { "spawn-path",   OPTF_ARGREQ,    0,      'p' },
350       { "spawn-args",   OPTF_ARGREQ,    0,      'S' },
351       { "syslog",       0,              0,      'l' },
352       { "logfile",      OPTF_ARGREQ,    0,      'f' },
353       { "warnings",     0,              0,      'w' },
354       { "pidfile",      OPTF_ARGREQ,    0,      'P' },
355       { 0,              0,              0,      0 }
356     };
357
358     int i = mdwopt(argc, argv, "+hvuDd:a:sp:S:lwf:nP:", opts, 0, 0, 0);
359     if (i < 0)
360       break;
361     switch (i) {
362       case 'h':
363         help(stdout);
364         exit(0);
365       case 'v':
366         version(stdout);
367         exit(0);
368       case 'u':
369         usage(stdout);
370         exit(0);
371       case 'D':
372         f |= f_daemon | f_noinput;
373         break;
374       case 'd':
375         dir = optarg;
376         break;
377       case 'a':
378         sock = optarg;
379         break;
380       case 's':
381         f |= f_spawn;
382         break;
383       case 'p':
384         f |= f_spawn;
385         spawnpath = optarg;
386         break;
387       case 'S':
388         f |= f_spawn | f_spawnopts;
389         for (p = strtok(optarg, ","); p; p = strtok(0, ","))
390           DA_PUSH(&spawnopts, p);
391         break;
392       case 'l':
393         f |= f_syslog | f_noinput;
394         break;
395       case 'w':
396         f |= f_warn;
397         break;
398       case 'f':
399         logname = optarg;
400         f |= f_noinput;
401         break;
402       case 'P':
403         pidfile = optarg;
404         break;
405       default:
406         f |= f_bogus;
407         break;
408     }
409   }
410   if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
411     usage(stderr);
412     exit(EXIT_FAILURE);
413   }
414
415   /* --- Set various things up --- */
416
417   if (chdir(dir)) {
418     die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
419         dir, strerror(errno));
420   }
421   if (logname)
422     logfile(logname);
423   if (!pidfile && (f & f_daemon) && ((f & f_syslog) || logname))
424     pidfile = "tripectl.pid";
425   if (pidfile && (pidfp = fopen(pidfile, "w")) == 0) {
426     die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
427         pidfile, strerror(errno));
428   }
429   signal(SIGINT, sigdie);
430   signal(SIGQUIT, sigdie);
431   signal(SIGTERM, sigdie);
432   atexit(cleanup);
433
434   /* --- Connect to the server --- */
435
436   if (f & f_spawn) {
437     int pfd[2];
438     pid_t kid;
439     struct sigaction sa;
440     sigset_t newmask, oldmask;
441
442     sa.sa_handler = reap;
443     sigemptyset(&sa.sa_mask);
444     sa.sa_flags = SA_NOCLDSTOP;
445 #ifdef SA_RESTART
446     sa.sa_flags |= SA_RESTART;
447 #endif
448     sigaction(SIGCHLD, &sa, 0);
449
450     DA_UNSHIFT(&spawnopts, (char *)sock);
451     DA_UNSHIFT(&spawnopts, "-a");
452     DA_UNSHIFT(&spawnopts, "-d.");
453     DA_UNSHIFT(&spawnopts, "-F");
454     DA_UNSHIFT(&spawnopts, (char *)spawnpath);
455     DA_PUSH(&spawnopts, 0);
456     if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd))
457       die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
458     sigemptyset(&newmask);
459     sigaddset(&newmask, SIGCHLD);
460     sigprocmask(SIG_BLOCK, &newmask, &oldmask);
461     if ((kid = fork()) < 0)
462       die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
463     if (!kid) {
464       dup2(pfd[1], STDIN_FILENO);
465       dup2(pfd[1], STDOUT_FILENO);
466       close(pfd[0]);
467       close(pfd[1]);
468       if (logfp) fclose(logfp);
469       if (pidfp) fclose(pidfp);
470       closelog();
471       if (f & f_daemon) detachtty();
472       execvp(DA(&spawnopts)[0], DA(&spawnopts));
473       die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
474     }
475     sigprocmask(SIG_SETMASK, &oldmask, 0);
476     fd = pfd[0];
477     close(pfd[1]);
478   } else {
479     struct sockaddr_un sun;
480     size_t sz = strlen(sock) + 1;
481     if (sz > sizeof(sun.sun_path))
482       die(EXIT_FAILURE, "socket name `%s' too long", sock);
483     memset(&sun, 0, sizeof(sun));
484     sun.sun_family = AF_UNIX;
485     memcpy(sun.sun_path, sock, sz);
486     sz = sz + offsetof(struct sockaddr_un, sun_path);
487     if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
488       die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
489     if (connect(fd, (struct sockaddr *)&sun, sz)) {
490       die(EXIT_FAILURE, "error connecting to `%s': %s",
491           sun.sun_path, strerror(errno));
492     }
493   }
494
495   if (f & f_daemon) {
496     if (daemonize())
497       die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
498   }
499   if (pidfp) {
500     fprintf(pidfp, "%li\n", (long)getpid());
501     fclose(pidfp);
502   }
503   signal(SIGPIPE, SIG_IGN);
504
505   /* --- If we're meant to be interactive, do that --- */
506
507   if (optind == argc)
508     setup("WATCH -A+tw");
509   if (!(f & f_noinput) && optind == argc) {
510     sel_state sel;
511     selbuf bu, bs;
512
513     sel_init(&sel);
514     selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
515     selbuf_init(&bs, &sel, fd, sline, &bs);
516     for (;;) {
517       if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
518         die(EXIT_FAILURE, "select failed: %s", strerror(errno));
519     }
520   }
521
522   /* --- If there's a command, submit it --- */
523
524   if (optind < argc) {
525     dstr d = DSTR_INIT;
526     setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
527     while (optind < argc)
528       u_quotify(&d, argv[optind++]);
529     dstr_putc(&d, '\n');
530     errno = EIO;
531     if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
532       die(EXIT_FAILURE, "write failed: %s", strerror(errno));
533     dstr_destroy(&d);
534     f |= f_command;
535   }
536
537   /* --- Pull everything else out of the box --- */
538
539   {
540     sel_state sel;
541     selbuf b;
542     sig hup;
543
544     sel_init(&sel);
545     selbuf_init(&b, &sel, fd, cline, 0);
546
547     if (f & f_syslog)
548       openlog(QUIS, 0, LOG_DAEMON);
549     if (logfp) {
550       sig_init(&sel);
551       sig_add(&hup, SIGHUP, sighup, 0);
552     }
553     for (;;) {
554       if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
555         die(EXIT_FAILURE, "select failed: %s", strerror(errno));
556     }
557   }
558
559   return (0);
560 }
561
562 /*----- That's all, folks -------------------------------------------------*/