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