yaid.c: Time out idle connections after 30s.
[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
c3794524
MW
79static const struct policy default_policy = POLICY_INIT(A_NAME);
80static policy_v policy = DA_INIT; /* Vector of global policy rules */
81static fwatch polfw; /* Watch policy file for changes */
9da480be 82
c3794524
MW
83static unsigned char tokenbuf[4096]; /* Random-ish data for tokens */
84static size_t tokenptr = sizeof(tokenbuf); /* Current read position */
85static int randfd; /* File descriptor for random data */
9da480be 86
c3794524 87/*----- Ident protocol parsing --------------------------------------------*/
9da480be 88
c3794524
MW
89/* Advance *PP over whitespace characters. */
90static void skipws(const char **pp)
91 { while (isspace((unsigned char )**pp)) (*pp)++; }
92
93/* Copy a token of no more than N bytes starting at *PP into Q, advancing *PP
94 * over it.
95 */
96static int idtoken(const char **pp, char *q, size_t n)
9da480be 97{
c3794524 98 const char *p = *pp;
9da480be 99
c3794524
MW
100 skipws(&p);
101 n--;
102 for (;;) {
103 if (*p == ':' || *p <= 32 || *p >= 127) break;
104 if (!n) return (-1);
105 *q++ = *p++;
106 n--;
9da480be 107 }
c3794524
MW
108 *q++ = 0;
109 *pp = p;
110 return (0);
111}
112
113/* Read an unsigned decimal number from *PP, and store it in *II. Check that
114 * it's between MIN and MAX, and advance *PP over it. Return zero for
115 * success, or nonzero if something goes wrong.
116 */
117static int unum(const char **pp, unsigned *ii, unsigned min, unsigned max)
118{
119 char *q;
120 unsigned long i;
121 int e;
122
123 skipws(pp);
124 if (!isdigit((unsigned char)**pp)) return (-1);
125 e = errno; errno = 0;
126 i = strtoul(*pp, &q, 10);
127 if (errno) return (-1);
128 *pp = q;
129 errno = e;
130 if (i < min || i > max) return (-1);
131 *ii = i;
132 return (0);
9da480be
MW
133}
134
c3794524
MW
135/*----- Asynchronous writing ----------------------------------------------*/
136
137/* Callback for actually writing stuff from a `writebuf'. */
9da480be
MW
138static void write_out(int fd, unsigned mode, void *p)
139{
140 ssize_t n;
141 struct writebuf *wb = p;
142
c3794524 143 /* Try to write something. */
9da480be
MW
144 if ((n = write(fd, wb->buf + wb->o, wb->n)) < 0) {
145 if (errno == EAGAIN || errno == EWOULDBLOCK) return;
146 wb->n = 0;
147 sel_rmfile(&wb->wr);
148 wb->func(errno, wb->p);
149 }
150 wb->o += n;
151 wb->n -= n;
c3794524
MW
152
153 /* If there's nothing left then restore the buffer to its empty state. */
9da480be
MW
154 if (!wb->n) {
155 wb->o = 0;
156 sel_rmfile(&wb->wr);
157 wb->func(0, wb->p);
158 }
159}
160
c3794524 161/* Queue N bytes starting at P to be written. */
9da480be
MW
162static int queue_write(struct writebuf *wb, const void *p, size_t n)
163{
c3794524 164 /* Maybe there's nothing to actually do. */
9da480be 165 if (!n) return (0);
c3794524
MW
166
167 /* Make sure it'll fit. */
9da480be 168 if (wb->n - wb->o + n > WRBUFSZ) return (-1);
c3794524
MW
169
170 /* If there's anything there already, then make sure it's at the start of
171 * the available space.
172 */
9da480be
MW
173 if (wb->o) {
174 memmove(wb->buf, wb->buf + wb->o, wb->n);
175 wb->o = 0;
176 }
c3794524
MW
177
178 /* If there's nothing currently there, then we're not requesting write
179 * notifications, so set that up, and force an initial wake-up.
180 */
9da480be
MW
181 if (!wb->n) {
182 sel_addfile(&wb->wr);
183 sel_force(&wb->wr);
184 }
c3794524
MW
185
186 /* Copy the new material over. */
187 memcpy(wb->buf + wb->n, p, n);
9da480be 188 wb->n += n;
c3794524
MW
189
190 /* Done. */
9da480be
MW
191 return (0);
192}
193
c3794524 194/* Release resources allocated to WB. */
9da480be
MW
195static void free_writebuf(struct writebuf *wb)
196 { if (wb->n) sel_rmfile(&wb->wr); }
197
c3794524
MW
198/* Initialize a writebuf in *WB, writing to file descriptor FD. On
199 * completion, call FUNC, passing it P and an error indicator: either 0 for
200 * success or an `errno' value on failure.
201 */
9da480be
MW
202static void init_writebuf(struct writebuf *wb,
203 int fd, void (*func)(int, void *), void *p)
204{
205 sel_initfile(&sel, &wb->wr, fd, SEL_WRITE, write_out, wb);
206 wb->func = func;
207 wb->p = p;
208 wb->n = wb->o = 0;
209}
210
c3794524 211/*----- General utilities -------------------------------------------------*/
9da480be 212
c3794524
MW
213/* Format and log MSG somewhere sensible, at the syslog(3) priority PRIO.
214 * Prefix it with a description of the query Q, if non-null.
215 */
216void logmsg(const struct query *q, int prio, const char *msg, ...)
9da480be 217{
c3794524
MW
218 va_list ap;
219 dstr d = DSTR_INIT;
220
221 va_start(ap, msg);
222 if (q) {
223 dputsock(&d, q->ao, &q->s[L]);
224 dstr_puts(&d, " <-> ");
225 dputsock(&d, q->ao, &q->s[R]);
226 dstr_puts(&d, ": ");
227 }
228 dstr_vputf(&d, msg, &ap);
229 va_end(ap);
230 fprintf(stderr, "yaid: %s\n", d.buf);
231 dstr_destroy(&d);
9da480be
MW
232}
233
c3794524
MW
234/* Fix up a socket FD so that it won't bite us. Returns zero on success, or
235 * nonzero on error.
236 */
95df134c
MW
237static int fix_up_socket(int fd, const char *what)
238{
239 int yes = 1;
240
241 if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
242 logmsg(0, LOG_ERR, "failed to set %s connection nonblocking: %s",
243 what, strerror(errno));
244 return (-1);
245 }
246
247 if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &yes, sizeof(yes))) {
248 logmsg(0, LOG_ERR,
249 "failed to disable `out-of-band' data on %s connection: %s",
250 what, strerror(errno));
251 return (-1);
252 }
253
254 return (0);
255}
256
c3794524
MW
257/*----- Client output functions -------------------------------------------*/
258
259static void disconnect_client(struct client *c);
260
261/* Notification that output has been written. If successful, re-enable the
262 * input buffer and prepare for another query.
263 */
9da480be
MW
264static void done_client_write(int err, void *p)
265{
266 struct client *c = p;
267
268 if (!err)
269 selbuf_enable(&c->b);
270 else {
271 logmsg(&c->q, LOG_ERR, "failed to send reply: %s", strerror(err));
272 disconnect_client(c);
273 }
274}
275
c3794524
MW
276/* Format the message FMT and queue it to be sent to the client. Client
277 * input will be disabled until the write completes.
278 */
9da480be
MW
279static void write_to_client(struct client *c, const char *fmt, ...)
280{
281 va_list ap;
282 char buf[WRBUFSZ];
283 ssize_t n;
284
285 va_start(ap, fmt);
286 n = vsnprintf(buf, sizeof(buf), fmt, ap);
287 if (n < 0) {
288 logmsg(&c->q, LOG_ERR, "failed to format output: %s", strerror(errno));
289 disconnect_client(c);
290 return;
291 } else if (n > sizeof(buf)) {
292 logmsg(&c->q, LOG_ERR, "output too long for client send buffer");
293 disconnect_client(c);
294 return;
295 }
296
297 selbuf_disable(&c->b);
298 if (queue_write(&c->wb, buf, n)) {
299 logmsg(&c->q, LOG_ERR, "write buffer overflow");
300 disconnect_client(c);
301 }
302}
303
c3794524
MW
304/* Format a reply to the client, with the form LPORT:RPORT:TY:TOK0[:TOK1].
305 * Typically, TY will be `ERROR' or `USERID'. In the former case, TOK0 will
306 * be the error token and TOK1 will be null; in the latter case, TOK0 will be
307 * the operating system and TOK1 the user name.
308 */
c809f908
MW
309static void reply(struct client *c, const char *ty,
310 const char *tok0, const char *tok1)
9da480be 311{
c809f908
MW
312 write_to_client(c, "%u,%u:%s:%s%s%s\r\n",
313 c->q.s[L].port, c->q.s[R].port, ty,
314 tok0, tok1 ? ":" : "", tok1 ? tok1 : "");
9da480be
MW
315}
316
c3794524 317/* Mapping from error codes to their protocol tokens. */
bf4d9761
MW
318const char *const errtok[] = {
319#define DEFTOK(err, tok) tok,
320 ERROR(DEFTOK)
321#undef DEFTOK
322};
323
c3794524 324/* Report an error with code ERR to the client. */
9da480be
MW
325static void reply_error(struct client *c, unsigned err)
326{
327 assert(err < E_LIMIT);
c809f908 328 reply(c, "ERROR", errtok[err], 0);
9da480be
MW
329}
330
c3794524 331/*----- NAT proxy functions -----------------------------------------------*/
9da480be 332
c3794524
MW
333/* Cancel the proxy operation PX, closing the connection and releasing
334 * resources. This is used for both normal and unexpected closures.
335 */
336static void cancel_proxy(struct proxy *px)
9da480be 337{
c3794524
MW
338 if (px->fd == -1)
339 conn_kill(&px->cn);
340 else {
341 close(px->fd);
342 selbuf_destroy(&px->b);
343 free_writebuf(&px->wb);
9da480be 344 }
c3794524
MW
345 selbuf_enable(&px->c->b);
346 px->c->px = 0;
347 xfree(px);
9da480be
MW
348}
349
c3794524
MW
350/* Notification that a line (presumably a reply) has been received from the
351 * server. We should check it, log it, and propagate the answer back.
352 * Whatever happens, this proxy operation is now complete.
353 */
9da480be
MW
354static void proxy_line(char *line, size_t sz, void *p)
355{
356 struct proxy *px = p;
357 char buf[1024];
358 const char *q = line;
359 unsigned lp, rp;
360
c3794524 361 /* Trim trailing space. */
9da480be 362 while (sz && isspace((unsigned char)line[sz - 1])) sz--;
9da480be 363
c3794524 364 /* Parse the port numbers. These should match the request. */
9da480be
MW
365 if (unum(&q, &lp, 1, 65535)) goto syntax;
366 skipws(&q); if (*q != ',') goto syntax; q++;
367 if (unum(&q, &rp, 1, 65535)) goto syntax;
368 skipws(&q); if (*q != ':') goto syntax; q++;
369 if (lp != px->c->q.u.nat.port || rp != px->c->q.s[R].port) goto syntax;
c3794524
MW
370
371 /* Find out what kind of reply this is. */
9da480be
MW
372 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
373 skipws(&q); if (*q != ':') goto syntax; q++;
c3794524 374
9da480be 375 if (strcmp(buf, "ERROR") == 0) {
c3794524
MW
376
377 /* Report the error without interpreting it. It might be meaningful to
378 * the client.
379 */
9da480be
MW
380 skipws(&q);
381 logmsg(&px->c->q, LOG_ERR, "proxy error from %s: %s", px->nat, q);
c809f908 382 reply(px->c, "ERROR", q, 0);
c3794524 383
9da480be 384 } else if (strcmp(buf, "USERID") == 0) {
c3794524
MW
385
386 /* Parse out the operating system and user name, and pass them on. */
9da480be
MW
387 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
388 skipws(&q); if (*q != ':') goto syntax; q++;
389 skipws(&q);
390 logmsg(&px->c->q, LOG_ERR, "user `%s'; proxy = %s, os = %s",
391 q, px->nat, buf);
c809f908 392 reply(px->c, "USERID", buf, q);
c3794524 393
9da480be
MW
394 } else
395 goto syntax;
396 goto done;
397
398syntax:
c3794524 399 /* We didn't understand the message from the client. */
9da480be
MW
400 logmsg(&px->c->q, LOG_ERR, "failed to parse response from %s", px->nat);
401 reply_error(px->c, E_UNKNOWN);
402done:
c3794524 403 /* All finished, no matter what. */
9da480be
MW
404 cancel_proxy(px);
405}
406
c3794524
MW
407/* Notification that we have written the query to the server. Await a
408 * response if successful.
409 */
9da480be
MW
410static void done_proxy_write(int err, void *p)
411{
412 struct proxy *px = p;
413
414 if (err) {
415 logmsg(&px->c->q, LOG_ERR, "failed to proxy query to %s: %s",
416 px->nat, strerror(errno));
417 reply_error(px->c, E_UNKNOWN);
418 cancel_proxy(px);
419 return;
420 }
421 selbuf_enable(&px->b);
422}
423
c3794524
MW
424/* Notification that the connection to the server is either established or
425 * failed. In the former case, queue the right query.
426 */
9da480be
MW
427static void proxy_connected(int fd, void *p)
428{
429 struct proxy *px = p;
430 char buf[16];
431 int n;
432
c3794524 433 /* If the connection failed then report the problem and give up. */
9da480be
MW
434 if (fd < 0) {
435 logmsg(&px->c->q, LOG_ERR,
436 "failed to make %s proxy connection to %s: %s",
bf4d9761 437 px->c->l->ao->name, px->nat, strerror(errno));
9da480be
MW
438 reply_error(px->c, E_UNKNOWN);
439 cancel_proxy(px);
440 return;
441 }
442
c3794524 443 /* We're now ready to go, so set things up. */
9da480be
MW
444 px->fd = fd;
445 selbuf_init(&px->b, &sel, fd, proxy_line, px);
446 selbuf_setsize(&px->b, 1024);
447 selbuf_disable(&px->b);
448 init_writebuf(&px->wb, fd, done_proxy_write, px);
449
c3794524
MW
450 /* Write the query. This buffer is large enough because we've already
451 * range-checked the remote the port number and the local one came from the
452 * kernel, which we trust not to do anything stupid.
453 */
9da480be
MW
454 n = sprintf(buf, "%u,%u\r\n", px->c->q.u.nat.port, px->c->q.s[R].port);
455 queue_write(&px->wb, buf, n);
456}
457
c3794524
MW
458/* Proxy the query through to a client machine for which we're providing NAT
459 * disservice.
460 */
9da480be
MW
461static void proxy_query(struct client *c)
462{
463 struct socket s;
464 struct sockaddr_storage ss;
465 size_t ssz;
466 struct proxy *px;
9da480be
MW
467 int fd;
468
c3794524 469 /* Allocate the context structure for the NAT. */
9da480be 470 px = xmalloc(sizeof(*px));
c3794524
MW
471
472 /* We'll use the client host's address in lots of log messages, so we may
473 * as well format it once and use it over and over.
474 */
bf4d9761 475 inet_ntop(c->q.ao->af, &c->q.u.nat.addr, px->nat, sizeof(px->nat));
9da480be 476
c3794524 477 /* Create the socket for the connection. */
bf4d9761 478 if ((fd = socket(c->q.ao->af, SOCK_STREAM, 0)) < 0) {
9da480be 479 logmsg(&c->q, LOG_ERR, "failed to make %s socket for proxy: %s",
bf4d9761 480 c->l->ao->name, strerror(errno));
9da480be
MW
481 goto err_0;
482 }
95df134c 483 if (fix_up_socket(fd, "proxy")) goto err_1;
9da480be 484
c3794524
MW
485 /* Set up the connection to the client host. The connection interface is a
486 * bit broken: if the connection completes immediately, then the callback
487 * function is called synchronously, and that might decide to shut
488 * everything down. So we must have fully initialized our context before
489 * calling `conn_init', and mustn't touch it again afterwards -- since the
490 * block may have been freed.
491 */
9da480be
MW
492 s = c->q.u.nat;
493 s.port = 113;
bf4d9761 494 c->l->ao->socket_to_sockaddr(&s, &ss, &ssz);
9da480be 495 selbuf_disable(&c->b);
79805e61
MW
496 c->px = px; px->c = c;
497 px->fd = -1;
9da480be
MW
498 if (conn_init(&px->cn, &sel, fd, (struct sockaddr *)&ss, ssz,
499 proxy_connected, px)) {
500 logmsg(&c->q, LOG_ERR, "failed to make %s proxy connection to %s: %s",
bf4d9761 501 c->l->ao->name, px->nat, strerror(errno));
9da480be
MW
502 goto err_2;
503 }
504
c3794524 505 /* All ready to go. */
9da480be
MW
506 return;
507
c3794524 508 /* Tidy up after various kinds of failures. */
9da480be
MW
509err_2:
510 selbuf_enable(&c->b);
511err_1:
512 close(px->fd);
513err_0:
514 xfree(px);
515 reply_error(c, E_UNKNOWN);
516}
517
c3794524
MW
518/*----- Client connection functions ---------------------------------------*/
519
520/* Disconnect a client, freeing up any associated resources. */
521static void disconnect_client(struct client *c)
522{
523 close(c->fd);
524 selbuf_destroy(&c->b);
4f8fdcc1 525 sel_rmtimer(&c->t);
c3794524
MW
526 free_writebuf(&c->wb);
527 if (c->px) cancel_proxy(c->px);
528 xfree(c);
529}
9da480be 530
4f8fdcc1
MW
531/* Time out a client because it's been idle for too long. */
532static void timeout_client(struct timeval *tv, void *p)
533{
534 struct client *c = p;
535 logmsg(&c->q, LOG_NOTICE, "timing out idle or stuck client");
536 sel_addtimer(&sel, &c->t, tv, timeout_client, 0);
537 disconnect_client(c);
538}
539
540/* Reset the client idle timer, as a result of activity. Set EXISTP if
541 * there is an existing timer which needs to be removed.
542 */
543static void reset_client_timer(struct client *c, int existp)
544{
545 struct timeval tv;
546
547 gettimeofday(&tv, 0);
548 tv.tv_sec += 30;
549 if (existp) sel_rmtimer(&c->t);
550 sel_addtimer(&sel, &c->t, &tv, timeout_client, c);
551}
552
c3794524
MW
553/* Write a pseudorandom token into the buffer at P, which must have space for
554 * at least TOKENSZ bytes.
555 */
556#define TOKENRANDSZ 8
557#define TOKENSZ ((4*TOKENRANDSZ + 5)/3)
9da480be
MW
558static void user_token(char *p)
559{
9da480be
MW
560 unsigned a = 0;
561 unsigned b = 0;
562 int i;
c3794524
MW
563 static const char tokmap[64] =
564 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
9da480be 565
c3794524
MW
566 /* If there's not enough pseudorandom stuff lying around, then read more
567 * from the kernel.
568 */
569 if (tokenptr + TOKENRANDSZ >= sizeof(tokenbuf)) {
9da480be
MW
570 if (read(randfd, tokenbuf, sizeof(tokenbuf)) < sizeof(tokenbuf))
571 die(1, "unexpected short read or error from `/dev/urandom'");
572 tokenptr = 0;
573 }
574
c3794524
MW
575 /* Now encode the bytes using a slightly tweaked base-64 encoding. Read
576 * bytes into the accumulator and write out characters while there's
577 * enough material.
578 */
579 for (i = 0; i < TOKENRANDSZ; i++) {
9da480be
MW
580 a = (a << 8) | tokenbuf[tokenptr++]; b += 8;
581 while (b >= 6) {
582 b -= 6;
583 *p++ = tokmap[(a >> b) & 0x3f];
584 }
585 }
c3794524
MW
586
587 /* If there's anything left in the accumulator then flush it out. */
9da480be
MW
588 if (b)
589 *p++ = tokmap[(a << (6 - b)) & 0x3f];
c3794524
MW
590
591 /* Null-terminate the token. */
9da480be
MW
592 *p++ = 0;
593}
594
c3794524
MW
595/* Notification that a line has been received from the client. Parse it,
596 * find out about the connection it's referring to, apply the relevant
597 * policy rules, and produce a response. This is where almost everything
598 * interesting happens.
599 */
9da480be
MW
600static void client_line(char *line, size_t len, void *p)
601{
602 struct client *c = p;
603 const char *q;
604 struct passwd *pw = 0;
605 const struct policy *pol;
606 dstr d = DSTR_INIT;
607 struct policy upol = POLICY_INIT(A_LIMIT);
608 struct policy_file pf;
609 char buf[16];
610 int i;
611
c3794524 612 /* If the connection has closed, then tidy stuff away. */
9da480be
MW
613 c->q.s[L].port = c->q.s[R].port = 0;
614 if (!line) {
615 disconnect_client(c);
616 return;
617 }
618
4f8fdcc1
MW
619 /* Client activity, so update the timer. */
620 reset_client_timer(c, 1);
621
c3794524
MW
622 /* See if the policy file has changed since we last looked. If so, try to
623 * read the new version.
624 */
9da480be
MW
625 if (fwatch_update(&polfw, "yaid.policy")) {
626 logmsg(0, LOG_INFO, "reload master policy file `%s'", "yaid.policy");
627 load_policy_file("yaid.policy", &policy);
628 }
629
c3794524 630 /* Read the local and remote port numbers into the query structure. */
9da480be
MW
631 q = line;
632 if (unum(&q, &c->q.s[L].port, 1, 65535)) goto bad;
633 skipws(&q); if (*q != ',') goto bad; q++;
634 if (unum(&q, &c->q.s[R].port, 1, 65535)) goto bad;
635 skipws(&q); if (*q) goto bad;
636
c3794524 637 /* Identify the connection. Act on the result. */
9da480be
MW
638 identify(&c->q);
639 switch (c->q.resp) {
c3794524 640
9da480be 641 case R_UID:
c3794524
MW
642 /* We found a user. Track down the user's password entry, because
643 * we'll want that later. Most of the processing for this case is
644 * below.
645 */
9da480be
MW
646 if ((pw = getpwuid(c->q.u.uid)) == 0) {
647 logmsg(&c->q, LOG_ERR, "no passwd entry for user %d", c->q.u.uid);
648 reply_error(c, E_NOUSER);
649 return;
650 }
651 break;
c3794524 652
9da480be 653 case R_NAT:
c3794524
MW
654 /* We've acted as a NAT for this connection. Proxy the query through
655 * to the actal client host.
656 */
9da480be
MW
657 proxy_query(c);
658 return;
c3794524 659
9da480be 660 case R_ERROR:
c3794524
MW
661 /* We failed to identify the connection for some reason. We should
662 * already have logged an error, so there's not much to do here.
663 */
9da480be
MW
664 reply_error(c, c->q.u.error);
665 return;
c3794524 666
9da480be 667 default:
c3794524 668 /* Something happened that we don't understand. */
9da480be
MW
669 abort();
670 }
671
c3794524 672 /* Search the table of policy rules to find a match. */
9da480be
MW
673 for (i = 0; i < DA_LEN(&policy); i++) {
674 pol = &DA(&policy)[i];
675 if (!match_policy(pol, &c->q)) continue;
c3794524
MW
676
677 /* If this is something simple, then apply the resulting policy rule. */
678 if (pol->act.act != A_USER) goto match;
679
680 /* The global policy has decided to let the user have a say, so we must
681 * parse the user file.
682 */
9da480be
MW
683 DRESET(&d);
684 dstr_putf(&d, "%s/.yaid.policy", pw->pw_dir);
685 if (open_policy_file(&pf, d.buf, "user policy file", &c->q))
686 continue;
687 while (!read_policy_file(&pf)) {
c3794524
MW
688
689 /* Give up after 100 lines. If the user's policy is that complicated,
690 * something's gone very wrong. Or there's too much commentary or
691 * something.
692 */
9da480be
MW
693 if (pf.lno > 100) {
694 logmsg(&c->q, LOG_ERR, "%s:%d: user policy file too long",
695 pf.name, pf.lno);
696 break;
697 }
c3794524
MW
698
699 /* If this isn't a match, go around for the next rule. */
9da480be 700 if (!match_policy(&pf.p, &c->q)) continue;
c3794524
MW
701
702 /* Check that the user is allowed to request this action. If not, see
703 * if there's a more acceptable action later on.
704 */
9da480be
MW
705 if (!(pol->act.u.user & (1 << pf.p.act.act))) {
706 logmsg(&c->q, LOG_ERR,
707 "%s:%d: user action forbidden by global policy",
708 pf.name, pf.lno);
709 continue;
710 }
c3794524
MW
711
712 /* We've found a match, so grab it, close the file, and say we're
713 * done.
714 */
9da480be
MW
715 upol = pf.p; pol = &upol;
716 init_policy(&pf.p);
717 close_policy_file(&pf);
c3794524 718 DDESTROY(&d);
9da480be
MW
719 goto match;
720 }
721 close_policy_file(&pf);
c3794524 722 DDESTROY(&d);
9da480be 723 }
c3794524
MW
724
725 /* No match: apply the built-in default policy. */
9da480be
MW
726 pol = &default_policy;
727
728match:
9da480be 729 switch (pol->act.act) {
c3794524 730
9da480be 731 case A_NAME:
c3794524 732 /* Report the actual user's name. */
9da480be 733 logmsg(&c->q, LOG_INFO, "user `%s' (%d)", pw->pw_name, c->q.u.uid);
c809f908 734 reply(c, "USERID", "UNIX", pw->pw_name);
9da480be 735 break;
c3794524 736
9da480be 737 case A_TOKEN:
c3794524 738 /* Report an arbitrary token which we can look up in our log file. */
9da480be
MW
739 user_token(buf);
740 logmsg(&c->q, LOG_INFO, "user `%s' (%d); token = %s",
741 pw->pw_name, c->q.u.uid, buf);
c809f908 742 reply(c, "USERID", "OTHER", buf);
9da480be 743 break;
c3794524 744
9da480be 745 case A_DENY:
c3794524 746 /* Deny that there's anyone there at all. */
9da480be
MW
747 logmsg(&c->q, LOG_INFO, "user `%s' (%d); denying",
748 pw->pw_name, c->q.u.uid);
749 break;
c3794524 750
9da480be 751 case A_HIDE:
c3794524 752 /* Report the user as being hidden. */
9da480be
MW
753 logmsg(&c->q, LOG_INFO, "user `%s' (%d); hiding",
754 pw->pw_name, c->q.u.uid);
755 reply_error(c, E_HIDDEN);
756 break;
c3794524 757
9da480be 758 case A_LIE:
c3794524 759 /* Tell an egregious lie about who the user is. */
9da480be
MW
760 logmsg(&c->q, LOG_INFO, "user `%s' (%d); lie = `%s'",
761 pw->pw_name, c->q.u.uid, pol->act.u.lie);
c809f908 762 reply(c, "USERID", "UNIX", pol->act.u.lie);
9da480be 763 break;
c3794524 764
9da480be 765 default:
c3794524 766 /* Something has gone very wrong. */
9da480be
MW
767 abort();
768 }
769
c3794524 770 /* All done. */
9da480be
MW
771 free_policy(&upol);
772 return;
773
774bad:
775 logmsg(&c->q, LOG_ERR, "failed to parse query from client");
776 disconnect_client(c);
777}
778
c3794524 779/* Notification that a new client has connected. Prepare to read a query. */
9da480be
MW
780static void accept_client(int fd, unsigned mode, void *p)
781{
782 struct listen *l = p;
783 struct client *c;
784 struct sockaddr_storage ssr, ssl;
785 size_t ssz = sizeof(ssr);
786 int sk;
787
c3794524 788 /* Accept the new connection. */
9da480be
MW
789 if ((sk = accept(fd, (struct sockaddr *)&ssr, &ssz)) < 0) {
790 if (errno != EAGAIN && errno == EWOULDBLOCK) {
791 logmsg(0, LOG_ERR, "failed to accept incoming %s connection: %s",
bf4d9761 792 l->ao->name, strerror(errno));
9da480be
MW
793 }
794 return;
795 }
95df134c 796 if (fix_up_socket(sk, "incoming client")) { close(sk); return; }
9da480be 797
c3794524 798 /* Build a client block and fill it in. */
9da480be
MW
799 c = xmalloc(sizeof(*c));
800 c->l = l;
bf4d9761 801 c->q.ao = l->ao;
c3794524
MW
802
803 /* Collect the local and remote addresses. */
bf4d9761 804 l->ao->sockaddr_to_addr(&ssr, &c->q.s[R].addr);
9da480be
MW
805 ssz = sizeof(ssl);
806 if (getsockname(sk, (struct sockaddr *)&ssl, &ssz)) {
807 logmsg(0, LOG_ERR,
808 "failed to read local address for incoming %s connection: %s",
bf4d9761 809 l->ao->name, strerror(errno));
9da480be
MW
810 close(sk);
811 xfree(c);
812 return;
813 }
bf4d9761 814 l->ao->sockaddr_to_addr(&ssl, &c->q.s[L].addr);
9da480be
MW
815 c->q.s[L].port = c->q.s[R].port = 0;
816
c3794524 817 /* Set stuff up for reading the query and sending responses. */
9da480be
MW
818 selbuf_init(&c->b, &sel, sk, client_line, c);
819 selbuf_setsize(&c->b, 1024);
4f8fdcc1 820 reset_client_timer(c, 0);
9da480be
MW
821 c->fd = sk;
822 c->px = 0;
823 init_writebuf(&c->wb, sk, done_client_write, c);
824}
825
c3794524
MW
826/*----- Main code ---------------------------------------------------------*/
827
828/* Set up a listening socket for the address family described by AO,
829 * listening on PORT.
830 */
bf4d9761 831static int make_listening_socket(const struct addrops *ao, int port)
9da480be
MW
832{
833 int fd;
bf4d9761
MW
834 int yes = 1;
835 struct socket s;
9da480be
MW
836 struct sockaddr_storage ss;
837 struct listen *l;
838 size_t ssz;
839
c3794524 840 /* Make the socket. */
bf4d9761 841 if ((fd = socket(ao->af, SOCK_STREAM, 0)) < 0) {
a20696ca 842 if (errno == EAFNOSUPPORT) return (-1);
9da480be 843 die(1, "failed to create %s listening socket: %s",
bf4d9761 844 ao->name, strerror(errno));
9da480be 845 }
c3794524
MW
846
847 /* Build the appropriate local address. */
bf4d9761
MW
848 s.addr = *ao->any;
849 s.port = port;
850 ao->socket_to_sockaddr(&s, &ss, &ssz);
c3794524
MW
851
852 /* Perform any initialization specific to the address type. */
bf4d9761
MW
853 if (ao->init_listen_socket(fd)) {
854 die(1, "failed to initialize %s listening socket: %s",
855 ao->name, strerror(errno));
856 }
c3794524
MW
857
858 /* Bind to the address. */
859 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
bf4d9761
MW
860 if (bind(fd, (struct sockaddr *)&ss, ssz)) {
861 die(1, "failed to bind %s listening socket: %s",
862 ao->name, strerror(errno));
9da480be 863 }
c3794524
MW
864
865 /* Avoid unpleasant race conditions. */
bf4d9761 866 if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
9da480be 867 die(1, "failed to set %s listening socket nonblocking: %s",
bf4d9761 868 ao->name, strerror(errno));
9da480be 869 }
c3794524
MW
870
871 /* Prepare to listen. */
9da480be 872 if (listen(fd, 5))
bf4d9761 873 die(1, "failed to listen for %s: %s", ao->name, strerror(errno));
9da480be 874
c3794524 875 /* Make a record of all of this. */
9da480be 876 l = xmalloc(sizeof(*l));
bf4d9761 877 l->ao = ao;
9da480be
MW
878 sel_initfile(&sel, &l->f, fd, SEL_READ, accept_client, l);
879 sel_addfile(&l->f);
880
c3794524 881 /* Done. */
a20696ca 882 return (0);
9da480be
MW
883}
884
885int main(int argc, char *argv[])
886{
887 int port = 113;
bf4d9761
MW
888 const struct addrops *ao;
889 int any = 0;
9da480be
MW
890
891 ego(argv[0]);
892
893 fwatch_init(&polfw, "yaid.policy");
b093b41d 894 init_sys();
9da480be
MW
895 if (load_policy_file("yaid.policy", &policy))
896 exit(1);
897 { int i;
898 for (i = 0; i < DA_LEN(&policy); i++)
899 print_policy(&DA(&policy)[i]);
900 }
901
902 if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
903 die(1, "failed to open `/dev/urandom' for reading: %s",
904 strerror(errno));
905 }
906
9da480be 907 sel_init(&sel);
bf4d9761
MW
908 for (ao = addroptab; ao->name; ao++)
909 if (!make_listening_socket(ao, port)) any = 1;
910 if (!any)
a20696ca 911 die(1, "no IP protocols supported");
9da480be
MW
912
913 for (;;)
914 if (sel_select(&sel)) die(1, "select failed: %s", strerror(errno));
915
916 return (0);
917}
918
919/*----- That's all, folks -------------------------------------------------*/