about summary refs log tree commit diff
path: root/filters (follow)
Commit message (Expand)AuthorAge
* email-gravatar: fix html syntax issuesChristian Hesse2014-01-15
* email-gravatar: do not scale icons upJason A. Donenfeld2014-01-14
* filter: allow returning exit code from filterJason A. Donenfeld2014-01-14
* email-gravatar: fix html syntax issuesChristian Hesse2014-01-14
* email-gravatar.py: fix UTF-8Christian Hesse2014-01-14
* email-gravatar.lua: fix for lua 5.2Christian Hesse2014-01-14
* filter: add page source to email filterJason A. Donenfeld2014-01-14
* filter: add gravatar scriptsJason A. Donenfeld2014-01-14
* filters: Improved syntax-highlighting.pyStefan Tatschner2014-01-13
* Fix UTF-8 with syntax-highlighting.pyPřemysl Janouch2014-01-08
* Fix about-formatting.shPřemysl Janouch2014-01-08
* filters: highlight.sh: add css comments for highlight 2.6 and 3.8Ferry Huberts2014-01-08
* filters: toggle perl utf8 situationJason A. Donenfeld2013-05-28
* filters: import more modern scriptsJason A. Donenfeld2013-05-27
* syntax-highlighting.sh: Fix command injection.Jason A. Donenfeld2012-10-27
* syntax-highlight: when the file has no extension, assume textFerry Huberts2012-10-09
* Revert "filters/syntax-highlighting.sh: work around highlight --force bug"Ferry Huberts2012-10-09
* Merge branch 'stable'Lars Hjemli2012-03-18
|\
| * filters/syntax-highlighting.sh: work around highlight --force bugFerry Huberts2012-03-18
| * filters/highlight.sh: manually support highlight version 2 and 3Ferry Huberts2012-03-18
* | commit-links.sh: improve regular expressionsFerry Huberts2011-07-19
* | filters: document environment variables in filter scriptsFerry Huberts2011-03-26
|/
* commit-links.sh: Seperate the expressions for filtering commit messages.Jeff Smith2010-07-22
* syntax highlighting for all formats supported by "highlight"Georg Lukas2009-11-19
* Add some example filter scriptsLars Hjemli2009-08-09
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
/* Copyright (C) 2020  C. McEnroe <june@causal.agency>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Additional permission under GNU GPL version 3 section 7:
 *
 * If you modify this Program, or any covered work, by linking or
 * combining it with OpenSSL (or a modified version of that library),
 * containing parts covered by the terms of the OpenSSL License and the
 * original SSLeay license, the licensors of this Program grant you
 * additional permission to convey the resulting work. Corresponding
 * Source for a non-source form of such a combination shall include the
 * source code for the parts of OpenSSL used as well as that of the
 * covered work.
 */

#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <wchar.h>

#include "chat.h"

uint replies[ReplyCap];

static const char *CapNames[] = {
#define X(name, id) [id##Bit] = name,
	ENUM_CAP
#undef X
};

static enum Cap capParse(const char *list) {
	enum Cap caps = 0;
	while (*list) {
		enum Cap cap = 0;
		size_t len = strcspn(list, " ");
		for (size_t i = 0; i < ARRAY_LEN(CapNames); ++i) {
			if (len != strlen(CapNames[i])) continue;
			if (strncmp(list, CapNames[i], len)) continue;
			cap = 1 << i;
			break;
		}
		caps |= cap;
		list += len;
		if (*list) list++;
	}
	return caps;
}

static void capList(char *buf, size_t cap, enum Cap caps) {
	*buf = '\0';
	char *ptr = buf, *end = &buf[cap];
	for (size_t i = 0; i < ARRAY_LEN(CapNames); ++i) {
		if (caps & (1 << i)) {
			ptr = seprintf(
				ptr, end, "%s%s", (ptr > buf ? " " : ""), CapNames[i]
			);
		}
	}
}

static void require(struct Message *msg, bool origin, uint len) {
	if (origin) {
		if (!msg->nick) msg->nick = "*.*";
		if (!msg->user) msg->user = msg->nick;
		if (!msg->host) msg->host = msg->user;
	}
	for (uint i = 0; i < len; ++i) {
		if (msg->params[i]) continue;
		errx(EX_PROTOCOL, "%s missing parameter %u", msg->cmd, 1 + i);
	}
}

static const time_t *tagTime(const struct Message *msg) {
	static time_t time;
	struct tm tm;
	if (!msg->tags[TagTime]) return NULL;
	if (!strptime(msg->tags[TagTime], "%FT%T", &tm)) return NULL;
	time = timegm(&tm);
	return &time;
}

typedef void Handler(struct Message *msg);

static void handleStandardReply(struct Message *msg) {
	require(msg, false, 3);
	for (uint i = 2; i < ParamCap - 1; ++i) {
		if (msg->params[i + 1]) continue;
		uiFormat(
			Network, Warm, tagTime(msg),
			"%s", msg->params[i]
		);
		break;
	}
}

static void handleErrorGeneric(struct Message *msg) {
	require(msg, false, 2);
	if (msg->params[2]) {
		size_t len = strlen(msg->params[2]);
		if (msg->params[2][len - 1] == '.') msg->params[2][len - 1] = '\0';
		uiFormat(
			Network, Warm, tagTime(msg),
			"%s: %s", msg->params[2], msg->params[1]
		);
	} else {
		uiFormat(
			Network, Warm, tagTime(msg),
			"%s", msg->params[1]
		);
	}
}

static void handleErrorNicknameInUse(struct Message *msg) {
	require(msg, false, 2);
	if (!strcmp(self.nick, "*")) {
		ircFormat("NICK :%s_\r\n", msg->params[1]);
	} else {
		handleErrorGeneric(msg);
	}
}

static void handleErrorErroneousNickname(struct Message *msg) {
	require(msg, false, 3);
	if (!strcmp(self.nick, "*")) {
		errx(EX_CONFIG, "%s: %s", msg->params[1], msg->params[2]);
	} else {
		handleErrorGeneric(msg);
	}
}

static void handleCap(struct Message *msg) {
	require(msg, false, 3);
	enum Cap caps = capParse(msg->params[2]);
	if (!strcmp(msg->params[1], "LS")) {
		caps &= ~CapSASL;
		if (caps & CapConsumer && self.pos) {
			ircFormat("CAP REQ %s=%zu\r\n", CapNames[CapConsumerBit], self.pos);
			caps &= ~CapConsumer;
		}
		if (caps) {
			char buf[512];
			capList(buf, sizeof(buf), caps);
			ircFormat("CAP REQ :%s\r\n", buf);
		} else {
			if (!(self.caps & CapSASL)) ircFormat("CAP END\r\n");
		}
	} else if (!strcmp(msg->params[1], "ACK")) {
		self.caps |= caps;
		if (caps & CapSASL) {
			ircFormat("AUTHENTICATE %s\r\n", (self.plain ? "PLAIN" : "EXTERNAL"));
		}
		if (!(self.caps & CapSASL)) ircFormat("CAP END\r\n");
	} else if (!strcmp(msg->params[1], "NAK")) {
		errx(EX_CONFIG, "server does not support %s", msg->params[2]);
	}
}

