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