source: code/icbd.c@ c9402c3

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

Rework bufferevent read code

  • 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 a dns resolver thread */
215 dns_init();
216
217 if (!foreground)
218 icbd_restrict();
219
220 (void)signal(SIGPIPE, SIG_IGN);
221
222 (void)event_dispatch();
223
224 syslog(LOG_ERR, "event_dispatch: %m");
225
226 return (EX_UNAVAILABLE);
227}
228
229static inline int
230icbd_session_cmp(struct icb_session *a, struct icb_session *b)
231{
232 if (a->id > b->id)
233 return (1);
234 if (a->id < b->id)
235 return (-1);
236 return (0);
237}
238
239inline struct icb_session *
240icbd_session_lookup(uint64_t sid)
241{
242 struct icb_session key;
243
244 key.id = sid;
245 return (RB_FIND(icbd_sessions, &icbd_sessions, &key));
246}
247
248void
249icbd_accept(int fd, short event __attribute__((__unused__)),
250 void *arg __attribute__((__unused__)))
251{
252 struct sockaddr_storage ss;
253 struct icb_session *is;
254 socklen_t ss_len = sizeof ss;
255 int s, on = 1, tos = IPTOS_LOWDELAY;
256
257 ss.ss_len = ss_len;
258 if ((s = accept(fd, (struct sockaddr *)&ss, &ss_len)) < 0) {
259 syslog(LOG_ERR, "accept: %m");
260 return;
261 }
262 if (ss.ss_family == AF_INET)
263 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof tos) < 0)
264 syslog(LOG_WARNING, "IP_TOS: %m");
265 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof on) < 0)
266 syslog(LOG_WARNING, "SO_KEEPALIVE: %m");
267 if ((is = calloc(1, sizeof *is)) == NULL) {
268 syslog(LOG_ERR, "calloc: %m");
269 (void)close(s);
270 return;
271 }
272 if ((is->bev = bufferevent_new(s, icbd_dispatch, NULL, icbd_ioerr,
273 is)) == NULL) {
274 syslog(LOG_ERR, "bufferevent_new: %m");
275 (void)close(s);
276 free(is);
277 return;
278 }
279 if (bufferevent_enable(is->bev, EV_READ)) {
280 syslog(LOG_ERR, "bufferevent_enable: %m");
281 (void)close(s);
282 bufferevent_free(is->bev);
283 free(is);
284 return;
285 }
286
287 is->id = sessionid++;
288 RB_INSERT(icbd_sessions, &icbd_sessions, is);
289
290 /* save host information */
291 getpeerinfo(is);
292
293 /* start icb conversation */
294 icb_start(is);
295}
296
297__dead void
298usage(void)
299{
300 (void)fprintf(stderr, "usage: %s [-46Cdv] [-G group1[,group2,...]] "
301 "[-M modtab]\n\t[-S name] [[addr][:port] ...]\n", __progname);
302 exit(EX_USAGE);
303}
304
305/*
306 * bufferevent functions
307 */
308
309void
310icbd_dispatch(struct bufferevent *bev, void *arg)
311{
312 struct icb_session *is = (struct icb_session *)arg;
313
314 while (EVBUFFER_LENGTH(EVBUFFER_INPUT(bev)) > 0) {
315 if (is->length == 0) {
316 /* read length */
317 is->rlen = bufferevent_read(bev, is->buffer, 1);
318 is->length = (size_t)(unsigned char)is->buffer[0];
319 if (is->length == 0) {
320 icbd_drop(is, "invalid packet");
321 return;
322 }
323 }
324 /* read as much as we can */
325 is->rlen += bufferevent_read(bev, &is->buffer[is->rlen],
326 is->length);
327#ifdef DEBUG
328 {
329 int i;
330
331 printf("-> read %lu out of %lu from %s:%d:\n",
332 is->rlen, is->length, is->host, is->port);
333 for (i = 0; i < (int)is->rlen; i++)
334 printf(" %02x", (unsigned char)is->buffer[i]);
335 printf("\n");
336 }
337#endif
338 /* see you next time around */
339 if (is->rlen < is->length)
340 return;
341 /* process the message in full */
342 icb_input(is);
343 is->rlen = is->length = 0;
344 }
345}
346
347void
348icbd_write(struct icb_session *is, char *buf, ssize_t size)
349{
350 if (bufferevent_write(is->bev, buf, size) == -1)
351 syslog(LOG_ERR, "bufferevent_write: %m");
352#ifdef DEBUG
353 {
354 int i;
355
356 printf("-> wrote %lu to %s:%d:\n", size, is->host, is->port);
357 for (i = 0; i < size; i++)
358 printf(" %02x", (unsigned char)buf[i]);
359 printf("\n");
360 }
361#endif
362}
363
364void
365icbd_drop(struct icb_session *is, char *reason)
366{
367 if (reason) {
368 icb_remove(is, reason);
369 icbd_log(is, LOG_DEBUG, reason);
370 } else
371 icb_remove(is, NULL);
372 (void)evbuffer_write(EVBUFFER_OUTPUT(is->bev), EVBUFFER_FD(is->bev));
373 (void)close(EVBUFFER_FD(is->bev));
374 bufferevent_free(is->bev);
375 RB_REMOVE(icbd_sessions, &icbd_sessions, is);
376 free(is);
377}
378
379void
380icbd_ioerr(struct bufferevent *bev __attribute__((__unused__)), short what,
381 void *arg)
382{
383 struct icb_session *is = (struct icb_session *)arg;
384
385 if (what & EVBUFFER_TIMEOUT)
386 icbd_drop(is, "timeout");
387 else if (what & EVBUFFER_EOF)
388 icbd_drop(is, NULL);
389 else if (what & EVBUFFER_ERROR)
390 icbd_drop(is, (what & EVBUFFER_READ) ? "read error" :
391 "write error");
392}
393
394void
395icbd_log(struct icb_session *is, int level, const char *fmt, ...)
396{
397 char buf[512];
398 va_list ap;
399
400 if (!verbose && level == LOG_DEBUG)
401 return;
402
403 va_start(ap, fmt);
404 (void)vsnprintf(buf, sizeof buf, fmt, ap);
405 va_end(ap);
406 if (is)
407 syslog(level, "%s:%u: %s", is->host, is->port, buf);
408 else
409 syslog(level, "%s", buf);
410}
411
412void
413icbd_restrict(void)
414{
415 struct stat sb;
416 struct passwd *pw;
417
418 if ((pw = getpwnam(ICBD_USER)) == NULL) {
419 syslog(LOG_ERR, "No passwd entry for %s", ICBD_USER);
420 exit(EX_NOUSER);
421 }
422
423 if (setusercontext(NULL, pw, pw->pw_uid,
424 LOGIN_SETALL & ~LOGIN_SETUSER) < 0)
425 exit(EX_NOPERM);
426
427 if (stat(pw->pw_dir, &sb) == -1) {
428 syslog(LOG_ERR, "%s: %m", pw->pw_name);
429 exit(EX_NOPERM);
430 }
431
432 if (sb.st_uid != 0 || (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
433 syslog(LOG_ERR, "bad directory permissions");
434 exit(EX_NOPERM);
435 }
436
437 if (chroot(pw->pw_dir) < 0) {
438 syslog(LOG_ERR, "%s: %m", pw->pw_dir);
439 exit(EX_UNAVAILABLE);
440 }
441
442 if (setuid(pw->pw_uid) < 0) {
443 syslog(LOG_ERR, "%d: %m", pw->pw_uid);
444 exit(EX_NOPERM);
445 }
446
447 if (chdir("/") < 0) {
448 syslog(LOG_ERR, "/: %m");
449 exit(EX_UNAVAILABLE);
450 }
451
452 (void)setproctitle("icbd");
453}
454
455void
456icbd_grplist(char *list)
457{
458 char *s, *s1, *s2;
459 int last = 0;
460
461 if (!list || strlen(list) == 0)
462 return;
463
464 /* "group1[:pass1][,group2[:pass2],...]" */
465 s = list;
466 s1 = s2 = NULL;
467 while (!last && s) {
468 if ((s1 = strchr(s, ',')) != NULL)
469 *s1 = '\0';
470 else {
471 last = 1;
472 s1 = s;
473 }
474 if ((s2 = strchr(s, ':')) != NULL)
475 *s2 = '\0';
476 if (icb_addgroup(NULL, s, s2 ? ++s2 : NULL) == NULL)
477 err(EX_UNAVAILABLE, NULL);
478 s = ++s1;
479 s1 = s2 = NULL;
480 }
481}
482
483void
484icbd_modtab(char *mtab)
485{
486 FILE *fp;
487 char *buf, *lbuf;
488 size_t len;
489
490 if ((fp = fopen(mtab, "r")) == NULL)
491 err(EX_NOINPUT, "%s", mtab);
492
493 bzero(modtab, ICB_MTABLEN * ICB_MAXNICKLEN);
494 lbuf = NULL;
495 while ((buf = fgetln(fp, &len)) && modtabcnt < ICB_MTABLEN) {
496 if (buf[len - 1] == '\n')
497 buf[len - 1] = '\0';
498 else {
499 /* EOF without EOL, copy and add the NUL */
500 if ((lbuf = malloc(len + 1)) == NULL)
501 err(1, NULL);
502 memcpy(lbuf, buf, len);
503 lbuf[len] = '\0';
504 buf = lbuf;
505 }
506 while (buf[0] == ' ' || buf[0] == '\t')
507 buf++;
508 if (buf[0] == '#' || buf[0] == '\0')
509 continue;
510 strlcpy(modtab[modtabcnt++], buf, ICB_MAXNICKLEN);
511 }
512 free(lbuf);
513
514 qsort(modtab, modtabcnt, ICB_MAXNICKLEN,
515 (int (*)(const void *, const void *))strcmp);
516
517 fclose(fp);
518}
519
520time_t
521getmonotime(void)
522{
523 struct timespec ts;
524
525 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
526 syslog(LOG_ERR, "%m");
527 exit(EX_OSERR);
528 }
529 return (ts.tv_sec);
530}
531
532void
533getpeerinfo(struct icb_session *is)
534{
535 struct sockaddr_storage ss;
536 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
537 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
538 socklen_t ss_len = sizeof ss;
539
540 bzero(&ss, sizeof ss);
541 if (getpeername(EVBUFFER_FD(is->bev), (struct sockaddr *)&ss,
542 &ss_len) != 0)
543 return;
544
545 is->port = 0;
546 switch (ss.ss_family) {
547 case AF_INET:
548 is->port = ntohs(sin->sin_port);
549 break;
550
551 case AF_INET6:
552 is->port = ntohs(sin6->sin6_port);
553 break;
554 }
555
556 inet_ntop(ss.ss_family, ss.ss_family == AF_INET ?
557 (void *)&sin->sin_addr : (void *)&sin6->sin6_addr,
558 is->host, sizeof is->host);
559
560 dns_rresolv(is, &ss);
561}
Note: See TracBrowser for help on using the repository browser.