chiark / gitweb /
6a2f82ab265f5c0f4c29a7ef692d3b7e2dbc10fe
[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 -U, --setuid=USER       Set uid to USER after initialization.\n\
322 -G, --setgid=GROUP      Set gid to GROUP after initialization.\n\
323 -a, --admin-socket=FILE Select socket to connect to\n\
324                           [default " SOCKETDIR "/tripesock].\n\
325 -P, --pidfile=FILE      Write process-id to FILE.\n\
326 \n\
327 -s, --spawn             Start server rather than connecting.\n\
328 -p, --spawn-path=PATH   Specify path to executable.\n\
329 -S, --spawn-args=ARGS   Specify comma-separated arguments.\n\
330 \n\
331 -l, --syslog            Log messages to system log.\n\
332 -f, --logfile=FILE      Log messages to FILE.\n\
333 -w, --warnings          Show warnings when running commands.\n\
334 ", fp);
335 }
336
337 int main(int argc, char *argv[])
338 {
339   const char *dir = CONFIGDIR;
340   const char *sock = SOCKETDIR "/tripesock";
341   const char *spawnpath = "tripe";
342   string_v spawnopts = DA_INIT;
343   char *p;
344   FILE *pidfp = 0;
345   uid_t u = -1;
346   gid_t g = -1;
347
348   ego(argv[0]);
349
350   if ((p = getenv("TRIPEDIR")) != 0)
351     dir = p;
352   if ((p = getenv("TRIPESOCK")) != 0)
353     sock = p;
354
355   /* --- Parse the arguments --- */
356
357   for (;;) {
358     static const struct option opts[] = {
359       { "help",         0,              0,      'h' },
360       { "version",      0,              0,      'v' },
361       { "usage",        0,              0,      'u' },
362       { "daemon",       0,              0,      'D' },
363       { "uid",          OPTF_ARGREQ,    0,      'U' },
364       { "setuid",       OPTF_ARGREQ,    0,      'U' },
365       { "gid",          OPTF_ARGREQ,    0,      'G' },
366       { "setgid",       OPTF_ARGREQ,    0,      'G' },
367       { "directory",    OPTF_ARGREQ,    0,      'd' },
368       { "admin-socket", OPTF_ARGREQ,    0,      'a' },
369       { "spawn",        0,              0,      's' },
370       { "spawn-path",   OPTF_ARGREQ,    0,      'p' },
371       { "spawn-args",   OPTF_ARGREQ,    0,      'S' },
372       { "syslog",       0,              0,      'l' },
373       { "logfile",      OPTF_ARGREQ,    0,      'f' },
374       { "warnings",     0,              0,      'w' },
375       { "pidfile",      OPTF_ARGREQ,    0,      'P' },
376       { 0,              0,              0,      0 }
377     };
378
379     int i = mdwopt(argc, argv, "+hvuDU:G:d:a:sp:S:lwf:nP:", opts, 0, 0, 0);
380     if (i < 0)
381       break;
382     switch (i) {
383       case 'h':
384         help(stdout);
385         exit(0);
386       case 'v':
387         version(stdout);
388         exit(0);
389       case 'u':
390         usage(stdout);
391         exit(0);
392       case 'D':
393         f |= f_daemon | f_noinput;
394         break;
395       case 'U':
396         u = u_getuser(optarg, &g);
397         break;
398       case 'G':
399         g = u_getgroup(optarg);
400         break;
401       case 'd':
402         dir = optarg;
403         break;
404       case 'a':
405         sock = optarg;
406         break;
407       case 's':
408         f |= f_spawn;
409         break;
410       case 'p':
411         f |= f_spawn;
412         spawnpath = optarg;
413         break;
414       case 'S':
415         f |= f_spawn | f_spawnopts;
416         for (p = strtok(optarg, ","); p; p = strtok(0, ","))
417           DA_PUSH(&spawnopts, p);
418         break;
419       case 'l':
420         f |= f_syslog | f_noinput;
421         break;
422       case 'w':
423         f |= f_warn;
424         break;
425       case 'f':
426         logname = optarg;
427         f |= f_noinput;
428         break;
429       case 'P':
430         pidfile = optarg;
431         break;
432       default:
433         f |= f_bogus;
434         break;
435     }
436   }
437   if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
438     usage(stderr);
439     exit(EXIT_FAILURE);
440   }
441
442   /* --- Set various things up --- */
443
444   if (chdir(dir)) {
445     die(EXIT_FAILURE, "couldn't set `%s' as current directory: %s",
446         dir, strerror(errno));
447   }
448   if (logname)
449     logfile(logname);
450   if (!pidfile && (f & f_daemon) && ((f & f_syslog) || logname))
451     pidfile = "tripectl.pid";
452   if (pidfile && (pidfp = fopen(pidfile, "w")) == 0) {
453     die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
454         pidfile, strerror(errno));
455   }
456   signal(SIGINT, sigdie);
457   signal(SIGQUIT, sigdie);
458   signal(SIGTERM, sigdie);
459   atexit(cleanup);
460
461   /* --- Connect to the server --- */
462
463   if (f & f_spawn) {
464     int pfd[2];
465     pid_t kid;
466     struct sigaction sa;
467     sigset_t newmask, oldmask;
468
469     sa.sa_handler = reap;
470     sigemptyset(&sa.sa_mask);
471     sa.sa_flags = SA_NOCLDSTOP;
472 #ifdef SA_RESTART
473     sa.sa_flags |= SA_RESTART;
474 #endif
475     sigaction(SIGCHLD, &sa, 0);
476
477     DA_PUSH(&spawnopts, 0);
478     if (g != (gid_t)-1) putarg(&spawnopts, "-G%lu", (unsigned long)g);
479     if (u != (uid_t)-1) putarg(&spawnopts, "-U%lu", (unsigned long)u);
480     putarg(&spawnopts, "-a%s", sock);
481     putarg(&spawnopts, "-d.");
482     putarg(&spawnopts, "-F");
483     putarg(&spawnopts, "%s", spawnpath);
484     if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd))
485       die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
486     sigemptyset(&newmask);
487     sigaddset(&newmask, SIGCHLD);
488     sigprocmask(SIG_BLOCK, &newmask, &oldmask);
489     if ((kid = fork()) < 0)
490       die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
491     if (!kid) {
492       dup2(pfd[1], STDIN_FILENO);
493       dup2(pfd[1], STDOUT_FILENO);
494       close(pfd[0]);
495       close(pfd[1]);
496       if (logfp) fclose(logfp);
497       if (pidfp) fclose(pidfp);
498       closelog();
499       if (f & f_daemon) detachtty();
500       execvp(DA(&spawnopts)[0], DA(&spawnopts));
501       die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
502     }
503     sigprocmask(SIG_SETMASK, &oldmask, 0);
504     fd = pfd[0];
505     close(pfd[1]);
506   } else {
507     struct sockaddr_un sun;
508     size_t sz = strlen(sock) + 1;
509     if (sz > sizeof(sun.sun_path))
510       die(EXIT_FAILURE, "socket name `%s' too long", sock);
511     memset(&sun, 0, sizeof(sun));
512     sun.sun_family = AF_UNIX;
513     memcpy(sun.sun_path, sock, sz);
514     sz = sz + offsetof(struct sockaddr_un, sun_path);
515     if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
516       die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
517     if (connect(fd, (struct sockaddr *)&sun, sz)) {
518       die(EXIT_FAILURE, "error connecting to `%s': %s",
519           sun.sun_path, strerror(errno));
520     }
521   }
522
523   u_setugid(u, g);
524   if (f & f_daemon) {
525     if (daemonize())
526       die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
527   }
528   if (pidfp) {
529     fprintf(pidfp, "%li\n", (long)getpid());
530     fclose(pidfp);
531   }
532   signal(SIGPIPE, SIG_IGN);
533
534   /* --- If we're meant to be interactive, do that --- */
535
536   if (optind == argc)
537     setup("WATCH -A+tw");
538   if (!(f & f_noinput) && optind == argc) {
539     sel_state sel;
540     selbuf bu, bs;
541
542     sel_init(&sel);
543     selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
544     selbuf_init(&bs, &sel, fd, sline, &bs);
545     for (;;) {
546       if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
547         die(EXIT_FAILURE, "select failed: %s", strerror(errno));
548     }
549   }
550
551   /* --- If there's a command, submit it --- */
552
553   if (optind < argc) {
554     dstr d = DSTR_INIT;
555     setup((f & f_warn) ? "WATCH -A+w" : "WATCH -A");
556     while (optind < argc)
557       u_quotify(&d, argv[optind++]);
558     dstr_putc(&d, '\n');
559     errno = EIO;
560     if (write(fd, d.buf, d.len) != d.len || shutdown(fd, 1))
561       die(EXIT_FAILURE, "write failed: %s", strerror(errno));
562     dstr_destroy(&d);
563     f |= f_command;
564   }
565
566   /* --- Pull everything else out of the box --- */
567
568   {
569     sel_state sel;
570     selbuf b;
571     sig hup;
572
573     sel_init(&sel);
574     selbuf_init(&b, &sel, fd, cline, 0);
575
576     if (f & f_syslog)
577       openlog(QUIS, 0, LOG_DAEMON);
578     if (logfp) {
579       sig_init(&sel);
580       sig_add(&hup, SIGHUP, sighup, 0);
581     }
582     for (;;) {
583       if (sel_select(&sel) && errno != EINTR && errno != EAGAIN)
584         die(EXIT_FAILURE, "select failed: %s", strerror(errno));
585     }
586   }
587
588   return (0);
589 }
590
591 /*----- That's all, folks -------------------------------------------------*/