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