source: code/icbd.c@ 5ea93bc

Last change on this file since 5ea93bc was 411aa63, checked in by Tim Kuijsten <tim@…>, 9 years ago

pledge icbd and it's logger process

  • Property mode set to 100644
File size: 13.2 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 <ctype.h>
39#include <netdb.h>
40#include <event.h>
41#include <errno.h>
42#include <err.h>
43#include <resolv.h>
44
45#include "icb.h"
46#include "icbd.h"
47
48struct stat modtabst;
49char modtabpath[PATH_MAX];
50char modtab[ICB_MTABLEN][ICB_MAXNICKLEN];
51int modtabcnt;
52char srvname[NI_MAXHOST];
53int creategroups;
54int foreground;
55char logprefix[PATH_MAX/2];
56int dodns = 1;
57int dologging;
58int verbose;
59
60void usage(void);
61void getpeerinfo(struct icb_session *);
62void icbd_accept(int, short, void *);
63void icbd_paused(int, short, void *);
64void icbd_drop(struct icb_session *, char *);
65void icbd_ioerr(struct bufferevent *, short, void *);
66void icbd_dispatch(struct bufferevent *, void *);
67void icbd_log(struct icb_session *, int, const char *, ...);
68void icbd_restrict(void);
69void icbd_send(struct icb_session *, char *, ssize_t);
70
71struct icbd_listener {
72 struct event ev, pause;
73};
74
75int
76main(int argc, char *argv[])
77{
78 const char *cause = NULL;
79 int ch, nsocks = 0, save_errno = 0;
80 int inet4 = 0, inet6 = 0;
81 char group[ICB_MAXGRPLEN], *grplist = NULL;
82 char *ptr = NULL;
83
84 /* init group lists before calling icb_addgroup */
85 icb_init();
86
87 while ((ch = getopt(argc, argv, "46CdG:M:nL:S:v")) != -1)
88 switch (ch) {
89 case '4':
90 inet4++;
91 break;
92 case '6':
93 inet6++;
94 break;
95 case 'C':
96 creategroups++;
97 break;
98 case 'd':
99 foreground++;
100 break;
101 case 'G':
102 grplist = optarg;
103 break;
104 case 'L':
105 strlcpy(logprefix, optarg, sizeof logprefix);
106 dologging++;
107 break;
108 case 'M':
109 strlcpy(modtabpath, optarg, sizeof modtabpath);
110 break;
111 case 'n':
112 dodns = 0;
113 break;
114 case 'S':
115 strlcpy(srvname, optarg, sizeof srvname);
116 break;
117 case 'v':
118 verbose++;
119 break;
120 default:
121 usage();
122 /* NOTREACHED */
123 }
124 argc -= optind;
125 argv += optind;
126
127 /* add group "1" as it's a login group for most of the clients */
128 if (icb_addgroup(NULL, "1") == NULL)
129 err(EX_UNAVAILABLE, NULL);
130
131 if (grplist) {
132 while (icb_token(grplist, strlen(grplist), &ptr, group,
133 ICB_MAXGRPLEN, ',', 0) > 0)
134 if (icb_addgroup(NULL, group) == NULL)
135 err(EX_UNAVAILABLE, NULL);
136 }
137
138 if (argc == 0)
139 argc++;
140
141 if (inet4 && inet6)
142 errx(EX_USAGE, "Can't specify both -4 and -6");
143
144 tzset();
145 (void)setlocale(LC_ALL, "C");
146
147 if (foreground)
148 openlog("icbd", LOG_PID | LOG_PERROR, LOG_DAEMON);
149 else
150 openlog("icbd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
151
152 if (!foreground && daemon(0, 0) < 0)
153 err(EX_OSERR, NULL);
154
155 (void)event_init();
156
157 for (ch = 0; ch < argc; ch++) {
158 struct addrinfo hints, *res, *res0;
159 struct icbd_listener *l;
160 char *addr, *port;
161 int error, s, on = 1;
162
163 addr = port = NULL;
164 if (argv[ch] != NULL) {
165 if (argv[ch][0] != ':')
166 addr = argv[ch];
167 if ((port = strrchr(argv[ch], ':')) != NULL)
168 *port++ = '\0';
169 }
170
171 bzero(&hints, sizeof hints);
172 if (inet4 || inet6)
173 hints.ai_family = inet4 ? PF_INET : PF_INET6;
174 else
175 hints.ai_family = PF_UNSPEC;
176 hints.ai_socktype = SOCK_STREAM;
177 hints.ai_flags = AI_PASSIVE;
178 if ((error = getaddrinfo(addr, port ? port : "icb", &hints,
179 &res0)) != 0) {
180 syslog(LOG_ERR, "%s", gai_strerror(error));
181 return (EX_UNAVAILABLE);
182 }
183
184 for (res = res0; res != NULL; res = res->ai_next) {
185 if ((s = socket(res->ai_family, res->ai_socktype,
186 res->ai_protocol)) < 0) {
187 cause = "socket";
188 save_errno = errno;
189 continue;
190 }
191
192 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on,
193 sizeof on) < 0) {
194 cause = "SO_REUSEADDR";
195 save_errno = errno;
196 (void)close(s);
197 continue;
198 }
199
200 if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
201 cause = "bind";
202 save_errno = errno;
203 (void)close(s);
204 continue;
205 }
206
207 (void)listen(s, TCP_BACKLOG);
208
209 if ((l = calloc(1, sizeof *l)) == NULL)
210 err(EX_UNAVAILABLE, NULL);
211 event_set(&l->ev, s, EV_READ | EV_PERSIST,
212 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 /* initialize resolver */
235 res_init();
236
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(isprint(is->buffer[i]) ? "%c" :
389 "\\x%02x", (unsigned char)is->buffer[i]);
390 printf("\n");
391 }
392#endif
393 /* see you next time around */
394 if (is->rlen < is->length)
395 return;
396 /* null-terminate the data */
397 is->buffer[MIN(is->rlen, ICB_MSGSIZE - 1)] = '\0';
398 /* process the message in full */
399 if (icb_input(is))
400 return;
401 /* cleanup the input buffer */
402 memset(is->buffer, 0, ICB_MSGSIZE);
403 is->rlen = is->length = 0;
404 }
405}
406
407void
408icbd_send(struct icb_session *is, char *buf, ssize_t size)
409{
410 if (bufferevent_write(is->bev, buf, size) == -1)
411 syslog(LOG_ERR, "bufferevent_write: %m");
412#ifdef DEBUG
413 {
414 int i;
415
416 printf("-> wrote %lu to %s:%d:\n", size, is->host, is->port);
417 for (i = 0; i < size; i++)
418 printf(isprint(buf[i]) ? "%c" : "\\x%02x",
419 (unsigned char)buf[i]);
420 printf("\n");
421 }
422#endif
423}
424
425void
426icbd_drop(struct icb_session *is, char *reason)
427{
428 if (reason) {
429 icb_remove(is, reason);
430 icbd_log(is, LOG_DEBUG, reason);
431 } else
432 icb_remove(is, NULL);
433
434 /* cleanup the input buffer */
435 memset(is->buffer, 0, ICB_MSGSIZE);
436 is->rlen = is->length = 0;
437
438 (void)close(EVBUFFER_FD(is->bev));
439 bufferevent_free(is->bev);
440 if (!ISSETF(is->flags, ICB_SF_DNSINPROGRESS))
441 free(is);
442 else
443 SETF(is->flags, ICB_SF_PENDINGDROP);
444}
445
446void
447icbd_log(struct icb_session *is, int level, const char *fmt, ...)
448{
449 char buf[512];
450 va_list ap;
451
452 if (!verbose && level == LOG_DEBUG)
453 return;
454
455 va_start(ap, fmt);
456 (void)vsnprintf(buf, sizeof buf, fmt, ap);
457 va_end(ap);
458 if (is)
459 syslog(level, "%s:%u: %s", is->host, is->port, buf);
460 else
461 syslog(level, "%s", buf);
462}
463
464void
465icbd_restrict(void)
466{
467 struct stat sb;
468 struct passwd *pw;
469
470 if ((pw = getpwnam(ICBD_USER)) == NULL) {
471 syslog(LOG_ERR, "No passwd entry for %s", ICBD_USER);
472 exit(EX_NOUSER);
473 }
474
475 if (setusercontext(NULL, pw, pw->pw_uid,
476 LOGIN_SETALL & ~LOGIN_SETUSER) < 0)
477 exit(EX_NOPERM);
478
479 if (stat(pw->pw_dir, &sb) == -1) {
480 syslog(LOG_ERR, "%s: %m", pw->pw_name);
481 exit(EX_NOPERM);
482 }
483
484 if (sb.st_uid != 0 || (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
485 syslog(LOG_ERR, "bad directory permissions");
486 exit(EX_NOPERM);
487 }
488
489 if (chroot(pw->pw_dir) < 0) {
490 syslog(LOG_ERR, "%s: %m", pw->pw_dir);
491 exit(EX_UNAVAILABLE);
492 }
493
494 if (chdir("/") < 0) {
495 syslog(LOG_ERR, "/" ICBD_HOME ": %m");
496 exit(EX_UNAVAILABLE);
497 }
498
499 chdir(ICBD_HOME);
500
501 if (setuid(pw->pw_uid) < 0) {
502 syslog(LOG_ERR, "%d: %m", pw->pw_uid);
503 exit(EX_NOPERM);
504 }
505
506 if (dodns) {
507 if (pledge("stdio inet rpath dns", NULL) == -1) {
508 syslog(LOG_ERR, "pledge");
509 exit(EX_NOPERM);
510 }
511 } else {
512 if (pledge("stdio inet rpath", NULL) == -1) {
513 syslog(LOG_ERR, "pledge");
514 exit(EX_NOPERM);
515 }
516 }
517
518 (void)setproctitle("icbd");
519}
520
521void
522icbd_modupdate(void)
523{
524 struct stat st;
525 FILE *fp;
526 char *buf, *lbuf;
527 size_t len;
528
529 if (strlen(modtabpath) == 0)
530 return;
531 if (stat(modtabpath, &st)) {
532 syslog(LOG_ERR, "stat %s: %m", modtabpath);
533 return;
534 }
535 /* see if there are any changes */
536 if (timespeccmp(&st.st_mtim, &modtabst.st_mtim, ==) ||
537 st.st_size == 0)
538 return;
539
540 if ((fp = fopen(modtabpath, "r")) == NULL) {
541 syslog(LOG_ERR, "open %s: %m", modtabpath);
542 return;
543 }
544
545 modtabcnt = 0;
546 bzero(modtab, ICB_MTABLEN * ICB_MAXNICKLEN);
547 lbuf = NULL;
548 while ((buf = fgetln(fp, &len)) && modtabcnt < ICB_MTABLEN) {
549 if (buf[len - 1] == '\n')
550 buf[len - 1] = '\0';
551 else {
552 /* EOF without EOL, copy and add the NUL */
553 if ((lbuf = malloc(len + 1)) == NULL)
554 err(1, NULL);
555 memcpy(lbuf, buf, len);
556 lbuf[len] = '\0';
557 buf = lbuf;
558 }
559 while (buf[0] == ' ' || buf[0] == '\t')
560 buf++;
561 if (buf[0] == '#' || buf[0] == '\0')
562 continue;
563 strlcpy(modtab[modtabcnt++], buf, ICB_MAXNICKLEN);
564 }
565 free(lbuf);
566
567 qsort(modtab, modtabcnt, ICB_MAXNICKLEN,
568 (int (*)(const void *, const void *))strcmp);
569
570 fclose(fp);
571
572 memcpy(&modtabst, &st, sizeof modtabst);
573}
574
575time_t
576getmonotime(void)
577{
578 struct timespec ts;
579
580 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
581 syslog(LOG_ERR, "%m");
582 exit(EX_OSERR);
583 }
584 return (ts.tv_sec);
585}
586
587void
588getpeerinfo(struct icb_session *is)
589{
590 struct sockaddr_in *sin = (struct sockaddr_in *)&is->ss;
591 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&is->ss;
592 socklen_t ss_len = sizeof is->ss;
593
594 bzero(&is->ss, sizeof is->ss);
595 if (getpeername(EVBUFFER_FD(is->bev), (struct sockaddr *)&is->ss,
596 &ss_len) != 0)
597 return;
598
599 is->port = 0;
600 switch (is->ss.ss_family) {
601 case AF_INET:
602 is->port = ntohs(sin->sin_port);
603 break;
604
605 case AF_INET6:
606 is->port = ntohs(sin6->sin6_port);
607 break;
608 }
609
610 inet_ntop(is->ss.ss_family, is->ss.ss_family == AF_INET ?
611 (void *)&sin->sin_addr : (void *)&sin6->sin6_addr,
612 is->host, sizeof is->host);
613
614 dns_resolve(is);
615}
Note: See TracBrowser for help on using the repository browser.