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