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