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