source: code/icbd.c@ d488e1b

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

enable tcp keepalives to help clear out dead connections

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