#define BASE64_SIZE(len) (1 + ((len) + 2) / 3 * 4)

static void base64(char *dst, const byte *src, size_t len) {
	static const char Base64[64] = {
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
	};
	size_t i = 0;
	while (len > 2) {
		dst[i++] = Base64[0x3F & (src[0] >> 2)];
		dst[i++] = Base64[0x3F & (src[0] << 4 | src[1] >> 4)];
		dst[i++] = Base64[0x3F & (src[1] << 2 | src[2] >> 6)];
		dst[i++] = Base64[0x3F & src[2]];
		src += 3;
		len -= 3;
	}
	if (len) {
		dst[i++] = Base64[0x3F & (src[0] >> 2)];
		if (len > 1) {
			dst[i++] = Base64[0x3F & (src[0] << 4 | src[1] >> 4)];
			dst[i++] = Base64[0x3F & (src[1] << 2)];
		} else {
			dst[i++] = Base64[0x3F & (src[0] << 4)];
			dst[i++] = '=';
		}
		dst[i++] = '=';
	}
	dst[i] = '\0';
}

static void handleAuthenticate(struct Message *msg) {
	(void)msg;
	if (!self.plain) {
		ircFormat("AUTHENTICATE +\r\n");
		return;
	}

	byte buf[299];
	size_t len = 1 + strlen(self.plain);
	if (sizeof(buf) < len) errx(EX_CONFIG, "SASL PLAIN is too long");
	buf[0] = 0;
	for (size_t i = 0; self.plain[i]; ++i) {
		buf[1 + i] = (self.plain[i] == ':' ? 0 : self.plain[i]);
	}

	char b64[BASE64_SIZE(sizeof(buf))];
	base64(b64, buf, len);
	ircFormat("AUTHENTICATE ");
	ircSend(b64, BASE64_SIZE(len));
	ircFormat("\r\n");

	explicit_bzero(b64, sizeof(b64));
	explicit_bzero(buf, sizeof(buf));
	explicit_bzero(self.plain, strlen(self.plain));
}

static void handleReplyLoggedIn(struct Message *msg) {
	(void)msg;
	ircFormat("CAP END\r\n");
}

static void handleErrorSASLFail(struct Message *msg) {
	require(msg, false, 2);
	errx(EX_CONFIG, "%s", msg->params[1]);
}

static void handleReplyWelcome(struct Message *msg) {
	require(msg, false, 1);
	set(&self.nick, msg->params[0]);
	completeTouch(Network, self.nick, Default);
	if (self.join) {
		uint count = 1;
		for (const char *ch = self.join; *ch && *ch != ' '; ++ch) {
			if (*ch == ',') count++;
		}
		ircFormat("JOIN %s\r\n", self.join);
		if (count == 1) replies[ReplyJoin]++;
		replies[ReplyTopicAuto] += count;
		replies[ReplyNamesAuto] += count;
	}
}

static void handleReplyISupport(struct Message *msg) {
	for (uint i = 1; i < ParamCap; ++i) {
		if (!msg->params[i]) break;
		char *key = strsep(&msg->params[i], "=");
		if (!strcmp(key, "NETWORK")) {
			if (!msg->params[i]) continue;
			set(&network.name, msg->params[i]);
			uiFormat(
				Network, Cold, tagTime(msg),
				"You arrive in %s", msg->params[i]
			);
		} else if (!strcmp(key, "USERLEN")) {
			if (!msg->params[i]) continue;
			network.userLen = strtoul(msg->params[i], NULL, 10);
		} else if (!strcmp(key, "HOSTLEN")) {
			if (!msg->params[i]) continue;
			network.hostLen = strtoul(msg->params[i], NULL, 10);
		} else if (!strcmp(key, "CHANTYPES")) {
			if (!msg->params[i]) continue;
			set(&network.chanTypes, msg->params[i]);
		} else if (!strcmp(key, "STATUSMSG")) {
			if (!msg->params[i]) continue;
			set(&network.statusmsg, msg->params[i]);
		} else if (!strcmp(key, "PREFIX")) {
			strsep(&msg->params[i], "(");
			char *modes = strsep(&msg->params[i], ")");
			char *prefixes = msg->params[i];
			if (!modes || !prefixes || strlen(modes) != strlen(prefixes)) {
				errx(EX_PROTOCOL, "invalid PREFIX value");
			}
			set(&network.prefixModes, modes);
			set(&network.prefixes, prefixes);
		} else if (!strcmp(key, "CHANMODES")) {
			char *list = strsep(&msg->params[i], ",");
			char *param = strsep(&msg->params[i], ",");
			char *setParam = strsep(&msg->params[i], ",");
			char *channel = strsep(&msg->params[i], ",");
			if (!list || !param || !setParam || !channel) {
				errx(EX_PROTOCOL, "invalid CHANMODES value");
			}
			set(&network.listModes, list);
			set(&network.paramModes, param);
			set(&network.setParamModes, setParam);
			set(&network.channelModes, channel);
		} else if (!strcmp(key, "EXCEPTS")) {
			network.excepts = (msg->params[i] ?: "e")[0];
		} else if (!strcmp(key, "INVEX")) {
			network.invex = (msg->params[i] ?: "I")[0];
		}
	}
}

static void handleReplyMOTD(struct Message *msg) {
	require(msg, false, 2);
	char *line = msg->params[1];
	urlScan(Network, NULL, line);
	if (!strncmp(line, "- ", 2)) {
		uiFormat(Network, Cold, tagTime(msg), "\3%d-\3\t%s", Gray, &line[2]);
	} else {
		uiFormat(Network, Cold, tagTime(msg), "%s", line);
	}
}

static void handleErrorNoMOTD(struct Message *msg) {
	(void)msg;
}

static void handleReplyHelp(struct Message *msg) {
	require(msg, false, 3);
	urlScan(Network, NULL, msg->params[2]);
	uiWrite(Network, Warm, tagTime(msg), msg->params[2]);
}

