configure.ac, yaid.c: Make it be a proper Unix daemon.
[yaid] / yaid.c
CommitLineData
9da480be
MW
1/* -*-c-*-
2 *
3 * Main daemon
4 *
5 * (c) 2012 Straylight/Edgeware
6 */
7
8/*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Yet Another Ident Daemon (YAID).
11 *
12 * YAID is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * YAID is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with YAID; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 */
26
27/*----- Header files ------------------------------------------------------*/
28
29#include "yaid.h"
30
31/*----- Data structures ---------------------------------------------------*/
32
c3794524
MW
33/* A write buffer is the gadget which keeps track of our output and writes
34 * portions of it out as and when connections are ready for it.
35 */
9da480be
MW
36#define WRBUFSZ 1024
37struct writebuf {
c3794524
MW
38 size_t o; /* Offset of remaining data */
39 size_t n; /* Length of remaining data */
40 sel_file wr; /* Write selector */
41 void (*func)(int /*err*/, void *); /* Function to call on completion */
42 void *p; /* Context for `func' */
43 unsigned char buf[WRBUFSZ]; /* Output buffer */
9da480be
MW
44};
45
c3794524
MW
46/* Structure for a listening socket. There's one of these for each address
47 * family we're looking after.
48 */
49struct listen {
50 const struct addrops *ao; /* Address family operations */
51 sel_file f; /* Watch for incoming connections */
9da480be
MW
52};
53
c3794524 54/* The main structure for a client. */
9da480be 55struct client {
c3794524
MW
56 int fd; /* The connection to the client */
57 selbuf b; /* Accumulate lines of input */
58 struct query q; /* The clients query and our reply */
4f8fdcc1 59 struct sel_timer t; /* Timeout for idle or doomed conn */
c3794524
MW
60 struct listen *l; /* Back to the listener (and ops) */
61 struct writebuf wb; /* Write buffer for our reply */
62 struct proxy *px; /* Proxy if conn goes via NAT */
63};
64
65/* A proxy connection. */
66struct proxy {
67 int fd; /* Connection; -1 if in progress */
68 struct client *c; /* Back to the client */
69 conn cn; /* Nonblocking connection */
70 selbuf b; /* Accumulate the response line */
71 struct writebuf wb; /* Write buffer for query */
72 char nat[ADDRLEN]; /* Server address, as text */
9da480be
MW
73};
74
75/*----- Static variables --------------------------------------------------*/
76
c3794524 77static sel_state sel; /* I/O multiplexer state */
9da480be 78
74716d82
MW
79static const char *pidfile = 0; /* Where to write daemon's pid */
80
81static const char *policyfile = POLICYFILE; /* Filename for global policy */
c3794524
MW
82static const struct policy default_policy = POLICY_INIT(A_NAME);
83static policy_v policy = DA_INIT; /* Vector of global policy rules */
84static fwatch polfw; /* Watch policy file for changes */
9da480be 85
c3794524
MW
86static unsigned char tokenbuf[4096]; /* Random-ish data for tokens */
87static size_t tokenptr = sizeof(tokenbuf); /* Current read position */
88static int randfd; /* File descriptor for random data */
9da480be 89
74716d82
MW
90static unsigned flags = 0; /* Various interesting flags */
91#define F_SYSLOG 1u /* Use syslog for logging */
92#define F_RUNNING 2u /* Running properly now */
93
c3794524 94/*----- Ident protocol parsing --------------------------------------------*/
9da480be 95
c3794524
MW
96/* Advance *PP over whitespace characters. */
97static void skipws(const char **pp)
98 { while (isspace((unsigned char )**pp)) (*pp)++; }
99
100/* Copy a token of no more than N bytes starting at *PP into Q, advancing *PP
101 * over it.
102 */
103static int idtoken(const char **pp, char *q, size_t n)
9da480be 104{
c3794524 105 const char *p = *pp;
9da480be 106
c3794524
MW
107 skipws(&p);
108 n--;
109 for (;;) {
110 if (*p == ':' || *p <= 32 || *p >= 127) break;
111 if (!n) return (-1);
112 *q++ = *p++;
113 n--;
9da480be 114 }
c3794524
MW
115 *q++ = 0;
116 *pp = p;
117 return (0);
118}
119
120/* Read an unsigned decimal number from *PP, and store it in *II. Check that
121 * it's between MIN and MAX, and advance *PP over it. Return zero for
122 * success, or nonzero if something goes wrong.
123 */
124static int unum(const char **pp, unsigned *ii, unsigned min, unsigned max)
125{
126 char *q;
127 unsigned long i;
128 int e;
129
130 skipws(pp);
131 if (!isdigit((unsigned char)**pp)) return (-1);
132 e = errno; errno = 0;
133 i = strtoul(*pp, &q, 10);
134 if (errno) return (-1);
135 *pp = q;
136 errno = e;
137 if (i < min || i > max) return (-1);
138 *ii = i;
139 return (0);
9da480be
MW
140}
141
c3794524
MW
142/*----- Asynchronous writing ----------------------------------------------*/
143
144/* Callback for actually writing stuff from a `writebuf'. */
9da480be
MW
145static void write_out(int fd, unsigned mode, void *p)
146{
147 ssize_t n;
148 struct writebuf *wb = p;
149
c3794524 150 /* Try to write something. */
9da480be
MW
151 if ((n = write(fd, wb->buf + wb->o, wb->n)) < 0) {
152 if (errno == EAGAIN || errno == EWOULDBLOCK) return;
153 wb->n = 0;
154 sel_rmfile(&wb->wr);
155 wb->func(errno, wb->p);
156 }
157 wb->o += n;
158 wb->n -= n;
c3794524
MW
159
160 /* If there's nothing left then restore the buffer to its empty state. */
9da480be
MW
161 if (!wb->n) {
162 wb->o = 0;
163 sel_rmfile(&wb->wr);
164 wb->func(0, wb->p);
165 }
166}
167
c3794524 168/* Queue N bytes starting at P to be written. */
9da480be
MW
169static int queue_write(struct writebuf *wb, const void *p, size_t n)
170{
c3794524 171 /* Maybe there's nothing to actually do. */
9da480be 172 if (!n) return (0);
c3794524
MW
173
174 /* Make sure it'll fit. */
9da480be 175 if (wb->n - wb->o + n > WRBUFSZ) return (-1);
c3794524
MW
176
177 /* If there's anything there already, then make sure it's at the start of
178 * the available space.
179 */
9da480be
MW
180 if (wb->o) {
181 memmove(wb->buf, wb->buf + wb->o, wb->n);
182 wb->o = 0;
183 }
c3794524
MW
184
185 /* If there's nothing currently there, then we're not requesting write
186 * notifications, so set that up, and force an initial wake-up.
187 */
9da480be
MW
188 if (!wb->n) {
189 sel_addfile(&wb->wr);
190 sel_force(&wb->wr);
191 }
c3794524
MW
192
193 /* Copy the new material over. */
194 memcpy(wb->buf + wb->n, p, n);
9da480be 195 wb->n += n;
c3794524
MW
196
197 /* Done. */
9da480be
MW
198 return (0);
199}
200
c3794524 201/* Release resources allocated to WB. */
9da480be
MW
202static void free_writebuf(struct writebuf *wb)
203 { if (wb->n) sel_rmfile(&wb->wr); }
204
c3794524
MW
205/* Initialize a writebuf in *WB, writing to file descriptor FD. On
206 * completion, call FUNC, passing it P and an error indicator: either 0 for
207 * success or an `errno' value on failure.
208 */
9da480be
MW
209static void init_writebuf(struct writebuf *wb,
210 int fd, void (*func)(int, void *), void *p)
211{
212 sel_initfile(&sel, &wb->wr, fd, SEL_WRITE, write_out, wb);
213 wb->func = func;
214 wb->p = p;
215 wb->n = wb->o = 0;
216}
217
c3794524 218/*----- General utilities -------------------------------------------------*/
9da480be 219
c3794524
MW
220/* Format and log MSG somewhere sensible, at the syslog(3) priority PRIO.
221 * Prefix it with a description of the query Q, if non-null.
222 */
223void logmsg(const struct query *q, int prio, const char *msg, ...)
9da480be 224{
c3794524
MW
225 va_list ap;
226 dstr d = DSTR_INIT;
74716d82
MW
227 time_t t;
228 struct tm *tm;
229 char buf[64];
c3794524
MW
230
231 va_start(ap, msg);
232 if (q) {
233 dputsock(&d, q->ao, &q->s[L]);
234 dstr_puts(&d, " <-> ");
235 dputsock(&d, q->ao, &q->s[R]);
236 dstr_puts(&d, ": ");
237 }
238 dstr_vputf(&d, msg, &ap);
239 va_end(ap);
74716d82
MW
240
241 if (!(flags & F_RUNNING))
242 moan("%s", d.buf);
243 else if (flags & F_SYSLOG)
244 syslog(prio, "%s", d.buf);
245 else {
246 t = time(0);
247 tm = localtime(&t);
248 strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S %z", tm);
249 fprintf(stderr, "%s %s: %s\n", buf, QUIS, d.buf);
250 }
251
c3794524 252 dstr_destroy(&d);
9da480be
MW
253}
254
c3794524
MW
255/* Fix up a socket FD so that it won't bite us. Returns zero on success, or
256 * nonzero on error.
257 */
95df134c
MW
258static int fix_up_socket(int fd, const char *what)
259{
260 int yes = 1;
261
262 if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
263 logmsg(0, LOG_ERR, "failed to set %s connection nonblocking: %s",
264 what, strerror(errno));
265 return (-1);
266 }
267
268 if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &yes, sizeof(yes))) {
269 logmsg(0, LOG_ERR,
270 "failed to disable `out-of-band' data on %s connection: %s",
271 what, strerror(errno));
272 return (-1);
273 }
274
275 return (0);
276}
277
c3794524
MW
278/*----- Client output functions -------------------------------------------*/
279
280static void disconnect_client(struct client *c);
281
282/* Notification that output has been written. If successful, re-enable the
283 * input buffer and prepare for another query.
284 */
9da480be
MW
285static void done_client_write(int err, void *p)
286{
287 struct client *c = p;
288
289 if (!err)
290 selbuf_enable(&c->b);
291 else {
292 logmsg(&c->q, LOG_ERR, "failed to send reply: %s", strerror(err));
293 disconnect_client(c);
294 }
295}
296
c3794524
MW
297/* Format the message FMT and queue it to be sent to the client. Client
298 * input will be disabled until the write completes.
299 */
9da480be
MW
300static void write_to_client(struct client *c, const char *fmt, ...)
301{
302 va_list ap;
303 char buf[WRBUFSZ];
304 ssize_t n;
305
306 va_start(ap, fmt);
307 n = vsnprintf(buf, sizeof(buf), fmt, ap);
308 if (n < 0) {
309 logmsg(&c->q, LOG_ERR, "failed to format output: %s", strerror(errno));
310 disconnect_client(c);
311 return;
312 } else if (n > sizeof(buf)) {
313 logmsg(&c->q, LOG_ERR, "output too long for client send buffer");
314 disconnect_client(c);
315 return;
316 }
317
318 selbuf_disable(&c->b);
319 if (queue_write(&c->wb, buf, n)) {
320 logmsg(&c->q, LOG_ERR, "write buffer overflow");
321 disconnect_client(c);
322 }
323}
324
c3794524
MW
325/* Format a reply to the client, with the form LPORT:RPORT:TY:TOK0[:TOK1].
326 * Typically, TY will be `ERROR' or `USERID'. In the former case, TOK0 will
327 * be the error token and TOK1 will be null; in the latter case, TOK0 will be
328 * the operating system and TOK1 the user name.
329 */
c809f908
MW
330static void reply(struct client *c, const char *ty,
331 const char *tok0, const char *tok1)
9da480be 332{
c809f908
MW
333 write_to_client(c, "%u,%u:%s:%s%s%s\r\n",
334 c->q.s[L].port, c->q.s[R].port, ty,
335 tok0, tok1 ? ":" : "", tok1 ? tok1 : "");
9da480be
MW
336}
337
c3794524 338/* Mapping from error codes to their protocol tokens. */
bf4d9761
MW
339const char *const errtok[] = {
340#define DEFTOK(err, tok) tok,
341 ERROR(DEFTOK)
342#undef DEFTOK
343};
344
c3794524 345/* Report an error with code ERR to the client. */
9da480be
MW
346static void reply_error(struct client *c, unsigned err)
347{
348 assert(err < E_LIMIT);
c809f908 349 reply(c, "ERROR", errtok[err], 0);
9da480be
MW
350}
351
c3794524 352/*----- NAT proxy functions -----------------------------------------------*/
9da480be 353
c3794524
MW
354/* Cancel the proxy operation PX, closing the connection and releasing
355 * resources. This is used for both normal and unexpected closures.
356 */
357static void cancel_proxy(struct proxy *px)
9da480be 358{
c3794524
MW
359 if (px->fd == -1)
360 conn_kill(&px->cn);
361 else {
362 close(px->fd);
363 selbuf_destroy(&px->b);
364 free_writebuf(&px->wb);
9da480be 365 }
c3794524
MW
366 selbuf_enable(&px->c->b);
367 px->c->px = 0;
368 xfree(px);
9da480be
MW
369}
370
c3794524
MW
371/* Notification that a line (presumably a reply) has been received from the
372 * server. We should check it, log it, and propagate the answer back.
373 * Whatever happens, this proxy operation is now complete.
374 */
9da480be
MW
375static void proxy_line(char *line, size_t sz, void *p)
376{
377 struct proxy *px = p;
378 char buf[1024];
379 const char *q = line;
380 unsigned lp, rp;
381
c3794524 382 /* Trim trailing space. */
9da480be 383 while (sz && isspace((unsigned char)line[sz - 1])) sz--;
9da480be 384
c3794524 385 /* Parse the port numbers. These should match the request. */
9da480be
MW
386 if (unum(&q, &lp, 1, 65535)) goto syntax;
387 skipws(&q); if (*q != ',') goto syntax; q++;
388 if (unum(&q, &rp, 1, 65535)) goto syntax;
389 skipws(&q); if (*q != ':') goto syntax; q++;
390 if (lp != px->c->q.u.nat.port || rp != px->c->q.s[R].port) goto syntax;
c3794524
MW
391
392 /* Find out what kind of reply this is. */
9da480be
MW
393 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
394 skipws(&q); if (*q != ':') goto syntax; q++;
c3794524 395
9da480be 396 if (strcmp(buf, "ERROR") == 0) {
c3794524
MW
397
398 /* Report the error without interpreting it. It might be meaningful to
399 * the client.
400 */
9da480be
MW
401 skipws(&q);
402 logmsg(&px->c->q, LOG_ERR, "proxy error from %s: %s", px->nat, q);
c809f908 403 reply(px->c, "ERROR", q, 0);
c3794524 404
9da480be 405 } else if (strcmp(buf, "USERID") == 0) {
c3794524
MW
406
407 /* Parse out the operating system and user name, and pass them on. */
9da480be
MW
408 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
409 skipws(&q); if (*q != ':') goto syntax; q++;
410 skipws(&q);
411 logmsg(&px->c->q, LOG_ERR, "user `%s'; proxy = %s, os = %s",
412 q, px->nat, buf);
c809f908 413 reply(px->c, "USERID", buf, q);
c3794524 414
9da480be
MW
415 } else
416 goto syntax;
417 goto done;
418
419syntax:
c3794524 420 /* We didn't understand the message from the client. */
9da480be
MW
421 logmsg(&px->c->q, LOG_ERR, "failed to parse response from %s", px->nat);
422 reply_error(px->c, E_UNKNOWN);
423done:
c3794524 424 /* All finished, no matter what. */
9da480be
MW
425 cancel_proxy(px);
426}
427
c3794524
MW
428/* Notification that we have written the query to the server. Await a
429 * response if successful.
430 */
9da480be
MW
431static void done_proxy_write(int err, void *p)
432{
433 struct proxy *px = p;
434
435 if (err) {
436 logmsg(&px->c->q, LOG_ERR, "failed to proxy query to %s: %s",
437 px->nat, strerror(errno));
438 reply_error(px->c, E_UNKNOWN);
439 cancel_proxy(px);
440 return;
441 }
442 selbuf_enable(&px->b);
443}
444
c3794524
MW
445/* Notification that the connection to the server is either established or
446 * failed. In the former case, queue the right query.
447 */
9da480be
MW
448static void proxy_connected(int fd, void *p)
449{
450 struct proxy *px = p;
451 char buf[16];
452 int n;
453
c3794524 454 /* If the connection failed then report the problem and give up. */
9da480be
MW
455 if (fd < 0) {
456 logmsg(&px->c->q, LOG_ERR,
457 "failed to make %s proxy connection to %s: %s",
bf4d9761 458 px->c->l->ao->name, px->nat, strerror(errno));
9da480be
MW
459 reply_error(px->c, E_UNKNOWN);
460 cancel_proxy(px);
461 return;
462 }
463
c3794524 464 /* We're now ready to go, so set things up. */
9da480be
MW
465 px->fd = fd;
466 selbuf_init(&px->b, &sel, fd, proxy_line, px);
467 selbuf_setsize(&px->b, 1024);
468 selbuf_disable(&px->b);
469 init_writebuf(&px->wb, fd, done_proxy_write, px);
470
c3794524
MW
471 /* Write the query. This buffer is large enough because we've already
472 * range-checked the remote the port number and the local one came from the
473 * kernel, which we trust not to do anything stupid.
474 */
9da480be
MW
475 n = sprintf(buf, "%u,%u\r\n", px->c->q.u.nat.port, px->c->q.s[R].port);
476 queue_write(&px->wb, buf, n);
477}
478
c3794524
MW
479/* Proxy the query through to a client machine for which we're providing NAT
480 * disservice.
481 */
9da480be
MW
482static void proxy_query(struct client *c)
483{
484 struct socket s;
485 struct sockaddr_storage ss;
486 size_t ssz;
487 struct proxy *px;
9da480be
MW
488 int fd;
489
c3794524 490 /* Allocate the context structure for the NAT. */
9da480be 491 px = xmalloc(sizeof(*px));
c3794524
MW
492
493 /* We'll use the client host's address in lots of log messages, so we may
494 * as well format it once and use it over and over.
495 */
bf4d9761 496 inet_ntop(c->q.ao->af, &c->q.u.nat.addr, px->nat, sizeof(px->nat));
9da480be 497
c3794524 498 /* Create the socket for the connection. */
bf4d9761 499 if ((fd = socket(c->q.ao->af, SOCK_STREAM, 0)) < 0) {
9da480be 500 logmsg(&c->q, LOG_ERR, "failed to make %s socket for proxy: %s",
bf4d9761 501 c->l->ao->name, strerror(errno));
9da480be
MW
502 goto err_0;
503 }
95df134c 504 if (fix_up_socket(fd, "proxy")) goto err_1;
9da480be 505
c3794524
MW
506 /* Set up the connection to the client host. The connection interface is a
507 * bit broken: if the connection completes immediately, then the callback
508 * function is called synchronously, and that might decide to shut
509 * everything down. So we must have fully initialized our context before
510 * calling `conn_init', and mustn't touch it again afterwards -- since the
511 * block may have been freed.
512 */
9da480be
MW
513 s = c->q.u.nat;
514 s.port = 113;
bf4d9761 515 c->l->ao->socket_to_sockaddr(&s, &ss, &ssz);
9da480be 516 selbuf_disable(&c->b);
79805e61
MW
517 c->px = px; px->c = c;
518 px->fd = -1;
9da480be
MW
519 if (conn_init(&px->cn, &sel, fd, (struct sockaddr *)&ss, ssz,
520 proxy_connected, px)) {
521 logmsg(&c->q, LOG_ERR, "failed to make %s proxy connection to %s: %s",
bf4d9761 522 c->l->ao->name, px->nat, strerror(errno));
9da480be
MW
523 goto err_2;
524 }
525
c3794524 526 /* All ready to go. */
9da480be
MW
527 return;
528
c3794524 529 /* Tidy up after various kinds of failures. */
9da480be
MW
530err_2:
531 selbuf_enable(&c->b);
532err_1:
533 close(px->fd);
534err_0:
535 xfree(px);
536 reply_error(c, E_UNKNOWN);
537}
538
c3794524
MW
539/*----- Client connection functions ---------------------------------------*/
540
541/* Disconnect a client, freeing up any associated resources. */
542static void disconnect_client(struct client *c)
543{
544 close(c->fd);
545 selbuf_destroy(&c->b);
4f8fdcc1 546 sel_rmtimer(&c->t);
c3794524
MW
547 free_writebuf(&c->wb);
548 if (c->px) cancel_proxy(c->px);
549 xfree(c);
550}
9da480be 551
4f8fdcc1
MW
552/* Time out a client because it's been idle for too long. */
553static void timeout_client(struct timeval *tv, void *p)
554{
555 struct client *c = p;
556 logmsg(&c->q, LOG_NOTICE, "timing out idle or stuck client");
557 sel_addtimer(&sel, &c->t, tv, timeout_client, 0);
558 disconnect_client(c);
559}
560
561/* Reset the client idle timer, as a result of activity. Set EXISTP if
562 * there is an existing timer which needs to be removed.
563 */
564static void reset_client_timer(struct client *c, int existp)
565{
566 struct timeval tv;
567
568 gettimeofday(&tv, 0);
569 tv.tv_sec += 30;
570 if (existp) sel_rmtimer(&c->t);
571 sel_addtimer(&sel, &c->t, &tv, timeout_client, c);
572}
573
c3794524
MW
574/* Write a pseudorandom token into the buffer at P, which must have space for
575 * at least TOKENSZ bytes.
576 */
577#define TOKENRANDSZ 8
578#define TOKENSZ ((4*TOKENRANDSZ + 5)/3)
9da480be
MW
579static void user_token(char *p)
580{
9da480be
MW
581 unsigned a = 0;
582 unsigned b = 0;
583 int i;
c3794524
MW
584 static const char tokmap[64] =
585 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
9da480be 586
c3794524
MW
587 /* If there's not enough pseudorandom stuff lying around, then read more
588 * from the kernel.
589 */
590 if (tokenptr + TOKENRANDSZ >= sizeof(tokenbuf)) {
9da480be
MW
591 if (read(randfd, tokenbuf, sizeof(tokenbuf)) < sizeof(tokenbuf))
592 die(1, "unexpected short read or error from `/dev/urandom'");
593 tokenptr = 0;
594 }
595
c3794524
MW
596 /* Now encode the bytes using a slightly tweaked base-64 encoding. Read
597 * bytes into the accumulator and write out characters while there's
598 * enough material.
599 */
600 for (i = 0; i < TOKENRANDSZ; i++) {
9da480be
MW
601 a = (a << 8) | tokenbuf[tokenptr++]; b += 8;
602 while (b >= 6) {
603 b -= 6;
604 *p++ = tokmap[(a >> b) & 0x3f];
605 }
606 }
c3794524
MW
607
608 /* If there's anything left in the accumulator then flush it out. */
9da480be
MW
609 if (b)
610 *p++ = tokmap[(a << (6 - b)) & 0x3f];
c3794524
MW
611
612 /* Null-terminate the token. */
9da480be
MW
613 *p++ = 0;
614}
615
c3794524
MW
616/* Notification that a line has been received from the client. Parse it,
617 * find out about the connection it's referring to, apply the relevant
618 * policy rules, and produce a response. This is where almost everything
619 * interesting happens.
620 */
9da480be
MW
621static void client_line(char *line, size_t len, void *p)
622{
623 struct client *c = p;
624 const char *q;
625 struct passwd *pw = 0;
626 const struct policy *pol;
627 dstr d = DSTR_INIT;
628 struct policy upol = POLICY_INIT(A_LIMIT);
629 struct policy_file pf;
630 char buf[16];
631 int i;
632
c3794524 633 /* If the connection has closed, then tidy stuff away. */
9da480be
MW
634 c->q.s[L].port = c->q.s[R].port = 0;
635 if (!line) {
636 disconnect_client(c);
637 return;
638 }
639
4f8fdcc1
MW
640 /* Client activity, so update the timer. */
641 reset_client_timer(c, 1);
642
c3794524
MW
643 /* See if the policy file has changed since we last looked. If so, try to
644 * read the new version.
645 */
74716d82
MW
646 if (fwatch_update(&polfw, policyfile)) {
647 logmsg(0, LOG_INFO, "reload master policy file `%s'", policyfile);
648 load_policy_file(policyfile, &policy);
9da480be
MW
649 }
650
c3794524 651 /* Read the local and remote port numbers into the query structure. */
9da480be
MW
652 q = line;
653 if (unum(&q, &c->q.s[L].port, 1, 65535)) goto bad;
654 skipws(&q); if (*q != ',') goto bad; q++;
655 if (unum(&q, &c->q.s[R].port, 1, 65535)) goto bad;
656 skipws(&q); if (*q) goto bad;
657
c3794524 658 /* Identify the connection. Act on the result. */
9da480be
MW
659 identify(&c->q);
660 switch (c->q.resp) {
c3794524 661
9da480be 662 case R_UID:
c3794524
MW
663 /* We found a user. Track down the user's password entry, because
664 * we'll want that later. Most of the processing for this case is
665 * below.
666 */
9da480be
MW
667 if ((pw = getpwuid(c->q.u.uid)) == 0) {
668 logmsg(&c->q, LOG_ERR, "no passwd entry for user %d", c->q.u.uid);
669 reply_error(c, E_NOUSER);
670 return;
671 }
672 break;
c3794524 673
9da480be 674 case R_NAT:
c3794524
MW
675 /* We've acted as a NAT for this connection. Proxy the query through
676 * to the actal client host.
677 */
9da480be
MW
678 proxy_query(c);
679 return;
c3794524 680
9da480be 681 case R_ERROR:
c3794524
MW
682 /* We failed to identify the connection for some reason. We should
683 * already have logged an error, so there's not much to do here.
684 */
9da480be
MW
685 reply_error(c, c->q.u.error);
686 return;
c3794524 687
9da480be 688 default:
c3794524 689 /* Something happened that we don't understand. */
9da480be
MW
690 abort();
691 }
692
c3794524 693 /* Search the table of policy rules to find a match. */
9da480be
MW
694 for (i = 0; i < DA_LEN(&policy); i++) {
695 pol = &DA(&policy)[i];
696 if (!match_policy(pol, &c->q)) continue;
c3794524
MW
697
698 /* If this is something simple, then apply the resulting policy rule. */
699 if (pol->act.act != A_USER) goto match;
700
701 /* The global policy has decided to let the user have a say, so we must
702 * parse the user file.
703 */
9da480be
MW
704 DRESET(&d);
705 dstr_putf(&d, "%s/.yaid.policy", pw->pw_dir);
706 if (open_policy_file(&pf, d.buf, "user policy file", &c->q))
707 continue;
708 while (!read_policy_file(&pf)) {
c3794524
MW
709
710 /* Give up after 100 lines. If the user's policy is that complicated,
711 * something's gone very wrong. Or there's too much commentary or
712 * something.
713 */
9da480be
MW
714 if (pf.lno > 100) {
715 logmsg(&c->q, LOG_ERR, "%s:%d: user policy file too long",
716 pf.name, pf.lno);
717 break;
718 }
c3794524
MW
719
720 /* If this isn't a match, go around for the next rule. */
9da480be 721 if (!match_policy(&pf.p, &c->q)) continue;
c3794524
MW
722
723 /* Check that the user is allowed to request this action. If not, see
724 * if there's a more acceptable action later on.
725 */
9da480be
MW
726 if (!(pol->act.u.user & (1 << pf.p.act.act))) {
727 logmsg(&c->q, LOG_ERR,
728 "%s:%d: user action forbidden by global policy",
729 pf.name, pf.lno);
730 continue;
731 }
c3794524
MW
732
733 /* We've found a match, so grab it, close the file, and say we're
734 * done.
735 */
9da480be
MW
736 upol = pf.p; pol = &upol;
737 init_policy(&pf.p);
738 close_policy_file(&pf);
c3794524 739 DDESTROY(&d);
9da480be
MW
740 goto match;
741 }
742 close_policy_file(&pf);
c3794524 743 DDESTROY(&d);
9da480be 744 }
c3794524
MW
745
746 /* No match: apply the built-in default policy. */
9da480be
MW
747 pol = &default_policy;
748
749match:
9da480be 750 switch (pol->act.act) {
c3794524 751
9da480be 752 case A_NAME:
c3794524 753 /* Report the actual user's name. */
9da480be 754 logmsg(&c->q, LOG_INFO, "user `%s' (%d)", pw->pw_name, c->q.u.uid);
c809f908 755 reply(c, "USERID", "UNIX", pw->pw_name);
9da480be 756 break;
c3794524 757
9da480be 758 case A_TOKEN:
c3794524 759 /* Report an arbitrary token which we can look up in our log file. */
9da480be
MW
760 user_token(buf);
761 logmsg(&c->q, LOG_INFO, "user `%s' (%d); token = %s",
762 pw->pw_name, c->q.u.uid, buf);
c809f908 763 reply(c, "USERID", "OTHER", buf);
9da480be 764 break;
c3794524 765
9da480be 766 case A_DENY:
c3794524 767 /* Deny that there's anyone there at all. */
9da480be
MW
768 logmsg(&c->q, LOG_INFO, "user `%s' (%d); denying",
769 pw->pw_name, c->q.u.uid);
770 break;
c3794524 771
9da480be 772 case A_HIDE:
c3794524 773 /* Report the user as being hidden. */
9da480be
MW
774 logmsg(&c->q, LOG_INFO, "user `%s' (%d); hiding",
775 pw->pw_name, c->q.u.uid);
776 reply_error(c, E_HIDDEN);
777 break;
c3794524 778
9da480be 779 case A_LIE:
c3794524 780 /* Tell an egregious lie about who the user is. */
9da480be
MW
781 logmsg(&c->q, LOG_INFO, "user `%s' (%d); lie = `%s'",
782 pw->pw_name, c->q.u.uid, pol->act.u.lie);
c809f908 783 reply(c, "USERID", "UNIX", pol->act.u.lie);
9da480be 784 break;
c3794524 785
9da480be 786 default:
c3794524 787 /* Something has gone very wrong. */
9da480be
MW
788 abort();
789 }
790
c3794524 791 /* All done. */
9da480be
MW
792 free_policy(&upol);
793 return;
794
795bad:
796 logmsg(&c->q, LOG_ERR, "failed to parse query from client");
797 disconnect_client(c);
798}
799
c3794524 800/* Notification that a new client has connected. Prepare to read a query. */
9da480be
MW
801static void accept_client(int fd, unsigned mode, void *p)
802{
803 struct listen *l = p;
804 struct client *c;
805 struct sockaddr_storage ssr, ssl;
806 size_t ssz = sizeof(ssr);
807 int sk;
808
c3794524 809 /* Accept the new connection. */
9da480be
MW
810 if ((sk = accept(fd, (struct sockaddr *)&ssr, &ssz)) < 0) {
811 if (errno != EAGAIN && errno == EWOULDBLOCK) {
812 logmsg(0, LOG_ERR, "failed to accept incoming %s connection: %s",
bf4d9761 813 l->ao->name, strerror(errno));
9da480be
MW
814 }
815 return;
816 }
95df134c 817 if (fix_up_socket(sk, "incoming client")) { close(sk); return; }
9da480be 818
c3794524 819 /* Build a client block and fill it in. */
9da480be
MW
820 c = xmalloc(sizeof(*c));
821 c->l = l;
bf4d9761 822 c->q.ao = l->ao;
c3794524
MW
823
824 /* Collect the local and remote addresses. */
bf4d9761 825 l->ao->sockaddr_to_addr(&ssr, &c->q.s[R].addr);
9da480be
MW
826 ssz = sizeof(ssl);
827 if (getsockname(sk, (struct sockaddr *)&ssl, &ssz)) {
828 logmsg(0, LOG_ERR,
829 "failed to read local address for incoming %s connection: %s",
bf4d9761 830 l->ao->name, strerror(errno));
9da480be
MW
831 close(sk);
832 xfree(c);
833 return;
834 }
bf4d9761 835 l->ao->sockaddr_to_addr(&ssl, &c->q.s[L].addr);
9da480be
MW
836 c->q.s[L].port = c->q.s[R].port = 0;
837
c3794524 838 /* Set stuff up for reading the query and sending responses. */
9da480be
MW
839 selbuf_init(&c->b, &sel, sk, client_line, c);
840 selbuf_setsize(&c->b, 1024);
4f8fdcc1 841 reset_client_timer(c, 0);
9da480be
MW
842 c->fd = sk;
843 c->px = 0;
844 init_writebuf(&c->wb, sk, done_client_write, c);
845}
846
c3794524
MW
847/*----- Main code ---------------------------------------------------------*/
848
849/* Set up a listening socket for the address family described by AO,
850 * listening on PORT.
851 */
bf4d9761 852static int make_listening_socket(const struct addrops *ao, int port)
9da480be
MW
853{
854 int fd;
bf4d9761
MW
855 int yes = 1;
856 struct socket s;
9da480be
MW
857 struct sockaddr_storage ss;
858 struct listen *l;
859 size_t ssz;
860
c3794524 861 /* Make the socket. */
bf4d9761 862 if ((fd = socket(ao->af, SOCK_STREAM, 0)) < 0) {
a20696ca 863 if (errno == EAFNOSUPPORT) return (-1);
9da480be 864 die(1, "failed to create %s listening socket: %s",
bf4d9761 865 ao->name, strerror(errno));
9da480be 866 }
c3794524
MW
867
868 /* Build the appropriate local address. */
bf4d9761
MW
869 s.addr = *ao->any;
870 s.port = port;
871 ao->socket_to_sockaddr(&s, &ss, &ssz);
c3794524
MW
872
873 /* Perform any initialization specific to the address type. */
bf4d9761
MW
874 if (ao->init_listen_socket(fd)) {
875 die(1, "failed to initialize %s listening socket: %s",
876 ao->name, strerror(errno));
877 }
c3794524
MW
878
879 /* Bind to the address. */
880 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
bf4d9761
MW
881 if (bind(fd, (struct sockaddr *)&ss, ssz)) {
882 die(1, "failed to bind %s listening socket: %s",
883 ao->name, strerror(errno));
9da480be 884 }
c3794524
MW
885
886 /* Avoid unpleasant race conditions. */
bf4d9761 887 if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
9da480be 888 die(1, "failed to set %s listening socket nonblocking: %s",
bf4d9761 889 ao->name, strerror(errno));
9da480be 890 }
c3794524
MW
891
892 /* Prepare to listen. */
9da480be 893 if (listen(fd, 5))
bf4d9761 894 die(1, "failed to listen for %s: %s", ao->name, strerror(errno));
9da480be 895
c3794524 896 /* Make a record of all of this. */
9da480be 897 l = xmalloc(sizeof(*l));
bf4d9761 898 l->ao = ao;
9da480be
MW
899 sel_initfile(&sel, &l->f, fd, SEL_READ, accept_client, l);
900 sel_addfile(&l->f);
901
c3794524 902 /* Done. */
a20696ca 903 return (0);
9da480be
MW
904}
905
74716d82
MW
906/* Quit because of a fatal signal. */
907static void quit(int sig, void *p)
908{
909 const char *signame = p;
910
911 logmsg(0, LOG_NOTICE, "shutting down on %s", signame);
912 if (pidfile) unlink(pidfile);
913 exit(0);
914}
915
916/* Answer whether the string pointed to by P consists entirely of digits. */
917static int numericp(const char *p)
918{
919 while (*p)
920 if (!isdigit((unsigned char)*p++)) return (0);
921 return (1);
922}
923
924static void usage(FILE *fp)
925{
926 pquis(fp, "Usage: $ [-Dl] [-G GROUP] [-U USER] [-P FILE] "
927 "[-c FILE] [-p PORT]\n");
928}
929
930static void version(FILE *fp)
931 { pquis(fp, "$, version " VERSION "\n"); }
932
933static void help(FILE *fp)
934{
935 version(fp); fputc('\n', fp);
936 usage(fp);
937 fputs("\n\
938Yet Another Ident Daemon. Really, the world doesn't need such a thing.\n\
939It's just a shame none of the others do the right things.\n\
940\n\
941Options:\n\
942\n\
943 -h, --help Show this help message.\n\
944 -v, --version Show the version number.\n\
945 -u, --usage Show a very short usage summary.\n\
946\n\
947 -D, --daemon Become a daemon, running in the background.\n\
948 -G, --group=GROUP Set group after initialization.\n\
949 -P, --pidfile=FILE Write process id to FILE.\n\
950 -U, --user=USER Set user after initialization.\n\
951 -c, --config=FILE Read global policy from FILE.\n\
952 -l, --syslog Write log messages using syslog(3).\n\
953 -p, --port=PORT Listen for connections on this port.\n",
954 fp);
955}
956
9da480be
MW
957int main(int argc, char *argv[])
958{
959 int port = 113;
74716d82
MW
960 uid_t u = -1;
961 gid_t g = -1;
962 struct passwd *pw = 0;
963 struct group *gr;
964 struct servent *s;
965 sig sigint, sigterm;
966 FILE *fp = 0;
967 int i;
968 unsigned f = 0;
969#define f_bogus 1u
970#define f_daemon 2u
bf4d9761
MW
971 const struct addrops *ao;
972 int any = 0;
9da480be
MW
973
974 ego(argv[0]);
975
74716d82
MW
976 /* Parse command-line options. */
977 for (;;) {
978 const struct option opts[] = {
979 { "help", 0, 0, 'h' },
980 { "version", 0, 0, 'v' },
981 { "usage", 0, 0, 'u' },
982 { "daemon", 0, 0, 'D' },
983 { "group", OPTF_ARGREQ, 0, 'G' },
984 { "pidfile", OPTF_ARGREQ, 0, 'P' },
985 { "user", OPTF_ARGREQ, 0, 'U' },
986 { "config", OPTF_ARGREQ, 0, 'c' },
987 { "syslog", 0, 0, 'l' },
988 { "port", OPTF_ARGREQ, 0, 'p' },
989 { 0, 0, 0, 0 }
990 };
991
992 if ((i = mdwopt(argc, argv, "hvuDG:P:U:c:lp:", opts, 0, 0, 0)) < 0)
993 break;
994 switch (i) {
995 case 'h': help(stdout); exit(0);
996 case 'v': version(stdout); exit(0);
997 case 'u': usage(stdout); exit(0);
998 case 'D': f |= f_daemon; break;
999 case 'P': pidfile = optarg; break;
1000 case 'c': policyfile = optarg; break;
1001 case 'l': flags |= F_SYSLOG; break;
1002 case 'G':
1003 if (numericp(optarg))
1004 g = atoi(optarg);
1005 else if ((gr = getgrnam(optarg)) == 0)
1006 die(1, "unknown group `%s'", optarg);
1007 else
1008 g = gr->gr_gid;
1009 break;
1010 case 'U':
1011 if (numericp(optarg))
1012 u = atoi(optarg);
1013 else if ((pw = getpwnam(optarg)) == 0)
1014 die(1, "unknown user `%s'", optarg);
1015 else
1016 u = pw->pw_uid;
1017 break;
1018 case 'p':
1019 if (numericp(optarg))
1020 port = atoi(optarg);
1021 else if ((s = getservbyname(optarg, "tcp")) == 0)
1022 die(1, "unknown service name `%s'", optarg);
1023 else
1024 port = ntohs(s->s_port);
1025 break;
1026 default: f |= f_bogus; break;
1027 }
1028 }
1029 if (optind < argc) f |= f_bogus;
1030 if (f & f_bogus) { usage(stderr); exit(1); }
1031
1032 /* If a user has been requested, but no group, then find the user's primary
1033 * group. If the user was given by name, then we already have a password
1034 * entry and should use that, in case two differently-named users have the
1035 * same uid but distinct gids.
1036 */
1037 if (u != -1 && g == -1) {
1038 if (!pw && (pw = getpwuid(u)) == 0) {
1039 die(1, "failed to find password entry for user %d: "
1040 "request group explicitly", u);
1041 }
1042 g = pw->pw_gid;
1043 }
1044
1045 /* Initialize system-specific machinery. */
b093b41d 1046 init_sys();
74716d82
MW
1047
1048 /* Load the global policy rules. */
1049 fwatch_init(&polfw, policyfile);
1050 if (load_policy_file(policyfile, &policy))
9da480be 1051 exit(1);
9da480be 1052
74716d82 1053 /* Open the random data source. */
9da480be
MW
1054 if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
1055 die(1, "failed to open `/dev/urandom' for reading: %s",
1056 strerror(errno));
1057 }
1058
74716d82 1059 /* Set up the I/O event system. */
9da480be 1060 sel_init(&sel);
74716d82
MW
1061
1062 /* Watch for some interesting signals. */
1063 sig_init(&sel);
1064 sig_add(&sigint, SIGINT, quit, "SIGINT");
1065 sig_add(&sigterm, SIGTERM, quit, "SIGTERM");
1066
1067 /* Listen for incoming connections. */
bf4d9761
MW
1068 for (ao = addroptab; ao->name; ao++)
1069 if (!make_listening_socket(ao, port)) any = 1;
74716d82
MW
1070 if (!any) die(1, "no IP protocols supported");
1071
1072 /* Open the pidfile now, in case it's somewhere we can't write. */
1073 if (pidfile && (fp = fopen(pidfile, "w")) == 0) {
1074 die(1, "failed to open pidfile `%s' for writing: %s",
1075 pidfile, strerror(errno));
1076 }
1077
1078 /* If we're meant to use syslog, then open the log. */
1079 if (flags & F_SYSLOG)
1080 openlog(QUIS, 0, LOG_DAEMON);
1081
1082 /* Drop privileges. */
1083 if ((g != -1 && (setegid(g) || setgid(g) ||
1084 (getuid() == 0 && setgroups(1, &g)))) ||
1085 (u != -1 && setuid(u)))
1086 die(1, "failed to drop privileges: %s", strerror(errno));
9da480be 1087
74716d82
MW
1088 /* Become a background process, if requested. */
1089 if ((f & f_daemon) && daemonize())
1090 die(1, "failed to become daemon: %s", strerror(errno));
1091
1092 /* Write the process id to the pidfile. */
1093 if (fp) {
1094 fprintf(fp, "%d\n", getpid());
1095 fclose(fp);
1096 }
1097
1098 /* And now we're going. */
1099 flags |= F_RUNNING;
1100
1101 /* Read events and process them. */
1102 for (;;) {
1103 if (sel_select(&sel) && errno != EINTR)
1104 die(1, "select failed: %s", strerror(errno));
1105 }
9da480be 1106
74716d82 1107 /* This just keeps the compiler happy. */
9da480be
MW
1108 return (0);
1109}
1110
1111/*----- That's all, folks -------------------------------------------------*/