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