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