source: code/icbd.c@ 82d3c1f

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

stat(2) the modtab every time pass is requested

plus some minor style changes

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