static void handleJoin(struct Message *msg) {
	require(msg, true, 1);
	uint id = idFor(msg->params[0]);
	if (!strcmp(msg->nick, self.nick)) {
		if (!self.user || strcmp(self.user, msg->user)) {
			set(&self.user, msg->user);
			self.color = hash(msg->user);
		}
		if (!self.host || strcmp(self.host, msg->host)) {
			set(&self.host, msg->host);
		}
		idColors[id] = hash(msg->params[0]);
		completeTouch(None, msg->params[0], idColors[id]);
		if (replies[ReplyJoin]) {
			uiShowID(id);
			replies[ReplyJoin]--;
		}
	}
	completeTouch(id, msg->nick, hash(msg->user));
	if (msg->params[2] && !strcasecmp(msg->params[2], msg->nick)) {
		msg->params[2] = NULL;
	}
	uiFormat(
		id, filterCheck(Cold, id, msg), tagTime(msg),
		"\3%02d%s\3\t%s%s%sarrives in \3%02d%s\3",
		hash(msg->user), msg->nick,
		(msg->params[2] ? "(" : ""),
		(msg->params[2] ?: ""),
		(msg->params[2] ? "\17) " : ""),
		hash(msg->params[0]), msg->params[0]
	);
	logFormat(id, tagTime(msg), "%s arrives in %s", msg->nick, msg->params[0]);
}

static void handleChghost(struct Message *msg) {
	require(msg, true, 2);
	if (strcmp(msg->nick, self.nick)) return;
	if (!self.user || strcmp(self.user, msg->params[0])) {
		set(&self.user, msg->params[0]);
		self.color = hash(msg->params[0]);
	}
	if (!self.host || strcmp(self.host, msg->params[1])) {
		set(&self.host, msg->params[1]);
	}
}

static void handlePart(struct Message *msg) {
	require(msg, true, 1);
	uint id = idFor(msg->params[0]);
	if (!strcmp(msg->nick, self.nick)) {
		completeClear(id);
	}
	completeRemove(id, msg->nick);
	enum Heat heat = filterCheck(Cold, id, msg);
	if (heat > Ice) urlScan(id, msg->nick, msg->params[1]);
	uiFormat(
		id, heat, tagTime(msg),
		"\3%02d%s\3\tleaves \3%02d%s\3%s%s",
		hash(msg->user), msg->nick, hash(msg->params[0]), msg->params[0],
		(msg->params[1] ? ": " : ""), (msg->params[1] ?: "")
	);
	logFormat(
		id, tagTime(msg), "%s leaves %s%s%s",
		msg->nick, msg->params[0],
		(msg->params[1] ? ": " : ""), (msg->params[1] ?: "")
	);
}

static void handleKick(struct Message *msg) {
	require(msg, true, 2);
	uint id = idFor(msg->params[0]);
	bool kicked = !strcmp(msg->params[1], self.nick);
	completeTouch(id, msg->nick, hash(msg->user));
	urlScan(id, msg->nick, msg->params[2]);
	uiFormat(
		id, (kicked ? Hot : Cold), tagTime(msg),
		"%s\3%02d%s\17\tkicks \3%02d%s\3 out of \3%02d%s\3%s%s",
		(kicked ? "\26" : ""),
		hash(msg->user), msg->nick,
		completeColor(id, msg->params[1]), msg->params[1],
		hash(msg->params[0]), msg->params[0],
		(msg->params[2] ? ": " : ""), (msg->params[2] ?: "")
	);
	logFormat(
		id, tagTime(msg), "%s kicks %s out of %s%s%s",
		msg->nick, msg->params[1], msg->params[0],
		(msg->params[2] ? ": " : ""), (msg->params[2] ?: "")
	);
	completeRemove(id, msg->params[1]);
	if (kicked) completeClear(id);
}

static void handleNick(struct Message *msg) {
	require(msg, true, 1);
	if (!strcmp(msg->nick, self.nick)) {
		set(&self.nick, msg->params[0]);
		uiRead(); // Update prompt.
	}
	for (uint id; (id = completeID(msg->nick));) {
		if (!strcmp(idNames[id], msg->nick)) {
			set(&idNames[id], msg->params[0]);
		}
		uiFormat(
			id, filterCheck(Cold, id, msg), tagTime(msg),
			"\3%02d%s\3\tis now known as \3%02d%s\3",
			hash(msg->user), msg->nick, hash(msg->user), msg->params[0]
		);
		if (id == Network) continue;
		logFormat(
			id, tagTime(msg), "%s is now known as %s",
			msg->nick, msg->params[0]
		);
	}
	completeReplace(None, msg->nick, msg->params[0]);
}

static void handleSetname(struct Message *msg) {
	require(msg, true, 1);
	for (uint id; (id = completeID(msg->nick));) {
		uiFormat(
			id, filterCheck(Cold, id, msg), tagTime(msg),
			"\3%02d%s\3\tis now known as \3%02d%s\3 (%s)",
			hash(msg->user), msg->nick, hash(msg->user), msg->nick,
			msg->params[0]
		);
	}
}

static void handleQuit(struct Message *msg) {
	require(msg, true, 0);
	for (uint id; (id = completeID(msg->nick));) {
		enum Heat heat = filterCheck(Cold, id, msg);
		if (heat > Ice) urlScan(id, msg->nick, msg->params[0]);
		uiFormat(
			id, heat, tagTime(msg),
			"\3%02d%s\3\tleaves%s%s",
			hash(msg->user), msg->nick,
			(msg->params[0] ? ": " : ""), (msg->params[0] ?: "")
		);
		if (id == Network) continue;
		logFormat(
			id, tagTime(msg), "%s leaves%s%s",
			msg->nick,
			(msg->params[0] ? ": " : ""), (msg->params[0] ?: "")
		);
	}
	completeRemove(None, msg->nick);
}

static void handleInvite(struct Message *msg) {
	require(msg, true, 2);
	if (!strcmp(msg->params[0], self.nick)) {
		uiFormat(
			Network, filterCheck(Hot, Network, msg), tagTime(msg),
			"\3%02d%s\3\tinvites you to \3%02d%s\3",
			hash(msg->user), msg->nick, hash(msg->params[1]), msg->params[1]
		);
	} else {
		uint id = idFor(msg->params[1]);
		uiFormat(
			id, Cold, tagTime(msg),
			"\3%02d%s\3\tinvites %s to \3%02d%s\3",
			hash(msg->user), msg->nick,
			msg->params[0],
			hash(msg->params[1]), msg->params[1]
		);
		logFormat(
			id, tagTime(msg), "%s invites %s to %s",
			msg->nick, msg->params[0], msg->params[1]
		);
	}
}

