5 * (c) 2012 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Yet Another Ident Daemon (YAID).
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.
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.
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.
27 /*----- Header files ------------------------------------------------------*/
31 /*----- Data structures ---------------------------------------------------*/
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.
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 */
46 /* Structure for a listening socket. There's one of these for each address
47 * family we're looking after.
50 const struct addrops
*ao
; /* Address family operations */
51 sel_file f
; /* Watch for incoming connections */
54 /* The main structure for a client. */
56 int fd
; /* The connection to the client */
57 selbuf b
; /* Accumulate lines of input */
58 struct query q
; /* The clients query and our reply */
59 struct sel_timer t
; /* Timeout for idle or doomed conn */
60 struct listen
*l
; /* Back to the listener (and ops) */
61 struct writebuf wb
; /* Write buffer for our reply */
62 struct proxy
*px
; /* Proxy if conn goes via NAT */
65 /* A proxy connection. */
67 int fd
; /* Connection; -1 if in progress */
68 struct client
*c
; /* Back to the client */
69 conn cn
; /* Nonblocking connection */
70 selbuf b
; /* Accumulate the response line */
71 struct writebuf wb
; /* Write buffer for query */
72 char nat
[ADDRLEN
]; /* Server address, as text */
75 /*----- Static variables --------------------------------------------------*/
77 static sel_state sel
; /* I/O multiplexer state */
79 static const char *pidfile
= 0; /* Where to write daemon's pid */
81 static const char *policyfile
= POLICYFILE
; /* Filename for global policy */
82 static const struct policy default_policy
= POLICY_INIT(A_NAME
);
83 static policy_v policy
= DA_INIT
; /* Vector of global policy rules */
84 static fwatch polfw
; /* Watch policy file for changes */
86 static unsigned char tokenbuf
[4096]; /* Random-ish data for tokens */
87 static size_t tokenptr
= sizeof(tokenbuf
); /* Current read position */
88 static int randfd
; /* File descriptor for random data */
90 static unsigned flags
= 0; /* Various interesting flags */
91 #define F_SYSLOG 1u /* Use syslog for logging */
92 #define F_RUNNING 2u /* Running properly now */
94 /*----- Ident protocol parsing --------------------------------------------*/
96 /* Advance *PP over whitespace characters. */
97 static void skipws(const char **pp
)
98 { while (isspace((unsigned char )**pp
)) (*pp
)++; }
100 /* Copy a token of no more than N bytes starting at *PP into Q, advancing *PP
103 static int idtoken(const char **pp
, char *q
, size_t n
)
110 if (*p
== ':' || *p
<= 32 || *p
>= 127) break;
120 /* Read an unsigned decimal number from *PP, and store it in *II. Check that
121 * it's between MIN and MAX, and advance *PP over it. Return zero for
122 * success, or nonzero if something goes wrong.
124 static int unum(const char **pp
, unsigned *ii
, unsigned min
, unsigned max
)
131 if (!isdigit((unsigned char)**pp
)) return (-1);
132 e
= errno
; errno
= 0;
133 i
= strtoul(*pp
, &q
, 10);
134 if (errno
) return (-1);
137 if (i
< min
|| i
> max
) return (-1);
142 /*----- Asynchronous writing ----------------------------------------------*/
144 /* Callback for actually writing stuff from a `writebuf'. */
145 static void write_out(int fd
, unsigned mode
, void *p
)
148 struct writebuf
*wb
= p
;
150 /* Try to write something. */
151 if ((n
= write(fd
, wb
->buf
+ wb
->o
, wb
->n
)) < 0) {
152 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
) return;
155 wb
->func(errno
, wb
->p
);
160 /* If there's nothing left then restore the buffer to its empty state. */
168 /* Queue N bytes starting at P to be written. */
169 static int queue_write(struct writebuf
*wb
, const void *p
, size_t n
)
171 /* Maybe there's nothing to actually do. */
174 /* Make sure it'll fit. */
175 if (wb
->n
- wb
->o
+ n
> WRBUFSZ
) return (-1);
177 /* If there's anything there already, then make sure it's at the start of
178 * the available space.
181 memmove(wb
->buf
, wb
->buf
+ wb
->o
, wb
->n
);
185 /* If there's nothing currently there, then we're not requesting write
186 * notifications, so set that up, and force an initial wake-up.
189 sel_addfile(&wb
->wr
);
193 /* Copy the new material over. */
194 memcpy(wb
->buf
+ wb
->n
, p
, n
);
201 /* Release resources allocated to WB. */
202 static void free_writebuf(struct writebuf
*wb
)
203 { if (wb
->n
) sel_rmfile(&wb
->wr
); }
205 /* Initialize a writebuf in *WB, writing to file descriptor FD. On
206 * completion, call FUNC, passing it P and an error indicator: either 0 for
207 * success or an `errno' value on failure.
209 static void init_writebuf(struct writebuf
*wb
,
210 int fd
, void (*func
)(int, void *), void *p
)
212 sel_initfile(&sel
, &wb
->wr
, fd
, SEL_WRITE
, write_out
, wb
);
218 /*----- General utilities -------------------------------------------------*/
220 /* Format and log MSG somewhere sensible, at the syslog(3) priority PRIO.
221 * Prefix it with a description of the query Q, if non-null.
223 void logmsg(const struct query
*q
, int prio
, const char *msg
, ...)
233 dputsock(&d
, q
->ao
, &q
->s
[L
]);
234 dstr_puts(&d
, " <-> ");
235 dputsock(&d
, q
->ao
, &q
->s
[R
]);
238 dstr_vputf(&d
, msg
, &ap
);
241 if (!(flags
& F_RUNNING
))
243 else if (flags
& F_SYSLOG
)
244 syslog(prio
, "%s", d
.buf
);
248 strftime(buf
, sizeof(buf
), "%Y-%m-%d %H:%M:%S %z", tm
);
249 fprintf(stderr
, "%s %s: %s\n", buf
, QUIS
, d
.buf
);
255 /* Fix up a socket FD so that it won't bite us. Returns zero on success, or
258 static int fix_up_socket(int fd
, const char *what
)
262 if (fdflags(fd
, O_NONBLOCK
, O_NONBLOCK
, 0, 0)) {
263 logmsg(0, LOG_ERR
, "failed to set %s connection nonblocking: %s",
264 what
, strerror(errno
));
268 if (setsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &yes
, sizeof(yes
))) {
270 "failed to disable `out-of-band' data on %s connection: %s",
271 what
, strerror(errno
));
278 /*----- Client output functions -------------------------------------------*/
280 static void disconnect_client(struct client
*c
);
282 /* Notification that output has been written. If successful, re-enable the
283 * input buffer and prepare for another query.
285 static void done_client_write(int err
, void *p
)
287 struct client
*c
= p
;
290 selbuf_enable(&c
->b
);
292 logmsg(&c
->q
, LOG_ERR
, "failed to send reply: %s", strerror(err
));
293 disconnect_client(c
);
297 /* Format the message FMT and queue it to be sent to the client. Client
298 * input will be disabled until the write completes.
300 static void write_to_client(struct client
*c
, const char *fmt
, ...)
307 n
= vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
309 logmsg(&c
->q
, LOG_ERR
, "failed to format output: %s", strerror(errno
));
310 disconnect_client(c
);
312 } else if (n
> sizeof(buf
)) {
313 logmsg(&c
->q
, LOG_ERR
, "output too long for client send buffer");
314 disconnect_client(c
);
318 selbuf_disable(&c
->b
);
319 if (queue_write(&c
->wb
, buf
, n
)) {
320 logmsg(&c
->q
, LOG_ERR
, "write buffer overflow");
321 disconnect_client(c
);
325 /* Format a reply to the client, with the form LPORT:RPORT:TY:TOK0[:TOK1].
326 * Typically, TY will be `ERROR' or `USERID'. In the former case, TOK0 will
327 * be the error token and TOK1 will be null; in the latter case, TOK0 will be
328 * the operating system and TOK1 the user name.
330 static void reply(struct client
*c
, const char *ty
,
331 const char *tok0
, const char *tok1
)
333 write_to_client(c
, "%u,%u:%s:%s%s%s\r\n",
334 c
->q
.s
[L
].port
, c
->q
.s
[R
].port
, ty
,
335 tok0
, tok1 ?
":" : "", tok1 ? tok1
: "");
338 /* Mapping from error codes to their protocol tokens. */
339 const char *const errtok
[] = {
340 #define DEFTOK(err, tok) tok,
345 /* Report an error with code ERR to the client. */
346 static void reply_error(struct client
*c
, unsigned err
)
348 assert(err
< E_LIMIT
);
349 reply(c
, "ERROR", errtok
[err
], 0);
352 /*----- NAT proxy functions -----------------------------------------------*/
354 /* Cancel the proxy operation PX, closing the connection and releasing
355 * resources. This is used for both normal and unexpected closures.
357 static void cancel_proxy(struct proxy
*px
)
363 selbuf_destroy(&px
->b
);
364 free_writebuf(&px
->wb
);
366 selbuf_enable(&px
->c
->b
);
371 /* Notification that a line (presumably a reply) has been received from the
372 * server. We should check it, log it, and propagate the answer back.
373 * Whatever happens, this proxy operation is now complete.
375 static void proxy_line(char *line
, size_t sz
, void *p
)
377 struct proxy
*px
= p
;
379 const char *q
= line
;
382 /* Trim trailing space. */
383 while (sz
&& isspace((unsigned char)line
[sz
- 1])) sz
--;
385 /* Parse the port numbers. These should match the request. */
386 if (unum(&q
, &lp
, 1, 65535)) goto syntax
;
387 skipws(&q
); if (*q
!= ',') goto syntax
; q
++;
388 if (unum(&q
, &rp
, 1, 65535)) goto syntax
;
389 skipws(&q
); if (*q
!= ':') goto syntax
; q
++;
390 if (lp
!= px
->c
->q
.u
.nat
.port
|| rp
!= px
->c
->q
.s
[R
].port
) goto syntax
;
392 /* Find out what kind of reply this is. */
393 if (idtoken(&q
, buf
, sizeof(buf
))) goto syntax
;
394 skipws(&q
); if (*q
!= ':') goto syntax
; q
++;
396 if (strcmp(buf
, "ERROR") == 0) {
398 /* Report the error without interpreting it. It might be meaningful to
402 logmsg(&px
->c
->q
, LOG_ERR
, "proxy error from %s: %s", px
->nat
, q
);
403 reply(px
->c
, "ERROR", q
, 0);
405 } else if (strcmp(buf
, "USERID") == 0) {
407 /* Parse out the operating system and user name, and pass them on. */
408 if (idtoken(&q
, buf
, sizeof(buf
))) goto syntax
;
409 skipws(&q
); if (*q
!= ':') goto syntax
; q
++;
411 logmsg(&px
->c
->q
, LOG_ERR
, "user `%s'; proxy = %s, os = %s",
413 reply(px
->c
, "USERID", buf
, q
);
420 /* We didn't understand the message from the client. */
421 logmsg(&px
->c
->q
, LOG_ERR
, "failed to parse response from %s", px
->nat
);
422 reply_error(px
->c
, E_UNKNOWN
);
424 /* All finished, no matter what. */
428 /* Notification that we have written the query to the server. Await a
429 * response if successful.
431 static void done_proxy_write(int err
, void *p
)
433 struct proxy
*px
= p
;
436 logmsg(&px
->c
->q
, LOG_ERR
, "failed to proxy query to %s: %s",
437 px
->nat
, strerror(errno
));
438 reply_error(px
->c
, E_UNKNOWN
);
442 selbuf_enable(&px
->b
);
445 /* Notification that the connection to the server is either established or
446 * failed. In the former case, queue the right query.
448 static void proxy_connected(int fd
, void *p
)
450 struct proxy
*px
= p
;
454 /* If the connection failed then report the problem and give up. */
456 logmsg(&px
->c
->q
, LOG_ERR
,
457 "failed to make %s proxy connection to %s: %s",
458 px
->c
->l
->ao
->name
, px
->nat
, strerror(errno
));
459 reply_error(px
->c
, E_UNKNOWN
);
464 /* We're now ready to go, so set things up. */
466 selbuf_init(&px
->b
, &sel
, fd
, proxy_line
, px
);
467 selbuf_setsize(&px
->b
, 1024);
468 selbuf_disable(&px
->b
);
469 init_writebuf(&px
->wb
, fd
, done_proxy_write
, px
);
471 /* Write the query. This buffer is large enough because we've already
472 * range-checked the remote the port number and the local one came from the
473 * kernel, which we trust not to do anything stupid.
475 n
= sprintf(buf
, "%u,%u\r\n", px
->c
->q
.u
.nat
.port
, px
->c
->q
.s
[R
].port
);
476 queue_write(&px
->wb
, buf
, n
);
479 /* Proxy the query through to a client machine for which we're providing NAT
482 static void proxy_query(struct client
*c
)
485 struct sockaddr_storage ss
;
490 /* Allocate the context structure for the NAT. */
491 px
= xmalloc(sizeof(*px
));
493 /* We'll use the client host's address in lots of log messages, so we may
494 * as well format it once and use it over and over.
496 inet_ntop(c
->q
.ao
->af
, &c
->q
.u
.nat
.addr
, px
->nat
, sizeof(px
->nat
));
498 /* Create the socket for the connection. */
499 if ((fd
= socket(c
->q
.ao
->af
, SOCK_STREAM
, 0)) < 0) {
500 logmsg(&c
->q
, LOG_ERR
, "failed to make %s socket for proxy: %s",
501 c
->l
->ao
->name
, strerror(errno
));
504 if (fix_up_socket(fd
, "proxy")) goto err_1
;
506 /* Set up the connection to the client host. The connection interface is a
507 * bit broken: if the connection completes immediately, then the callback
508 * function is called synchronously, and that might decide to shut
509 * everything down. So we must have fully initialized our context before
510 * calling `conn_init', and mustn't touch it again afterwards -- since the
511 * block may have been freed.
515 c
->l
->ao
->socket_to_sockaddr(&s
, &ss
, &ssz
);
516 selbuf_disable(&c
->b
);
517 c
->px
= px
; px
->c
= c
;
519 if (conn_init(&px
->cn
, &sel
, fd
, (struct sockaddr
*)&ss
, ssz
,
520 proxy_connected
, px
)) {
521 logmsg(&c
->q
, LOG_ERR
, "failed to make %s proxy connection to %s: %s",
522 c
->l
->ao
->name
, px
->nat
, strerror(errno
));
526 /* All ready to go. */
529 /* Tidy up after various kinds of failures. */
531 selbuf_enable(&c
->b
);
536 reply_error(c
, E_UNKNOWN
);
539 /*----- Client connection functions ---------------------------------------*/
541 /* Disconnect a client, freeing up any associated resources. */
542 static void disconnect_client(struct client
*c
)
545 selbuf_destroy(&c
->b
);
547 free_writebuf(&c
->wb
);
548 if (c
->px
) cancel_proxy(c
->px
);
552 /* Time out a client because it's been idle for too long. */
553 static void timeout_client(struct timeval
*tv
, void *p
)
555 struct client
*c
= p
;
556 logmsg(&c
->q
, LOG_NOTICE
, "timing out idle or stuck client");
557 sel_addtimer(&sel
, &c
->t
, tv
, timeout_client
, 0);
558 disconnect_client(c
);
561 /* Reset the client idle timer, as a result of activity. Set EXISTP if
562 * there is an existing timer which needs to be removed.
564 static void reset_client_timer(struct client
*c
, int existp
)
568 gettimeofday(&tv
, 0);
570 if (existp
) sel_rmtimer(&c
->t
);
571 sel_addtimer(&sel
, &c
->t
, &tv
, timeout_client
, c
);
574 /* Write a pseudorandom token into the buffer at P, which must have space for
575 * at least TOKENSZ bytes.
577 #define TOKENRANDSZ 8
578 #define TOKENSZ ((4*TOKENRANDSZ + 5)/3)
579 static void user_token(char *p
)
584 static const char tokmap
[64] =
585 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
587 /* If there's not enough pseudorandom stuff lying around, then read more
590 if (tokenptr
+ TOKENRANDSZ
>= sizeof(tokenbuf
)) {
591 if (read(randfd
, tokenbuf
, sizeof(tokenbuf
)) < sizeof(tokenbuf
))
592 die(1, "unexpected short read or error from `/dev/urandom'");
596 /* Now encode the bytes using a slightly tweaked base-64 encoding. Read
597 * bytes into the accumulator and write out characters while there's
600 for (i
= 0; i
< TOKENRANDSZ
; i
++) {
601 a
= (a
<< 8) | tokenbuf
[tokenptr
++]; b
+= 8;
604 *p
++ = tokmap
[(a
>> b
) & 0x3f];
608 /* If there's anything left in the accumulator then flush it out. */
610 *p
++ = tokmap
[(a
<< (6 - b
)) & 0x3f];
612 /* Null-terminate the token. */
616 /* Notification that a line has been received from the client. Parse it,
617 * find out about the connection it's referring to, apply the relevant
618 * policy rules, and produce a response. This is where almost everything
619 * interesting happens.
621 static void client_line(char *line
, size_t len
, void *p
)
623 struct client
*c
= p
;
625 struct passwd
*pw
= 0;
626 const struct policy
*pol
;
628 struct policy upol
= POLICY_INIT(A_LIMIT
);
629 struct policy_file pf
;
633 /* If the connection has closed, then tidy stuff away. */
634 c
->q
.s
[L
].port
= c
->q
.s
[R
].port
= 0;
636 disconnect_client(c
);
640 /* Client activity, so update the timer. */
641 reset_client_timer(c
, 1);
643 /* See if the policy file has changed since we last looked. If so, try to
644 * read the new version.
646 if (fwatch_update(&polfw
, policyfile
)) {
647 logmsg(0, LOG_INFO
, "reload master policy file `%s'", policyfile
);
648 load_policy_file(policyfile
, &policy
);
651 /* Read the local and remote port numbers into the query structure. */
653 if (unum(&q
, &c
->q
.s
[L
].port
, 1, 65535)) goto bad
;
654 skipws(&q
); if (*q
!= ',') goto bad
; q
++;
655 if (unum(&q
, &c
->q
.s
[R
].port
, 1, 65535)) goto bad
;
656 skipws(&q
); if (*q
) goto bad
;
658 /* Identify the connection. Act on the result. */
663 /* We found a user. Track down the user's password entry, because
664 * we'll want that later. Most of the processing for this case is
667 if ((pw
= getpwuid(c
->q
.u
.uid
)) == 0) {
668 logmsg(&c
->q
, LOG_ERR
, "no passwd entry for user %d", c
->q
.u
.uid
);
669 reply_error(c
, E_NOUSER
);
675 /* We've acted as a NAT for this connection. Proxy the query through
676 * to the actal client host.
682 /* We failed to identify the connection for some reason. We should
683 * already have logged an error, so there's not much to do here.
685 reply_error(c
, c
->q
.u
.error
);
689 /* Something happened that we don't understand. */
693 /* Search the table of policy rules to find a match. */
694 for (i
= 0; i
< DA_LEN(&policy
); i
++) {
695 pol
= &DA(&policy
)[i
];
696 if (!match_policy(pol
, &c
->q
)) continue;
698 /* If this is something simple, then apply the resulting policy rule. */
699 if (pol
->act
.act
!= A_USER
) goto match
;
701 /* The global policy has decided to let the user have a say, so we must
702 * parse the user file.
705 dstr_putf(&d
, "%s/.yaid.policy", pw
->pw_dir
);
706 if (open_policy_file(&pf
, d
.buf
, "user policy file", &c
->q
))
708 while (!read_policy_file(&pf
)) {
710 /* Give up after 100 lines. If the user's policy is that complicated,
711 * something's gone very wrong. Or there's too much commentary or
715 logmsg(&c
->q
, LOG_ERR
, "%s:%d: user policy file too long",
720 /* If this isn't a match, go around for the next rule. */
721 if (!match_policy(&pf
.p
, &c
->q
)) continue;
723 /* Check that the user is allowed to request this action. If not, see
724 * if there's a more acceptable action later on.
726 if (!(pol
->act
.u
.user
& (1 << pf
.p
.act
.act
))) {
727 logmsg(&c
->q
, LOG_ERR
,
728 "%s:%d: user action forbidden by global policy",
733 /* We've found a match, so grab it, close the file, and say we're
736 upol
= pf
.p
; pol
= &upol
;
738 close_policy_file(&pf
);
742 close_policy_file(&pf
);
746 /* No match: apply the built-in default policy. */
747 pol
= &default_policy
;
750 switch (pol
->act
.act
) {
753 /* Report the actual user's name. */
754 logmsg(&c
->q
, LOG_INFO
, "user `%s' (%d)", pw
->pw_name
, c
->q
.u
.uid
);
755 reply(c
, "USERID", "UNIX", pw
->pw_name
);
759 /* Report an arbitrary token which we can look up in our log file. */
761 logmsg(&c
->q
, LOG_INFO
, "user `%s' (%d); token = %s",
762 pw
->pw_name
, c
->q
.u
.uid
, buf
);
763 reply(c
, "USERID", "OTHER", buf
);
767 /* Deny that there's anyone there at all. */
768 logmsg(&c
->q
, LOG_INFO
, "user `%s' (%d); denying",
769 pw
->pw_name
, c
->q
.u
.uid
);
773 /* Report the user as being hidden. */
774 logmsg(&c
->q
, LOG_INFO
, "user `%s' (%d); hiding",
775 pw
->pw_name
, c
->q
.u
.uid
);
776 reply_error(c
, E_HIDDEN
);
780 /* Tell an egregious lie about who the user is. */
781 logmsg(&c
->q
, LOG_INFO
, "user `%s' (%d); lie = `%s'",
782 pw
->pw_name
, c
->q
.u
.uid
, pol
->act
.u
.lie
);
783 reply(c
, "USERID", "UNIX", pol
->act
.u
.lie
);
787 /* Something has gone very wrong. */
796 logmsg(&c
->q
, LOG_ERR
, "failed to parse query from client");
797 disconnect_client(c
);
800 /* Notification that a new client has connected. Prepare to read a query. */
801 static void accept_client(int fd
, unsigned mode
, void *p
)
803 struct listen
*l
= p
;
805 struct sockaddr_storage ssr
, ssl
;
806 size_t ssz
= sizeof(ssr
);
809 /* Accept the new connection. */
810 if ((sk
= accept(fd
, (struct sockaddr
*)&ssr
, &ssz
)) < 0) {
811 if (errno
!= EAGAIN
&& errno
== EWOULDBLOCK
) {
812 logmsg(0, LOG_ERR
, "failed to accept incoming %s connection: %s",
813 l
->ao
->name
, strerror(errno
));
817 if (fix_up_socket(sk
, "incoming client")) { close(sk
); return; }
819 /* Build a client block and fill it in. */
820 c
= xmalloc(sizeof(*c
));
824 /* Collect the local and remote addresses. */
825 l
->ao
->sockaddr_to_addr(&ssr
, &c
->q
.s
[R
].addr
);
827 if (getsockname(sk
, (struct sockaddr
*)&ssl
, &ssz
)) {
829 "failed to read local address for incoming %s connection: %s",
830 l
->ao
->name
, strerror(errno
));
835 l
->ao
->sockaddr_to_addr(&ssl
, &c
->q
.s
[L
].addr
);
836 c
->q
.s
[L
].port
= c
->q
.s
[R
].port
= 0;
838 /* Set stuff up for reading the query and sending responses. */
839 selbuf_init(&c
->b
, &sel
, sk
, client_line
, c
);
840 selbuf_setsize(&c
->b
, 1024);
841 reset_client_timer(c
, 0);
844 init_writebuf(&c
->wb
, sk
, done_client_write
, c
);
847 /*----- Main code ---------------------------------------------------------*/
849 /* Set up a listening socket for the address family described by AO,
852 static int make_listening_socket(const struct addrops
*ao
, int port
)
857 struct sockaddr_storage ss
;
861 /* Make the socket. */
862 if ((fd
= socket(ao
->af
, SOCK_STREAM
, 0)) < 0) {
863 if (errno
== EAFNOSUPPORT
) return (-1);
864 die(1, "failed to create %s listening socket: %s",
865 ao
->name
, strerror(errno
));
868 /* Build the appropriate local address. */
871 ao
->socket_to_sockaddr(&s
, &ss
, &ssz
);
873 /* Perform any initialization specific to the address type. */
874 if (ao
->init_listen_socket(fd
)) {
875 die(1, "failed to initialize %s listening socket: %s",
876 ao
->name
, strerror(errno
));
879 /* Bind to the address. */
880 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(yes
));
881 if (bind(fd
, (struct sockaddr
*)&ss
, ssz
)) {
882 die(1, "failed to bind %s listening socket: %s",
883 ao
->name
, strerror(errno
));
886 /* Avoid unpleasant race conditions. */
887 if (fdflags(fd
, O_NONBLOCK
, O_NONBLOCK
, 0, 0)) {
888 die(1, "failed to set %s listening socket nonblocking: %s",
889 ao
->name
, strerror(errno
));
892 /* Prepare to listen. */
894 die(1, "failed to listen for %s: %s", ao
->name
, strerror(errno
));
896 /* Make a record of all of this. */
897 l
= xmalloc(sizeof(*l
));
899 sel_initfile(&sel
, &l
->f
, fd
, SEL_READ
, accept_client
, l
);
906 /* Quit because of a fatal signal. */
907 static void quit(int sig
, void *p
)
909 const char *signame
= p
;
911 logmsg(0, LOG_NOTICE
, "shutting down on %s", signame
);
912 if (pidfile
) unlink(pidfile
);
916 /* Answer whether the string pointed to by P consists entirely of digits. */
917 static int numericp(const char *p
)
920 if (!isdigit((unsigned char)*p
++)) return (0);
924 static void usage(FILE *fp
)
926 pquis(fp
, "Usage: $ [-Dl] [-G GROUP] [-U USER] [-P FILE] "
927 "[-c FILE] [-p PORT]\n");
930 static void version(FILE *fp
)
931 { pquis(fp
, "$, version " VERSION
"\n"); }
933 static void help(FILE *fp
)
935 version(fp
); fputc('\n', fp
);
938 Yet Another Ident Daemon. Really, the world doesn't need such a thing.\n\
939 It's just a shame none of the others do the right things.\n\
943 -h, --help Show this help message.\n\
944 -v, --version Show the version number.\n\
945 -u, --usage Show a very short usage summary.\n\
947 -D, --daemon Become a daemon, running in the background.\n\
948 -G, --group=GROUP Set group after initialization.\n\
949 -P, --pidfile=FILE Write process id to FILE.\n\
950 -U, --user=USER Set user after initialization.\n\
951 -c, --config=FILE Read global policy from FILE.\n\
952 -l, --syslog Write log messages using syslog(3).\n\
953 -p, --port=PORT Listen for connections on this port.\n",
957 int main(int argc
, char *argv
[])
962 struct passwd
*pw
= 0;
971 const struct addrops
*ao
;
976 /* Parse command-line options. */
978 const struct option opts
[] = {
979 { "help", 0, 0, 'h' },
980 { "version", 0, 0, 'v' },
981 { "usage", 0, 0, 'u' },
982 { "daemon", 0, 0, 'D' },
983 { "group", OPTF_ARGREQ
, 0, 'G' },
984 { "pidfile", OPTF_ARGREQ
, 0, 'P' },
985 { "user", OPTF_ARGREQ
, 0, 'U' },
986 { "config", OPTF_ARGREQ
, 0, 'c' },
987 { "syslog", 0, 0, 'l' },
988 { "port", OPTF_ARGREQ
, 0, 'p' },
992 if ((i
= mdwopt(argc
, argv
, "hvuDG:P:U:c:lp:", opts
, 0, 0, 0)) < 0)
995 case 'h': help(stdout
); exit(0);
996 case 'v': version(stdout
); exit(0);
997 case 'u': usage(stdout
); exit(0);
998 case 'D': f
|= f_daemon
; break;
999 case 'P': pidfile
= optarg
; break;
1000 case 'c': policyfile
= optarg
; break;
1001 case 'l': flags
|= F_SYSLOG
; break;
1003 if (numericp(optarg
))
1005 else if ((gr
= getgrnam(optarg
)) == 0)
1006 die(1, "unknown group `%s'", optarg
);
1011 if (numericp(optarg
))
1013 else if ((pw
= getpwnam(optarg
)) == 0)
1014 die(1, "unknown user `%s'", optarg
);
1019 if (numericp(optarg
))
1020 port
= atoi(optarg
);
1021 else if ((s
= getservbyname(optarg
, "tcp")) == 0)
1022 die(1, "unknown service name `%s'", optarg
);
1024 port
= ntohs(s
->s_port
);
1026 default: f
|= f_bogus
; break;
1029 if (optind
< argc
) f
|= f_bogus
;
1030 if (f
& f_bogus
) { usage(stderr
); exit(1); }
1032 /* If a user has been requested, but no group, then find the user's primary
1033 * group. If the user was given by name, then we already have a password
1034 * entry and should use that, in case two differently-named users have the
1035 * same uid but distinct gids.
1037 if (u
!= -1 && g
== -1) {
1038 if (!pw
&& (pw
= getpwuid(u
)) == 0) {
1039 die(1, "failed to find password entry for user %d: "
1040 "request group explicitly", u
);
1045 /* Initialize system-specific machinery. */
1048 /* Load the global policy rules. */
1049 fwatch_init(&polfw
, policyfile
);
1050 if (load_policy_file(policyfile
, &policy
))
1053 /* Open the random data source. */
1054 if ((randfd
= open("/dev/urandom", O_RDONLY
)) < 0) {
1055 die(1, "failed to open `/dev/urandom' for reading: %s",
1059 /* Set up the I/O event system. */
1062 /* Watch for some interesting signals. */
1064 sig_add(&sigint
, SIGINT
, quit
, "SIGINT");
1065 sig_add(&sigterm
, SIGTERM
, quit
, "SIGTERM");
1067 /* Listen for incoming connections. */
1068 for (ao
= addroptab
; ao
->name
; ao
++)
1069 if (!make_listening_socket(ao
, port
)) any
= 1;
1070 if (!any
) die(1, "no IP protocols supported");
1072 /* Open the pidfile now, in case it's somewhere we can't write. */
1073 if (pidfile
&& (fp
= fopen(pidfile
, "w")) == 0) {
1074 die(1, "failed to open pidfile `%s' for writing: %s",
1075 pidfile
, strerror(errno
));
1078 /* If we're meant to use syslog, then open the log. */
1079 if (flags
& F_SYSLOG
)
1080 openlog(QUIS
, 0, LOG_DAEMON
);
1082 /* Drop privileges. */
1083 if ((g
!= -1 && (setegid(g
) || setgid(g
) ||
1084 (getuid() == 0 && setgroups(1, &g
)))) ||
1085 (u
!= -1 && setuid(u
)))
1086 die(1, "failed to drop privileges: %s", strerror(errno
));
1088 /* Become a background process, if requested. */
1089 if ((f
& f_daemon
) && daemonize())
1090 die(1, "failed to become daemon: %s", strerror(errno
));
1092 /* Write the process id to the pidfile. */
1094 fprintf(fp
, "%d\n", getpid());
1098 /* And now we're going. */
1101 /* Read events and process them. */
1103 if (sel_select(&sel
) && errno
!= EINTR
)
1104 die(1, "select failed: %s", strerror(errno
));
1107 /* This just keeps the compiler happy. */
1111 /*----- That's all, folks -------------------------------------------------*/