IRC bouncer
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.c 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /* Copyright (C) 2019 C. McEnroe <june@causal.agency>
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  15. */
  16. #include <assert.h>
  17. #include <err.h>
  18. #include <stdarg.h>
  19. #include <stdbool.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <strings.h>
  24. #include <sysexits.h>
  25. #include <tls.h>
  26. #include <unistd.h>
  27. #include "bounce.h"
  28. static size_t count;
  29. enum Need {
  30. BIT(NeedNick),
  31. BIT(NeedUser),
  32. BIT(NeedPass),
  33. BIT(NeedCapEnd),
  34. };
  35. struct Client {
  36. struct tls *tls;
  37. enum Need need;
  38. size_t consumer;
  39. enum Cap caps;
  40. char buf[1024];
  41. size_t len;
  42. bool error;
  43. };
  44. struct Client *clientAlloc(struct tls *tls) {
  45. struct Client *client = calloc(1, sizeof(*client));
  46. if (!client) err(EX_OSERR, "calloc");
  47. client->tls = tls;
  48. client->need = NeedNick | NeedUser | (clientPass ? NeedPass : 0);
  49. return client;
  50. }
  51. void clientFree(struct Client *client) {
  52. if (!client->need) {
  53. if (!--count) serverFormat("AWAY :%s\r\n", clientAway);
  54. }
  55. tls_close(client->tls);
  56. tls_free(client->tls);
  57. free(client);
  58. }
  59. bool clientError(const struct Client *client) {
  60. return client->error;
  61. }
  62. void clientSend(struct Client *client, const char *ptr, size_t len) {
  63. if (verbose) fprintf(stderr, "\x1B[34m%.*s\x1B[m", (int)len, ptr);
  64. while (len) {
  65. ssize_t ret = tls_write(client->tls, ptr, len);
  66. if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) continue;
  67. if (ret < 0) {
  68. warnx("client tls_write: %s", tls_error(client->tls));
  69. client->error = true;
  70. return;
  71. }
  72. ptr += ret;
  73. len -= ret;
  74. }
  75. }
  76. void clientFormat(struct Client *client, const char *format, ...) {
  77. char buf[1024];
  78. va_list ap;
  79. va_start(ap, format);
  80. int len = vsnprintf(buf, sizeof(buf), format, ap);
  81. va_end(ap);
  82. assert((size_t)len < sizeof(buf));
  83. clientSend(client, buf, len);
  84. }
  85. static void passRequired(struct Client *client) {
  86. clientFormat(
  87. client,
  88. ":%s 464 * :Password incorrect\r\n"
  89. "ERROR :Password incorrect\r\n",
  90. ORIGIN
  91. );
  92. client->error = true;
  93. }
  94. static void maybeSync(struct Client *client) {
  95. if (client->need == NeedPass) passRequired(client);
  96. if (!client->need) {
  97. stateSync(client);
  98. if (!count++) serverFormat("AWAY\r\n");
  99. }
  100. }
  101. typedef void Handler(struct Client *client, struct Message *msg);
  102. static void handleNick(struct Client *client, struct Message *msg) {
  103. (void)msg;
  104. client->need &= ~NeedNick;
  105. maybeSync(client);
  106. }
  107. static void handleUser(struct Client *client, struct Message *msg) {
  108. if (!msg->params[0]) {
  109. client->error = true;
  110. return;
  111. }
  112. if (client->need & NeedPass) {
  113. passRequired(client);
  114. } else {
  115. client->need &= ~NeedUser;
  116. client->consumer = ringConsumer(msg->params[0]);
  117. maybeSync(client);
  118. }
  119. }
  120. static void handlePass(struct Client *client, struct Message *msg) {
  121. if (!clientPass) return;
  122. if (!msg->params[0]) {
  123. client->error = true;
  124. return;
  125. }
  126. if (!strcmp(crypt(msg->params[0], clientPass), clientPass)) {
  127. client->need &= ~NeedPass;
  128. maybeSync(client);
  129. } else {
  130. passRequired(client);
  131. }
  132. explicit_bzero(msg->params[0], strlen(msg->params[0]));
  133. }
  134. static void handleCap(struct Client *client, struct Message *msg) {
  135. if (!msg->params[0]) msg->params[0] = "";
  136. enum Cap avail = CapServerTime | (stateCaps & ~CapSASL);
  137. if (!strcmp(msg->params[0], "END")) {
  138. if (!client->need) return;
  139. client->need &= ~NeedCapEnd;
  140. maybeSync(client);
  141. } else if (!strcmp(msg->params[0], "LS")) {
  142. if (client->need) client->need |= NeedCapEnd;
  143. clientFormat(client, ":%s CAP * LS :%s\r\n", ORIGIN, capList(avail));
  144. } else if (!strcmp(msg->params[0], "REQ") && msg->params[1]) {
  145. if (client->need) client->need |= NeedCapEnd;
  146. enum Cap caps = capParse(msg->params[1]);
  147. if (caps == (avail & caps)) {
  148. client->caps |= caps;
  149. clientFormat(client, ":%s CAP * ACK :%s\r\n", ORIGIN, msg->params[1]);
  150. } else {
  151. clientFormat(client, ":%s CAP * NAK :%s\r\n", ORIGIN, msg->params[1]);
  152. }
  153. } else if (!strcmp(msg->params[0], "LIST")) {
  154. clientFormat(
  155. client, ":%s CAP * LIST :%s\r\n",
  156. ORIGIN, capList(client->caps)
  157. );
  158. } else {
  159. clientFormat(client, ":%s 410 * :Invalid CAP subcommand\r\n", ORIGIN);
  160. }
  161. }
  162. static void handleQuit(struct Client *client, struct Message *msg) {
  163. (void)msg;
  164. clientFormat(client, "ERROR :Detaching\r\n");
  165. client->error = true;
  166. }
  167. static void handlePrivmsg(struct Client *client, struct Message *msg) {
  168. if (!msg->params[0] || !msg->params[1]) return;
  169. char line[1024];
  170. snprintf(
  171. line, sizeof(line), ":%s %s %s :%s",
  172. stateEcho(), msg->cmd, msg->params[0], msg->params[1]
  173. );
  174. size_t diff = ringDiff(client->consumer);
  175. ringProduce(line);
  176. if (!diff) ringConsume(NULL, client->consumer);
  177. serverFormat("%s %s :%s\r\n", msg->cmd, msg->params[0], msg->params[1]);
  178. }
  179. static const struct {
  180. const char *cmd;
  181. Handler *fn;
  182. bool need;
  183. } Handlers[] = {
  184. { "CAP", handleCap, false },
  185. { "NICK", handleNick, false },
  186. { "NOTICE", handlePrivmsg, true },
  187. { "PASS", handlePass, false },
  188. { "PRIVMSG", handlePrivmsg, true },
  189. { "QUIT", handleQuit, true },
  190. { "USER", handleUser, false },
  191. };
  192. static void clientParse(struct Client *client, char *line) {
  193. struct Message msg = parse(line);
  194. if (!msg.cmd) return;
  195. for (size_t i = 0; i < ARRAY_LEN(Handlers); ++i) {
  196. if (strcmp(msg.cmd, Handlers[i].cmd)) continue;
  197. if (Handlers[i].need && client->need) break;
  198. Handlers[i].fn(client, &msg);
  199. return;
  200. }
  201. client->error = true;
  202. }
  203. static bool intercept(const char *line, size_t len) {
  204. if (len >= 4 && !memcmp(line, "CAP ", 4)) return true;
  205. if (len >= 5 && !memcmp(line, "QUIT ", 5)) return true;
  206. if (len >= 7 && !memcmp(line, "NOTICE ", 7)) return true;
  207. if (len >= 8 && !memcmp(line, "PRIVMSG ", 8)) return true;
  208. return false;
  209. }
  210. void clientRecv(struct Client *client) {
  211. assert(client->len < sizeof(client->buf));
  212. ssize_t read = tls_read(
  213. client->tls,
  214. &client->buf[client->len], sizeof(client->buf) - client->len
  215. );
  216. if (read == TLS_WANT_POLLIN || read == TLS_WANT_POLLOUT) return;
  217. if (read <= 0) {
  218. if (read < 0) warnx("client tls_read: %s", tls_error(client->tls));
  219. client->error = true;
  220. return;
  221. }
  222. client->len += read;
  223. char *crlf;
  224. char *line = client->buf;
  225. for (;;) {
  226. crlf = memmem(line, &client->buf[client->len] - line, "\r\n", 2);
  227. if (!crlf) break;
  228. if (verbose) {
  229. fprintf(stderr, "\x1B[33m%.*s\x1B[m\n", (int)(crlf - line), line);
  230. }
  231. if (client->need || intercept(line, crlf - line)) {
  232. crlf[0] = '\0';
  233. clientParse(client, line);
  234. } else {
  235. serverSend(line, crlf + 2 - line);
  236. }
  237. line = crlf + 2;
  238. }
  239. client->len -= line - client->buf;
  240. memmove(client->buf, line, client->len);
  241. }
  242. size_t clientDiff(const struct Client *client) {
  243. if (client->need) return 0;
  244. return ringDiff(client->consumer);
  245. }
  246. typedef const char *Filter(const char *line);
  247. static int strncmpn(const char *a, size_t alen, const char *b, size_t blen) {
  248. return alen == blen
  249. ? memcmp(a, b, alen)
  250. : alen - blen;
  251. }
  252. static size_t strlcpyn(char *dst, size_t cap, const char *src, size_t len) {
  253. if (len < cap) {
  254. memcpy(dst, src, len);
  255. dst[len] = '\0';
  256. } else {
  257. memcpy(dst, src, cap - 1);
  258. dst[cap - 1] = '\0';
  259. }
  260. return len;
  261. }
  262. static int wordcmp(const char *line, size_t i, const char *word) {
  263. while (i--) {
  264. line += strcspn(line, " ");
  265. if (*line) line++;
  266. }
  267. size_t len = strcspn(line, " ");
  268. return strncmpn(line, len, word, strlen(word));
  269. }
  270. static size_t wordcpy(char *dst, size_t cap, const char *src, size_t count) {
  271. size_t len = 0;
  272. while (count--) {
  273. if (src[len] == ' ') len++;
  274. len += strcspn(&src[len], " ");
  275. }
  276. return strlcpyn(dst, cap, src, len);
  277. }
  278. static const char *filterAccountNotify(const char *line) {
  279. return (wordcmp(line, 1, "ACCOUNT") ? line : NULL);
  280. }
  281. static const char *filterAwayNotify(const char *line) {
  282. return (wordcmp(line, 1, "AWAY") ? line : NULL);
  283. }
  284. static const char *filterChghost(const char *line) {
  285. return (wordcmp(line, 1, "CHGHOST") ? line : NULL);
  286. }
  287. static const char *filterExtendedJoin(const char *line) {
  288. if (wordcmp(line, 1, "JOIN")) return line;
  289. static char buf[512];
  290. wordcpy(buf, sizeof(buf), line, 3);
  291. return buf;
  292. }
  293. static const char *filterInviteNotify(const char *line) {
  294. if (wordcmp(line, 1, "INVITE")) return line;
  295. return (wordcmp(line, 2, stateNick()) ? NULL : line);
  296. }
  297. static const char *filterUserhostInNames(const char *line) {
  298. if (wordcmp(line, 1, "353")) return line;
  299. static char buf[512];
  300. size_t len = wordcpy(buf, sizeof(buf), line, 5);
  301. if (len >= sizeof(buf)) return NULL;
  302. line += len;
  303. while (*line) {
  304. size_t nick = strcspn(line, "!");
  305. len += strlcpyn(&buf[len], sizeof(buf) - len, line, nick);
  306. if (len >= sizeof(buf)) return NULL;
  307. line += nick;
  308. line += strcspn(line, " ");
  309. }
  310. return buf;
  311. }
  312. static Filter *Filters[] = {
  313. [CapAccountNotifyBit] = filterAccountNotify,
  314. [CapAwayNotifyBit] = filterAwayNotify,
  315. [CapChghostBit] = filterChghost,
  316. [CapExtendedJoinBit] = filterExtendedJoin,
  317. [CapInviteNotifyBit] = filterInviteNotify,
  318. [CapUserhostInNamesBit] = filterUserhostInNames,
  319. };
  320. void clientConsume(struct Client *client) {
  321. time_t time;
  322. const char *line = ringPeek(&time, client->consumer);
  323. if (!line) return;
  324. enum Cap diff = client->caps ^ stateCaps;
  325. for (size_t i = 0; line && i < ARRAY_LEN(Filters); ++i) {
  326. if (!Filters[i]) continue;
  327. if (diff & (1 << i)) line = Filters[i](line);
  328. }
  329. if (!line) {
  330. ringConsume(NULL, client->consumer);
  331. return;
  332. }
  333. // TODO: Move into a filter?
  334. if (client->caps & CapServerTime) {
  335. char ts[sizeof("YYYY-MM-DDThh:mm:ss.sssZ")];
  336. struct tm *tm = gmtime(&time);
  337. strftime(ts, sizeof(ts), "%FT%T.000Z", tm);
  338. clientFormat(client, "@time=%s %s\r\n", ts, line);
  339. } else {
  340. clientFormat(client, "%s\r\n", line);
  341. }
  342. if (!client->error) ringConsume(NULL, client->consumer);
  343. }