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