source: code/icbd.c@ b7bc432

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

Set SO_KEEPALIVE on the client socket, not on the server one

  • Property mode set to 100644
File size: 12.0 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, on = 1, 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 (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof on) < 0)
266 syslog(LOG_WARNING, "SO_KEEPALIVE: %m");
267 if ((is = calloc(1, sizeof *is)) == NULL) {
268 syslog(LOG_ERR, "calloc: %m");
269 (void)close(s);
270 return;
271 }
272 if ((is->bev = bufferevent_new(s, icbd_dispatch, NULL, icbd_ioerr,
273 is)) == NULL) {
274 syslog(LOG_ERR, "bufferevent_new: %m");
275 (void)close(s);
276 free(is);
277 return;
278 }
279 if (bufferevent_enable(is->bev, EV_READ)) {
280 syslog(LOG_ERR, "bufferevent_enable: %m");
281 (void)close(s);
282 bufferevent_free(is->bev);
283 free(is);
284 return;
285 }
286
287 is->id = sessionid++;
288 RB_INSERT(icbd_sessions, &icbd_sessions, is);
289
290 /* save host information */
291 getpeerinfo(is);
292
293 /* start icb conversation */
294 icb_start(is);
295}
296
297__dead void
298usage(void)
299{
300 (void)fprintf(stderr, "usage: %s [-46Cdv] [-G group1[,group2,...]] "
301 "[-M modtab]\n\t[-S name] [[addr][:port] ...]\n", __progname);
302 exit(EX_USAGE);
303}
304
305/*
306 * bufferevent functions
307 */
308
309void
310icbd_dispatch(struct bufferevent *bev, void *arg)
311{
312 struct icb_session *is = (struct icb_session *)arg;
313
314 if (is->length == 0) {
315 bzero(is->buffer, sizeof is->buffer);
316 /* read length */
317 (void)bufferevent_read(bev, is->buffer, 1);
318 /* we're about to read the whole packet */
319 is->length = (size_t)(unsigned char)is->buffer[0];
320 if (is->length == 0) {
321 icbd_drop(is, "invalid packet");
322 return;
323 }
324 if (EVBUFFER_LENGTH(EVBUFFER_INPUT(bev)) < is->length) {
325 /* set watermark to the expected length */
326 bufferevent_setwatermark(bev, EV_READ, is->length, 0);
327 return;
328 }
329 }
330 (void)bufferevent_read(bev, &is->buffer[1], is->length);
331#ifdef DEBUG
332 {
333 int i;
334
335 printf("-> read from %s:%d:\n", is->host, is->port);
336 for (i = 0; i < (int)is->length + 1; i++)
337 printf(" %02x", (unsigned char)is->buffer[i]);
338 printf("\n");
339 }
340#endif
341 icb_input(is);
342 is->length = 0;
343}
344
345void
346icbd_write(struct icb_session *is, char *buf, ssize_t size)
347{
348 if (bufferevent_write(is->bev, buf, size) == -1)
349 syslog(LOG_ERR, "bufferevent_write: %m");
350#ifdef DEBUG
351 {
352 int i;
353
354 printf("-> wrote to %s:%d:\n", is->host, is->port);
355 for (i = 0; i < size; i++)
356 printf(" %02x", (unsigned char)buf[i]);
357 printf("\n");
358 }
359#endif
360}
361
362void
363icbd_drop(struct icb_session *is, char *reason)
364{
365 if (reason) {
366 icb_remove(is, reason);
367 icbd_log(is, LOG_DEBUG, reason);
368 } else
369 icb_remove(is, NULL);
370 (void)evbuffer_write(EVBUFFER_OUTPUT(is->bev), EVBUFFER_FD(is->bev));
371 (void)close(EVBUFFER_FD(is->bev));
372 bufferevent_free(is->bev);
373 RB_REMOVE(icbd_sessions, &icbd_sessions, is);
374 free(is);
375}
376
377void
378icbd_ioerr(struct bufferevent *bev __attribute__((__unused__)), short what,
379 void *arg)
380{
381 struct icb_session *is = (struct icb_session *)arg;
382
383 if (what & EVBUFFER_TIMEOUT)
384 icbd_drop(is, "timeout");
385 else if (what & EVBUFFER_EOF)
386 icbd_drop(is, NULL);
387 else if (what & EVBUFFER_ERROR)
388 icbd_drop(is, (what & EVBUFFER_READ) ? "read error" :
389 "write error");
390}
391
392void
393icbd_log(struct icb_session *is, int level, const char *fmt, ...)
394{
395 char buf[512];
396 va_list ap;
397
398 if (!verbose && level == LOG_DEBUG)
399 return;
400
401 va_start(ap, fmt);
402 (void)vsnprintf(buf, sizeof buf, fmt, ap);
403 va_end(ap);
404 if (is)
405 syslog(level, "%s:%u: %s", is->host, is->port, buf);
406 else
407 syslog(level, "%s", buf);
408}
409
410void
411icbd_restrict(void)
412{
413 struct stat sb;
414 struct passwd *pw;
415
416 if ((pw = getpwnam(ICBD_USER)) == NULL) {
417 syslog(LOG_ERR, "No passwd entry for %s", ICBD_USER);
418 exit(EX_NOUSER);
419 }
420
421 if (setusercontext(NULL, pw, pw->pw_uid,
422 LOGIN_SETALL & ~LOGIN_SETUSER) < 0)
423 exit(EX_NOPERM);
424
425 if (stat(pw->pw_dir, &sb) == -1) {
426 syslog(LOG_ERR, "%s: %m", pw->pw_name);
427 exit(EX_NOPERM);
428 }
429
430 if (sb.st_uid != 0 || (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
431 syslog(LOG_ERR, "bad directory permissions");
432 exit(EX_NOPERM);
433 }
434
435 if (chroot(pw->pw_dir) < 0) {
436 syslog(LOG_ERR, "%s: %m", pw->pw_dir);
437 exit(EX_UNAVAILABLE);
438 }
439
440 if (setuid(pw->pw_uid) < 0) {
441 syslog(LOG_ERR, "%d: %m", pw->pw_uid);
442 exit(EX_NOPERM);
443 }
444
445 if (chdir("/") < 0) {
446 syslog(LOG_ERR, "/: %m");
447 exit(EX_UNAVAILABLE);
448 }
449
450 (void)setproctitle("icbd");
451}
452
453void
454icbd_grplist(char *list)
455{
456 char *s, *s1, *s2;
457 int last = 0;
458
459 if (!list || strlen(list) == 0)
460 return;
461
462 /* "group1[:pass1][,group2[:pass2],...]" */
463 s = list;
464 s1 = s2 = NULL;
465 while (!last && s) {
466 if ((s1 = strchr(s, ',')) != NULL)
467 *s1 = '\0';
468 else {
469 last = 1;
470 s1 = s;
471 }
472 if ((s2 = strchr(s, ':')) != NULL)
473 *s2 = '\0';
474 if (icb_addgroup(NULL, s, s2 ? ++s2 : NULL) == NULL)
475 err(EX_UNAVAILABLE, NULL);
476 s = ++s1;
477 s1 = s2 = NULL;
478 }
479}
480
481void
482icbd_modtab(char *mtab)
483{
484 FILE *fp;
485 char *buf, *lbuf;
486 size_t len;
487
488 if ((fp = fopen(mtab, "r")) == NULL)
489 err(EX_NOINPUT, "%s", mtab);
490
491 bzero(modtab, ICB_MTABLEN * ICB_MAXNICKLEN);
492 lbuf = NULL;
493 while ((buf = fgetln(fp, &len)) && modtabcnt < ICB_MTABLEN) {
494 if (buf[len - 1] == '\n')
495 buf[len - 1] = '\0';
496 else {
497 /* EOF without EOL, copy and add the NUL */
498 if ((lbuf = malloc(len + 1)) == NULL)
499 err(1, NULL);
500 memcpy(lbuf, buf, len);
501 lbuf[len] = '\0';
502 buf = lbuf;
503 }
504 while (buf[0] == ' ' || buf[0] == '\t')
505 buf++;
506 if (buf[0] == '#' || buf[0] == '\0')
507 continue;
508 strlcpy(modtab[modtabcnt++], buf, ICB_MAXNICKLEN);
509 }
510 free(lbuf);
511
512 qsort(modtab, modtabcnt, ICB_MAXNICKLEN,
513 (int (*)(const void *, const void *))strcmp);
514
515 fclose(fp);
516}
517
518time_t
519getmonotime(void)
520{
521 struct timespec ts;
522
523 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
524 syslog(LOG_ERR, "%m");
525 exit(EX_OSERR);
526 }
527 return (ts.tv_sec);
528}
529
530void
531getpeerinfo(struct icb_session *is)
532{
533 struct sockaddr_storage ss;
534 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
535 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
536 socklen_t ss_len = sizeof ss;
537
538 bzero(&ss, sizeof ss);
539 if (getpeername(EVBUFFER_FD(is->bev), (struct sockaddr *)&ss,
540 &ss_len) != 0)
541 return;
542
543 is->port = 0;
544 switch (ss.ss_family) {
545 case AF_INET:
546 is->port = ntohs(sin->sin_port);
547 break;
548
549 case AF_INET6:
550 is->port = ntohs(sin6->sin6_port);
551 break;
552 }
553
554 inet_ntop(ss.ss_family, ss.ss_family == AF_INET ?
555 (void *)&sin->sin_addr : (void *)&sin6->sin6_addr,
556 is->host, sizeof is->host);
557
558 dns_rresolv(is, &ss);
559}
Note: See TracBrowser for help on using the repository browser.