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