source: code/icbd.c@ e87ab6d

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

Convert DNS code to use ASR

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