static void handleReplyInviting(struct Message *msg) {
	require(msg, false, 3);
	struct Message invite = {
		.nick = self.nick,
		.user = self.user,
		.cmd = "INVITE",
		.params[0] = msg->params[1],
		.params[1] = msg->params[2],
	};
	handleInvite(&invite);
}

static void handleErrorUserOnChannel(struct Message *msg) {
	require(msg, false, 3);
	uint id = idFor(msg->params[2]);
	uiFormat(
		id, Warm, tagTime(msg),
		"\3%02d%s\3 is already in \3%02d%s\3",
		completeColor(id, msg->params[1]), msg->params[1],
		hash(msg->params[2]), msg->params[2]
	);
}

static void handleReplyNames(struct Message *msg) {
	require(msg, false, 4);
	uint id = idFor(msg->params[2]);
	char buf[1024];
	char *ptr = buf, *end = &buf[sizeof(buf)];
	while (msg->params[3]) {
		char *name = strsep(&msg->params[3], " ");
		char *prefixes = strsep(&name, "!");
		char *nick = &prefixes[strspn(prefixes, network.prefixes)];
		char *user = strsep(&name, "@");
		enum Color color = (user ? hash(user) : Default);
		completeAdd(id, nick, color);
		if (!replies[ReplyNames] && !replies[ReplyNamesAuto]) continue;
		ptr = seprintf(
			ptr, end, "%s\3%02d%s\3", (ptr > buf ? ", " : ""), color, prefixes
		);
	}
	if (ptr == buf) return;
	uiFormat(
		id, (replies[ReplyNamesAuto] ? Cold : Warm), tagTime(msg),
		"In \3%02d%s\3 are %s",
		hash(msg->params[2]), msg->params[2], buf
	);
}

static void handleReplyEndOfNames(struct Message *msg) {
	(void)msg;
	if (replies[ReplyNamesAuto]) {
		replies[ReplyNamesAuto]--;
	} else if (replies[ReplyNames]) {
		replies[ReplyNames]--;
	}
}

static struct {
	char buf[1024];
	char *ptr;
	char *end;
} who = {
	.ptr = who.buf,
	.end = &who.buf[sizeof(who.buf)],
};

static void handleReplyWho(struct Message *msg) {
	require(msg, false, 7);
	if (who.ptr == who.buf) {
		who.ptr = seprintf(
			who.ptr, who.end, "The operators of \3%02d%s\3 are ",
			hash(msg->params[1]), msg->params[1]
		);
	}
	char *prefixes = &msg->params[6][1];
	if (prefixes[0] == '*') prefixes++;
	prefixes[strspn(prefixes, network.prefixes)] = '\0';
	if (!prefixes[0] || prefixes[0] == '+') return;
	who.ptr = seprintf(
		who.ptr, who.end, "%s\3%02d%s%s\3%s",
		(who.ptr[-1] == ' ' ? "" : ", "),
		hash(msg->params[2]), prefixes, msg->params[5],
		(msg->params[6][0] == 'H' ? "" : " (away)")
	);
}

static void handleReplyEndOfWho(struct Message *msg) {
	require(msg, false, 2);
	uiWrite(idFor(msg->params[1]), Warm, tagTime(msg), who.buf);
	who.ptr = who.buf;
}

static void handleReplyNoTopic(struct Message *msg) {
	require(msg, false, 2);
	uiFormat(
		idFor(msg->params[1]), Warm, tagTime(msg),
		"There is no sign in \3%02d%s\3",
		hash(msg->params[1]), msg->params[1]
	);
}

static void topicComplete(uint id, const char *topic) {
	char buf[512];
	const char *prev = complete(id, "/topic ");
	if (prev) {
		snprintf(buf, sizeof(buf), "%s", prev);
		completeRemove(id, buf);
	}
	if (topic) {
		snprintf(buf, sizeof(buf), "/topic %s", topic);
		completeAdd(id, buf, Default);
	}
}

static void handleReplyTopic(struct Message *msg) {
	require(msg, false, 3);
	uint id = idFor(msg->params[1]);
	topicComplete(id, msg->params[2]);
	if (!replies[ReplyTopic] && !replies[ReplyTopicAuto]) return;
	urlScan(id, NULL, msg->params[2]);
	uiFormat(
		id, (replies[ReplyTopicAuto] ? Cold : Warm), tagTime(msg),
		"The sign in \3%02d%s\3 reads: %s",
		hash(msg->params[1]), msg->params[1], msg->params[2]
	);
	logFormat(
		id, tagTime(msg), "The sign in %s reads: %s",
		msg->params[1], msg->params[2]
	);
	if (replies[ReplyTopicAuto]) {
		replies[ReplyTopicAuto]--;
	} else {
		replies[ReplyTopic]--;
	}
}

static void swap(wchar_t *a, wchar_t *b) {
	wchar_t x = *a;
	*a = *b;
	*b = x;
}

static void handleTopic(struct Message *msg) {
	require(msg, true, 2);
	uint id = idFor(msg->params[0]);
	if (!msg->params[1][0]) {
		topicComplete(id, NULL);
		uiFormat(
			id, Warm, tagTime(msg),
			"\3%02d%s\3\tremoves the sign in \3%02d%s\3",
			hash(msg->user), msg->nick, hash(msg->params[0]), msg->params[0]
		);
		logFormat(
			id, tagTime(msg), "%s removes the sign in %s",
			msg->nick, msg->params[0]
		);
		return;
	}

	char buf[1024];
	char *ptr = buf, *end = &buf[sizeof(buf)];
	const char *prev = complete(id, "/topic ");
	completeReject();
	if (prev) {
		prev += 7;
	} else {
		goto plain;
	}

	wchar_t old[512];
	wchar_t new[512];
	if (swprintf(old, ARRAY_LEN(old), L"%s", prev) < 0) goto plain;
	if (swprintf(new, ARRAY_LEN(new), L"%s", msg->params[1]) < 0) goto plain;

	if (!hashBound) {
		ptr = seprintf(ptr, end, "%c%ls%c -> %c%ls%c", R, old, O, R, new, O);
		goto plain;
	}

	size_t pre;
	for (pre = 0; old[pre] && new[pre] && old[pre] == new[pre]; ++pre);
	wchar_t *osuf = &old[wcslen(old)];
	wchar_t *nsuf = &new[wcslen(new)];
	while (osuf > &old[pre] && nsuf > &new[pre] && osuf[-1] == nsuf[-1]) {
		osuf--;
		nsuf--;
	}

	wchar_t nul = L'\0';
	swap(&new[pre], &nul);
	ptr = seprintf(ptr, end, "%ls", new);
	swap(&new[pre], &nul);
	swap(osuf, &nul);
	ptr = seprintf(ptr, end, "\3%02d,%02d%ls", Default, Brown, &old[pre]);
	swap(osuf, &nul);
	swap(nsuf, &nul);
	ptr = seprintf(ptr, end, "\3%02d,%02d%ls", Default, Green, &new[pre]);
	swap(nsuf, &nul);
	ptr = seprintf(ptr, end, "\3%02d,%02d%ls", Default, Default, nsuf);

plain:
	topicComplete(id, msg->params[1]);
	urlScan(id, msg->nick, msg->params[1]);
	uiFormat(
		id, Warm, tagTime(msg),
		"\3%02d%s\3\tplaces a new sign in \3%02d%s\3: %s",
		hash(msg->user), msg->nick, hash(msg->params[0]), msg->params[0],
		(ptr > buf ? buf : msg->params[1])
	);
	logFormat(
		id, tagTime(msg), "%s places a new sign in %s: %s",
		msg->nick, msg->params[0], msg->params[1]
	);
}

