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