1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20#include "libbb.h"
21#include <syslog.h>
22#include "isrv.h"
23
24enum { TIMEOUT = 20 };
25
26typedef struct identd_buf_t {
27 int pos;
28 int fd_flag;
29 char buf[64 - 2*sizeof(int)];
30} identd_buf_t;
31
32#define bogouser bb_common_bufsiz1
33
34static int new_peer(isrv_state_t *state, int fd)
35{
36 int peer;
37 identd_buf_t *buf = xzalloc(sizeof(*buf));
38
39 peer = isrv_register_peer(state, buf);
40 if (peer < 0)
41 return 0;
42 if (isrv_register_fd(state, peer, fd) < 0)
43 return peer;
44
45 buf->fd_flag = fcntl(fd, F_GETFL) | O_NONBLOCK;
46 isrv_want_rd(state, fd);
47 return 0;
48}
49
50static int do_rd(int fd, void **paramp)
51{
52 identd_buf_t *buf = *paramp;
53 char *cur, *p;
54 int retval = 0;
55 int sz;
56
57 cur = buf->buf + buf->pos;
58
59 if (buf->fd_flag & O_NONBLOCK)
60 fcntl(fd, F_SETFL, buf->fd_flag);
61 sz = safe_read(fd, cur, sizeof(buf->buf) - buf->pos);
62
63 if (sz < 0) {
64 if (errno != EAGAIN)
65 goto term;
66 goto ok;
67 }
68
69 buf->pos += sz;
70 buf->buf[buf->pos] = '\0';
71 p = strpbrk(cur, "\r\n");
72 if (p)
73 *p = '\0';
74 if (!p && sz && buf->pos <= (int)sizeof(buf->buf))
75 goto ok;
76
77
78 if (fd == 0) fd++;
79 fdprintf(fd, "%s : USERID : UNIX : %s\r\n", buf->buf, bogouser);
80 term:
81 free(buf);
82 retval = 1;
83 ok:
84 if (buf->fd_flag & O_NONBLOCK)
85 fcntl(fd, F_SETFL, buf->fd_flag & ~O_NONBLOCK);
86 return retval;
87}
88
89static int do_timeout(void **paramp UNUSED_PARAM)
90{
91 return 1;
92}
93
94static void inetd_mode(void)
95{
96 identd_buf_t *buf = xzalloc(sizeof(*buf));
97
98
99
100 do
101 alarm(TIMEOUT);
102 while (do_rd(0, (void*)&buf) == 0);
103}
104
105int fakeidentd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
106int fakeidentd_main(int argc UNUSED_PARAM, char **argv)
107{
108 enum {
109 OPT_foreground = 0x1,
110 OPT_inetd = 0x2,
111 OPT_inetdwait = 0x4,
112 OPT_fiw = 0x7,
113 OPT_bindaddr = 0x8,
114 };
115
116 const char *bind_address = NULL;
117 unsigned opt;
118 int fd;
119
120 opt = getopt32(argv, "fiwb:", &bind_address);
121 strcpy(bogouser, "nobody");
122 if (argv[optind])
123 strncpy(bogouser, argv[optind], sizeof(bogouser));
124
125
126 if (!(opt & OPT_fiw))
127 bb_daemonize_or_rexec(0, argv);
128
129
130
131
132
133
134 if (!(opt & OPT_fiw) ) {
135 openlog(applet_name, LOG_PID, LOG_DAEMON);
136 logmode = LOGMODE_SYSLOG;
137 }
138
139 if (opt & OPT_inetd) {
140 inetd_mode();
141 return 0;
142 }
143
144
145 signal(SIGPIPE, SIG_IGN);
146
147 fd = 0;
148 if (!(opt & OPT_inetdwait)) {
149 fd = create_and_bind_stream_or_die(bind_address,
150 bb_lookup_port("identd", "tcp", 113));
151 xlisten(fd, 5);
152 }
153
154 isrv_run(fd, new_peer, do_rd, NULL, do_timeout,
155 TIMEOUT, (opt & OPT_inetdwait) ? TIMEOUT : 0);
156 return 0;
157}
158