static const char *UserModes[256] = {
	['O'] = "local oper",
	['i'] = "invisible",
	['o'] = "oper",
	['r'] = "registered",
	['w'] = "wallops",
};

static void handleReplyUserModeIs(struct Message *msg) {
	require(msg, false, 2);
	char buf[1024];
	char *ptr = buf, *end = &buf[sizeof(buf)];
	for (char *ch = msg->params[1]; *ch; ++ch) {
		if (*ch == '+') continue;
		const char *name = UserModes[(byte)*ch];
		ptr = seprintf(
			ptr, end, ", +%c%s%s", *ch, (name ? " " : ""), (name ?: "")
		);
	}
	uiFormat(
		Network, Warm, tagTime(msg),
		"\3%02d%s\3\tis %s",
		self.color, self.nick, (ptr > buf ? &buf[2] : "modeless")
	);
}

static const char *ChanModes[256] = {
	['a'] = "protected",
	['h'] = "halfop",
	['i'] = "invite-only",
	['k'] = "key",
	['l'] = "client limit",
	['m'] = "moderated",
	['n'] = "no external messages",
	['o'] = "operator",
	['q'] = "founder",
	['s'] = "secret",
	['t'] = "protected topic",
	['v'] = "voice",
};

static void handleReplyChannelModeIs(struct Message *msg) {
	require(msg, false, 3);
	uint param = 3;
	char buf[1024];
	char *ptr = buf, *end = &buf[sizeof(buf)];
	for (char *ch = msg->params[2]; *ch; ++ch) {
		if (*ch == '+') continue;
		const char *name = ChanModes[(byte)*ch];
		if (
			strchr(network.paramModes, *ch) ||
			strchr(network.setParamModes, *ch)
		) {
			assert(param < ParamCap);
			ptr = seprintf(
				ptr, end, ", +%c%s%s %s",
				*ch, (name ? " " : ""), (name ?: ""),
				msg->params[param++]
			);
		} else {
			ptr = seprintf(
				ptr, end, ", +%c%s%s",
				*ch, (name ? " " : ""), (name ?: "")
			);
		}
	}
	uiFormat(
		idFor(msg->params[1]), Warm, tagTime(msg),
		"\3%02d%s\3\tis %s",
		hash(msg->params[1]), msg->params[1],
		(ptr > buf ? &buf[2] : "modeless")
	);
}

static void handleMode(struct Message *msg) {
	require(msg, true, 2);

	if (!strchr(network.chanTypes, msg->params[0][0])) {
		bool set = true;
		for (char *ch = msg->params[1]; *ch; ++ch) {
			if (*ch == '+') { set = true; continue; }
			if (*ch == '-') { set = false; continue; }
			const char *name = UserModes[(byte)*ch];
			uiFormat(
				Network, Warm, tagTime(msg),
				"\3%02d%s\3\t%ssets \3%02d%s\3 %c%c%s%s",
				hash(msg->user), msg->nick,
				(set ? "" : "un"),
				self.color, msg->params[0],
				set["-+"], *ch, (name ? " " : ""), (name ?: "")
			);
		}
		return;
	}

	uint id = idFor(msg->params[0]);
	bool set = true;
	uint i = 2;
	for (char *ch = msg->params[1]; *ch; ++ch) {
		if (*ch == '+') { set = true; continue; }
		if (*ch == '-') { set = false; continue; }

		const char *verb = (set ? "sets" : "unsets");
		const char *name = ChanModes[(byte)*ch];
		if (*ch == network.excepts) name = "except";
		if (*ch == network.invex) name = "invite";
		const char *mode = (const char[]) {
			set["-+"], *ch, (name ? ' ' : '\0'), '\0'
		};
		if (!name) name = "";

		if (strchr(network.prefixModes, *ch)) {
			if (i >= ParamCap || !msg->params[i]) {
				errx(EX_PROTOCOL, "MODE missing %s parameter", mode);
			}
			char *nick = msg->params[i++];
			char prefix = network.prefixes[
				strchr(network.prefixModes, *ch) - network.prefixModes
			];
			uiFormat(
				id, Cold, tagTime(msg),
				"\3%02d%s\3\t%s \3%02d%c%s\3 %s%s in \3%02d%s\3",
				hash(msg->user), msg->nick, verb,
				completeColor(id, nick), prefix, nick,
				mode, name, hash(msg->params[0]), msg->params[0]
			);
			logFormat(
				id, tagTime(msg), "%s %s %c%s %s%s in %s",
				msg->nick, verb, prefix, nick, mode, name, msg->params[0]
			);
		}

		if (strchr(network.listModes, *ch)) {
			if (i >= ParamCap || !msg->params[i]) {
				errx(EX_PROTOCOL, "MODE missing %s parameter", mode);
			}
			char *mask = msg->params[i++];
			if (*ch == 'b') {
				verb = (set ? "bans" : "unbans");
				uiFormat(
					id, Cold, tagTime(msg),
					"\3%02d%s\3\t%s %c%c %s from \3%02d%s\3",
					hash(msg->user), msg->nick, verb, set["-+"], *ch, mask,
					hash(msg->params[0]), msg->params[0]
				);
				logFormat(
					id, tagTime(msg), "%s %s %c%c %s from %s",
					msg->nick, verb, set["-+"], *ch, mask, msg->params[0]
				);
			} else {
				verb = (set ? "adds" : "removes");
				const char *to = (set ? "to" : "from");
				uiFormat(
					id, Cold, tagTime(msg),
					"\3%02d%s\3\t%s %s %s the \3%02d%s\3 %s%s list",
					hash(msg->user), msg->nick, verb, mask, to,
					hash(msg->params[0]), msg->params[0], mode, name
				);
				logFormat(
					id, tagTime(msg), "%s %s %s %s the %s %s%s list",
					msg->nick, verb, mask, to, msg->params[0], mode, name
				);
			}
		}

		if (strchr(network.paramModes, *ch)) {
			if (i >= ParamCap || !msg->params[i]) {
				errx(EX_PROTOCOL, "MODE missing %s parameter", mode);
			}
			char *param = msg->params[i++];
			uiFormat(
				id, Cold, tagTime(msg),
				"\3%02d%s\3\t%s \3%02d%s\3 %s%s %s",
				hash(msg->user), msg->nick, verb,
				hash(msg->params[0]), msg->params[0], mode, name, param
			);
			logFormat(
				id, tagTime(msg), "%s %s %s %s%s %s",
				msg->nick, verb, msg->params[0], mode, name, param
			);
		}

		if (strchr(network.setParamModes, *ch) && set) {
			if (i >= ParamCap || !msg->params[i]) {
				errx(EX_PROTOCOL, "MODE missing %s parameter", mode);
			}
			char *param = msg->params[i++];
			uiFormat(
				id, Cold, tagTime(msg),
				"\3%02d%s\3\t%s \3%02d%s\3 %s%s %s",
				hash(msg->user), msg->nick, verb,
				hash(msg->params[0]), msg->params[0], mode, name, param
			);
			logFormat(
				id, tagTime(msg), "%s %s %s %s%s %s",
				msg->nick, verb, msg->params[0], mode, name, param
			);
		} else if (strchr(network.setParamModes, *ch)) {
			uiFormat(
				id, Cold, tagTime(msg),
				"\3%02d%s\3\t%s \3%02d%s\3 %s%s",
				hash(msg->user), msg->nick, verb,
				hash(msg->params[0]), msg->params[0], mode, name
			);
			logFormat(
				id, tagTime(msg), "%s %s %s %s%s",
				msg->nick, verb, msg->params[0], mode, name
			);
		}

		if (strchr(network.channelModes, *ch)) {
			uiFormat(
				id, Cold, tagTime(msg),
				"\3%02d%s\3\t%s \3%02d%s\3 %s%s",
				hash(msg->user), msg->nick, verb,
				hash(msg->params[0]), msg->params[0], mode, name
			);
			logFormat(
				id, tagTime(msg), "%s %s %s %s%s",
				msg->nick, verb, msg->params[0], mode, name
			);
		}
	}
}

