source: code/icbd.c@ 5815eef

Last change on this file since 5815eef was b4049f9, checked in by Mike Belopuhov <mike@…>, 11 years ago

Rewrite DNS resolver to do things truly asynchronously

  • Property mode set to 100644
File size: 11.9 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
45extern char *__progname;
46
47uint64_t sessionid;
48char modtab[ICB_MTABLEN][ICB_MAXNICKLEN];
49int modtabcnt;
50char srvname[MAXHOSTNAMELEN];
51int creategroups;
52int foreground;
53int verbose;
54
55void usage(void);
56void getpeerinfo(struct icb_session *);
57void icbd_accept(int, short, void *);
58void icbd_drop(struct icb_session *, char *);
59void icbd_ioerr(struct bufferevent *, short, void *);
60void icbd_dispatch(struct bufferevent *, void *);
61void icbd_log(struct icb_session *, int, const char *, ...);
62void icbd_grplist(char *);
63void icbd_modtab(char *);
64void icbd_restrict(void);
65void icbd_write(struct icb_session *, char *, ssize_t);
66
67static inline int icbd_session_cmp(struct icb_session *, struct icb_session *);
68
69RB_HEAD(icbd_sessions, icb_session) icbd_sessions;
70RB_PROTOTYPE(icbd_sessions, icb_session, node, icbd_session_cmp);
71RB_GENERATE(icbd_sessions, icb_session, node, icbd_session_cmp);
72
73int
74main(int argc, char *argv[])
75{
76 struct icbd_callbacks ic = { icbd_drop, icbd_log, icbd_write };
77 const char *cause = NULL;
78 int ch, nsocks = 0, save_errno = 0;
79 int inet4 = 0, inet6 = 0;
80
81 RB_INIT(&icbd_sessions);
82
83 /* init group lists before calling icb_addgroup */
84 icb_init(&ic);
85
86 while ((ch = getopt(argc, argv, "46CdG:M:S:v")) != -1)
87 switch (ch) {
88 case '4':
89 inet4++;
90 break;
91 case '6':
92 inet6++;
93 break;
94 case 'C':
95 creategroups++;
96 break;
97 case 'd':
98 foreground++;
99 break;
100 case 'G':
101 icbd_grplist(optarg);
102 break;
103 case 'M':
104 icbd_modtab(optarg);
105 break;
106 case 'S':
107 strlcpy(srvname, optarg, sizeof srvname);
108 break;
109 case 'v':
110 verbose++;
111 break;
112 default:
113 usage();
114 /* NOTREACHED */
115 }
116 argc -= optind;
117 argv += optind;
118
119 /* add group "1" as it's a login group for most of the clients */
120 if (icb_addgroup(NULL, "1", NULL) == NULL)
121 err(EX_UNAVAILABLE, NULL);
122
123 if (argc == 0)
124 argc++;
125
126 if (inet4 && inet6)
127 errx(EX_USAGE, "Can't specify both -4 and -6");
128
129 tzset();
130 (void)setlocale(LC_ALL, "C");
131
132 if (foreground)
133 openlog("icbd", LOG_PID | LOG_PERROR, LOG_DAEMON);
134 else
135 openlog("icbd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
136
137 if (!foreground && daemon(0, 0) < 0)
138 err(EX_OSERR, NULL);
139
140 (void)event_init();
141
142 for (ch = 0; ch < argc; ch++) {
143 struct addrinfo hints, *res, *res0;
144 struct event *ev;
145 char *addr, *port;
146 int error, s, on = 1;
147
148 addr = port = NULL;
149 if (argv[ch] != NULL) {
150 if (argv[ch][0] != ':')
151 addr = argv[ch];
152 if ((port = strrchr(argv[ch], ':')) != NULL)
153 *port++ = '\0';
154 }
155
156 bzero(&hints, sizeof hints);
157 if (inet4 || inet6)
158 hints.ai_family = inet4 ? PF_INET : PF_INET6;
159 else
160 hints.ai_family = PF_UNSPEC;
161 hints.ai_socktype = SOCK_STREAM;
162 hints.ai_flags = AI_PASSIVE;
163 if ((error = getaddrinfo(addr, port ? port : "icb", &hints,
164 &res0)) != 0) {
165 syslog(LOG_ERR, "%s", gai_strerror(error));
166 return (EX_UNAVAILABLE);
167 }
168
169 for (res = res0; res != NULL; res = res->ai_next) {
170 if ((s = socket(res->ai_family, res->ai_socktype,
171 res->ai_protocol)) < 0) {
172 cause = "socket";
173 save_errno = errno;
174 continue;
175 }
176
177 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on,
178 sizeof on) < 0) {
179 cause = "SO_REUSEADDR";
180 save_errno = errno;
181 (void)close(s);
182 continue;
183 }
184
185 if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
186 cause = "bind";
187 save_errno = errno;
188 (void)close(s);
189 continue;
190 }
191
192 (void)listen(s, TCP_BACKLOG);
193
194 if ((ev = calloc(1, sizeof *ev)) == NULL)
195 err(EX_UNAVAILABLE, NULL);
196 event_set(ev, s, EV_READ | EV_PERSIST, icbd_accept, ev);
197 if (event_add(ev, NULL) < 0) {
198 syslog(LOG_ERR, "event_add: %m");
199 return (EX_UNAVAILABLE);
200 }
201
202 nsocks++;
203 }
204
205 freeaddrinfo(res0);
206 }
207
208 if (nsocks == 0) {
209 errno = save_errno;
210 syslog(LOG_ERR, "%s: %m", cause);
211 return (EX_UNAVAILABLE);
212 }
213
214 /* start a dns resolver thread */
215 dns_init();
216
217 if (!foreground)
218 icbd_restrict();
219
220 (void)signal(SIGPIPE, SIG_IGN);
221
222 (void)event_dispatch();
223
224 syslog(LOG_ERR, "event_dispatch: %m");
225
226 return (EX_UNAVAILABLE);
227}
228
229static inline int
230icbd_session_cmp(struct icb_session *a, struct icb_session *b)
231{
232 if (a->id > b->id)
233 return (1);
234 if (a->id < b->id)
235 return (-1);
236 return (0);
237}
238
239inline struct icb_session *
240icbd_session_lookup(uint64_t sid)
241{
242 struct icb_session key;
243
244 key.id = sid;
245 return (RB_FIND(icbd_sessions, &icbd_sessions, &key));
246}
247
248void
249icbd_accept(int fd, short event __attribute__((__unused__)),
250 void *arg __attribute__((__unused__)))
251{
252 struct sockaddr_storage ss;
253 struct icb_session *is;
254 socklen_t ss_len = sizeof ss;
255 int s, tos = IPTOS_LOWDELAY;
256
257 ss.ss_len = ss_len;
258 if ((s = accept(fd, (struct sockaddr *)&ss, &ss_len)) < 0) {
259 syslog(LOG_ERR, "accept: %m");
260 return;
261 }
262 if (ss.ss_family == AF_INET)
263 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof tos) < 0)
264 syslog(LOG_WARNING, "IP_TOS: %m");
265 if ((is = calloc(1, sizeof *is)) == NULL) {
266 syslog(LOG_ERR, "calloc: %m");
267 (void)close(s);
268 return;
269 }
270 if ((is->bev = bufferevent_new(s, icbd_dispatch, NULL, icbd_ioerr,
271 is)) == NULL) {
272 syslog(LOG_ERR, "bufferevent_new: %m");
273 (void)close(s);
274 free(is);
275 return;
276 }
277 if (bufferevent_enable(is->bev, EV_READ)) {
278 syslog(LOG_ERR, "bufferevent_enable: %m");
279 (void)close(s);
280 bufferevent_free(is->bev);
281 free(is);
282 return;
283 }
284
285 is->id = sessionid++;
286 RB_INSERT(icbd_sessions, &icbd_sessions, is);
287
288 /* save host information */
289 getpeerinfo(is);
290
291 /* start icb conversation */
292 icb_start(is);
293}
294
295__dead void
296usage(void)
297{
298 (void)fprintf(stderr, "usage: %s [-46Cdv] [-G group1[,group2,...]] "
299 "[-M modtab]\n\t[-S name] [[addr][:port] ...]\n", __progname);
300 exit(EX_USAGE);
301}
302
303/*
304 * bufferevent functions
305 */
306
307void
308icbd_dispatch(struct bufferevent *bev, void *arg)
309{
310 struct icb_session *is = (struct icb_session *)arg;
311
312 if (is->length == 0) {
313 bzero(is->buffer, sizeof is->buffer);
314 /* read length */
315 (void)bufferevent_read(bev, is->buffer, 1);
316 /* we're about to read the whole packet */
317 is->length = (size_t)(unsigned char)is->buffer[0];
318 if (is->length == 0) {
319 icbd_drop(is, "invalid packet");
320 return;
321 }
322 if (EVBUFFER_LENGTH(EVBUFFER_INPUT(bev)) < is->length) {
323 /* set watermark to the expected length */
324 bufferevent_setwatermark(bev, EV_READ, is->length, 0);
325 return;
326 }
327 }
328 (void)bufferevent_read(bev, &is->buffer[1], is->length);
329#ifdef DEBUG
330 {
331 int i;
332
333 printf("-> read from %s:%d:\n", is->host, is->port);
334 for (i = 0; i < (int)is->length + 1; i++)
335 printf(" %02x", (unsigned char)is->buffer[i]);
336 printf("\n");
337 }
338#endif
339 icb_input(is);
340 is->length = 0;
341}
342
343void
344icbd_write(struct icb_session *is, char *buf, ssize_t size)
345{
346 if (bufferevent_write(is->bev, buf, size) == -1)
347 syslog(LOG_ERR, "bufferevent_write: %m");
348#ifdef DEBUG
349 {
350 int i;
351
352 printf("-> wrote to %s:%d:\n", is->host, is->port);
353 for (i = 0; i < size; i++)
354 printf(" %02x", (unsigned char)buf[i]);
355 printf("\n");
356 }
357#endif
358}
359
360void
361icbd_drop(struct icb_session *is, char *reason)
362{
363 if (reason) {
364 icb_remove(is, reason);
365 icbd_log(is, LOG_DEBUG, reason);
366 } else
367 icb_remove(is, NULL);
368 (void)evbuffer_write(EVBUFFER_OUTPUT(is->bev), EVBUFFER_FD(is->bev));
369 (void)close(EVBUFFER_FD(is->bev));
370 bufferevent_free(is->bev);
371 RB_REMOVE(icbd_sessions, &icbd_sessions, is);
372 free(is);
373}
374
375void
376icbd_ioerr(struct bufferevent *bev __attribute__((__unused__)), short what,
377 void *arg)
378{
379 struct icb_session *is = (struct icb_session *)arg;
380
381 if (what & EVBUFFER_TIMEOUT)
382 icbd_drop(is, "timeout");
383 else if (what & EVBUFFER_EOF)
384 icbd_drop(is, NULL);
385 else if (what & EVBUFFER_ERROR)
386 icbd_drop(is, (what & EVBUFFER_READ) ? "read error" :
387 "write error");
388}
389
390void
391icbd_log(struct icb_session *is, int level, const char *fmt, ...)
392{
393 char buf[512];
394 va_list ap;
395
396 if (!verbose && level == LOG_DEBUG)
397 return;
398
399 va_start(ap, fmt);
400 (void)vsnprintf(buf, sizeof buf, fmt, ap);
401 va_end(ap);
402 if (is)
403 syslog(level, "%s:%u: %s", is->host, is->port, buf);
404 else
405 syslog(level, "%s", buf);
406}
407
408void
409icbd_restrict(void)
410{
411 struct stat sb;
412 struct passwd *pw;
413
414 if ((pw = getpwnam(ICBD_USER)) == NULL) {
415 syslog(LOG_ERR, "No passwd entry for %s", ICBD_USER);
416 exit(EX_NOUSER);
417 }
418
419 if (setusercontext(NULL, pw, pw->pw_uid,
420 LOGIN_SETALL & ~LOGIN_SETUSER) < 0)
421 exit(EX_NOPERM);
422
423 if (stat(pw->pw_dir, &sb) == -1) {
424 syslog(LOG_ERR, "%s: %m", pw->pw_name);
425 exit(EX_NOPERM);
426 }
427
428 if (sb.st_uid != 0 || (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
429 syslog(LOG_ERR, "bad directory permissions");
430 exit(EX_NOPERM);
431 }
432
433 if (chroot(pw->pw_dir) < 0) {
434 syslog(LOG_ERR, "%s: %m", pw->pw_dir);
435 exit(EX_UNAVAILABLE);
436 }
437
438 if (setuid(pw->pw_uid) < 0) {
439 syslog(LOG_ERR, "%d: %m", pw->pw_uid);
440 exit(EX_NOPERM);
441 }
442
443 if (chdir("/") < 0) {
444 syslog(LOG_ERR, "/: %m");
445 exit(EX_UNAVAILABLE);
446 }
447
448 (void)setproctitle("icbd");
449}
450
451void
452icbd_grplist(char *list)
453{
454 char *s, *s1, *s2;
455 int last = 0;
456
457 if (!list || strlen(list) == 0)
458 return;
459
460 /* "group1[:pass1][,group2[:pass2],...]" */
461 s = list;
462 s1 = s2 = NULL;
463 while (!last && s) {
464 if ((s1 = strchr(s, ',')) != NULL)
465 *s1 = '\0';
466 else {
467 last = 1;
468 s1 = s;
469 }
470 if ((s2 = strchr(s, ':')) != NULL)
471 *s2 = '\0';
472 if (icb_addgroup(NULL, s, s2 ? ++s2 : NULL) == NULL)
473 err(EX_UNAVAILABLE, NULL);
474 s = ++s1;
475 s1 = s2 = NULL;
476 }
477}
478
479void
480icbd_modtab(char *mtab)
481{
482 FILE *fp;
483 char *buf, *lbuf;
484 size_t len;
485
486 if ((fp = fopen(mtab, "r")) == NULL)
487 err(EX_NOINPUT, "%s", mtab);
488
489 bzero(modtab, ICB_MTABLEN * ICB_MAXNICKLEN);
490 lbuf = NULL;
491 while ((buf = fgetln(fp, &len)) && modtabcnt < ICB_MTABLEN) {
492 if (buf[len - 1] == '\n')
493 buf[len - 1] = '\0';
494 else {
495 /* EOF without EOL, copy and add the NUL */
496 if ((lbuf = malloc(len + 1)) == NULL)
497 err(1, NULL);
498 memcpy(lbuf, buf, len);
499 lbuf[len] = '\0';
500 buf = lbuf;
501 }
502 while (buf[0] == ' ' || buf[0] == '\t')
503 buf++;
504 if (buf[0] == '#' || buf[0] == '\0')
505 continue;
506 strlcpy(modtab[modtabcnt++], buf, ICB_MAXNICKLEN);
507 }
508 free(lbuf);
509
510 qsort(modtab, modtabcnt, ICB_MAXNICKLEN,
511 (int (*)(const void *, const void *))strcmp);
512
513 fclose(fp);
514}
515
516time_t
517getmonotime(void)
518{
519 struct timespec ts;
520
521 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
522 syslog(LOG_ERR, "%m");
523 exit(EX_OSERR);
524 }
525 return (ts.tv_sec);
526}
527
528void
529getpeerinfo(struct icb_session *is)
530{
531 struct sockaddr_storage ss;
532 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
533 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
534 socklen_t ss_len = sizeof ss;
535
536 bzero(&ss, sizeof ss);
537 if (getpeername(EVBUFFER_FD(is->bev), (struct sockaddr *)&ss,
538 &ss_len) != 0)
539 return;
540
541 is->port = 0;
542 switch (ss.ss_family) {
543 case AF_INET:
544 is->port = ntohs(sin->sin_port);
545 break;
546
547 case AF_INET6:
548 is->port = ntohs(sin6->sin6_port);
549 break;
550 }
551
552 inet_ntop(ss.ss_family, ss.ss_family == AF_INET ?
553 (void *)&sin->sin_addr : (void *)&sin6->sin6_addr,
554 is->host, sizeof is->host);
555
556 dns_rresolv(is, &ss);
557}
Note: See TracBrowser for help on using the repository browser.