Remove code for protocols we don't properly support. (Most of this could
[oweals/busybox.git] / networking / fakeidentd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * A fake identd server
4  *
5  * Adapted to busybox by Thomas Lundquist <thomasez@zelow.no>
6  * Original Author: Tomi Ollila <too@iki.fi>
7  *                  http://www.guru-group.fi/~too/sw/
8  *
9  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10  */
11
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <stdarg.h>
16 #include <string.h>
17 #include <fcntl.h>
18 #include <signal.h>
19 #include <sys/syslog.h>
20
21 #include <pwd.h>
22 #include <netdb.h>
23
24 #include <sys/syslog.h>
25 #include <sys/types.h>
26 #include <sys/time.h>
27 #include <time.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <errno.h>
31 #include <arpa/inet.h>
32 #include <sys/uio.h>
33
34 #include "busybox.h"
35
36 #define IDENT_PORT  113
37 #define MAXCONNS    20
38 #define MAXIDLETIME 45
39
40 static const char ident_substr[] = " : USERID : UNIX : ";
41 enum { ident_substr_len = sizeof(ident_substr) - 1 };
42 #define PIDFILE "/var/run/identd.pid"
43
44 /*
45  * We have to track the 'first connection socket' so that we
46  * don't go around closing file descriptors for non-clients.
47  *
48  * descriptor setup normally
49  *  0 = server socket
50  *  1 = syslog fd (hopefully -- otherwise this won't work)
51  *  2 = connection socket after detached from tty. standard error before that
52  *  3 - 2 + MAXCONNS = rest connection sockets
53  *
54  * To try to make sure that syslog fd is what is "requested", the that fd
55  * is closed before openlog() call.  It can only severely fail if fd 0
56  * is initially closed.
57  */
58 #define FCS 2
59
60 /*
61  * FD of the connection is always the index of the connection structure
62  * in `conns' array + FCS
63  */
64 static struct {
65         char buf[20];
66         int len;
67         time_t lasttime;
68 } conns[MAXCONNS];
69
70 /* When using global variables, bind those at least to a structure. */
71 static struct {
72         const char *identuser;
73         fd_set readfds;
74         int conncnt;
75 } G;
76
77 /*
78  * Prototypes
79  */
80 static void reply(int s, char *buf);
81 static void replyError(int s, char *buf);
82
83 static const char *nobodystr = "nobody"; /* this needs to be declared like this */
84 static char *bind_ip_address = "0.0.0.0";
85
86 static inline void movefd(int from, int to)
87 {
88         if (from != to) {
89                 dup2(from, to);
90                 close(from);
91         }
92 }
93
94 static void inetbind(void)
95 {
96         int s, port;
97         struct sockaddr_in addr;
98         int len = sizeof(addr);
99         int one = 1;
100         struct servent *se;
101
102         if ((se = getservbyname("identd", "tcp")) == NULL)
103                 port = IDENT_PORT;
104         else
105                 port = se->s_port;
106
107         s = bb_xsocket(AF_INET, SOCK_STREAM, 0);
108
109         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
110
111         memset(&addr, 0, sizeof(addr));
112         addr.sin_addr.s_addr = inet_addr(bind_ip_address);
113         addr.sin_family = AF_INET;
114         addr.sin_port = htons(port);
115
116         if (bind(s, (struct sockaddr *)&addr, len) < 0) /* bb_xbind? */
117                 bb_perror_msg_and_die("Cannot bind() port %i", IDENT_PORT);
118
119         if (listen(s, 5) < 0) /* bb_xlisten? */
120                 bb_perror_msg_and_die("Cannot listen() on port %i", IDENT_PORT);
121
122         movefd(s, 0);
123 }
124
125 static void handlexitsigs(int signum)
126 {
127         if (unlink(PIDFILE) < 0)
128                 close(open(PIDFILE, O_WRONLY|O_CREAT|O_TRUNC, 0644));
129         exit(0);
130 }
131
132 /* May succeed. If not, won't care. */
133 static inline void writepid(uid_t nobody, uid_t nogrp)
134 {
135         char buf[24];
136         int fd = open(PIDFILE, O_WRONLY|O_CREAT|O_TRUNC, 0664);
137
138         if (fd < 0)
139                 return;
140
141         snprintf(buf, 23, "%d\n", getpid());
142         write(fd, buf, strlen(buf));
143         fchown(fd, nobody, nogrp);
144         close(fd);
145
146         /* should this handle ILL, ... (see signal(7)) */
147         signal(SIGTERM, handlexitsigs);
148         signal(SIGINT,  handlexitsigs);
149         signal(SIGQUIT, handlexitsigs);
150 }
151
152 /* return 0 as parent, 1 as child */
153 static int godaemon(void)
154 {
155         uid_t nobody, nogrp;
156         struct passwd *pw;
157
158         switch (fork()) {
159         case -1:
160                 bb_perror_msg_and_die("Could not fork");
161
162         case 0:
163                 pw = getpwnam(nobodystr);
164                 if (pw == NULL)
165                         bb_error_msg_and_die("Cannot find uid/gid of user '%s'", nobodystr);
166                 nobody = pw->pw_uid;
167                 nogrp = pw->pw_gid;
168                 writepid(nobody, nogrp);
169
170                 close(0);
171                 inetbind();
172                 if (setgid(nogrp))   bb_error_msg_and_die("Could not setgid()");
173                 if (setuid(nobody))  bb_error_msg_and_die("Could not setuid()");
174                 close(1);
175                 close(2);
176
177                 signal(SIGHUP, SIG_IGN);
178                 signal(SIGPIPE, SIG_IGN); /* connection closed when writing (raises ???) */
179
180                 setsid();
181
182                 openlog(bb_applet_name, 0, LOG_DAEMON);
183                 return 1;
184         }
185
186         return 0;
187 }
188
189 static void deleteConn(int s)
190 {
191         int i = s - FCS;
192
193         close(s);
194
195         G.conncnt--;
196
197         /*
198          * Most of the time there is 0 connections. Most often that there
199          * is connections, there is just one connection. When this one connection
200          * closes, i == G.conncnt = 0 -> no copying.
201          * When there is more than one connection, the oldest connections closes
202          * earlier on average. When this happens, the code below starts copying
203          * the connection structure w/ highest index to the place which which is
204          * just deleted. This means that the connection structures are no longer
205          * in chronological order. I'd quess this means that when there is more
206          * than 1 connection, on average every other connection structure needs
207          * to be copied over the time all these connections are deleted.
208          */
209         if (i != G.conncnt) {
210                 memcpy(&conns[i], &conns[G.conncnt], sizeof(conns[0]));
211                 movefd(G.conncnt + FCS, s);
212         }
213
214         FD_CLR(G.conncnt + FCS, &G.readfds);
215 }
216
217 static int closeOldest(void)
218 {
219         time_t min = conns[0].lasttime;
220         int idx = 0;
221         int i;
222
223         for (i = 1; i < MAXCONNS; i++)
224                 if (conns[i].lasttime < min)
225                         idx = i;
226
227         replyError(idx + FCS, "X-SERVER-TOO-BUSY");
228         close(idx + FCS);
229
230         return idx;
231 }
232
233 static int checkInput(char *buf, int len, int l)
234 {
235         int i;
236         for (i = len; i < len + l; ++i)
237                 if (buf[i] == '\n')
238                         return 1;
239         return 0;
240 }
241
242 int fakeidentd_main(int argc, char **argv)
243 {
244         memset(conns, 0, sizeof(conns));
245         memset(&G, 0, sizeof(G));
246         FD_ZERO(&G.readfds);
247         FD_SET(0, &G.readfds);
248
249         /* handle -b <ip> parameter */
250         bb_getopt_ulflags(argc, argv, "b:", &bind_ip_address);
251         /* handle optional REPLY STRING */
252         if (optind < argc)
253                 G.identuser = argv[optind];
254         else
255                 G.identuser = nobodystr;
256
257         /* daemonize and have the parent return */
258         if (godaemon() == 0)
259                 return 0;
260
261         /* main loop where we process all events and never exit */
262         while (1) {
263         fd_set rfds = G.readfds;
264         struct timeval tv = { 15, 0 };
265         int i;
266         int tim = time(NULL);
267
268         select(G.conncnt + FCS, &rfds, NULL, NULL, G.conncnt? &tv: NULL);
269
270         for (i = G.conncnt - 1; i >= 0; i--) {
271                 int s = i + FCS;
272
273                 if (FD_ISSET(s, &rfds)) {
274                         char *buf = conns[i].buf;
275                         unsigned int len = conns[i].len;
276                         unsigned int l;
277
278                         if ((l = read(s, buf + len, sizeof(conns[0].buf) - len)) > 0) {
279                                 if (checkInput(buf, len, l)) {
280                                         reply(s, buf);
281                                         goto deleteconn;
282                                 } else if (len + l >= sizeof(conns[0].buf)) {
283                                         replyError(s, "X-INVALID-REQUEST");
284                                         goto deleteconn;
285                                 } else {
286                                         conns[i].len += l;
287                                 }
288                         } else {
289                                 goto deleteconn;
290                         }
291
292                         conns[i].lasttime = tim;
293                         continue;
294
295 deleteconn:
296                         deleteConn(s);
297                 } else {
298                         /* implement as time_after() in linux kernel sources ... */
299                         if (conns[i].lasttime + MAXIDLETIME <= tim) {
300                                 replyError(s, "X-TIMEOUT");
301                                 deleteConn(s);
302                         }
303                 }
304         }
305
306         if (FD_ISSET(0, &rfds)) {
307                 int s = accept(0, NULL, 0);
308
309                 if (s < 0) {
310                         if (errno != EINTR) /* EINTR */
311                                 syslog(LOG_ERR, "accept: %s", strerror(errno));
312                 } else {
313                         if (G.conncnt == MAXCONNS)
314                                 i = closeOldest();
315                         else
316                                 i = G.conncnt++;
317
318                         movefd(s, i + FCS); /* move if not already there */
319                         FD_SET(i + FCS, &G.readfds);
320
321                         conns[i].len = 0;
322                         conns[i].lasttime = time(NULL);
323                 }
324         }
325         } /* end of while(1) */
326
327         return 0;
328 }
329
330 static int parseAddrs(char *ptr, char **myaddr, char **heraddr);
331 static void reply(int s, char *buf)
332 {
333         char *myaddr, *heraddr;
334
335         myaddr = heraddr = NULL;
336
337         if (parseAddrs(buf, &myaddr, &heraddr))
338                 replyError(s, "X-INVALID-REQUEST");
339         else {
340                 struct iovec iv[6];
341                 iv[0].iov_base = myaddr;               iv[0].iov_len = strlen(myaddr);
342                 iv[1].iov_base = ", ";                 iv[1].iov_len = 2;
343                 iv[2].iov_base = heraddr;              iv[2].iov_len = strlen(heraddr);
344                 iv[3].iov_base = (void *)ident_substr; iv[3].iov_len = ident_substr_len;
345                 iv[4].iov_base = (void *)G.identuser;  iv[4].iov_len = strlen(G.identuser);
346                 iv[5].iov_base = "\r\n";               iv[5].iov_len = 2;
347                 writev(s, iv, 6);
348         }
349 }
350
351 static void replyError(int s, char *buf)
352 {
353         struct iovec iv[3];
354         iv[0].iov_base = "0, 0 : ERROR : ";   iv[0].iov_len = 15;
355         iv[1].iov_base = buf;                 iv[1].iov_len = strlen(buf);
356         iv[2].iov_base = "\r\n";              iv[2].iov_len = 2;
357         writev(s, iv, 3);
358 }
359
360 static int chmatch(char c, char *chars)
361 {
362         for (; *chars; chars++)
363                 if (c == *chars)
364                         return 1;
365         return 0;
366 }
367
368 static int skipchars(char **p, char *chars)
369 {
370         while (chmatch(**p, chars))
371                 (*p)++;
372         if (**p == '\r' || **p == '\n')
373                 return 0;
374         return 1;
375 }
376
377 static int parseAddrs(char *ptr, char **myaddr, char **heraddr)
378 {
379         /* parse <port-on-server> , <port-on-client> */
380
381         if (!skipchars(&ptr, " \t"))
382                 return -1;
383
384         *myaddr = ptr;
385
386         if (!skipchars(&ptr, "1234567890"))
387                 return -1;
388
389         if (!chmatch(*ptr, " \t,"))
390                 return -1;
391
392         *ptr++ = '\0';
393
394         if (!skipchars(&ptr, " \t,") )
395                 return -1;
396
397         *heraddr = ptr;
398
399         skipchars(&ptr, "1234567890");
400
401         if (!chmatch(*ptr, " \n\r"))
402                 return -1;
403
404         *ptr = '\0';
405
406         return 0;
407 }