source: code/icbd.c@ bacf9da

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

line break

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