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