source: code/icbd.c@ b28dd0e

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

Add some basic logger framework

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