static void handleErrorChanopPrivsNeeded(struct Message *msg) {
	require(msg, false, 3);
	uiFormat(
		idFor(msg->params[1]), Warm, tagTime(msg),
		"%s", msg->params[2]
	);
}

static void handleErrorUserNotInChannel(struct Message *msg) {
	require(msg, false, 4);
	uiFormat(
		idFor(msg->params[2]), Warm, tagTime(msg),
		"%s\tis not in \3%02d%s\3",
		msg->params[1], hash(msg->params[2]), msg->params[2]
	);
}

static void handleErrorBanListFull(struct Message *msg) {
	require(msg, false, 4);
	uiFormat(
		idFor(msg->params[1]), Warm, tagTime(msg),
		"%s", (msg->params[4] ?: msg->params[3])
	);
}

static void handleReplyBanList(struct Message *msg) {
	require(msg, false, 3);
	uint id = idFor(msg->params[1]);
	if (msg->params[3] && msg->params[4]) {
		char since[sizeof("0000-00-00 00:00:00")];
		time_t time = strtol(msg->params[4], NULL, 10);
		strftime(since, sizeof(since), "%F %T", localtime(&time));
		uiFormat(
			id, Warm, tagTime(msg),
			"Banned from \3%02d%s\3 since %s by \3%02d%s\3: %s",
			hash(msg->params[1]), msg->params[1],
			since, completeColor(id, msg->params[3]), msg->params[3],
			msg->params[2]
		);
	} else {
		uiFormat(
			id, Warm, tagTime(msg),
			"Banned from \3%02d%s\3: %s",
			hash(msg->params[1]), msg->params[1], msg->params[2]
		);
	}
}

static void onList(const char *list, struct Message *msg) {
	require(msg, false, 3);
	uint id = idFor(msg->params[1]);
	if (msg->params[3] && msg->params[4]) {
		char since[sizeof("0000-00-00 00:00:00")];
		time_t time = strtol(msg->params[4], NULL, 10);
		strftime(since, sizeof(since), "%F %T", localtime(&time));
		uiFormat(
			id, Warm, tagTime(msg),
			"On the \3%02d%s\3 %s list since %s by \3%02d%s\3: %s",
			hash(msg->params[1]), msg->params[1], list,
			since, completeColor(id, msg->params[3]), msg->params[3],
			msg->params[2]
		);
	} else {
		uiFormat(
			id, Warm, tagTime(msg),
			"On the \3%02d%s\3 %s list: %s",
			hash(msg->params[1]), msg->params[1], list, msg->params[2]
		);
	}
}

static void handleReplyExceptList(struct Message *msg) {
	onList("except", msg);
}

static void handleReplyInviteList(struct Message *msg) {
	onList("invite", msg);
}

static void handleReplyList(struct Message *msg) {
	require(msg, false, 4);
	uiFormat(
		Network, Warm, tagTime(msg),
		"In \3%02d%s\3 are %ld under the banner: %s",
		hash(msg->params[1]), msg->params[1],
		strtol(msg->params[2], NULL, 10),
		msg->params[3]
	);
}

static void handleReplyWhoisUser(struct Message *msg) {
	require(msg, false, 6);
	completeTouch(Network, msg->params[1], hash(msg->params[2]));
	uiFormat(
		Network, Warm, tagTime(msg),
		"\3%02d%s\3\tis %s!%s@%s (%s\17)",
		hash(msg->params[2]), msg->params[1],
		msg->params[1], msg->params[2], msg->params[3], msg->params[5]
	);
}

static void handleReplyWhoisServer(struct Message *msg) {
	if (!replies[ReplyWhois] && !replies[ReplyWhowas]) return;
	require(msg, false, 4);
	uiFormat(
		Network, Warm, tagTime(msg),
		"\3%02d%s\3\t%s connected to %s (%s)",
		completeColor(Network, msg->params[1]), msg->params[1],
		(replies[ReplyWhowas] ? "was" : "is"), msg->params[2], msg->params[3]
	);
}

