1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 2007 Denys Vlasenko
7 * Licensed under GPL version 2, see file LICENSE in this tarball for details.
14 enum { TIMEOUT = 20 };
16 typedef struct identd_buf_t {
19 char buf[64 - 2*sizeof(int)];
22 #define bogouser bb_common_bufsiz1
24 static int new_peer(isrv_state_t *state, int fd)
27 identd_buf_t *buf = xzalloc(sizeof(*buf));
29 peer = isrv_register_peer(state, buf);
31 return 0; /* failure */
32 if (isrv_register_fd(state, peer, fd) < 0)
33 return peer; /* failure, unregister peer */
35 buf->fd_flag = fcntl(fd, F_GETFL) | O_NONBLOCK;
36 isrv_want_rd(state, fd);
40 static int do_rd(int fd, void **paramp)
42 identd_buf_t *buf = *paramp;
44 int retval = 0; /* session is ok (so far) */
47 cur = buf->buf + buf->pos;
49 if (buf->fd_flag & O_NONBLOCK)
50 fcntl(fd, F_SETFL, buf->fd_flag);
51 sz = safe_read(fd, cur, sizeof(buf->buf) - buf->pos);
55 goto term; /* terminate this session if !EAGAIN */
60 buf->buf[buf->pos] = '\0';
61 p = strpbrk(cur, "\r\n");
64 if (!p && sz && buf->pos <= (int)sizeof(buf->buf))
66 /* Terminate session. If we are in server mode, then
67 * fd is still in nonblocking mode - we never block here */
68 if (fd == 0) fd++; /* inetd mode? then write to fd 1 */
69 fdprintf(fd, "%s : USERID : UNIX : %s\r\n", buf->buf, bogouser);
72 retval = 1; /* terminate */
74 if (buf->fd_flag & O_NONBLOCK)
75 fcntl(fd, F_SETFL, buf->fd_flag & ~O_NONBLOCK);
79 static int do_timeout(void **paramp UNUSED_PARAM)
81 return 1; /* terminate session */
84 static void inetd_mode(void)
86 identd_buf_t *buf = xzalloc(sizeof(*buf));
87 /* buf->pos = 0; - xzalloc did it */
88 /* We do NOT want nonblocking I/O here! */
89 /* buf->fd_flag = 0; - xzalloc did it */
92 while (do_rd(0, (void*)&buf) == 0);
95 int fakeidentd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
96 int fakeidentd_main(int argc UNUSED_PARAM, char **argv)
106 const char *bind_address = NULL;
110 opt = getopt32(argv, "fiwb:", &bind_address);
111 strcpy(bogouser, "nobody");
113 strncpy(bogouser, argv[optind], sizeof(bogouser));
115 /* Daemonize if no -f and no -i and no -w */
116 if (!(opt & OPT_fiw))
117 bb_daemonize_or_rexec(0, argv);
119 /* Where to log in inetd modes? "Classic" inetd
120 * probably has its stderr /dev/null'ed (we need log to syslog?),
121 * but daemontools-like utilities usually expect that children
122 * log to stderr. I like daemontools more. Go their way.
123 * (Or maybe we need yet another option "log to syslog") */
124 if (!(opt & OPT_fiw) /* || (opt & OPT_syslog) */) {
125 openlog(applet_name, 0, LOG_DAEMON);
126 logmode = LOGMODE_SYSLOG;
129 if (opt & OPT_inetd) {
134 /* Ignore closed connections when writing */
135 signal(SIGPIPE, SIG_IGN);
138 if (!(opt & OPT_inetdwait)) {
139 fd = create_and_bind_stream_or_die(bind_address,
140 bb_lookup_port("identd", "tcp", 113));
144 isrv_run(fd, new_peer, do_rd, /*do_wr:*/ NULL, do_timeout,
145 TIMEOUT, (opt & OPT_inetdwait) ? TIMEOUT : 0);