chiark / gitweb /
priv/Makefile.am: Hack `libpriv' so that parallel builds work.
[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/mdup.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 #include <mLib/versioncmp.h>
64
65 #include "util.h"
66
67 #undef sun
68 #define IGNORE(x) do if (x); while (0)
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
79 static sel_state sel;
80 static const char *pidfile = 0;
81 static const char *logname = 0;
82 static FILE *logfp = 0;
83 static unsigned f = 0;
84 static int fd;
85 static const char *bgtag = 0;
86
87 #define f_bogus 1u
88 #define f_spawn 2u
89 #define f_daemon 4u
90 #define f_spawnopts 8u
91 #define f_syslog 16u
92 #define f_command 32u
93 #define f_noinput 64u
94 #define f_warn 128u
95 #define f_uclose 256u
96 #define f_losing 512u
97
98 /*----- Main code ---------------------------------------------------------*/
99
100 static void reap(int sig)
101 {
102   int e = errno;
103   while (waitpid(-1, 0, WNOHANG) > 0)
104     ;
105   errno = e;
106 }
107
108 static void writelog(const char *cat, const char *msg)
109 {
110   char buf[256];
111   time_t t = time(0);
112   struct tm *tm = localtime(&t);
113   strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
114   fprintf(logfp, "%s %s: %s\n", buf, cat, msg);
115 }
116
117 static void checkbg(char **p)
118 {
119   char *q = str_getword(p);
120   if (!q)
121     die(EXIT_FAILURE, "missing background tag");
122   if (!bgtag || strcmp(bgtag, q) != 0)
123     die(EXIT_FAILURE, "unexpected background tag `%s'", q);
124 }
125
126 static void dolog(int prio, const char *msg, ...)
127 {
128   va_list ap;
129   dstr d = DSTR_INIT;
130   const char *cat;
131
132   va_start(ap, msg);
133   dstr_vputf(&d, msg, &ap);
134   va_end(ap);
135   if (f & f_syslog) syslog(prio, "%s", d.buf);
136   if (logfp) {
137     switch (prio) {
138       case LOG_WARNING: cat = "warning"; break;
139       case LOG_DEBUG: cat = "debug"; break;
140       case LOG_ERR: cat = "error"; break;
141       default: cat = "message"; break;
142     }
143     writelog(cat, d.buf);
144   }
145   if (prio == LOG_WARNING && (f & f_warn))
146     fprintf(stderr, "Warning: %s\n", d.buf);
147   dstr_destroy(&d);
148 }
149
150 static void checkfg(void)
151   { if (bgtag) die(EXIT_FAILURE, "unexpected foreground response"); }
152
153 static void cline(char *p, size_t len, void *b)
154 {
155   char *q;
156   if (!p) {
157     if (f & f_command)
158       die(EXIT_FAILURE, "server dropped the connection");
159     f &= ~f_losing;
160     exit(0);
161   }
162   q = str_getword(&p);
163   if (!q)
164     return;
165   if (strcmp(q, "WARN") == 0)
166     dolog(LOG_WARNING, p);
167   else if (strcmp(q, "TRACE") == 0)
168     dolog(LOG_DEBUG, p);
169   else if (!(f & f_command))
170     dolog(LOG_ERR, "unexpected output `%s %s'", q, p);
171   else if (strcmp(q, "FAIL") == 0) {
172     checkfg();
173     die(EXIT_FAILURE, "%s", p);
174   } else if (strcmp(q, "INFO") == 0) {
175     checkfg();
176     puts(p);
177     fflush(stdout);
178   } else if (strcmp(q, "OK") == 0) {
179     checkfg();
180     exit(0);
181   } else if (strcmp(q, "BGDETACH") == 0) {
182     if (bgtag)
183       die(EXIT_FAILURE, "repeat detach");
184     bgtag = xstrdup(p);
185   } else if (strcmp(q, "BGOK") == 0) {
186     checkbg(&p);
187     exit(0);
188   } else if (strcmp(q, "BGINFO") == 0) {
189     checkbg(&p);
190     puts(p);
191     fflush(stdout);
192   } else if (strcmp(q, "BGFAIL") == 0) {
193     checkbg(&p);
194     die(EXIT_FAILURE, "%s", p);
195   } else
196     die(EXIT_FAILURE, "unexpected output `%s %s'", q, p);
197 }
198
199 static void sline(char *p, size_t len, void *b)
200 {
201   if (!p) {
202     if (!(f & f_uclose))
203       moan("server closed the connection");
204     exit(0);
205   }
206   puts(p);
207   fflush(stdout);
208 }
209
210 static void uline(char *p, size_t len, void *b)
211 {
212   if (!p) {
213     selbuf_destroy(b);
214     shutdown(fd, 1);
215     f |= f_uclose;
216   } else {
217     p[len] = '\n';
218     errno = EIO;
219     if (write(fd, p, len + 1) != len + 1)
220       moan("write failed: %s", strerror(errno));
221   }
222 }
223
224 static void eline(char *p, size_t len, void *b)
225 {
226   if (p)
227     dolog(LOG_WARNING, "(stderr): %s", p);
228   else {
229     selbuf_destroy(b);
230     close(fd);
231   }
232 }
233
234 static void setup(const char *cmd)
235 {
236   dstr d = DSTR_INIT;
237   char ch;
238   char *p, *q;
239   int n;
240
241   dstr_puts(&d, cmd);
242   dstr_putc(&d, '\n');
243   errno = EIO; /* Relax: be vague */
244   if (write(fd, d.buf, d.len) != d.len) {
245     die(EXIT_FAILURE, "error sending setup command `%s': %s",
246         cmd, strerror(errno));
247   }
248   dstr_reset(&d);
249   for (;;) {
250     n = read(fd, &ch, 1);
251     if (!n)
252       die(EXIT_FAILURE, "unexpected EOF during setup");
253     if (n < 0) {
254       die(EXIT_FAILURE, "error receiving reply to `%s': %s",
255           cmd, strerror(errno));
256     }
257     if (d.len < 256)
258       dstr_putc(&d, ch);
259     if (ch == '\n') {
260       p = d.buf;
261       q = str_getword(&p);
262       if (!q)
263         ;
264       else if (strcmp(q, "OK") == 0)
265         return;
266       else if (strcmp(q, "FAIL") == 0)
267         die(EXIT_FAILURE, "setup command `%s' failed: %s", cmd, p);
268       dstr_reset(&d);
269     }
270   }
271 }
272
273 static void logfile(const char *name)
274 {
275   FILE *fp;
276
277   if ((fp = fopen(name, "a")) != 0) {
278     if (logfp)
279       fclose(logfp);
280     logfp =  fp;
281     setvbuf(logfp, 0, _IOLBF, BUFSIZ);
282   } else {
283     dstr d = DSTR_INIT;
284     dstr_putf(&d, "error opening logfile `%s': %s", name, strerror(errno));
285     if (logfp)
286       writelog("error", d.buf);
287     else if (logname)
288       die(EXIT_FAILURE, d.buf);
289     if (f & f_syslog)
290       syslog(LOG_ERR, "%s", d.buf);
291     dstr_destroy(&d);
292   }
293 }
294
295 static void sighup(int sig, void *v) { logfile(logname); }
296
297 static void cleanup(void) { if (pidfile) unlink(pidfile); }
298
299 static void sigdie(int sig)
300   { cleanup(); signal(sig, SIG_DFL); raise(sig); }
301
302 static void putarg(string_v *av, const char *fmt, ...)
303 {
304   va_list ap;
305   dstr d = DSTR_INIT;
306
307   va_start(ap, fmt);
308   dstr_vputf(&d, fmt, &ap);
309   dstr_putz(&d);
310   va_end(ap);
311   DA_UNSHIFT(av, xstrdup(d.buf));
312   dstr_destroy(&d);
313 }
314
315 static void version(FILE *fp)
316   { pquis(fp, "$, TrIPE version " VERSION "\n"); }
317
318 static void usage(FILE *fp)
319 {
320   pquis(fp, "\
321 Usage:\n\
322         $ [-w] [-OPTIONS] [COMMAND [ARGS]...]\n\
323         $ [-Dl] [-f FILE] [-OPTIONS]\n\
324 Options:\n\
325         [-s] [-d DIRECTORY] [-a SOCKET] [-P PIDFILE]\n\
326         [-p PROGRAM] [-S ARG,ARG,...]\n\
327 ");
328 }
329
330 static void help(FILE *fp)
331 {
332   version(fp);
333   fputc('\n', fp);
334   usage(fp);
335   fputs("\
336 \n\
337 Options in full:\n\
338 \n\
339 -h, --help              Show this help text.\n\
340 -v, --version           Show version number.\n\
341 -u, --usage             Show brief usage message.\n\
342 \n\
343 -D, --daemon            Become a background task after connecting.\n\
344 -d, --directory=DIR     Select current directory [default " CONFIGDIR "].\n\
345 -U, --setuid=USER       Set uid to USER after initialization.\n\
346 -G, --setgid=GROUP      Set gid to GROUP after initialization.\n\
347 -a, --admin-socket=FILE Select socket to connect to\n\
348                           [default " SOCKETDIR "/tripesock].\n\
349 -P, --pidfile=FILE      Write process-id to FILE.\n\
350 \n\
351 -s, --spawn             Start server rather than connecting.\n\
352 -p, --spawn-path=PATH   Specify path to executable.\n\
353 -S, --spawn-args=ARGS   Specify comma-separated arguments.\n\
354 \n\
355 -l, --syslog            Log messages to system log.\n\
356 -f, --logfile=FILE      Log messages to FILE.\n\
357 -w, --warnings          Show warnings when running commands.\n\
358 ", fp);
359 }
360
361 int main(int argc, char *argv[])
362 {
363   const char *dir = CONFIGDIR;
364   const char *sock = SOCKETDIR "/tripesock";
365   const char *spawnpath = "tripe";
366   string_v spawnopts = DA_INIT;
367   char *p;
368   FILE *pidfp = 0;
369   int i;
370   size_t sz;
371   uid_t u = -1;
372   gid_t g = -1;
373   int pfd[2], efd[2];
374   mdup_fd md[3];
375   pid_t kid;
376   struct sigaction sa;
377   sigset_t newmask, oldmask;
378   struct sockaddr_un sun;
379   selbuf bu, bs, be;
380   dstr d = DSTR_INIT;
381   sig hup;
382
383   ego(argv[0]);
384
385   if ((p = getenv("TRIPEDIR")) != 0)
386     dir = p;
387   if ((p = getenv("TRIPESOCK")) != 0)
388     sock = p;
389
390   /* --- Parse the arguments --- */
391
392   for (;;) {
393     static const struct option opts[] = {
394       { "help",         0,              0,      'h' },
395       { "version",      0,              0,      'v' },
396       { "usage",        0,              0,      'u' },
397       { "daemon",       0,              0,      'D' },
398       { "uid",          OPTF_ARGREQ,    0,      'U' },
399       { "setuid",       OPTF_ARGREQ,    0,      'U' },
400       { "gid",          OPTF_ARGREQ,    0,      'G' },
401       { "setgid",       OPTF_ARGREQ,    0,      'G' },
402       { "directory",    OPTF_ARGREQ,    0,      'd' },
403       { "admin-socket", OPTF_ARGREQ,    0,      'a' },
404       { "spawn",        0,              0,      's' },
405       { "spawn-path",   OPTF_ARGREQ,    0,      'p' },
406       { "spawn-args",   OPTF_ARGREQ,    0,      'S' },
407       { "syslog",       0,              0,      'l' },
408       { "logfile",      OPTF_ARGREQ,    0,      'f' },
409       { "warnings",     0,              0,      'w' },
410       { "pidfile",      OPTF_ARGREQ,    0,      'P' },
411       { 0,              0,              0,      0 }
412     };
413
414     i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:", opts, 0, 0, 0);
415     if (i < 0)
416       break;
417     switch (i) {
418       case 'h':
419         help(stdout);
420         exit(0);
421       case 'v':
422         version(stdout);
423         exit(0);
424       case 'u':
425         usage(stdout);
426         exit(0);
427       case 'D':
428         f |= f_daemon | f_noinput;
429         break;
430       case 'U':
431         u = u_getuser(optarg, &g);
432         break;
433       case 'G':
434         g = u_getgroup(optarg);
435         break;
436       case 'd':
437         dir = optarg;
438         break;
439       case 'a':
440         sock = optarg;
441         break;
442       case 's':
443         f |= f_spawn;
444         break;
445       case 'p':
446         f |= f_spawn;
447         spawnpath = optarg;
448         break;
449       case 'S':
450         f |= f_spawn | f_spawnopts;
451         for (p = strtok(optarg, ","); p; p = strtok(0, ","))
452           DA_PUSH(&spawnopts, p);
453         break;
454       case 'l':
455         f |= f_syslog | f_noinput;
456         break;
457       case 'w':
458         f |= f_warn;
459         break;
460       case 'f':
461         logname = optarg;
462         f |= f_noinput;
463         break;
464       case 'P':
465         pidfile = optarg;
466         break;
467       default:
468         f |= f_bogus;
469         break;
470     }
471   }
472   if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
473     usage(stderr);
474     exit(EXIT_FAILURE);
475   }
476
477   /* --- Set various things up --- */
478
479   if (chdir(dir)) {
480     die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
481         dir, strerror(errno));
482   }
483   if (!pidfile && (f & f_daemon) && ((f & f_syslog) || logname))
484     pidfile = "tripectl.pid";
485   if (pidfile && (pidfp = fopen(pidfile, "w")) == 0) {
486     die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
487         pidfile, strerror(errno));
488   }
489   sel_init(&sel);
490   sig_init(&sel);
491   signal(SIGINT, sigdie);
492   signal(SIGQUIT, sigdie);
493   signal(SIGTERM, sigdie);
494   atexit(cleanup);
495
496   /* --- Connect to the server --- */
497
498   if (f & f_spawn) {
499     sa.sa_handler = reap;
500     sigemptyset(&sa.sa_mask);
501     sa.sa_flags = SA_NOCLDSTOP;
502 #ifdef SA_RESTART
503     sa.sa_flags |= SA_RESTART;
504 #endif
505     sigaction(SIGCHLD, &sa, 0);
506
507     DA_PUSH(&spawnopts, 0);
508     if (g != (gid_t)-1) putarg(&spawnopts, "-G%lu", (unsigned long)g);
509     if (u != (uid_t)-1) putarg(&spawnopts, "-U%lu", (unsigned long)u);
510     putarg(&spawnopts, "-a%s", sock);
511     putarg(&spawnopts, "-d.");
512     putarg(&spawnopts, "-F");
513     putarg(&spawnopts, "%s", spawnpath);
514     if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd) || pipe(efd))
515       die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
516     sigemptyset(&newmask);
517     sigaddset(&newmask, SIGCHLD);
518     sigprocmask(SIG_BLOCK, &newmask, &oldmask);
519     if ((kid = fork()) < 0)
520       die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
521     if (!kid) {
522       close(pfd[0]); close(efd[0]);
523       md[0].cur = pfd[1]; md[0].want = STDIN_FILENO;
524       md[1].cur = pfd[1]; md[1].want = STDOUT_FILENO;
525       md[2].cur = efd[1]; md[2].want = STDERR_FILENO;
526       mdup(md, 3);
527       if (pidfp) fclose(pidfp);
528       closelog();
529       if (f & f_daemon) detachtty();
530       execvp(DA(&spawnopts)[0], DA(&spawnopts));
531       die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
532     }
533     sigprocmask(SIG_SETMASK, &oldmask, 0);
534     fd = pfd[0];
535     close(pfd[1]); close(efd[1]);
536     selbuf_init(&be, &sel, efd[0], eline, &be);
537   } else {
538     sz = strlen(sock) + 1;
539     if (sz > sizeof(sun.sun_path))
540       die(EXIT_FAILURE, "socket name `%s' too long", sock);
541     memset(&sun, 0, sizeof(sun));
542     sun.sun_family = AF_UNIX;
543     memcpy(sun.sun_path, sock, sz);
544     sz = sz + offsetof(struct sockaddr_un, sun_path);
545     if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
546       die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
547     if (connect(fd, (struct sockaddr *)&sun, sz)) {
548       die(EXIT_FAILURE, "error connecting to `%s': %s",
549           sun.sun_path, strerror(errno));
550     }
551   }
552
553   f |= f_losing; /* pessimism */
554   u_setugid(u, g);
555   if (logname)
556     logfile(logname);
557   if (f & f_daemon) {
558     if (daemonize())
559       die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
560   }
561   if (pidfp) {
562     fprintf(pidfp, "%li\n", (long)getpid());
563     fclose(pidfp);
564   }
565   signal(SIGPIPE, SIG_IGN);
566
567   /* --- If we're meant to be interactive, do that --- */
568
569   if (optind == argc)
570     setup("WATCH -A+tw");
571   if (!(f & f_noinput) && optind == argc) {
572     selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
573     selbuf_init(&bs, &sel, fd, sline, &bs);
574     for (;;) {
575       if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
576         die(EXIT_FAILURE, "select failed: %s", strerror(errno));
577     }
578   }
579
580   /* --- If there's a command, submit it --- */
581
582   if (optind < argc) {
583     setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
584     while (optind < argc)
585       u_quotify(&d, argv[optind++]);
586     dstr_putc(&d, '\n');
587     errno = EIO;
588     if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
589       die(EXIT_FAILURE, "write failed: %s", strerror(errno));
590     dstr_destroy(&d);
591     f |= f_command;
592   }
593
594   /* --- Pull everything else out of the box --- */
595
596   selbuf_init(&bs, &sel, fd, cline, 0);
597
598   if (f & f_syslog)
599     openlog(QUIS, 0, LOG_DAEMON);
600   if (logfp)
601     sig_add(&hup, SIGHUP, sighup, 0);
602   for (;;) {
603     if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
604       die(EXIT_FAILURE, "select failed: %s", strerror(errno));
605   }
606
607   return (0);
608 }
609
610 /*----- That's all, folks -------------------------------------------------*/