source: code/icbd.c@ 7289823

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

Get rid of ICB_MSGSIZE+1, fix various off-by-ones and do some truncation
where necessary.

  • 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
42#include "icb.h"
43#include "icbd.h"
44
45uint64_t sessionid;
46char modtabpath[MAXPATHLEN];
47char modtab[ICB_MTABLEN][ICB_MAXNICKLEN];
48int modtabcnt;
49char srvname[MAXHOSTNAMELEN];
50int creategroups;
51int foreground;
52char logprefix[MAXPATHLEN/2];
53int dodns = 1;
54int dologging;
55int verbose;
56
57void usage(void);
58void getpeerinfo(struct icb_session *);
59void icbd_accept(int, short, void *);
60void icbd_paused(int, short, void *);
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 *);
66void icbd_modtab(char *);
67void icbd_restrict(void);
68void icbd_write(struct icb_session *, char *, ssize_t);
69void icbd_signal(int);
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 event ev_sig;
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
90 RB_INIT(&icbd_sessions);
91
92 /* init group lists before calling icb_addgroup */
93 icb_init(&ic);
94
95 while ((ch = getopt(argc, argv, "46CdG:M:nL:S:v")) != -1)
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;
112 case 'L':
113 strlcpy(logprefix, optarg, sizeof logprefix);
114 dologging++;
115 break;
116 case 'M':
117 strlcpy(modtabpath, optarg, sizeof modtabpath);
118 break;
119 case 'n':
120 dodns = 0;
121 break;
122 case 'S':
123 strlcpy(srvname, optarg, sizeof srvname);
124 break;
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)
143 errx(EX_USAGE, "Can't specify both -4 and -6");
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;
160 struct icbd_listener *l;
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
210 if ((l = calloc(1, sizeof *l)) == NULL)
211 err(EX_UNAVAILABLE, NULL);
212 event_set(&l->ev, s, EV_READ | EV_PERSIST, 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 /* start a dns resolver thread */
235 dns_init();
236
237 if (!foreground)
238 icbd_restrict();
239
240 (void)signal(SIGPIPE, SIG_IGN);
241 if (strlen(modtabpath) > 0) {
242 icbd_modtab(modtabpath);
243 signal_set(&ev_sig, SIGHUP,
244 (void (*)(int, short, void *))icbd_signal, NULL);
245 signal_add(&ev_sig, NULL);
246 }
247
248 (void)event_dispatch();
249
250 syslog(LOG_ERR, "event_dispatch: %m");
251
252 return (EX_UNAVAILABLE);
253}
254
255static inline int
256icbd_session_cmp(struct icb_session *a, struct icb_session *b)
257{
258 if (a->id > b->id)
259 return (1);
260 if (a->id < b->id)
261 return (-1);
262 return (0);
263}
264
265inline struct icb_session *
266icbd_session_lookup(uint64_t sid)
267{
268 struct icb_session key;
269
270 key.id = sid;
271 return (RB_FIND(icbd_sessions, &icbd_sessions, &key));
272}
273
274void
275icbd_accept(int fd, short event __attribute__((__unused__)),
276 void *arg)
277{
278 struct icbd_listener *l = arg;
279 struct sockaddr_storage ss;
280 struct timeval p = { 1, 0 };
281 struct icb_session *is;
282 socklen_t ss_len = sizeof ss;
283 int s, on = 1, tos = IPTOS_LOWDELAY;
284
285 ss.ss_len = ss_len;
286 s = accept(fd, (struct sockaddr *)&ss, &ss_len);
287 if (s == -1) {
288 switch (errno) {
289 case EINTR:
290 case EWOULDBLOCK:
291 case ECONNABORTED:
292 return;
293 case EMFILE:
294 case ENFILE:
295 event_del(&l->ev);
296 evtimer_add(&l->pause, &p);
297 return;
298 default:
299 syslog(LOG_ERR, "accept: %m");
300 return;
301 }
302 }
303
304 if (ss.ss_family == AF_INET)
305 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof tos) < 0)
306 syslog(LOG_WARNING, "IP_TOS: %m");
307 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof on) < 0)
308 syslog(LOG_WARNING, "SO_KEEPALIVE: %m");
309 if ((is = calloc(1, sizeof *is)) == NULL) {
310 syslog(LOG_ERR, "calloc: %m");
311 (void)close(s);
312 return;
313 }
314 if ((is->bev = bufferevent_new(s, icbd_dispatch, NULL, icbd_ioerr,
315 is)) == NULL) {
316 syslog(LOG_ERR, "bufferevent_new: %m");
317 (void)close(s);
318 free(is);
319 return;
320 }
321 if (bufferevent_enable(is->bev, EV_READ)) {
322 syslog(LOG_ERR, "bufferevent_enable: %m");
323 (void)close(s);
324 bufferevent_free(is->bev);
325 free(is);
326 return;
327 }
328
329 is->id = sessionid++;
330 RB_INSERT(icbd_sessions, &icbd_sessions, is);
331
332 /* save host information */
333 getpeerinfo(is);
334
335 /* start icb conversation */
336 icb_start(is);
337}
338
339void
340icbd_paused(int fd __attribute__((__unused__)),
341 short events __attribute__((__unused__)), void *arg)
342{
343 struct icbd_listener *l = arg;
344 event_add(&l->ev, NULL);
345}
346
347__dead void
348usage(void)
349{
350 extern char *__progname;
351
352 (void)fprintf(stderr, "usage: %s [-46Cdv] [-G group1[,group2,...]] "
353 "[-L prefix] [-M modtab]\n\t[-S name] [[addr][:port] ...]\n",
354 __progname);
355 exit(EX_USAGE);
356}
357
358/*
359 * bufferevent functions
360 */
361void
362icbd_ioerr(struct bufferevent *bev __attribute__((__unused__)), short what,
363 void *arg)
364{
365 struct icb_session *is = (struct icb_session *)arg;
366
367 if (what & EVBUFFER_TIMEOUT)
368 icbd_drop(is, "timeout");
369 else if (what & EVBUFFER_EOF)
370 icbd_drop(is, NULL);
371 else if (what & EVBUFFER_ERROR)
372 icbd_drop(is, (what & EVBUFFER_READ) ? "read error" :
373 "write error");
374}
375
376void
377icbd_dispatch(struct bufferevent *bev, void *arg)
378{
379 struct icb_session *is = (struct icb_session *)arg;
380 unsigned char length;
381
382 while (EVBUFFER_LENGTH(EVBUFFER_INPUT(bev)) > 0) {
383 if (is->length == 0) {
384 /* read length */
385 bufferevent_read(bev, &length, 1);
386 if (length == 0) {
387 /*
388 * An extension has been proposed:
389 * if length is 0, the packet is part of an
390 * "extended packet". The packet should be
391 * treated as if length was 255 and the next
392 * packet received from the sender should be
393 * appended to this packet.
394 *
395 * This server doesn't support this yet.
396 */
397 icbd_drop(is, "invalid packet");
398 return;
399 }
400 is->length = (size_t)length;
401 is->rlen = 0;
402 }
403 /* read as much as we can */
404 is->rlen += bufferevent_read(bev, &is->buffer[is->rlen],
405 is->length);
406#ifdef DEBUG
407 {
408 int i;
409
410 printf("-> read %lu out of %lu from %s:%d:\n",
411 is->rlen, is->length, is->host, is->port);
412 for (i = 0; i < (int)is->rlen; i++)
413 printf(" %02x", (unsigned char)is->buffer[i]);
414 printf("\n");
415 }
416#endif
417 /* see you next time around */
418 if (is->rlen < is->length)
419 return;
420 /* null-terminate the data */
421 is->buffer[MIN(is->rlen, ICB_MSGSIZE - 1)] = '\0';
422 /* process the message in full */
423 icb_input(is);
424 is->rlen = is->length = 0;
425 }
426}
427
428void
429icbd_write(struct icb_session *is, char *buf, ssize_t size)
430{
431 if (bufferevent_write(is->bev, buf, size) == -1)
432 syslog(LOG_ERR, "bufferevent_write: %m");
433#ifdef DEBUG
434 {
435 int i;
436
437 printf("-> wrote %lu to %s:%d:\n", size, is->host, is->port);
438 for (i = 0; i < size; i++)
439 printf(" %02x", (unsigned char)buf[i]);
440 printf("\n");
441 }
442#endif
443}
444
445void
446icbd_drop(struct icb_session *is, char *reason)
447{
448 if (reason) {
449 icb_remove(is, reason);
450 icbd_log(is, LOG_DEBUG, reason);
451 } else
452 icb_remove(is, NULL);
453 (void)evbuffer_write(EVBUFFER_OUTPUT(is->bev), EVBUFFER_FD(is->bev));
454 (void)close(EVBUFFER_FD(is->bev));
455 bufferevent_free(is->bev);
456 RB_REMOVE(icbd_sessions, &icbd_sessions, is);
457 free(is);
458}
459
460void
461icbd_log(struct icb_session *is, int level, const char *fmt, ...)
462{
463 char buf[512];
464 va_list ap;
465
466 if (!verbose && level == LOG_DEBUG)
467 return;
468
469 va_start(ap, fmt);
470 (void)vsnprintf(buf, sizeof buf, fmt, ap);
471 va_end(ap);
472 if (is)
473 syslog(level, "%s:%u: %s", is->host, is->port, buf);
474 else
475 syslog(level, "%s", buf);
476}
477
478void
479icbd_restrict(void)
480{
481 struct stat sb;
482 struct passwd *pw;
483
484 if ((pw = getpwnam(ICBD_USER)) == NULL) {
485 syslog(LOG_ERR, "No passwd entry for %s", ICBD_USER);
486 exit(EX_NOUSER);
487 }
488
489 if (setusercontext(NULL, pw, pw->pw_uid,
490 LOGIN_SETALL & ~LOGIN_SETUSER) < 0)
491 exit(EX_NOPERM);
492
493 if (stat(pw->pw_dir, &sb) == -1) {
494 syslog(LOG_ERR, "%s: %m", pw->pw_name);
495 exit(EX_NOPERM);
496 }
497
498 if (sb.st_uid != 0 || (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
499 syslog(LOG_ERR, "bad directory permissions");
500 exit(EX_NOPERM);
501 }
502
503 if (chroot(pw->pw_dir) < 0) {
504 syslog(LOG_ERR, "%s: %m", pw->pw_dir);
505 exit(EX_UNAVAILABLE);
506 }
507
508 if (chdir("/") < 0) {
509 syslog(LOG_ERR, "/: %m");
510 exit(EX_UNAVAILABLE);
511 }
512
513 if (setuid(pw->pw_uid) < 0) {
514 syslog(LOG_ERR, "%d: %m", pw->pw_uid);
515 exit(EX_NOPERM);
516 }
517
518 (void)setproctitle("icbd");
519}
520
521void
522icbd_grplist(char *list)
523{
524 char *s, *s1, *s2;
525 int last = 0;
526
527 if (!list || strlen(list) == 0)
528 return;
529
530 /* "group1[:pass1][,group2[:pass2],...]" */
531 s = list;
532 s1 = s2 = NULL;
533 while (!last && s) {
534 if ((s1 = strchr(s, ',')) != NULL)
535 *s1 = '\0';
536 else {
537 last = 1;
538 s1 = s;
539 }
540 if ((s2 = strchr(s, ':')) != NULL)
541 *s2 = '\0';
542 if (icb_addgroup(NULL, s, s2 ? ++s2 : NULL) == NULL)
543 err(EX_UNAVAILABLE, NULL);
544 s = ++s1;
545 s1 = s2 = NULL;
546 }
547}
548
549void
550icbd_modtab(char *mtab)
551{
552 FILE *fp;
553 char *buf, *lbuf;
554 size_t len;
555
556 if ((fp = fopen(mtab, "r")) == NULL)
557 err(EX_NOINPUT, "%s", mtab);
558
559 bzero(modtab, ICB_MTABLEN * ICB_MAXNICKLEN);
560 lbuf = NULL;
561 while ((buf = fgetln(fp, &len)) && modtabcnt < ICB_MTABLEN) {
562 if (buf[len - 1] == '\n')
563 buf[len - 1] = '\0';
564 else {
565 /* EOF without EOL, copy and add the NUL */
566 if ((lbuf = malloc(len + 1)) == NULL)
567 err(1, NULL);
568 memcpy(lbuf, buf, len);
569 lbuf[len] = '\0';
570 buf = lbuf;
571 }
572 while (buf[0] == ' ' || buf[0] == '\t')
573 buf++;
574 if (buf[0] == '#' || buf[0] == '\0')
575 continue;
576 strlcpy(modtab[modtabcnt++], buf, ICB_MAXNICKLEN);
577 }
578 free(lbuf);
579
580 qsort(modtab, modtabcnt, ICB_MAXNICKLEN,
581 (int (*)(const void *, const void *))strcmp);
582
583 fclose(fp);
584}
585
586void
587icbd_signal(int sig)
588{
589 switch (sig) {
590 case SIGHUP:
591 if (strlen(modtabpath) > 0)
592 icbd_modtab(modtabpath);
593 break;
594 default:
595 syslog(LOG_WARNING, "unexpected signal %d", sig);
596 break;
597 }
598}
599
600time_t
601getmonotime(void)
602{
603 struct timespec ts;
604
605 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
606 syslog(LOG_ERR, "%m");
607 exit(EX_OSERR);
608 }
609 return (ts.tv_sec);
610}
611
612void
613getpeerinfo(struct icb_session *is)
614{
615 struct sockaddr_storage ss;
616 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
617 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
618 socklen_t ss_len = sizeof ss;
619
620 bzero(&ss, sizeof ss);
621 if (getpeername(EVBUFFER_FD(is->bev), (struct sockaddr *)&ss,
622 &ss_len) != 0)
623 return;
624
625 is->port = 0;
626 switch (ss.ss_family) {
627 case AF_INET:
628 is->port = ntohs(sin->sin_port);
629 break;
630
631 case AF_INET6:
632 is->port = ntohs(sin6->sin6_port);
633 break;
634 }
635
636 inet_ntop(ss.ss_family, ss.ss_family == AF_INET ?
637 (void *)&sin->sin_addr : (void *)&sin6->sin6_addr,
638 is->host, sizeof is->host);
639
640 dns_rresolv(is, &ss);
641}
Note: See TracBrowser for help on using the repository browser.