ii

irc it, simple FIFO based irc client
git clone git://git.suckless.org/ii
Log | Files | Refs | README | LICENSE

ii.c (20027B)


      1 /* See LICENSE file for license details. */
      2 #include <sys/select.h>
      3 #include <sys/socket.h>
      4 #include <sys/stat.h>
      5 #include <sys/types.h>
      6 #include <sys/un.h>
      7 
      8 #include <ctype.h>
      9 #include <errno.h>
     10 #include <fcntl.h>
     11 #include <limits.h>
     12 #include <netdb.h>
     13 #include <netinet/in.h>
     14 #include <pwd.h>
     15 #include <signal.h>
     16 #include <stdarg.h>
     17 #include <stdio.h>
     18 #include <stdlib.h>
     19 #include <string.h>
     20 #include <time.h>
     21 #include <unistd.h>
     22 
     23 char *argv0;
     24 
     25 #include "arg.h"
     26 
     27 #ifdef NEED_STRLCPY
     28 size_t strlcpy(char *, const char *, size_t);
     29 #endif /* NEED_STRLCPY */
     30 
     31 #define IRC_CHANNEL_MAX   200
     32 #define IRC_MSG_MAX       512 /* guaranteed to be <= than PIPE_BUF */
     33 #define PING_TIMEOUT      300
     34 
     35 enum { TOK_NICKSRV = 0, TOK_USER, TOK_CMD, TOK_CHAN, TOK_ARG, TOK_TEXT, TOK_LAST };
     36 
     37 typedef struct Channel Channel;
     38 struct Channel {
     39 	int fdin;
     40 	char name[IRC_CHANNEL_MAX]; /* channel name (normalized) */
     41 	char inpath[PATH_MAX];      /* input path */
     42 	char outpath[PATH_MAX];     /* output path */
     43 	Channel *next;
     44 };
     45 
     46 static Channel * channel_add(const char *);
     47 static Channel * channel_find(const char *);
     48 static Channel * channel_join(const char *);
     49 static void      channel_leave(Channel *);
     50 static Channel * channel_new(const char *);
     51 static void      channel_normalize_name(char *);
     52 static void      channel_normalize_path(char *);
     53 static int       channel_open(Channel *);
     54 static void      channel_print(Channel *, const char *);
     55 static int       channel_reopen(Channel *);
     56 static void      channel_rm(Channel *);
     57 static void      create_dirtree(const char *);
     58 static void      create_filepath(char *, size_t, const char *, const char *, const char *);
     59 static void      ewritestr(int, const char *);
     60 static void      handle_channels_input(int, Channel *);
     61 static void      handle_server_output(int);
     62 static int       isnumeric(const char *);
     63 static void      loginkey(int, const char *);
     64 static void      loginuser(int, const char *, const char *);
     65 static void      proc_channels_input(int, Channel *, char *);
     66 static void      proc_channels_privmsg(int, Channel *, char *);
     67 static void      proc_server_cmd(int, char *);
     68 static int       read_line(int, char *, size_t);
     69 static void      run(int, const char *);
     70 static void      setup(void);
     71 static void      sighandler(int);
     72 static int       tcpopen(const char *, const char *);
     73 static size_t    tokenize(char **, size_t, char *, int);
     74 static int       udsopen(const char *);
     75 static void      usage(void);
     76 
     77 static int      isrunning = 1;
     78 static time_t   last_response = 0;
     79 static Channel *channels = NULL;
     80 static Channel *channelmaster = NULL;
     81 static char     nick[32];          /* active nickname at runtime */
     82 static char     _nick[32];         /* nickname at startup */
     83 static char     ircpath[PATH_MAX]; /* irc dir (-i) */
     84 static char     msg[IRC_MSG_MAX];  /* message buf used for communication */
     85 
     86 static void
     87 usage(void)
     88 {
     89 	fprintf(stderr, "usage: %s <-s host> [-i <irc dir>] [-p <port>] "
     90 	        "[-u <sockname>] [-n <nick>] [-k <password>] "
     91 	        "[-f <fullname>]\n", argv0);
     92 	exit(1);
     93 }
     94 
     95 static void
     96 ewritestr(int fd, const char *s)
     97 {
     98 	size_t len, off = 0;
     99 	int w = -1;
    100 
    101 	len = strlen(s);
    102 	for (off = 0; off < len; off += w) {
    103 		if ((w = write(fd, s + off, len - off)) == -1)
    104 			break;
    105 	}
    106 	if (w == -1) {
    107 		fprintf(stderr, "%s: write: %s\n", argv0, strerror(errno));
    108 		exit(1);
    109 	}
    110 }
    111 
    112 /* creates directories bottom-up, if necessary */
    113 static void
    114 create_dirtree(const char *dir)
    115 {
    116 	char tmp[PATH_MAX], *p;
    117 	struct stat st;
    118 	size_t len;
    119 
    120 	strlcpy(tmp, dir, sizeof(tmp));
    121 	len = strlen(tmp);
    122 	if (len > 0 && tmp[len - 1] == '/')
    123 		tmp[len - 1] = '\0';
    124 
    125 	if ((stat(tmp, &st) != -1) && S_ISDIR(st.st_mode))
    126 		return; /* dir exists */
    127 
    128 	for (p = tmp + 1; *p; p++) {
    129 		if (*p != '/')
    130 			continue;
    131 		*p = '\0';
    132 		mkdir(tmp, S_IRWXU);
    133 		*p = '/';
    134 	}
    135 	mkdir(tmp, S_IRWXU);
    136 }
    137 
    138 static void
    139 channel_normalize_path(char *s)
    140 {
    141 	for (; *s; s++) {
    142 		if (isalpha((unsigned char)*s))
    143 			*s = tolower((unsigned char)*s);
    144 		else if (!isdigit((unsigned char)*s) && !strchr(".#&+!-", *s))
    145 			*s = '_';
    146 	}
    147 }
    148 
    149 static void
    150 channel_normalize_name(char *s)
    151 {
    152 	char *p;
    153 
    154 	while (*s == '&' || *s == '#')
    155 		s++;
    156 	for (p = s; *s; s++) {
    157 		if (!strchr(" ,&#\x07", *s)) {
    158 			*p = *s;
    159 			p++;
    160 		}
    161 	}
    162 	*p = '\0';
    163 }
    164 
    165 static void
    166 create_filepath(char *filepath, size_t len, const char *path,
    167 	const char *channel, const char *suffix)
    168 {
    169 	int r;
    170 
    171 	if (channel[0]) {
    172 		r = snprintf(filepath, len, "%s/%s", path, channel);
    173 		if (r < 0 || (size_t)r >= len)
    174 			goto error;
    175 		create_dirtree(filepath);
    176 		r = snprintf(filepath, len, "%s/%s/%s", path, channel, suffix);
    177 		if (r < 0 || (size_t)r >= len)
    178 			goto error;
    179 	} else {
    180 		r = snprintf(filepath, len, "%s/%s", path, suffix);
    181 		if (r < 0 || (size_t)r >= len)
    182 			goto error;
    183 	}
    184 	return;
    185 
    186 error:
    187 	fprintf(stderr, "%s: path to irc directory too long\n", argv0);
    188 	exit(1);
    189 }
    190 
    191 static int
    192 channel_open(Channel *c)
    193 {
    194 	int fd;
    195 	struct stat st;
    196 
    197 	/* make "in" fifo if it doesn't exist already. */
    198 	if (lstat(c->inpath, &st) != -1) {
    199 		if (!(st.st_mode & S_IFIFO))
    200 			return -1;
    201 	} else if (mkfifo(c->inpath, S_IRWXU)) {
    202 		return -1;
    203 	}
    204 	c->fdin = -1;
    205 	fd = open(c->inpath, O_RDONLY | O_NONBLOCK, 0);
    206 	if (fd == -1)
    207 		return -1;
    208 	c->fdin = fd;
    209 
    210 	return 0;
    211 }
    212 
    213 static int
    214 channel_reopen(Channel *c)
    215 {
    216 	if (c->fdin > 2) {
    217 		close(c->fdin);
    218 		c->fdin = -1;
    219 	}
    220 	return channel_open(c);
    221 }
    222 
    223 static Channel *
    224 channel_new(const char *name)
    225 {
    226 	Channel *c;
    227 	char channelpath[PATH_MAX];
    228 
    229 	strlcpy(channelpath, name, sizeof(channelpath));
    230 	channel_normalize_path(channelpath);
    231 
    232 	if (!(c = calloc(1, sizeof(Channel)))) {
    233 		fprintf(stderr, "%s: calloc: %s\n", argv0, strerror(errno));
    234 		exit(1);
    235 	}
    236 
    237 	strlcpy(c->name, name, sizeof(c->name));
    238 	channel_normalize_name(c->name);
    239 
    240 	create_filepath(c->inpath, sizeof(c->inpath), ircpath,
    241 	                channelpath, "in");
    242 	create_filepath(c->outpath, sizeof(c->outpath), ircpath,
    243 	                channelpath, "out");
    244 	return c;
    245 }
    246 
    247 static Channel *
    248 channel_find(const char *name)
    249 {
    250 	Channel *c;
    251 	char chan[IRC_CHANNEL_MAX];
    252 
    253 	strlcpy(chan, name, sizeof(chan));
    254 	channel_normalize_name(chan);
    255 	for (c = channels; c; c = c->next) {
    256 		if (!strcmp(chan, c->name))
    257 			return c; /* already handled */
    258 	}
    259 	return NULL;
    260 }
    261 
    262 static Channel *
    263 channel_add(const char *name)
    264 {
    265 	Channel *c;
    266 
    267 	c = channel_new(name);
    268 	if (channel_open(c) == -1) {
    269 		fprintf(stderr, "%s: cannot create channel: %s: %s\n",
    270 		         argv0, name, strerror(errno));
    271 		free(c);
    272 		return NULL;
    273 	}
    274 	if (!channels) {
    275 		channels = c;
    276 	} else {
    277 		c->next = channels;
    278 		channels = c;
    279 	}
    280 	return c;
    281 }
    282 
    283 static Channel *
    284 channel_join(const char *name)
    285 {
    286 	Channel *c;
    287 
    288 	if (!(c = channel_find(name)))
    289 		c = channel_add(name);
    290 	return c;
    291 }
    292 
    293 static void
    294 channel_rm(Channel *c)
    295 {
    296 	Channel *p;
    297 
    298 	if (channels == c) {
    299 		channels = channels->next;
    300 	} else {
    301 		for (p = channels; p && p->next != c; p = p->next)
    302 			;
    303 		if (p && p->next == c)
    304 			p->next = c->next;
    305 	}
    306 	free(c);
    307 }
    308 
    309 static void
    310 channel_leave(Channel *c)
    311 {
    312 	if (c->fdin > 2) {
    313 		close(c->fdin);
    314 		c->fdin = -1;
    315 	}
    316 	/* remove "in" file on leaving the channel */
    317 	unlink(c->inpath);
    318 	channel_rm(c);
    319 }
    320 
    321 static void
    322 loginkey(int ircfd, const char *key)
    323 {
    324 	snprintf(msg, sizeof(msg), "PASS %s\r\n", key);
    325 	ewritestr(ircfd, msg);
    326 }
    327 
    328 static void
    329 loginuser(int ircfd, const char *host, const char *fullname)
    330 {
    331 	snprintf(msg, sizeof(msg), "NICK %s\r\nUSER %s localhost %s :%s\r\n",
    332 	         nick, nick, host, fullname);
    333 	puts(msg);
    334 	ewritestr(ircfd, msg);
    335 }
    336 
    337 static int
    338 udsopen(const char *uds)
    339 {
    340 	struct sockaddr_un sun;
    341 	size_t len;
    342 	int fd;
    343 
    344 	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
    345 		fprintf(stderr, "%s: socket: %s\n", argv0, strerror(errno));
    346 		exit(1);
    347 	}
    348 
    349 	sun.sun_family = AF_UNIX;
    350 	if (strlcpy(sun.sun_path, uds, sizeof(sun.sun_path)) >= sizeof(sun.sun_path)) {
    351 		fprintf(stderr, "%s: UNIX domain socket path truncation\n", argv0);
    352 		exit(1);
    353 	}
    354 	len = strlen(sun.sun_path) + 1 + sizeof(sun.sun_family);
    355 	if (connect(fd, (struct sockaddr *)&sun, len) == -1) {
    356 		fprintf(stderr, "%s: connect: %s\n", argv0, strerror(errno));
    357 		exit(1);
    358 	}
    359 	return fd;
    360 }
    361 
    362 static int
    363 tcpopen(const char *host, const char *service)
    364 {
    365 	struct addrinfo hints, *res = NULL, *rp;
    366 	int fd = -1, e;
    367 
    368 	memset(&hints, 0, sizeof(hints));
    369 	hints.ai_family = AF_UNSPEC; /* allow IPv4 or IPv6 */
    370 	hints.ai_flags = AI_NUMERICSERV; /* avoid name lookup for port */
    371 	hints.ai_socktype = SOCK_STREAM;
    372 
    373 	if ((e = getaddrinfo(host, service, &hints, &res))) {
    374 		fprintf(stderr, "%s: getaddrinfo: %s\n", argv0, gai_strerror(e));
    375 		exit(1);
    376 	}
    377 
    378 	for (rp = res; rp; rp = rp->ai_next) {
    379 		fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
    380 		if (fd == -1)
    381 			continue;
    382 		if (connect(fd, rp->ai_addr, rp->ai_addrlen) == -1) {
    383 			close(fd);
    384 			fd = -1;
    385 			continue;
    386 		}
    387 		break; /* success */
    388 	}
    389 	if (fd == -1) {
    390 		fprintf(stderr, "%s: could not connect to %s:%s: %s\n",
    391 			argv0, host, service, strerror(errno));
    392 		exit(1);
    393 	}
    394 
    395 	freeaddrinfo(res);
    396 	return fd;
    397 }
    398 
    399 static int
    400 isnumeric(const char *s)
    401 {
    402 	errno = 0;
    403 	strtol(s, NULL, 10);
    404 	return errno == 0;
    405 }
    406 
    407 static size_t
    408 tokenize(char **result, size_t reslen, char *str, int delim)
    409 {
    410 	char *p = NULL, *n = NULL;
    411 	size_t i = 0;
    412 
    413 	for (n = str; *n == ' '; n++)
    414 		;
    415 	p = n;
    416 	while (*n != '\0') {
    417 		if (i >= reslen)
    418 			return 0;
    419 		if (i > TOK_CHAN - TOK_CMD && result[0] && isnumeric(result[0]))
    420 			delim = ':'; /* workaround non-RFC compliant messages */
    421 		if (*n == delim) {
    422 			*n = '\0';
    423 			result[i++] = p;
    424 			p = ++n;
    425 		} else {
    426 			n++;
    427 		}
    428 	}
    429 	/* add last entry */
    430 	if (i < reslen && p < n && p && *p)
    431 		result[i++] = p;
    432 	return i; /* number of tokens */
    433 }
    434 
    435 static void
    436 channel_print(Channel *c, const char *buf)
    437 {
    438 	FILE *fp = NULL;
    439 	time_t t = time(NULL);
    440 
    441 	if (!(fp = fopen(c->outpath, "a")))
    442 		return;
    443 	fprintf(fp, "%lu %s\n", (unsigned long)t, buf);
    444 	fclose(fp);
    445 }
    446 
    447 static void
    448 proc_channels_privmsg(int ircfd, Channel *c, char *buf)
    449 {
    450 	snprintf(msg, sizeof(msg), "<%s> %s", nick, buf);
    451 	channel_print(c, msg);
    452 	snprintf(msg, sizeof(msg), "PRIVMSG %s :%s\r\n", c->name, buf);
    453 	ewritestr(ircfd, msg);
    454 }
    455 
    456 static void
    457 proc_channels_input(int ircfd, Channel *c, char *buf)
    458 {
    459 	char *p = NULL;
    460 	size_t buflen;
    461 
    462 	if (buf[0] == '\0')
    463 		return;
    464 	if (buf[0] != '/') {
    465 		proc_channels_privmsg(ircfd, c, buf);
    466 		return;
    467 	}
    468 
    469 	msg[0] = '\0';
    470 	if ((buflen = strlen(buf)) < 2)
    471 		return;
    472 	if (buf[2] == ' ' || buf[2] == '\0') {
    473 		switch (buf[1]) {
    474 		case 'j': /* join */
    475 			if (buflen < 3)
    476 				return;
    477 			if ((p = strchr(&buf[3], ' '))) /* password parameter */
    478 				*p = '\0';
    479 			if ((buf[3] == '#') || (buf[3] == '&') || (buf[3] == '+') ||
    480 				(buf[3] == '!'))
    481 			{
    482 				/* password protected channel */
    483 				if (p)
    484 					snprintf(msg, sizeof(msg), "JOIN %s %s\r\n", &buf[3], p + 1);
    485 				else
    486 					snprintf(msg, sizeof(msg), "JOIN %s\r\n", &buf[3]);
    487 				channel_join(&buf[3]);
    488 			} else if (p) {
    489 				if ((c = channel_join(&buf[3])))
    490 					proc_channels_privmsg(ircfd, c, p + 1);
    491 				return;
    492 			}
    493 			break;
    494 		case 't': /* topic */
    495 			if (buflen >= 3)
    496 				snprintf(msg, sizeof(msg), "TOPIC %s :%s\r\n", c->name, &buf[3]);
    497 			break;
    498 		case 'a': /* away */
    499 			if (buflen >= 3) {
    500 				snprintf(msg, sizeof(msg), "-!- %s is away \"%s\"", nick, &buf[3]);
    501 				channel_print(c, msg);
    502 			}
    503 			if (buflen >= 3)
    504 				snprintf(msg, sizeof(msg), "AWAY :%s\r\n", &buf[3]);
    505 			else
    506 				snprintf(msg, sizeof(msg), "AWAY\r\n");
    507 			break;
    508 		case 'n': /* change nick */
    509 			if (buflen >= 3) {
    510 				strlcpy(_nick, &buf[3], sizeof(_nick));
    511 				snprintf(msg, sizeof(msg), "NICK %s\r\n", &buf[3]);
    512 			}
    513 			break;
    514 		case 'l': /* leave */
    515 			if (c == channelmaster)
    516 				return;
    517 			if (buflen >= 3)
    518 				snprintf(msg, sizeof(msg), "PART %s :%s\r\n", c->name, &buf[3]);
    519 			else
    520 				snprintf(msg, sizeof(msg),
    521 				         "PART %s :leaving\r\n", c->name);
    522 			ewritestr(ircfd, msg);
    523 			channel_leave(c);
    524 			return;
    525 			break;
    526 		case 'q': /* quit */
    527 			if (buflen >= 3)
    528 				snprintf(msg, sizeof(msg), "QUIT :%s\r\n", &buf[3]);
    529 			else
    530 				snprintf(msg, sizeof(msg),
    531 				         "QUIT %s\r\n", "bye");
    532 			ewritestr(ircfd, msg);
    533 			isrunning = 0;
    534 			return;
    535 			break;
    536 		default: /* raw IRC command */
    537 			snprintf(msg, sizeof(msg), "%s\r\n", &buf[1]);
    538 			break;
    539 		}
    540 	} else {
    541 		/* raw IRC command */
    542 		snprintf(msg, sizeof(msg), "%s\r\n", &buf[1]);
    543 	}
    544 	if (msg[0] != '\0')
    545 		ewritestr(ircfd, msg);
    546 }
    547 
    548 static void
    549 proc_server_cmd(int fd, char *buf)
    550 {
    551 	Channel *c;
    552 	const char *channel;
    553 	char *argv[TOK_LAST], *cmd = NULL, *p = NULL;
    554 	unsigned int i;
    555 
    556 	if (!buf || buf[0] == '\0')
    557 		return;
    558 
    559 	/* clear tokens */
    560 	for (i = 0; i < TOK_LAST; i++)
    561 		argv[i] = NULL;
    562 
    563 	/* check prefix */
    564 	if (buf[0] == ':') {
    565 		if (!(p = strchr(buf, ' ')))
    566 			return;
    567 		*p = '\0';
    568 		for (++p; *p == ' '; p++)
    569 			;
    570 		cmd = p;
    571 		argv[TOK_NICKSRV] = &buf[1];
    572 		if ((p = strchr(buf, '!'))) {
    573 			*p = '\0';
    574 			argv[TOK_USER] = ++p;
    575 		}
    576 	} else {
    577 		cmd = buf;
    578 	}
    579 
    580 	/* remove CRLFs */
    581 	for (p = cmd; p && *p != '\0'; p++) {
    582 		if (*p == '\r' || *p == '\n')
    583 			*p = '\0';
    584 	}
    585 
    586 	if ((p = strchr(cmd, ':'))) {
    587 		*p = '\0';
    588 		argv[TOK_TEXT] = ++p;
    589 	}
    590 
    591 	tokenize(&argv[TOK_CMD], TOK_LAST - TOK_CMD, cmd, ' ');
    592 
    593 	if (!argv[TOK_CMD] || !strcmp("PONG", argv[TOK_CMD])) {
    594 		return;
    595 	} else if (!strcmp("PING", argv[TOK_CMD])) {
    596 		snprintf(msg, sizeof(msg), "PONG %s\r\n", argv[TOK_TEXT]);
    597 		ewritestr(fd, msg);
    598 		return;
    599 	} else if (!argv[TOK_NICKSRV] || !argv[TOK_USER]) {
    600 		/* server command */
    601 		snprintf(msg, sizeof(msg), "%s%s",
    602 				argv[TOK_ARG] ? argv[TOK_ARG] : "",
    603 				argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
    604 		channel_print(channelmaster, msg);
    605 		return; /* don't process further */
    606 	} else if (!strcmp("ERROR", argv[TOK_CMD]))
    607 		snprintf(msg, sizeof(msg), "-!- error %s",
    608 				argv[TOK_TEXT] ? argv[TOK_TEXT] : "unknown");
    609 	else if (!strcmp("JOIN", argv[TOK_CMD]) && (argv[TOK_CHAN] || argv[TOK_TEXT])) {
    610 		if (argv[TOK_TEXT])
    611 			argv[TOK_CHAN] = argv[TOK_TEXT];
    612 		snprintf(msg, sizeof(msg), "-!- %s(%s) has joined %s",
    613 				argv[TOK_NICKSRV], argv[TOK_USER], argv[TOK_CHAN]);
    614 	} else if (!strcmp("PART", argv[TOK_CMD]) && argv[TOK_CHAN]) {
    615 		snprintf(msg, sizeof(msg), "-!- %s(%s) has left %s",
    616 				argv[TOK_NICKSRV], argv[TOK_USER], argv[TOK_CHAN]);
    617 		/* if user itself leaves, don't write to channel (don't reopen channel). */
    618 		if (!strcmp(argv[TOK_NICKSRV], nick))
    619 			return;
    620 	} else if (!strcmp("MODE", argv[TOK_CMD])) {
    621 		snprintf(msg, sizeof(msg), "-!- %s changed mode/%s -> %s %s",
    622 				argv[TOK_NICKSRV],
    623 				argv[TOK_CHAN] ? argv[TOK_CHAN] : "",
    624 				argv[TOK_ARG]  ? argv[TOK_ARG] : "",
    625 				argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
    626 	} else if (!strcmp("QUIT", argv[TOK_CMD])) {
    627 		snprintf(msg, sizeof(msg), "-!- %s(%s) has quit \"%s\"",
    628 				argv[TOK_NICKSRV], argv[TOK_USER],
    629 				argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
    630 	} else if (!strncmp("NICK", argv[TOK_CMD], 5) && argv[TOK_TEXT] &&
    631 	          !strcmp(_nick, argv[TOK_TEXT])) {
    632 		strlcpy(nick, _nick, sizeof(nick));
    633 		snprintf(msg, sizeof(msg), "-!- changed nick to \"%s\"", nick);
    634 		channel_print(channelmaster, msg);
    635 	} else if (!strcmp("NICK", argv[TOK_CMD]) && argv[TOK_TEXT]) {
    636 		snprintf(msg, sizeof(msg), "-!- %s changed nick to %s",
    637 				argv[TOK_NICKSRV], argv[TOK_TEXT]);
    638 	} else if (!strcmp("TOPIC", argv[TOK_CMD])) {
    639 		snprintf(msg, sizeof(msg), "-!- %s changed topic to \"%s\"",
    640 				argv[TOK_NICKSRV],
    641 				argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
    642 	} else if (!strcmp("KICK", argv[TOK_CMD]) && argv[TOK_ARG]) {
    643 		snprintf(msg, sizeof(msg), "-!- %s kicked %s (\"%s\")",
    644 				argv[TOK_NICKSRV], argv[TOK_ARG],
    645 				argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
    646 	} else if (!strcmp("NOTICE", argv[TOK_CMD])) {
    647 		snprintf(msg, sizeof(msg), "-!- \"%s\"",
    648 				argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
    649 	} else if (!strcmp("PRIVMSG", argv[TOK_CMD])) {
    650 		snprintf(msg, sizeof(msg), "<%s> %s", argv[TOK_NICKSRV],
    651 				argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
    652 	} else {
    653 		return; /* can't read this message */
    654 	}
    655 	if (argv[TOK_CHAN] && !strcmp(argv[TOK_CHAN], nick))
    656 		channel = argv[TOK_NICKSRV];
    657 	else
    658 		channel = argv[TOK_CHAN];
    659 
    660 	if (!channel || channel[0] == '\0')
    661 		c = channelmaster;
    662 	else
    663 		c = channel_join(channel);
    664 	if (c)
    665 		channel_print(c, msg);
    666 }
    667 
    668 static int
    669 read_line(int fd, char *buf, size_t bufsiz)
    670 {
    671 	size_t i = 0;
    672 	char c = '\0';
    673 
    674 	do {
    675 		if (read(fd, &c, sizeof(char)) != sizeof(char))
    676 			return -1;
    677 		buf[i++] = c;
    678 	} while (c != '\n' && i < bufsiz);
    679 	buf[i - 1] = '\0'; /* eliminates '\n' */
    680 	return 0;
    681 }
    682 
    683 static void
    684 handle_channels_input(int ircfd, Channel *c)
    685 {
    686 	char buf[IRC_MSG_MAX];
    687 
    688 	if (read_line(c->fdin, buf, sizeof(buf)) == -1) {
    689 		if (channel_reopen(c) == -1)
    690 			channel_rm(c);
    691 		return;
    692 	}
    693 	proc_channels_input(ircfd, c, buf);
    694 }
    695 
    696 static void
    697 handle_server_output(int ircfd)
    698 {
    699 	char buf[IRC_MSG_MAX];
    700 
    701 	if (read_line(ircfd, buf, sizeof(buf)) == -1) {
    702 		fprintf(stderr, "%s: remote host closed connection: %s\n",
    703 		        argv0, strerror(errno));
    704 		exit(1);
    705 	}
    706 	fprintf(stdout, "%lu %s\n", (unsigned long)time(NULL), buf);
    707 	fflush(stdout);
    708 	proc_server_cmd(ircfd, buf);
    709 }
    710 
    711 static void
    712 sighandler(int sig)
    713 {
    714 	if (sig == SIGTERM || sig == SIGINT)
    715 		isrunning = 0;
    716 }
    717 
    718 static void
    719 setup(void)
    720 {
    721 	struct sigaction sa;
    722 
    723 	memset(&sa, 0, sizeof(sa));
    724 	sa.sa_handler = sighandler;
    725 	sigaction(SIGTERM, &sa, NULL);
    726 	sigaction(SIGINT, &sa, NULL);
    727 }
    728 
    729 static void
    730 run(int ircfd, const char *host)
    731 {
    732 	Channel *c, *tmp;
    733 	fd_set rdset;
    734 	struct timeval tv;
    735 	char ping_msg[IRC_MSG_MAX];
    736 	int r, maxfd;
    737 
    738 	snprintf(ping_msg, sizeof(ping_msg), "PING %s\r\n", host);
    739 	while (isrunning) {
    740 		maxfd = ircfd;
    741 		FD_ZERO(&rdset);
    742 		FD_SET(ircfd, &rdset);
    743 		for (c = channels; c; c = c->next) {
    744 			if (c->fdin > maxfd)
    745 				maxfd = c->fdin;
    746 			FD_SET(c->fdin, &rdset);
    747 		}
    748 		memset(&tv, 0, sizeof(tv));
    749 		tv.tv_sec = 120;
    750 		r = select(maxfd + 1, &rdset, 0, 0, &tv);
    751 		if (r < 0) {
    752 			if (errno == EINTR)
    753 				continue;
    754 			fprintf(stderr, "%s: select: %s\n", argv0, strerror(errno));
    755 			exit(1);
    756 		} else if (r == 0) {
    757 			if (time(NULL) - last_response >= PING_TIMEOUT) {
    758 				channel_print(channelmaster, "-!- ii shutting down: ping timeout");
    759 				exit(2); /* status code 2 for timeout */
    760 			}
    761 			ewritestr(ircfd, ping_msg);
    762 			continue;
    763 		}
    764 		if (FD_ISSET(ircfd, &rdset)) {
    765 			handle_server_output(ircfd);
    766 			last_response = time(NULL);
    767 		}
    768 		for (c = channels; c; c = tmp) {
    769 			tmp = c->next;
    770 			if (FD_ISSET(c->fdin, &rdset))
    771 				handle_channels_input(ircfd, c);
    772 		}
    773 	}
    774 }
    775 
    776 int
    777 main(int argc, char *argv[])
    778 {
    779 	Channel *c, *tmp;
    780 	struct passwd *spw;
    781 	const char *key = NULL, *fullname = NULL, *host = "";
    782 	const char *uds = NULL, *service = "6667";
    783 	char prefix[PATH_MAX];
    784 	int ircfd, r;
    785 
    786 	/* use nickname and home dir of user by default */
    787 	if (!(spw = getpwuid(getuid()))) {
    788 		fprintf(stderr, "%s: getpwuid: %s\n", argv0, strerror(errno));
    789 		exit(1);
    790 	}
    791 	strlcpy(nick, spw->pw_name, sizeof(nick));
    792 	snprintf(prefix, sizeof(prefix), "%s/irc", spw->pw_dir);
    793 
    794 	ARGBEGIN {
    795 	case 'f':
    796 		fullname = EARGF(usage());
    797 		break;
    798 	case 'i':
    799 		strlcpy(prefix, EARGF(usage()), sizeof(prefix));
    800 		break;
    801 	case 'k':
    802 		key = getenv(EARGF(usage()));
    803 		break;
    804 	case 'n':
    805 		strlcpy(nick, EARGF(usage()), sizeof(nick));
    806 		break;
    807 	case 'p':
    808 		service = EARGF(usage());
    809 		break;
    810 	case 's':
    811 		host = EARGF(usage());
    812 		break;
    813 	case 'u':
    814 		uds = EARGF(usage());
    815 		break;
    816 	default:
    817 		usage();
    818 		break;
    819 	} ARGEND
    820 
    821 	if (!*host)
    822 		usage();
    823 
    824 	if (uds)
    825 		ircfd = udsopen(uds);
    826 	else
    827 		ircfd = tcpopen(host, service);
    828 
    829 #ifdef __OpenBSD__
    830 	/* OpenBSD pledge(2) support */
    831 	if (pledge("stdio rpath wpath cpath dpath", NULL) == -1) {
    832 		fprintf(stderr, "%s: pledge: %s\n", argv0, strerror(errno));
    833 		exit(1);
    834 	}
    835 #endif
    836 
    837 	r = snprintf(ircpath, sizeof(ircpath), "%s/%s", prefix, host);
    838 	if (r < 0 || (size_t)r >= sizeof(ircpath)) {
    839 		fprintf(stderr, "%s: path to irc directory too long\n", argv0);
    840 		exit(1);
    841 	}
    842 	create_dirtree(ircpath);
    843 
    844 	channelmaster = channel_add(""); /* master channel */
    845 	if (key)
    846 		loginkey(ircfd, key);
    847 	loginuser(ircfd, host, fullname && *fullname ? fullname : nick);
    848 	setup();
    849 	run(ircfd, host);
    850 	if (channelmaster)
    851 		channel_leave(channelmaster);
    852 
    853 	for (c = channels; c; c = tmp) {
    854 		tmp = c->next;
    855 		channel_leave(c);
    856 	}
    857 
    858 	return 0;
    859 }