source: code/icbd.c@ 940d2b5

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

Don't attempt to drain the output buffer on drop

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