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