static void handleReplyWhoisIdle(struct Message *msg) {
	require(msg, false, 3);
	unsigned long idle = strtoul(msg->params[2], NULL, 10);
	const char *unit = "second";
	if (idle / 60) {
		idle /= 60; unit = "minute";
		if (idle / 60) {
			idle /= 60; unit = "hour";
			if (idle / 24) {
				idle /= 24; unit = "day";
			}
		}
	}
	char signon[sizeof("0000-00-00 00:00:00")];
	time_t time = strtol((msg->params[3] ?: ""), NULL, 10);
	strftime(signon, sizeof(signon), "%F %T", localtime(&time));
	uiFormat(
		Network, Warm, tagTime(msg),
		"\3%02d%s\3\tis idle for %lu %s%s%s%s",
		completeColor(Network, msg->params[1]), msg->params[1],
		idle, unit, (idle != 1 ? "s" : ""),
		(msg->params[3] ? ", signed on " : ""), (msg->params[3] ? signon : "")
	);
}

static void handleReplyWhoisChannels(struct Message *msg) {
	require(msg, false, 3);
	char buf[1024];
	char *ptr = buf, *end = &buf[sizeof(buf)];
	while (msg->params[2]) {
		char *channel = strsep(&msg->params[2], " ");
		if (!channel[0]) break;
		char *name = &channel[strspn(channel, network.prefixes)];
		ptr = seprintf(
			ptr, end, "%s\3%02d%s\3",
			(ptr > buf ? ", " : ""), hash(name), channel
		);
	}
	uiFormat(
		Network, Warm, tagTime(msg),
		"\3%02d%s\3\tis in %s",
		completeColor(Network, msg->params[1]), msg->params[1], buf
	);
}

static void handleReplyWhoisGeneric(struct Message *msg) {
	require(msg, false, 3);
	if (msg->params[3]) {
		msg->params[0] = msg->params[2];
		msg->params[2] = msg->params[3];
		msg->params[3] = msg->params[0];
	}
	uiFormat(
		Network, Warm, tagTime(msg),
		"\3%02d%s\3\t%s%s%s",
		completeColor(Network, msg->params[1]), msg->params[1],
		msg->params[2], (msg->params[3] ? " " : ""), (msg->params[3] ?: "")
	);
}

static void handleReplyEndOfWhois(struct Message *msg) {
	require(msg, false, 2);
	if (strcmp(msg->params[1], self.nick)) {
		completeRemove(Network, msg->params[1]);
	}
}

static void handleReplyWhowasUser(struct Message *msg) {
	require(msg, false, 6);
	completeTouch(Network, msg->params[1], hash(msg->params[2]));
	uiFormat(
		Network, Warm, tagTime(msg),
		"\3%02d%s\3\twas %s!%s@%s (%s)",
		hash(msg->params[2]), msg->params[1],
		msg->params[1], msg->params[2], msg->params[3], msg->params[5]
	);
}

static void handleReplyEndOfWhowas(struct Message *msg) {
	require(msg, false, 2);
	if (strcmp(msg->params[1], self.nick)) {
		completeRemove(Network, msg->params[1]);
	}
}

static void handleReplyAway(struct Message *msg) {
	require(msg, false, 3);
	// Might be part of a WHOIS response.
	uint id;
	if (completeColor(Network, msg->params[1]) != Default) {
		id = Network;
	} else {
		id = idFor(msg->params[1]);
	}
	uiFormat(
		id, Warm, tagTime(msg),
		"\3%02d%s\3\tis away: %s",
		completeColor(id, msg->params[1]), msg->params[1], msg->params[2]
	);
	logFormat(
		id, tagTime(msg), "%s is away: %s",
		msg->params[1], msg->params[2]
	);
}

static void handleReplyNowAway(struct Message *msg) {
	require(msg, false, 2);
	uiFormat(Network, Warm, tagTime(msg), "%s", msg->params[1]);
}

static bool isAction(struct Message *msg) {
	if (strncmp(msg->params[1], "\1ACTION ", 8)) return false;
	msg->params[1] += 8;
	size_t len = strlen(msg->params[1]);
	if (msg->params[1][len - 1] == '\1') msg->params[1][len - 1] = '\0';
	return true;
}

static bool isMention(const struct Message *msg) {
	size_t len = strlen(self.nick);
	const char *match = msg->params[1];
	while (NULL != (match = strstr(match, self.nick))) {
		char a = (match > msg->params[1] ? match[-1] : ' ');
		char b = (match[len] ?: ' ');
		if ((isspace(a) || ispunct(a)) && (isspace(b) || ispunct(b))) {
			return true;
		}
		match = &match[len];
	}
	return false;
}

static void colorMentions(char *buf, size_t cap, uint id, struct Message *msg) {
	*buf = '\0';

	char *split = strstr(msg->params[1], ": ");
	if (!split) {
		split = strchr(msg->params[1], ' ');
		if (split) split = strchr(&split[1], ' ');
	}
	if (!split) split = &msg->params[1][strlen(msg->params[1])];
	for (char *ch = msg->params[1]; ch < split; ++ch) {
		if (iscntrl(*ch)) return;
	}
	char delimit = *split;
	char *mention = msg->params[1];
	msg->params[1] = (delimit ? &split[1] : split);
	*split = '\0';

	char *ptr = buf, *end = &buf[cap];
	while (*mention) {
		size_t skip = strspn(mention, ",<> ");
		ptr = seprintf(ptr, end, "%.*s", (int)skip, mention);
		mention += skip;

		size_t len = strcspn(mention, ",<> ");
		char punct = mention[len];
		mention[len] = '\0';
		enum Color color = completeColor(id, mention);
		if (color != Default) {
			ptr = seprintf(ptr, end, "\3%02d%s\3", color, mention);
		} else {
			ptr = seprintf(ptr, end, "%s", mention);
		}
		mention[len] = punct;
		mention += len;
	}
	seprintf(ptr, end, "%c", delimit);
}

