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