source: code/icbd.c@ 6e89d69

Last change on this file since 6e89d69 was 6e89d69, checked in by Florian Obser <florian@…>, 11 years ago

accept throttling on EM/ENFILE, add checks for other errnos

  • Property mode set to 100644
File size: 12.8 KB
Line 
1/*
2 * Copyright (c) 2009 Mike Belopuhov
3 * Copyright (c) 2007 Oleg Safiullin
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18#include <sys/types.h>
19#include <sys/queue.h>
20#include <sys/socket.h>
21#include <sys/stat.h>
22#include <sys/tree.h>
23#include <netinet/in_systm.h>
24#include <netinet/in.h>
25#include <netinet/ip.h>
26#include <arpa/inet.h>
27#include <fcntl.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <unistd.h>
31#include <string.h>
32#include <sysexits.h>
33#include <syslog.h>
34#include <pwd.h>
35#include <login_cap.h>
36#include <locale.h>
37#include <netdb.h>
38#include <event.h>
39#include <errno.h>
40#include <err.h>
41
42#include "icb.h"
43#include "icbd.h"
44
45uint64_t sessionid;
46char modtab[ICB_MTABLEN][ICB_MAXNICKLEN];
47int modtabcnt;
48char srvname[MAXHOSTNAMELEN];
49int creategroups;
50int foreground;
51char logprefix[MAXPATHLEN/2];
52int dologging;
53int verbose;
54
55void usage(void);
56void getpeerinfo(struct icb_session *);
57void icbd_accept(int, short, void *);
58void icbd_paused(int, short, void *);
59void icbd_drop(struct icb_session *, char *);
60void icbd_ioerr(struct bufferevent *, short, void *);
61void icbd_dispatch(struct bufferevent *, void *);
62void icbd_log(struct icb_session *, int, const char *, ...);
63void icbd_grplist(char *);
64void icbd_modtab(char *);
65void icbd_restrict(void);
66void icbd_write(struct icb_session *, char *, ssize_t);
67
68static inline int icbd_session_cmp(struct icb_session *, struct icb_session *);
69
70RB_HEAD(icbd_sessions, icb_session) icbd_sessions;
71RB_PROTOTYPE(icbd_sessions, icb_session, node, icbd_session_cmp);
72RB_GENERATE(icbd_sessions, icb_session, node, icbd_session_cmp);
73
74struct icbd_listener {
75 struct event ev, pause;
76};
77
78int
79main(int argc, char *argv[])
80{
81 struct icbd_callbacks ic = { icbd_drop, icbd_log, icbd_write };
82 const char *cause = NULL;
83 int ch, nsocks = 0, save_errno = 0;
84 int inet4 = 0, inet6 = 0;
85
86 RB_INIT(&icbd_sessions);
87
88 /* init group lists before calling icb_addgroup */
89 icb_init(&ic);
90
91 while ((ch = getopt(argc, argv, "46CdG:M:L:S:v")) != -1)
92 switch (ch) {
93 case '4':
94 inet4++;
95 break;
96 case '6':
97 inet6++;
98 break;
99 case 'C':
100 creategroups++;
101 break;
102 case 'd':
103 foreground++;
104 break;
105 case 'G':
106 icbd_grplist(optarg);
107 break;
108 case 'L':
109 strlcpy(logprefix, optarg, sizeof logprefix);
110 dologging++;
111 break;
112 case 'M':
113 icbd_modtab(optarg);
114 break;
115 case 'S':
116 strlcpy(srvname, optarg, sizeof srvname);
117 break;
118 case 'v':
119 verbose++;
120 break;
121 default:
122 usage();
123 /* NOTREACHED */
124 }
125 argc -= optind;
126 argv += optind;
127
128 /* add group "1" as it's a login group for most of the clients */
129 if (icb_addgroup(NULL, "1", NULL) == NULL)
130 err(EX_UNAVAILABLE, NULL);
131
132 if (argc == 0)
133 argc++;
134
135 if (inet4 && inet6)
136 errx(EX_USAGE, "Can't specify both -4 and -6");
137
138 tzset();
139 (void)setlocale(LC_ALL, "C");
140
141 if (foreground)
142 openlog("icbd", LOG_PID | LOG_PERROR, LOG_DAEMON);
143 else
144 openlog("icbd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
145
146 if (!foreground && daemon(0, 0) < 0)
147 err(EX_OSERR, NULL);
148
149 (void)event_init();
150
151 for (ch = 0; ch < argc; ch++) {
152 struct addrinfo hints, *res, *res0;
153 struct icbd_listener *l;
154 char *addr, *port;
155 int error, s, on = 1;
156
157 addr = port = NULL;
158 if (argv[ch] != NULL) {
159 if (argv[ch][0] != ':')
160 addr = argv[ch];
161 if ((port = strrchr(argv[ch], ':')) != NULL)
162 *port++ = '\0';
163 }
164
165 bzero(&hints, sizeof hints);
166 if (inet4 || inet6)
167 hints.ai_family = inet4 ? PF_INET : PF_INET6;
168 else
169 hints.ai_family = PF_UNSPEC;
170 hints.ai_socktype = SOCK_STREAM;
171 hints.ai_flags = AI_PASSIVE;
172 if ((error = getaddrinfo(addr, port ? port : "icb", &hints,
173 &res0)) != 0) {
174 syslog(LOG_ERR, "%s", gai_strerror(error));
175 return (EX_UNAVAILABLE);
176 }
177
178 for (res = res0; res != NULL; res = res->ai_next) {
179 if ((s = socket(res->ai_family, res->ai_socktype,
180 res->ai_protocol)) < 0) {
181 cause = "socket";
182 save_errno = errno;
183 continue;
184 }
185
186 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on,
187 sizeof on) < 0) {
188 cause = "SO_REUSEADDR";
189 save_errno = errno;
190 (void)close(s);
191 continue;
192 }
193
194 if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
195 cause = "bind";
196 save_errno = errno;
197 (void)close(s);
198 continue;
199 }
200
201 (void)listen(s, TCP_BACKLOG);
202
203 if ((l = calloc(1, sizeof *l)) == NULL)
204 err(EX_UNAVAILABLE, NULL);
205 event_set(&l->ev, s, EV_READ | EV_PERSIST, icbd_accept, l);
206 if (event_add(&l->ev, NULL) < 0) {
207 syslog(LOG_ERR, "event_add: %m");
208 return (EX_UNAVAILABLE);
209 }
210 evtimer_set(&l->pause, icbd_paused, l);
211
212 nsocks++;
213 }
214
215 freeaddrinfo(res0);
216 }
217
218 if (nsocks == 0) {
219 errno = save_errno;
220 syslog(LOG_ERR, "%s: %m", cause);
221 return (EX_UNAVAILABLE);
222 }
223
224 /* start the logger service */
225 logger_init();
226
227 /* start a dns resolver thread */
228 dns_init();
229
230 if (!foreground)
231 icbd_restrict();
232
233 (void)signal(SIGPIPE, SIG_IGN);
234
235 (void)event_dispatch();
236
237 syslog(LOG_ERR, "event_dispatch: %m");
238
239 return (EX_UNAVAILABLE);
240}
241
242static inline int
243icbd_session_cmp(struct icb_session *a, struct icb_session *b)
244{
245 if (a->id > b->id)
246 return (1);
247 if (a->id < b->id)
248 return (-1);
249 return (0);
250}
251
252inline struct icb_session *
253icbd_session_lookup(uint64_t sid)
254{
255 struct icb_session key;
256
257 key.id = sid;
258 return (RB_FIND(icbd_sessions, &icbd_sessions, &key));
259}
260
261void
262icbd_accept(int fd, short event __attribute__((__unused__)),
263 void *arg)
264{
265 struct icbd_listener *l = arg;
266 struct sockaddr_storage ss;
267 struct timeval p = { 1, 0 };
268 struct icb_session *is;
269 socklen_t ss_len = sizeof ss;
270 int s, on = 1, tos = IPTOS_LOWDELAY;
271
272 ss.ss_len = ss_len;
273 s = accept(fd, (struct sockaddr *)&ss, &ss_len);
274 if (s == -1) {
275 switch (errno) {
276 case EINTR:
277 case EWOULDBLOCK:
278 case ECONNABORTED:
279 return;
280 case EMFILE:
281 case ENFILE:
282 event_del(&l->ev);
283 evtimer_add(&l->pause, &p);
284 return;
285 default:
286 syslog(LOG_ERR, "accept: %m");
287 return;
288 }
289 }
290
291 if (ss.ss_family == AF_INET)
292 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof tos) < 0)
293 syslog(LOG_WARNING, "IP_TOS: %m");
294 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof on) < 0)
295 syslog(LOG_WARNING, "SO_KEEPALIVE: %m");
296 if ((is = calloc(1, sizeof *is)) == NULL) {
297 syslog(LOG_ERR, "calloc: %m");
298 (void)close(s);
299 return;
300 }
301 if ((is->bev = bufferevent_new(s, icbd_dispatch, NULL, icbd_ioerr,
302 is)) == NULL) {
303 syslog(LOG_ERR, "bufferevent_new: %m");
304 (void)close(s);
305 free(is);
306 return;
307 }
308 if (bufferevent_enable(is->bev, EV_READ)) {
309 syslog(LOG_ERR, "bufferevent_enable: %m");
310 (void)close(s);
311 bufferevent_free(is->bev);
312 free(is);
313 return;
314 }
315
316 is->id = sessionid++;
317 RB_INSERT(icbd_sessions, &icbd_sessions, is);
318
319 /* save host information */
320 getpeerinfo(is);
321
322 /* start icb conversation */
323 icb_start(is);
324}
325
326void
327icbd_paused(int fd __attribute__((__unused__)),
328 short events __attribute__((__unused__)), void *arg)
329{
330 struct icbd_listener *l = arg;
331 event_add(&l->ev, NULL);
332}
333
334__dead void
335usage(void)
336{
337 extern char *__progname;
338
339 (void)fprintf(stderr, "usage: %s [-46Cdv] [-G group1[,group2,...]] "
340 "[-L prefix] [-M modtab]\n\t[-S name] [[addr][:port] ...]\n",
341 __progname);
342 exit(EX_USAGE);
343}
344
345/*
346 * bufferevent functions
347 */
348
349void
350icbd_dispatch(struct bufferevent *bev, void *arg)
351{
352 struct icb_session *is = (struct icb_session *)arg;
353
354 while (EVBUFFER_LENGTH(EVBUFFER_INPUT(bev)) > 0) {
355 if (is->length == 0) {
356 /* read length */
357 is->rlen = bufferevent_read(bev, is->buffer, 1);
358 is->length = (size_t)(unsigned char)is->buffer[0];
359 if (is->length == 0) {
360 icbd_drop(is, "invalid packet");
361 return;
362 }
363 }
364 /* read as much as we can */
365 is->rlen += bufferevent_read(bev, &is->buffer[is->rlen],
366 is->length);
367#ifdef DEBUG
368 {
369 int i;
370
371 printf("-> read %lu out of %lu from %s:%d:\n",
372 is->rlen, is->length, is->host, is->port);
373 for (i = 0; i < (int)is->rlen; i++)
374 printf(" %02x", (unsigned char)is->buffer[i]);
375 printf("\n");
376 }
377#endif
378 /* see you next time around */
379 if (is->rlen < is->length)
380 return;
381 /* process the message in full */
382 icb_input(is);
383 is->rlen = is->length = 0;
384 }
385}
386
387void
388icbd_write(struct icb_session *is, char *buf, ssize_t size)
389{
390 if (bufferevent_write(is->bev, buf, size) == -1)
391 syslog(LOG_ERR, "bufferevent_write: %m");
392#ifdef DEBUG
393 {
394 int i;
395
396 printf("-> wrote %lu to %s:%d:\n", size, is->host, is->port);
397 for (i = 0; i < size; i++)
398 printf(" %02x", (unsigned char)buf[i]);
399 printf("\n");
400 }
401#endif
402}
403
404void
405icbd_drop(struct icb_session *is, char *reason)
406{
407 if (reason) {
408 icb_remove(is, reason);
409 icbd_log(is, LOG_DEBUG, reason);
410 } else
411 icb_remove(is, NULL);
412 (void)evbuffer_write(EVBUFFER_OUTPUT(is->bev), EVBUFFER_FD(is->bev));
413 (void)close(EVBUFFER_FD(is->bev));
414 bufferevent_free(is->bev);
415 RB_REMOVE(icbd_sessions, &icbd_sessions, is);
416 free(is);
417}
418
419void
420icbd_ioerr(struct bufferevent *bev __attribute__((__unused__)), short what,
421 void *arg)
422{
423 struct icb_session *is = (struct icb_session *)arg;
424
425 if (what & EVBUFFER_TIMEOUT)
426 icbd_drop(is, "timeout");
427 else if (what & EVBUFFER_EOF)
428 icbd_drop(is, NULL);
429 else if (what & EVBUFFER_ERROR)
430 icbd_drop(is, (what & EVBUFFER_READ) ? "read error" :
431 "write error");
432}
433
434void
435icbd_log(struct icb_session *is, int level, const char *fmt, ...)
436{
437 char buf[512];
438 va_list ap;
439
440 if (!verbose && level == LOG_DEBUG)
441 return;
442
443 va_start(ap, fmt);
444 (void)vsnprintf(buf, sizeof buf, fmt, ap);
445 va_end(ap);
446 if (is)
447 syslog(level, "%s:%u: %s", is->host, is->port, buf);
448 else
449 syslog(level, "%s", buf);
450}
451
452void
453icbd_restrict(void)
454{
455 struct stat sb;
456 struct passwd *pw;
457
458 if ((pw = getpwnam(ICBD_USER)) == NULL) {
459 syslog(LOG_ERR, "No passwd entry for %s", ICBD_USER);
460 exit(EX_NOUSER);
461 }
462
463 if (setusercontext(NULL, pw, pw->pw_uid,
464 LOGIN_SETALL & ~LOGIN_SETUSER) < 0)
465 exit(EX_NOPERM);
466
467 if (stat(pw->pw_dir, &sb) == -1) {
468 syslog(LOG_ERR, "%s: %m", pw->pw_name);
469 exit(EX_NOPERM);
470 }
471
472 if (sb.st_uid != 0 || (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
473 syslog(LOG_ERR, "bad directory permissions");
474 exit(EX_NOPERM);
475 }
476
477 if (chroot(pw->pw_dir) < 0) {
478 syslog(LOG_ERR, "%s: %m", pw->pw_dir);
479 exit(EX_UNAVAILABLE);
480 }
481
482 if (chdir("/") < 0) {
483 syslog(LOG_ERR, "/: %m");
484 exit(EX_UNAVAILABLE);
485 }
486
487 if (setuid(pw->pw_uid) < 0) {
488 syslog(LOG_ERR, "%d: %m", pw->pw_uid);
489 exit(EX_NOPERM);
490 }
491
492 (void)setproctitle("icbd");
493}
494
495void
496icbd_grplist(char *list)
497{
498 char *s, *s1, *s2;
499 int last = 0;
500
501 if (!list || strlen(list) == 0)
502 return;
503
504 /* "group1[:pass1][,group2[:pass2],...]" */
505 s = list;
506 s1 = s2 = NULL;
507 while (!last && s) {
508 if ((s1 = strchr(s, ',')) != NULL)
509 *s1 = '\0';
510 else {
511 last = 1;
512 s1 = s;
513 }
514 if ((s2 = strchr(s, ':')) != NULL)
515 *s2 = '\0';
516 if (icb_addgroup(NULL, s, s2 ? ++s2 : NULL) == NULL)
517 err(EX_UNAVAILABLE, NULL);
518 s = ++s1;
519 s1 = s2 = NULL;
520 }
521}
522
523void
524icbd_modtab(char *mtab)
525{
526 FILE *fp;
527 char *buf, *lbuf;
528 size_t len;
529
530 if ((fp = fopen(mtab, "r")) == NULL)
531 err(EX_NOINPUT, "%s", mtab);
532
533 bzero(modtab, ICB_MTABLEN * ICB_MAXNICKLEN);
534 lbuf = NULL;
535 while ((buf = fgetln(fp, &len)) && modtabcnt < ICB_MTABLEN) {
536 if (buf[len - 1] == '\n')
537 buf[len - 1] = '\0';
538 else {
539 /* EOF without EOL, copy and add the NUL */
540 if ((lbuf = malloc(len + 1)) == NULL)
541 err(1, NULL);
542 memcpy(lbuf, buf, len);
543 lbuf[len] = '\0';
544 buf = lbuf;
545 }
546 while (buf[0] == ' ' || buf[0] == '\t')
547 buf++;
548 if (buf[0] == '#' || buf[0] == '\0')
549 continue;
550 strlcpy(modtab[modtabcnt++], buf, ICB_MAXNICKLEN);
551 }
552 free(lbuf);
553
554 qsort(modtab, modtabcnt, ICB_MAXNICKLEN,
555 (int (*)(const void *, const void *))strcmp);
556
557 fclose(fp);
558}
559
560time_t
561getmonotime(void)
562{
563 struct timespec ts;
564
565 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
566 syslog(LOG_ERR, "%m");
567 exit(EX_OSERR);
568 }
569 return (ts.tv_sec);
570}
571
572void
573getpeerinfo(struct icb_session *is)
574{
575 struct sockaddr_storage ss;
576 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
577 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
578 socklen_t ss_len = sizeof ss;
579
580 bzero(&ss, sizeof ss);
581 if (getpeername(EVBUFFER_FD(is->bev), (struct sockaddr *)&ss,
582 &ss_len) != 0)
583 return;
584
585 is->port = 0;
586 switch (ss.ss_family) {
587 case AF_INET:
588 is->port = ntohs(sin->sin_port);
589 break;
590
591 case AF_INET6:
592 is->port = ntohs(sin6->sin6_port);
593 break;
594 }
595
596 inet_ntop(ss.ss_family, ss.ss_family == AF_INET ?
597 (void *)&sin->sin_addr : (void *)&sin6->sin6_addr,
598 is->host, sizeof is->host);
599
600 dns_rresolv(is, &ss);
601}
Note: See TracBrowser for help on using the repository browser.