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