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