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