chiark / gitweb /
Support for displaying statistics. Make client connections blocking, so
[tripe] / client.c
1 /* -*-c-*-
2  *
3  * $Id: client.c,v 1.4 2001/02/06 09:34:53 mdw Exp $
4  *
5  * Client for TrIPE
6  *
7  * (c) 2001 Straylight/Edgeware
8  */
9
10 /*----- Licensing notice --------------------------------------------------* 
11  *
12  * This file is part of Trivial IP Encryption (TrIPE).
13  *
14  * TrIPE is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  * 
19  * TrIPE is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  * 
24  * You should have received a copy of the GNU General Public License
25  * along with TrIPE; if not, write to the Free Software Foundation,
26  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27  */
28
29 /*----- Revision history --------------------------------------------------* 
30  *
31  * $Log: client.c,v $
32  * Revision 1.4  2001/02/06 09:34:53  mdw
33  * Change ERR response to FAIL for consistency with other programs.
34  *
35  * Revision 1.3  2001/02/04 17:10:15  mdw
36  * Reopen logfiles on receipt of @SIGHUP@ (not done very well).  Don't
37  * change directory -- just mangle pathnames instead.
38  *
39  * Revision 1.2  2001/02/04 01:17:54  mdw
40  * Create a configuration header file to tidy up command lines.
41  *
42  * Revision 1.1  2001/02/03 20:26:37  mdw
43  * Initial checkin.
44  *
45  */
46
47 /*----- Header files ------------------------------------------------------*/
48
49 #include "config.h"
50
51 #include <ctype.h>
52 #include <errno.h>
53 #include <signal.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <time.h>
58
59 #include <sys/types.h>
60 #include <sys/time.h>
61 #include <unistd.h>
62 #include <fcntl.h>
63 #include <sys/wait.h>
64 #include <syslog.h>
65
66 #include <sys/socket.h>
67 #include <sys/un.h>
68 #include <arpa/inet.h>
69 #include <netdb.h>
70
71 #include <mLib/alloc.h>
72 #include <mLib/darray.h>
73 #include <mLib/dstr.h>
74 #include <mLib/lbuf.h>
75 #include <mLib/mdwopt.h>
76 #include <mLib/quis.h>
77 #include <mLib/report.h>
78 #include <mLib/sel.h>
79 #include <mLib/selbuf.h>
80 #include <mLib/str.h>
81
82 #include "util.h"
83
84 #undef sun
85
86 /*----- Data structures ---------------------------------------------------*/
87
88 #ifndef STRING_V
89 #  define STRING_V
90    DA_DECL(string_v, char *);
91 #endif
92
93 /*----- Static variables --------------------------------------------------*/
94
95 static FILE *logfp = 0;
96 static unsigned f = 0;
97 static int fd;
98 static volatile sig_atomic_t reopen = 0;
99
100 #define f_bogus 1u
101 #define f_spawn 2u
102 #define f_daemon 4u
103 #define f_spawnopts 8u
104 #define f_syslog 16u
105 #define f_command 32u
106 #define f_noinput 64u
107 #define f_warn 128u
108 #define f_uclose 256u
109
110 /*----- Main code ---------------------------------------------------------*/
111
112 static void reap(int sig)
113 {
114   int s;
115   int e = errno;
116   while (waitpid(-1, &s, WNOHANG) > 0)
117     ;
118   errno = e;
119 }
120
121 static void sighup(int sig)
122 {
123   reopen = 1;
124 }
125
126 static void writelog(const char *cat, const char *msg)
127 {
128   char buf[256];
129   time_t t = time(0);
130   struct tm *tm = localtime(&t);
131   strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
132   fprintf(logfp, "%s %s: %s\n", buf, cat, msg);
133 }
134
135 static void cline(char *p, void *b)
136 {
137   char *q;
138   if (!p) {
139     if (f & f_command)
140       die(EXIT_FAILURE, "server dropped the connection");
141     exit(0);
142   }
143   q = str_getword(&p);
144   if (!q)
145     return;
146   if (strcmp(q, "WARN") == 0) {
147     if (f & f_syslog)
148       syslog(LOG_WARNING, "%s", p);
149     if (logfp)
150       writelog("warning", p);
151     if (f & f_warn)
152       fprintf(stderr, "Warning: %s\n", p);
153   } else if (strcmp(q, "TRACE") == 0) {
154     if (f & f_syslog)
155       syslog(LOG_DEBUG, "%s", p);
156     if (logfp)
157       writelog("debug", p);
158   } else if (!(f & f_command)) {
159     if (f & f_syslog)
160       syslog(LOG_ERR, "unexpected output `%s %s'", q, p);
161     if (logfp) {
162       dstr d = DSTR_INIT;
163       dstr_putf(&d, "unexpected output `%s %s'", q, p);
164       writelog("error", d.buf);
165       dstr_destroy(&d);
166     }
167   } else if (strcmp(q, "FAIL") == 0)
168     die(EXIT_FAILURE, "%s", p);
169   else if (strcmp(q, "INFO") == 0)
170     puts(p);
171   else if (strcmp(q, "OK") == 0)
172     exit(0);
173   else
174     die(EXIT_FAILURE, "unexpected output `%s %s'", q, p); 
175 }
176
177 static void sline(char *p, void *b)
178 {
179   if (!p) {
180     if (!(f & f_uclose))
181       moan("server closed the connection");
182     exit(0);
183   }
184   puts(p);
185 }
186
187 static void uline(char *p, void *b)
188 {
189   size_t sz;
190   if (!p) {
191     selbuf_destroy(b);
192     shutdown(fd, 1);
193     f |= f_uclose;
194   } else {
195     sz = strlen(p);
196     p[sz] = '\n';
197     write(fd, p, sz + 1);
198   }
199 }
200
201 static void logfile(const char *name)
202 {
203   if (logfp)
204     fclose(logfp);
205   if ((logfp = fopen(name, "a")) == 0) {
206     die(EXIT_FAILURE, "error opening logfile `%s': %s",
207         name, strerror(errno));
208   }
209   setvbuf(logfp, 0, _IOLBF, BUFSIZ);
210 }
211
212 static void version(FILE *fp)
213 {
214   pquis(fp, "$, TrIPE version " VERSION "\n");
215 }
216
217 static void usage(FILE *fp)
218 {
219   pquis(fp, "\
220 Usage:\n\
221         $ [-w] [-options] [command [args]...]\n\
222         $ [-Dl] [-f file] [-options]\n\
223 Options:\n\
224         [-s] [-d directory] [-a socket] [-p program] [-S arg,arg,...]\n\
225 ");
226 }
227
228 static void help(FILE *fp)
229 {
230   version(fp);
231   fputc('\n', fp);
232   usage(fp);
233   fputs("\
234 \n\
235 Options in full:\n\
236 \n\
237 -h, --help              Show this help text.\n\
238 -v, --version           Show version number.\n\
239 -u, --usage             Show brief usage message.\n\
240 \n\
241 -D, --daemon            Become a background task after connecting.\n\
242 -d, --directory=DIR     Select current directory [default /var/lib/tripe]\n\
243 -a, --admin-socket=FILE Select socket to connect to.\n\
244 \n\
245 -s, --spawn             Start server rather than connecting.\n\
246 -p, --spawn-path=PATH   Specify path to executable.\n\
247 -S, --spawn-args=ARGS   Specify comma-separated arguments.\n\
248 \n\
249 -l, --syslog            Log messages to system log.\n\
250 -f, --logfile=FILE      Log messages to FILE.\n\
251 -w, --warnings          Show warnings when running commands.\n\
252 ", fp);
253 }
254
255 int main(int argc, char *argv[])
256 {
257   const char *dir = "/var/lib/tripe";
258   const char *sock = "tripesock";
259   const char *spawnpath = "tripe";
260   string_v spawnopts = DA_INIT;
261   const char *logname = 0;
262   char *p;
263
264   ego(argv[0]);
265
266   if ((p = getenv("TRIPEDIR")) != 0)
267     dir = p;
268
269   /* --- Parse the arguments --- */
270
271   for (;;) {
272     static const struct option opts[] = {
273       { "help",         0,              0,      'h' },
274       { "version",      0,              0,      'v' },
275       { "usage",        0,              0,      'u' },
276       { "daemon",       0,              0,      'D' },
277       { "directory",    OPTF_ARGREQ,    0,      'd' },
278       { "admin-socket", OPTF_ARGREQ,    0,      'a' },
279       { "spawn",        0,              0,      's' },
280       { "spawn-path",   OPTF_ARGREQ,    0,      'p' },
281       { "spawn-args",   OPTF_ARGREQ,    0,      'S' },
282       { "syslog",       0,              0,      'l' },
283       { "logfile",      OPTF_ARGREQ,    0,      'f' },
284       { "warnings",     0,              0,      'w' },
285       { 0,              0,              0,      0 }
286     };
287
288     int i = mdwopt(argc, argv, "hvuDd:a:sp:S:lwf:n", opts, 0, 0, 0);
289     if (i < 0)
290       break;
291     switch (i) {
292       case 'h':
293         help(stdout);
294         exit(0);
295       case 'v':
296         version(stdout);
297         exit(0);
298       case 'u':
299         usage(stdout);
300         exit(0);
301       case 'D':
302         f |= f_daemon | f_noinput;
303         break;
304       case 'd':
305         dir = optarg;
306         break;
307       case 'a':
308         sock = optarg;
309         break;
310       case 's':
311         f |= f_spawn;
312         break;
313       case 'p':
314         f |= f_spawn;
315         spawnpath = optarg;
316         break;
317       case 'S':
318         f |= f_spawn | f_spawnopts;
319         for (p = strtok(optarg, ","); p; p = strtok(0, ","))
320           DA_PUSH(&spawnopts, p);
321         break;
322       case 'l':
323         f |= f_syslog | f_noinput;
324         break;
325       case 'w':
326         f |= f_warn;
327         break;
328       case 'f':
329         logname = optarg;
330         logfile(logname);
331         f |= f_noinput;
332         break;
333       default:
334         f |= f_bogus;
335         break;
336     }
337   }
338   if ((f & f_bogus) || ((f & f_noinput) && optind < argc)) {
339     usage(stderr);
340     exit(EXIT_FAILURE);
341   }
342
343   /* --- Connect to the server --- */
344
345   if (f & f_spawn) {
346     int pfd[2];
347     pid_t kid;
348     struct sigaction sa;
349     sigset_t newmask, oldmask;
350
351     sa.sa_handler = reap;
352     sigemptyset(&sa.sa_mask);
353     sa.sa_flags = SA_NOCLDSTOP;
354 #ifdef SA_RESTART
355     sa.sa_flags |= SA_RESTART;
356 #endif
357     sigaction(SIGCHLD, &sa, 0);
358
359     DA_UNSHIFT(&spawnopts, (char *)spawnpath);
360     if (!(f & f_spawnopts)) {
361       DA_PUSH(&spawnopts, "-d");
362       DA_PUSH(&spawnopts, (char *)dir);
363       DA_PUSH(&spawnopts, "-a");
364       DA_PUSH(&spawnopts, (char *)sock);
365     }
366     DA_PUSH(&spawnopts, 0);
367     if (socketpair(PF_UNIX, SOCK_STREAM, 0, pfd))
368       die(EXIT_FAILURE, "error from socketpair: %s", strerror(errno));
369     sigemptyset(&newmask);
370     sigaddset(&newmask, SIGCHLD);
371     sigprocmask(SIG_BLOCK, &newmask, &oldmask);
372     if ((kid = fork()) < 0)
373       die(EXIT_FAILURE, "fork failed: %s", strerror(errno));
374     if (!kid) {
375       dup2(pfd[1], STDIN_FILENO);
376       dup2(pfd[1], STDOUT_FILENO);
377       close(pfd[1]);
378       close(pfd[0]);
379       if (logfp)
380         fclose(logfp);
381       closelog();
382       execvp(DA(&spawnopts)[0], DA(&spawnopts));
383       die(127, "couldn't exec `%s': %s", spawnpath, strerror(errno));
384     }
385     sigprocmask(SIG_SETMASK, &oldmask, 0);
386     fd = pfd[0];
387     close(pfd[1]);
388   } else {
389     struct sockaddr_un sun;
390     size_t sz = strlen(sock) + 1;
391     dstr d = DSTR_INIT;
392     dstr_putf(&d, "%s/%s", dir, sock);
393     if (d.sz + 1 > sizeof(sun.sun_path))
394       die(EXIT_FAILURE, "socket name `%s' too long", sock);
395     memset(&sun, 0, sizeof(sun));
396     sun.sun_family = AF_UNIX;
397     memcpy(sun.sun_path, d.buf, d.sz + 1);
398     sz = d.sz + offsetof(struct sockaddr_un, sun_path) + 1;
399     dstr_destroy(&d);
400     if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
401       die(EXIT_FAILURE, "error making socket: %s", strerror(errno));
402     if (connect(fd, (struct sockaddr *)&sun, sz)) {
403       die(EXIT_FAILURE, "error connecting to `%s': %s",
404           sun.sun_path, strerror(errno));
405     }
406   }
407
408   if (f & f_daemon) {
409     if (u_daemon())
410       die(EXIT_FAILURE, "error becoming daemon: %s", strerror(errno));
411   }
412
413   /* --- If we're meant to be interactive, do that --- */
414
415   if (!(f & f_noinput) && optind == argc) {
416     sel_state sel;
417     selbuf bu, bs;
418
419     sel_init(&sel);
420     selbuf_init(&bu, &sel, STDIN_FILENO, uline, &bu);
421     selbuf_init(&bs, &sel, fd, sline, &bs);
422     for (;;) {
423       if (sel_select(&sel))
424         die(EXIT_FAILURE, "select failed: %s", strerror(errno));
425     }
426   }
427
428   /* --- If there's a command, submit it --- */
429
430   if (optind < argc) {
431     dstr d = DSTR_INIT;
432     dstr_puts(&d, argv[optind++]);
433     while (optind < argc) {
434       dstr_putc(&d, ' ');
435       dstr_puts(&d, argv[optind++]);
436     }
437     dstr_putc(&d, '\n');
438     write(fd, d.buf, d.len);
439     shutdown(fd, 1);
440     dstr_destroy(&d);
441     f |= f_command;
442   }
443
444   /* --- Pull everything else out of the box --- */
445
446   {
447     lbuf b;
448     lbuf_init(&b, cline, 0);
449     if (f & f_syslog)
450       openlog(QUIS, 0, LOG_DAEMON);
451     if (logfp) {
452       struct sigaction sa;
453       sa.sa_handler = sighup;
454       sa.sa_flags = 0;
455       sigemptyset(&sa.sa_mask);
456       sigaction(SIGHUP, &sa, 0);
457     }
458     for (;;) {
459       size_t sz;
460       ssize_t n;
461       if (reopen) {
462         logfile(logname);
463         reopen = 0;
464       }
465       sz = lbuf_free(&b, &p);
466       n = read(fd, p, sz);
467       if (n < 0) {
468         if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
469           continue;
470         die(EXIT_FAILURE, "read failed: %s", strerror(errno));
471       }
472       if (n == 0)
473         break;
474       lbuf_flush(&b, p, n);
475     }
476     lbuf_close(&b);
477   }
478
479   return (0);
480 }
481
482 /*----- That's all, folks -------------------------------------------------*/