static void handlePrivmsg(struct Message *msg) {
	require(msg, true, 2);
	if (network.statusmsg) {
		msg->params[0] += strspn(msg->params[0], network.statusmsg);
	}
	bool query = !strchr(network.chanTypes, msg->params[0][0]);
	bool server = strchr(msg->nick, '.');
	bool mine = !strcmp(msg->nick, self.nick);
	uint id;
	if (query && server) {
		id = Network;
	} else if (query && !mine) {
		id = idFor(msg->nick);
		idColors[id] = hash(msg->user);
	} else {
		id = idFor(msg->params[0]);
	}

	bool notice = (msg->cmd[0] == 'N');
	bool action = isAction(msg);
	bool highlight = !mine && isMention(msg);
	enum Heat heat = filterCheck((highlight || query ? Hot : Warm), id, msg);
	if (heat > Warm && !mine && !query) highlight = true;
	if (!notice && !mine && heat > Ice) {
		completeTouch(id, msg->nick, hash(msg->user));
	}
	if (heat > Ice) urlScan(id, msg->nick, msg->params[1]);

	char buf[1024];
	if (notice) {
		if (id != Network) {
			logFormat(id, tagTime(msg), "-%s- %s", msg->nick, msg->params[1]);
		}
		uiFormat(
			id, filterCheck(Warm, id, msg), tagTime(msg),
			"\3%d-%s-\3%d\t%s",
			hash(msg->user), msg->nick, LightGray, msg->params[1]
		);
	} else if (action) {
		logFormat(id, tagTime(msg), "* %s %s", msg->nick, msg->params[1]);
		colorMentions(buf, sizeof(buf), id, msg);
		uiFormat(
			id, heat, tagTime(msg),
			"%s\35\3%d* %s\17\35\t%s%s",
			(highlight ? "\26" : ""), hash(msg->user), msg->nick,
			buf, msg->params[1]
		);
	} else {
		logFormat(id, tagTime(msg), "<%s> %s", msg->nick, msg->params[1]);
		colorMentions(buf, sizeof(buf), id, msg);
		uiFormat(
			id, heat, tagTime(msg),
			"%s\3%d<%s>\17\t%s%s",
			(highlight ? "\26" : ""), hash(msg->user), msg->nick,
			buf, msg->params[1]
		);
	}
}

static void handlePing(struct Message *msg) {
	require(msg, false, 1);
	ircFormat("PONG :%s\r\n", msg->params[0]);
}

static void handleError(struct Message *msg) {
	require(msg, false, 1);
	errx(EX_UNAVAILABLE, "%s", msg->params[0]);
}

static const struct Handler {
	const char *cmd;
	int reply;
	Handler *fn;
} Handlers[] = {
	{ "001", 0, handleReplyWelcome },
	{ "005", 0, handleReplyISupport },
	{ "221", -ReplyMode, handleReplyUserModeIs },
	{ "276", +ReplyWhois, handleReplyWhoisGeneric },
	{ "301", 0, handleReplyAway },
	{ "305", -ReplyAway, handleReplyNowAway },
	{ "306", -ReplyAway, handleReplyNowAway },
	{ "307", +ReplyWhois, handleReplyWhoisGeneric },
	{ "311", +ReplyWhois, handleReplyWhoisUser },
	{ "312", 0, handleReplyWhoisServer },
	{ "313", +ReplyWhois, handleReplyWhoisGeneric },
	{ "314", +ReplyWhowas, handleReplyWhowasUser },
	{ "315", -ReplyWho, handleReplyEndOfWho },
	{ "317", +ReplyWhois, handleReplyWhoisIdle },
	{ "318", -ReplyWhois, handleReplyEndOfWhois },
	{ "319", +ReplyWhois, handleReplyWhoisChannels },
	{ "322", +ReplyList, handleReplyList },
	{ "323", -ReplyList, NULL },
	{ "324", -ReplyMode, handleReplyChannelModeIs },
	{ "330", +ReplyWhois, handleReplyWhoisGeneric },
	{ "331", -ReplyTopic, handleReplyNoTopic },
	{ "332", 0, handleReplyTopic },
	{ "335", +ReplyWhois, handleReplyWhoisGeneric },
	{ "341", 0, handleReplyInviting },
	{ "346", +ReplyInvex, handleReplyInviteList },
	{ "347", -ReplyInvex, NULL },
	{ "348", +ReplyExcepts, handleReplyExceptList },
	{ "349", -ReplyExcepts, NULL },
	{ "352", +ReplyWho, handleReplyWho },
	{ "353", 0, handleReplyNames },
	{ "366", 0, handleReplyEndOfNames },
	{ "367", +ReplyBan, handleReplyBanList },
	{ "368", -ReplyBan, NULL },
	{ "369", -ReplyWhowas, handleReplyEndOfWhowas },
	{ "372", 0, handleReplyMOTD },
	{ "378", +ReplyWhois, handleReplyWhoisGeneric },
	{ "379", +ReplyWhois, handleReplyWhoisGeneric },
	{ "422", 0, handleErrorNoMOTD },
	{ "432", 0, handleErrorErroneousNickname },
	{ "433", 0, handleErrorNicknameInUse },
	{ "437", 0, handleErrorNicknameInUse },
	{ "441", 0, handleErrorUserNotInChannel },
	{ "443", 0, handleErrorUserOnChannel },
	{ "478", 0, handleErrorBanListFull },
	{ "482", 0, handleErrorChanopPrivsNeeded },
	{ "671", +ReplyWhois, handleReplyWhoisGeneric },
	{ "704", +ReplyHelp, handleReplyHelp },
	{ "705", +ReplyHelp, handleReplyHelp },
	{ "706", -ReplyHelp, NULL },
	{ "900", 0, handleReplyLoggedIn },
	{ "904", 0, handleErrorSASLFail },
	{ "905", 0, handleErrorSASLFail },
	{ "906", 0, handleErrorSASLFail },
	{ "AUTHENTICATE", 0, handleAuthenticate },
	{ "CAP", 0, handleCap },
	{ "CHGHOST", 0, handleChghost },
	{ "ERROR", 0, handleError },
	{ "FAIL", 0, handleStandardReply },
	{ "INVITE", 0, handleInvite },
	{ "JOIN", 0, handleJoin },
	{ "KICK", 0, handleKick },
	{ "MODE", 0, handleMode },
	{ "NICK", 0, handleNick },
	{ "NOTE", 0, handleStandardReply },
	{ "NOTICE", 0, handlePrivmsg },
	{ "PART", 0, handlePart },
	{ "PING", 0, handlePing },
	{ "PRIVMSG", 0, handlePrivmsg },
	{ "QUIT", 0, handleQuit },
	{ "SETNAME", 0, handleSetname },
	{ "TOPIC", 0, handleTopic },
	{ "WARN", 0, handleStandardReply },
};

static int compar(const void *cmd, const void *_handler) {
	const struct Handler *handler = _handler;
	return strcmp(cmd, handler->cmd);
}

void handle(struct Message *msg) {
	if (!msg->cmd) return;
	if (msg->tags[TagPos]) {
		self.pos = strtoull(msg->tags[TagPos], NULL, 10);
	}
	const struct Handler *handler = bsearch(
		msg->cmd, Handlers, ARRAY_LEN(Handlers), sizeof(*handler), compar
	);
	if (handler) {
		if (handler->reply && !replies[abs(handler->reply)]) return;
		if (handler->fn) handler->fn(msg);
		if (handler->reply < 0) replies[abs(handler->reply)]--;
	} else if (strcmp(msg->cmd, "400") >= 0 && strcmp(msg->cmd, "599") <= 0) {
		handleErrorGeneric(msg);
	}
}