source: code/icbd.c@ e80f9fc

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

Remove the session tree

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