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