/* * irc_adapter.c -- dtchat's IRC adapter, protocol v1 on stdio * * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. * * T3.1 is the skeleton: hello with the setting schema, configure, connect, * a non-blocking TCP connection, the minimal RFC 1459 handshake (NICK/USER), * PING/PONG and the online state. TLS, CAP, SASL, the full parser, channels * and messages arrive with T3.2-T3.6; until then a "tls":true account gets a * clear, non-fatal error instead of a silent plain connection. */ #include "dc_internal.h" #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_LIBTLS #include #endif #include static char host[256] = "irc.libera.chat"; static int port = 6697; static int use_tls; static char nick[64] = ""; static char password[256] = ""; static char channels[512] = ""; static int configured; static int tls_want_write; static int want_connection; static long long reconnect_at; static int backoff_ms = 2000; static int nick_collisions; static int cap_done; static int sasl_offered; static int sasl_requested; static int sasl_done; static int tags_offered; static int tags_requested; static int have_message_tags; static char capbuf[1024]; static long long now_ms(void); /* is NAME a token in a space separated CAP list? */ static int cap_has(const char *list, const char *name) { size_t n = strlen(name); const char *p = list; while (p != NULL && *p != '\0') { while (*p == ' ') p++; if (strncmp(p, name, n) == 0 && (p[n] == '\0' || p[n] == ' ')) return 1; p = strchr(p, ' '); } return 0; } /* the value of KEY in an IRCv3 tag string ("a=b;+typing=active") */ static const char * tag_value(const char *tags, const char *key) { size_t n = strlen(key); const char *p = tags; if (p == NULL) return NULL; while (p != NULL && *p != '\0') { while (*p == ';') p++; if (strncmp(p, key, n) == 0 && p[n] == '=') return p + n + 1; p = strchr(p, ';'); } return NULL; } #ifdef HAVE_LIBTLS static struct tls *tls_ctx; #endif static void send_json(DcJson *json) { size_t len = 0; char *text; if (json == NULL) return; text = dc_json_write(json, &len); if (text != NULL) { (void)dc_frame_send(STDOUT_FILENO, text, len); free(text); } dc_json_free(json); } static void send_state(const char *state, const char *detail) { DcJson *json = dc_json_new_object(); (void)dc_json_object_set(json, "type", dc_json_new_string("state")); (void)dc_json_object_set(json, "state", dc_json_new_string(state)); if (detail != NULL && *detail != '\0') (void)dc_json_object_set(json, "detail", dc_json_new_string(detail)); send_json(json); } static void send_error(const char *code, const char *text, int fatal) { DcJson *json = dc_json_new_object(); (void)dc_json_object_set(json, "type", dc_json_new_string("error")); (void)dc_json_object_set(json, "code", dc_json_new_string(code)); (void)dc_json_object_set(json, "text", dc_json_new_string(text)); (void)dc_json_object_set(json, "fatal", dc_json_new_bool(fatal)); send_json(json); } static void send_hello(void) { DcJson *hello = dc_json_new_object(); DcJson *caps = dc_json_new_array(); DcJson *settings = dc_json_new_array(); static const char *const capnames[] = { "text", "channels", "typing" }; size_t i; for (i = 0; i < sizeof(capnames) / sizeof(capnames[0]); i++) (void)dc_json_array_append(caps, dc_json_new_string(capnames[i])); { DcJson *f = dc_json_new_object(); (void)dc_json_object_set(f, "key", dc_json_new_string("host")); (void)dc_json_object_set(f, "label", dc_json_new_string("Server")); (void)dc_json_object_set(f, "type", dc_json_new_string("text")); (void)dc_json_object_set(f, "required", dc_json_new_bool(1)); (void)dc_json_object_set(f, "default", dc_json_new_string("irc.libera.chat")); (void)dc_json_array_append(settings, f); } { DcJson *f = dc_json_new_object(); (void)dc_json_object_set(f, "key", dc_json_new_string("port")); (void)dc_json_object_set(f, "label", dc_json_new_string("Port")); (void)dc_json_object_set(f, "type", dc_json_new_string("int")); (void)dc_json_object_set(f, "default", dc_json_new_int(6697)); (void)dc_json_array_append(settings, f); } { DcJson *f = dc_json_new_object(); (void)dc_json_object_set(f, "key", dc_json_new_string("tls")); (void)dc_json_object_set(f, "label", dc_json_new_string("TLS")); (void)dc_json_object_set(f, "type", dc_json_new_string("bool")); (void)dc_json_object_set(f, "default", dc_json_new_bool(1)); (void)dc_json_array_append(settings, f); } { DcJson *f = dc_json_new_object(); (void)dc_json_object_set(f, "key", dc_json_new_string("nick")); (void)dc_json_object_set(f, "label", dc_json_new_string("Nickname")); (void)dc_json_object_set(f, "type", dc_json_new_string("text")); (void)dc_json_object_set(f, "required", dc_json_new_bool(1)); (void)dc_json_array_append(settings, f); } { DcJson *f = dc_json_new_object(); (void)dc_json_object_set(f, "key", dc_json_new_string("password")); (void)dc_json_object_set(f, "label", dc_json_new_string("Password")); (void)dc_json_object_set(f, "type", dc_json_new_string("secret")); (void)dc_json_array_append(settings, f); } { DcJson *f = dc_json_new_object(); (void)dc_json_object_set(f, "key", dc_json_new_string("channels")); (void)dc_json_object_set(f, "label", dc_json_new_string("Channels")); (void)dc_json_object_set(f, "type", dc_json_new_string("text")); (void)dc_json_object_set(f, "help", dc_json_new_string("comma separated")); (void)dc_json_array_append(settings, f); } (void)dc_json_object_set(hello, "type", dc_json_new_string("hello")); (void)dc_json_object_set(hello, "ipc", dc_json_new_int(DC_IPC_VERSION)); (void)dc_json_object_set(hello, "protocol", dc_json_new_string("irc")); (void)dc_json_object_set(hello, "version", dc_json_new_string("0.1")); (void)dc_json_object_set(hello, "caps", caps); (void)dc_json_object_set(hello, "settings", settings); send_json(hello); } static int set_nonblock(int fd) { int fl = fcntl(fd, F_GETFL, 0); if (fl < 0) return -1; return fcntl(fd, F_SETFL, fl | O_NONBLOCK); } /* Open the TCP connection; returns the fd or -1. */ static int open_socket(void) { struct addrinfo hints; struct addrinfo *res = NULL; struct addrinfo *ai; char service[16]; int fd = -1; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; snprintf(service, sizeof(service), "%d", port); if (getaddrinfo(host, service, &hints, &res) != 0) { send_error("network", "cannot resolve the IRC server", 0); send_state("offline", NULL); return -1; } for (ai = res; ai != NULL; ai = ai->ai_next) { int err = 0; socklen_t errlen = sizeof(err); fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (fd < 0) continue; (void)set_nonblock(fd); if (connect(fd, ai->ai_addr, ai->ai_addrlen) != 0) { struct pollfd p; if (errno != EINPROGRESS) { close(fd); fd = -1; continue; } p.fd = fd; p.events = POLLOUT; p.revents = 0; if (poll(&p, 1, 5000) <= 0 || getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) != 0 || err != 0) { close(fd); fd = -1; continue; } } break; } freeaddrinfo(res); if (fd < 0) { send_error("network", "cannot connect to the IRC server", 0); send_state("offline", NULL); } return fd; } static void schedule_reconnect(void) { if (!want_connection) return; send_state("offline", NULL); reconnect_at = now_ms() + backoff_ms; backoff_ms = backoff_ms * 2 > 60000 ? 60000 : backoff_ms * 2; } static char * b64_encode(const unsigned char *in, size_t len) { static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; char *out = malloc((len + 2) / 3 * 4 + 1); size_t i, o = 0; if (out == NULL) return NULL; for (i = 0; i + 2 < len; i += 3) { out[o++] = table[in[i] >> 2]; out[o++] = table[((in[i] & 3) << 4) | (in[i + 1] >> 4)]; out[o++] = table[((in[i + 1] & 15) << 2) | (in[i + 2] >> 6)]; out[o++] = table[in[i + 2] & 63]; } if (i < len) { out[o++] = table[in[i] >> 2]; if (i + 1 < len) { out[o++] = table[((in[i] & 3) << 4) | (in[i + 1] >> 4)]; out[o++] = table[(in[i + 1] & 15) << 2]; } else { out[o++] = table[(in[i] & 3) << 4]; out[o++] = '='; } out[o++] = '='; } out[o] = '\0'; return out; } #ifdef HAVE_LIBTLS static int tls_begin(int fd) { struct tls_config *cfg; const char *ca; struct timeval tv; int fl; if (tls_init() != 0) { send_error("tls", "tls_init failed", 0); return -1; } cfg = tls_config_new(); if (cfg == NULL) { send_error("tls", "out of memory", 0); return -1; } ca = getenv("DTCHAT_TLS_CA"); if (ca != NULL && *ca != '\0' && tls_config_set_ca_file(cfg, ca) != 0) { send_error("tls", "cannot load the CA file", 0); tls_config_free(cfg); return -1; } tls_ctx = tls_client(); if (tls_ctx == NULL) { send_error("tls", "out of memory", 0); tls_config_free(cfg); return -1; } if (tls_configure(tls_ctx, cfg) != 0) { send_error("tls", tls_error(tls_ctx), 0); tls_free(tls_ctx); tls_ctx = NULL; tls_config_free(cfg); return -1; } tls_config_free(cfg); tv.tv_sec = 10; tv.tv_usec = 0; (void)setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); (void)setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); fl = fcntl(fd, F_GETFL, 0); if (fl >= 0) (void)fcntl(fd, F_SETFL, fl & ~O_NONBLOCK); if (tls_connect_socket(tls_ctx, fd, host) != 0 || tls_handshake(tls_ctx) != 0) { send_error("tls", tls_error(tls_ctx), 0); (void)tls_close(tls_ctx); tls_free(tls_ctx); tls_ctx = NULL; return -1; } fl = fcntl(fd, F_GETFL, 0); if (fl >= 0) (void)fcntl(fd, F_SETFL, fl | O_NONBLOCK); tv.tv_sec = 0; tv.tv_usec = 0; (void)setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); (void)setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); return 0; } #else static int tls_begin(int fd) { (void)fd; send_error("tls", "this build has no libtls", 0); return -1; } #endif static void tls_teardown(void) { #ifdef HAVE_LIBTLS if (tls_ctx != NULL) { (void)tls_close(tls_ctx); tls_free(tls_ctx); tls_ctx = NULL; } #endif } static int send_all(int fd, const char *text) { size_t left = strlen(text); while (left > 0) { #ifdef HAVE_LIBTLS if (tls_ctx != NULL) { ssize_t n = tls_write(tls_ctx, text, left); if (n == TLS_WANT_POLLIN || n == TLS_WANT_POLLOUT) { struct pollfd p; p.fd = fd; p.events = n == TLS_WANT_POLLIN ? POLLIN : POLLOUT; p.revents = 0; if (poll(&p, 1, 2000) <= 0) return -1; continue; } if (n <= 0) return -1; text += n; left -= (size_t)n; continue; } #endif { ssize_t n = write(fd, text, left); if (n < 0) { if (errno == EINTR) continue; if (errno == EAGAIN) { struct pollfd p; p.fd = fd; p.events = POLLOUT; p.revents = 0; if (poll(&p, 1, 2000) <= 0) return -1; continue; } return -1; } text += n; left -= (size_t)n; } } return 0; } static ssize_t connection_read(int fd, char *buf, size_t len) { #ifdef HAVE_LIBTLS if (tls_ctx != NULL) { ssize_t n = tls_read(tls_ctx, buf, len); if (n == TLS_WANT_POLLIN) return -1; if (n == TLS_WANT_POLLOUT) return -2; return n; } #endif return read(fd, buf, len); } #define IRC_OUTQ_MAX 128 #define IRC_OUTQ_LINE 600 static char outq[IRC_OUTQ_MAX][IRC_OUTQ_LINE]; static size_t outq_head; static size_t outq_tail; static double outq_tokens = 4.0; static long long outq_last_ms; static long long now_ms(void) { struct timespec ts; (void)clock_gettime(CLOCK_MONOTONIC, &ts); return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } static void queue_line(const char *line) { size_t next = (outq_tail + 1) % IRC_OUTQ_MAX; if (next == outq_head) return; /* queue full: drop */ snprintf(outq[outq_tail], IRC_OUTQ_LINE, "%s", line); outq_tail = next; } /* * Send queued lines with a 4-message burst and 2 messages/s afterwards. * Returns the milliseconds until the next token is due, or -1 when idle. */ static long long pump_outq(int fd) { long long now; double need; if (fd < 0) return -1; if (outq_last_ms == 0) outq_last_ms = now_ms(); now = now_ms(); outq_tokens += (double)(now - outq_last_ms) * 0.002; if (outq_tokens > 4.0) outq_tokens = 4.0; outq_last_ms = now; while (outq_head != outq_tail && outq_tokens >= 1.0) { (void)send_all(fd, outq[outq_head]); outq_head = (outq_head + 1) % IRC_OUTQ_MAX; outq_tokens -= 1.0; } if (outq_head == outq_tail) return -1; need = 1.0 - outq_tokens; return (long long)(need / 0.002) + 1; } static void handshake(int fd) { char line[512]; cap_done = 0; sasl_offered = 0; sasl_requested = 0; sasl_done = 0; tags_offered = 0; tags_requested = 0; have_message_tags = 0; capbuf[0] = '\0'; (void)send_all(fd, "CAP LS 302\r\n"); if (password[0] != '\0') { snprintf(line, sizeof(line), "PASS %s\r\n", password); (void)send_all(fd, line); } snprintf(line, sizeof(line), "NICK %s\r\n", nick); (void)send_all(fd, line); snprintf(line, sizeof(line), "USER %s 0 * :%s\r\n", nick, nick); (void)send_all(fd, line); } static void start_connection(int *sockp) { int fd; send_state("connecting", host); fd = open_socket(); if (fd < 0) { schedule_reconnect(); return; } if (use_tls && tls_begin(fd) != 0) { close(fd); schedule_reconnect(); return; } *sockp = fd; handshake(fd); } #define IRC_MAX_CHANNELS 16 #define IRC_MAX_MEMBERS 128 typedef struct { char nick[64]; char mode; /* '@' op, '+' voice, 0 none */ } IrcMember; typedef struct { char name[128]; char topic[512]; IrcMember members[IRC_MAX_MEMBERS]; size_t nmembers; int names_started; } IrcChannel; static IrcChannel irc_channels[IRC_MAX_CHANNELS]; static size_t irc_nchannels; static char direct_convs[32][64]; static size_t ndirect; static int direct_seen(const char *name) { size_t i; for (i = 0; i < ndirect; i++) if (strcmp(direct_convs[i], name) == 0) return 1; if (ndirect == 32) return 1; snprintf(direct_convs[ndirect++], sizeof(direct_convs[0]), "%s", name); return 0; } static IrcChannel * channel_find(const char *name) { size_t i; if (name == NULL) return NULL; for (i = 0; i < irc_nchannels; i++) if (strcmp(irc_channels[i].name, name) == 0) return &irc_channels[i]; return NULL; } static IrcChannel * channel_get(const char *name) { IrcChannel *ch = channel_find(name); if (ch != NULL || name == NULL || *name != '#') return ch; if (irc_nchannels == IRC_MAX_CHANNELS) return NULL; ch = &irc_channels[irc_nchannels++]; memset(ch, 0, sizeof(*ch)); snprintf(ch->name, sizeof(ch->name), "%s", name); return ch; } static IrcMember * member_find(IrcChannel *ch, const char *nickname) { size_t i; if (ch == NULL || nickname == NULL) return NULL; for (i = 0; i < ch->nmembers; i++) if (strcmp(ch->members[i].nick, nickname) == 0) return &ch->members[i]; return NULL; } static void send_roster(const char *chan, const char *name, char mode) { DcJson *json = dc_json_new_object(); DcJson *contact = dc_json_new_object(); (void)dc_json_object_set(json, "type", dc_json_new_string("roster")); (void)dc_json_object_set(json, "conv", dc_json_new_string(chan)); (void)dc_json_object_set(contact, "id", dc_json_new_string(name)); (void)dc_json_object_set(contact, "name", dc_json_new_string(name)); (void)dc_json_object_set(contact, "mode", dc_json_new_string(mode == '@' ? "@" : mode == '+' ? "+" : "")); (void)dc_json_object_set(json, "contact", contact); send_json(json); } static void send_presence(const char *chan, const char *name, int online, const char *status) { DcJson *json = dc_json_new_object(); (void)dc_json_object_set(json, "type", dc_json_new_string("presence")); (void)dc_json_object_set(json, "conv", dc_json_new_string(chan)); (void)dc_json_object_set(json, "buddy", dc_json_new_string(name)); (void)dc_json_object_set(json, "show", dc_json_new_string(online ? "online" : "offline")); if (status != NULL && *status != '\0') (void)dc_json_object_set(json, "status", dc_json_new_string(status)); send_json(json); } static void send_kind_message(const char *conv, const char *from, const char *kind, const char *text) { DcJson *json = dc_json_new_object(); (void)dc_json_object_set(json, "type", dc_json_new_string("message")); (void)dc_json_object_set(json, "conv", dc_json_new_string(conv)); (void)dc_json_object_set(json, "from", dc_json_new_string(from != NULL && *from != '\0' ? from : "system")); (void)dc_json_object_set(json, "kind", dc_json_new_string(kind)); (void)dc_json_object_set(json, "text", dc_json_new_string(text)); (void)dc_json_object_set(json, "ts", dc_json_new_int((long long)time(NULL))); send_json(json); } static void send_conversation_kind(const char *conv, const char *kind, const char *topic) { DcJson *json = dc_json_new_object(); (void)dc_json_object_set(json, "type", dc_json_new_string("conversation")); (void)dc_json_object_set(json, "conv", dc_json_new_string(conv)); (void)dc_json_object_set(json, "kind", dc_json_new_string(kind)); (void)dc_json_object_set(json, "title", dc_json_new_string(conv)); if (topic != NULL && *topic != '\0') (void)dc_json_object_set(json, "topic", dc_json_new_string(topic)); send_json(json); } static void send_conversation(const char *conv, const char *topic) { send_conversation_kind(conv, "channel", topic); } /* "nick!user@host" or "nick" -> "nick" in OUT. */ static void prefix_nick(const char *prefix, char *out, size_t outlen) { size_t i = 0; if (prefix == NULL) prefix = ""; while (prefix[i] != '\0' && prefix[i] != '!' && prefix[i] != '@' && i + 1 < outlen) { out[i] = prefix[i]; i++; } out[i] = '\0'; } static const char * member_status(char mode) { if (mode == '@') return "op"; if (mode == '+') return "voice"; return NULL; } static void member_remove(IrcChannel *ch, const char *name) { size_t i; if (ch == NULL || name == NULL) return; for (i = 0; i < ch->nmembers; i++) { if (strcmp(ch->members[i].nick, name) == 0) { memmove(&ch->members[i], &ch->members[i + 1], (ch->nmembers - i - 1) * sizeof(ch->members[0])); ch->nmembers--; return; } } } static void join_configured_channels(int fd) { char list[512]; char *save = NULL; char *tok; snprintf(list, sizeof(list), "%s", channels); for (tok = strtok_r(list, ", ", &save); tok != NULL; tok = strtok_r(NULL, ", ", &save)) { char line[256]; if (*tok != '#') continue; snprintf(line, sizeof(line), "JOIN %s\r\n", tok); (void)send_all(fd, line); } } static void handle_names(const DcIrcMessage *msg) { IrcChannel *ch; char *list; char *save = NULL; char *tok; if (msg->nparams < 3 || msg->trailing == NULL) return; ch = channel_get(msg->params[2]); if (ch == NULL) return; if (!ch->names_started) { ch->nmembers = 0; ch->names_started = 1; } list = strdup(msg->trailing); if (list == NULL) return; for (tok = strtok_r(list, " ", &save); tok != NULL; tok = strtok_r(NULL, " ", &save)) { char mode = 0; const char *name = tok; IrcMember *m; if (*name == '@' || *name == '+') { mode = *name; name++; } if (*name == '\0' || strcmp(name, nick) == 0) continue; m = member_find(ch, name); if (m == NULL) { if (ch->nmembers == IRC_MAX_MEMBERS) continue; m = &ch->members[ch->nmembers++]; snprintf(m->nick, sizeof(m->nick), "%s", name); } m->mode = mode; send_roster(ch->name, m->nick, m->mode); } free(list); } static void handle_mode(IrcChannel *ch, const DcIrcMessage *msg) { const char *flags; size_t arg = 2; int adding = 1; size_t i; if (ch == NULL || msg->nparams < 2) return; flags = msg->params[1]; for (i = 0; flags[i] != '\0'; i++) { IrcMember *m; const char *name; if (flags[i] == '+') { adding = 1; continue; } if (flags[i] == '-') { adding = 0; continue; } if (flags[i] != 'o' && flags[i] != 'v') continue; if (arg >= msg->nparams) break; name = msg->params[arg++]; m = member_find(ch, name); if (m == NULL) continue; m->mode = adding ? (flags[i] == 'o' ? '@' : '+') : 0; send_presence(ch->name, m->nick, 1, member_status(m->mode)); } } static void handle_line(int fd, const char *line) { DcIrcMessage msg; char err[128]; if (dc_irc_parse(line, strlen(line), &msg, err, sizeof(err)) != 0) { send_error("protocol", err, 0); return; } if (strcmp(msg.command, "PING") == 0) { const char *token = msg.trailing != NULL ? msg.trailing : (msg.nparams > 0 ? msg.params[0] : ""); char reply[512]; snprintf(reply, sizeof(reply), "PONG :%s\r\n", token); (void)send_all(fd, reply); } else if (strcmp(msg.command, "001") == 0) { backoff_ms = 2000; nick_collisions = 0; reconnect_at = 0; send_state("online", host); join_configured_channels(fd); } else if (strcmp(msg.command, "353") == 0) { handle_names(&msg); } else if (strcmp(msg.command, "366") == 0) { IrcChannel *ch; if (msg.nparams >= 2) { ch = channel_find(msg.params[1]); if (ch != NULL) ch->names_started = 0; } } else if (strcmp(msg.command, "JOIN") == 0) { const char *chan = msg.trailing != NULL && msg.trailing[0] == '#' ? msg.trailing : (msg.nparams > 0 ? msg.params[0] : NULL); char who[64]; prefix_nick(msg.prefix, who, sizeof(who)); if (chan != NULL) { IrcChannel *ch = channel_get(chan); char line[256]; if (ch != NULL) { if (strcmp(who, nick) == 0) { send_conversation(ch->name, ch->topic); } else { IrcMember *m = member_find(ch, who); if (m == NULL && ch->nmembers < IRC_MAX_MEMBERS) { m = &ch->members[ch->nmembers++]; snprintf(m->nick, sizeof(m->nick), "%s", who); m->mode = 0; } if (m != NULL) send_roster(ch->name, m->nick, m->mode); send_presence(ch->name, who, 1, NULL); } snprintf(line, sizeof(line), "%s joined %s", who, ch->name); send_kind_message(ch->name, who, "system", line); } } } else if (strcmp(msg.command, "PART") == 0) { const char *chan = msg.nparams > 0 ? msg.params[0] : NULL; char who[64]; prefix_nick(msg.prefix, who, sizeof(who)); if (chan != NULL) { IrcChannel *ch = channel_find(chan); char line[256]; if (ch != NULL) { member_remove(ch, who); send_presence(ch->name, who, 0, NULL); snprintf(line, sizeof(line), "%s left %s", who, ch->name); send_kind_message(ch->name, who, "system", line); } } } else if (strcmp(msg.command, "QUIT") == 0) { char who[64]; size_t i; prefix_nick(msg.prefix, who, sizeof(who)); for (i = 0; i < irc_nchannels; i++) { IrcChannel *ch = &irc_channels[i]; char line[256]; if (member_find(ch, who) == NULL) continue; member_remove(ch, who); send_presence(ch->name, who, 0, NULL); snprintf(line, sizeof(line), "%s quit", who); send_kind_message(ch->name, who, "system", line); } } else if (strcmp(msg.command, "KICK") == 0) { const char *chan = msg.nparams > 0 ? msg.params[0] : NULL; const char *target = msg.nparams > 1 ? msg.params[1] : NULL; char who[64]; char line[512]; prefix_nick(msg.prefix, who, sizeof(who)); if (chan != NULL && target != NULL) { IrcChannel *ch = channel_find(chan); if (ch != NULL) { member_remove(ch, target); send_presence(ch->name, target, 0, NULL); snprintf(line, sizeof(line), "%s was kicked by %s%s%s", target, who, msg.trailing != NULL ? ": " : "", msg.trailing != NULL ? msg.trailing : ""); send_kind_message(ch->name, who, "system", line); } } } else if (strcmp(msg.command, "NICK") == 0) { char oldnick[64]; const char *newnick = msg.trailing != NULL ? msg.trailing : (msg.nparams > 0 ? msg.params[0] : NULL); size_t i; prefix_nick(msg.prefix, oldnick, sizeof(oldnick)); if (newnick != NULL && *newnick != '\0') { if (strcmp(oldnick, nick) == 0) snprintf(nick, sizeof(nick), "%s", newnick); for (i = 0; i < irc_nchannels; i++) { IrcChannel *ch = &irc_channels[i]; IrcMember *m = member_find(ch, oldnick); char line[256]; if (m == NULL) continue; snprintf(m->nick, sizeof(m->nick), "%s", newnick); send_roster(ch->name, m->nick, m->mode); send_presence(ch->name, m->nick, 1, member_status(m->mode)); snprintf(line, sizeof(line), "%s is now %s", oldnick, newnick); send_kind_message(ch->name, newnick, "system", line); } } } else if (strcmp(msg.command, "TOPIC") == 0) { const char *chan = msg.nparams > 0 ? msg.params[0] : NULL; char who[64]; prefix_nick(msg.prefix, who, sizeof(who)); if (chan != NULL) { IrcChannel *ch = channel_find(chan); char line[1024]; if (ch != NULL) { snprintf(ch->topic, sizeof(ch->topic), "%s", msg.trailing != NULL ? msg.trailing : ""); send_conversation(ch->name, ch->topic); snprintf(line, sizeof(line), "%s changed the topic to: %s", who, ch->topic); send_kind_message(ch->name, who, "system", line); } } } else if (strcmp(msg.command, "MODE") == 0) { if (msg.nparams >= 1) { IrcChannel *ch = channel_find(msg.params[0]); handle_mode(ch, &msg); } } else if (strcmp(msg.command, "TAGMSG") == 0 || strcmp(msg.command, "PRIVMSG") == 0 || strcmp(msg.command, "NOTICE") == 0) { const char *target = msg.nparams > 0 ? msg.params[0] : NULL; const char *typing = tag_value(msg.tags, "+typing"); if (typing != NULL) { char who[64]; char conv[128]; DcJson *json; prefix_nick(msg.prefix, who, sizeof(who)); if (target != NULL && *target == '#') snprintf(conv, sizeof(conv), "%s", target); else snprintf(conv, sizeof(conv), "%s", who); json = dc_json_new_object(); (void)dc_json_object_set(json, "type", dc_json_new_string("typing")); (void)dc_json_object_set(json, "conv", dc_json_new_string(conv)); (void)dc_json_object_set(json, "on", dc_json_new_bool(strcmp(typing, "active") == 0)); (void)dc_json_object_set(json, "who", dc_json_new_string(who)); send_json(json); } if (strcmp(msg.command, "TAGMSG") == 0) { dc_irc_message_free(&msg); return; } const char *text = msg.trailing != NULL ? msg.trailing : ""; char from[64]; char conv[128]; const char *body = text; const char *kind = strcmp(msg.command, "NOTICE") == 0 ? "notice" : "text"; size_t blen = strlen(text); prefix_nick(msg.prefix, from, sizeof(from)); if (target == NULL || *target == '\0' || strcmp(from, "system") == 0) { dc_irc_message_free(&msg); return; } if (*target == '#') { snprintf(conv, sizeof(conv), "%s", target); } else { snprintf(conv, sizeof(conv), "%s", from); if (!direct_seen(conv)) send_conversation_kind(conv, "direct", NULL); } /* CTCP ACTION */ if (blen >= 9 && strncmp(body, "\001" "ACTION ", 8) == 0 && body[blen - 1] == '\001') { kind = "action"; body += 8; blen -= 9; { char *cut = strndup(body, blen); if (cut != NULL) { send_kind_message(conv, from, kind, cut); free(cut); } } } else if (blen >= 2 && body[0] == '\001' && body[blen - 1] == '\001') { /* other CTCP (VERSION, TIME, ...): ignore in T3.5 */ } else { send_kind_message(conv, from, kind, body); } } else if (strcmp(msg.command, "ERROR") == 0) { send_error("protocol", msg.trailing != NULL ? msg.trailing : "server error", 0); } else if (strcmp(msg.command, "433") == 0) { if (nick_collisions < 3 && strlen(nick) < 60) { char line[128]; nick_collisions++; strcat(nick, "_"); snprintf(line, sizeof(line), "NICK %s\r\n", nick); (void)send_all(fd, line); } else { send_error("nick", "nickname already in use", 0); (void)send_all(fd, "QUIT :nick in use\r\n"); } } else if (strcmp(msg.command, "CAP") == 0) { const char *sub = msg.nparams > 1 ? msg.params[1] : ""; if (strcmp(sub, "LS") == 0) { size_t used = strlen(capbuf); if (msg.trailing != NULL && *msg.trailing != '\0') { snprintf(capbuf + used, sizeof(capbuf) - used, "%s%s", used > 0 ? " " : "", msg.trailing); } if (!(msg.nparams > 2 && strcmp(msg.params[2], "*") == 0)) { char req[128] = "CAP REQ :"; size_t used = strlen(req); int any = 0; sasl_offered = cap_has(capbuf, "sasl"); tags_offered = cap_has(capbuf, "message-tags"); if (password[0] != '\0' && sasl_offered) { snprintf(req + used, sizeof(req) - used, "sasl"); used = strlen(req); sasl_requested = 1; any = 1; } if (tags_offered) { snprintf(req + used, sizeof(req) - used, "%smessage-tags", any ? " " : ""); tags_requested = 1; any = 1; } if (any) { (void)send_all(fd, req); (void)send_all(fd, "\r\n"); } else { (void)send_all(fd, "CAP END\r\n"); cap_done = 1; } } } else if (strcmp(sub, "ACK") == 0) { if (msg.trailing != NULL && strstr(msg.trailing, "message-tags") != NULL) have_message_tags = 1; if (sasl_requested && msg.trailing != NULL && strstr(msg.trailing, "sasl") != NULL) { (void)send_all(fd, "AUTHENTICATE PLAIN\r\n"); } else if (!sasl_requested) { (void)send_all(fd, "CAP END\r\n"); cap_done = 1; } } else if (strcmp(sub, "NAK") == 0) { have_message_tags = 0; (void)send_all(fd, "CAP END\r\n"); cap_done = 1; } } else if (strcmp(msg.command, "AUTHENTICATE") == 0) { const char *arg = msg.nparams > 0 ? msg.params[0] : msg.trailing; if (arg != NULL && strcmp(arg, "+") == 0) { size_t plen = strlen(nick) + strlen(password) + 2; unsigned char *payload = malloc(plen); char *encoded; char line[1024]; if (payload != NULL) { size_t off = 0; payload[off++] = '\0'; memcpy(payload + off, nick, strlen(nick)); off += strlen(nick); payload[off++] = '\0'; memcpy(payload + off, password, strlen(password)); off += strlen(password); encoded = b64_encode(payload, off); if (encoded != NULL) { snprintf(line, sizeof(line), "AUTHENTICATE %s\r\n", encoded); (void)send_all(fd, line); free(encoded); } free(payload); } } } else if (strcmp(msg.command, "900") == 0 || strcmp(msg.command, "903") == 0) { sasl_done = 1; (void)send_all(fd, "CAP END\r\n"); cap_done = 1; } else if (strcmp(msg.command, "904") == 0 || strcmp(msg.command, "905") == 0 || strcmp(msg.command, "906") == 0) { DcJson *bye = dc_json_new_object(); send_error("auth", "SASL authentication failed", 1); (void)dc_json_object_set(bye, "type", dc_json_new_string("bye")); (void)dc_json_object_set(bye, "reason", dc_json_new_string("auth")); send_json(bye); _exit(0); } dc_irc_message_free(&msg); } static void read_stdin(DcFrameBuf *frame, int *sockp) { char buf[4096]; ssize_t n = read(STDIN_FILENO, buf, sizeof(buf)); if (n <= 0) return; if (dc_frame_feed(frame, buf, (size_t)n) != 0) return; for (;;) { size_t len = 0; char *line = dc_frame_next(frame, &len); DcJson *cmd; const char *type; if (line == NULL) break; cmd = dc_json_parse(line, len, NULL, 0); free(line); if (cmd == NULL) { send_error("protocol", "invalid JSON command", 0); continue; } type = dc_json_string(dc_json_get(cmd, "type")); if (type == NULL) { dc_json_free(cmd); continue; } if (strcmp(type, "configure") == 0) { DcJson *settings = dc_json_get(cmd, "settings"); DcJson *secrets = dc_json_get(cmd, "secrets"); const char *v; v = dc_json_string(dc_json_get(settings, "host")); if (v != NULL && *v != '\0') snprintf(host, sizeof(host), "%s", v); v = dc_json_string(dc_json_get(settings, "nick")); if (v != NULL) snprintf(nick, sizeof(nick), "%s", v); v = dc_json_string(dc_json_get(settings, "channels")); if (v != NULL) snprintf(channels, sizeof(channels), "%s", v); if (dc_json_get(settings, "port") != NULL) port = (int)dc_json_int(dc_json_get(settings, "port")); use_tls = dc_json_bool(dc_json_get(settings, "tls")); v = dc_json_string(dc_json_get(secrets, "password")); if (v != NULL) snprintf(password, sizeof(password), "%s", v); configured = 1; } else if (strcmp(type, "connect") == 0) { if (!configured || nick[0] == '\0') { send_error("config", "nickname is required", 0); send_state("offline", NULL); } else { want_connection = 1; backoff_ms = 2000; reconnect_at = 0; start_connection(sockp); } } else if (strcmp(type, "join") == 0) { const char *conv = dc_json_string( dc_json_get(cmd, "conv")); if (*sockp >= 0 && conv != NULL && *conv != '\0') { char line[300]; snprintf(line, sizeof(line), "JOIN %s\r\n", conv); queue_line(line); } } else if (strcmp(type, "part") == 0) { const char *conv = dc_json_string( dc_json_get(cmd, "conv")); const char *reason = dc_json_string( dc_json_get(cmd, "reason")); if (*sockp >= 0 && conv != NULL && *conv != '\0') { char line[400]; snprintf(line, sizeof(line), "PART %s :%s\r\n", conv, reason != NULL ? reason : "bye"); queue_line(line); } } else if (strcmp(type, "disconnect") == 0) { DcJson *bye = dc_json_new_object(); want_connection = 0; (void)dc_json_object_set(bye, "type", dc_json_new_string("bye")); (void)dc_json_object_set(bye, "reason", dc_json_new_string("requested")); send_json(bye); _exit(0); } else if (strcmp(type, "send") == 0) { if (*sockp >= 0) { const char *conv = dc_json_string( dc_json_get(cmd, "conv")); const char *text = dc_json_string( dc_json_get(cmd, "text")); char chunk[512]; char line[600]; size_t off = 0; size_t budget; size_t n; if (conv == NULL) conv = ""; if (text == NULL) text = ""; budget = 512 > strlen(conv) + 12 ? 512 - strlen(conv) - 12 : 1; if (budget > sizeof(chunk) - 1) budget = sizeof(chunk) - 1; while ((n = dc_irc_split_next(text, &off, budget, chunk, sizeof(chunk))) > 0) { snprintf(line, sizeof(line), "PRIVMSG %s :%s\r\n", conv, chunk); queue_line(line); } (void)n; } } else if (strcmp(type, "typing") == 0) { const char *conv = dc_json_string( dc_json_get(cmd, "conv")); int on = dc_json_bool(dc_json_get(cmd, "on")); if (*sockp >= 0 && have_message_tags && conv != NULL && *conv != '\0') { char line[300]; snprintf(line, sizeof(line), "@+typing=%s TAGMSG %s\r\n", on ? "active" : "paused", conv); queue_line(line); } } dc_json_free(cmd); } } int main(int argc, char **argv) { DcFrameBuf frame; char inbuf[8192]; size_t inlen = 0; int sock = -1; (void)argc; (void)argv; signal(SIGPIPE, SIG_IGN); dc_frame_init(&frame); send_hello(); for (;;) { struct pollfd fds[2]; int nfds = 0; int ret; fds[nfds].fd = STDIN_FILENO; fds[nfds].events = POLLIN; fds[nfds].revents = 0; nfds++; if (sock >= 0) { fds[nfds].fd = sock; fds[nfds].events = POLLIN | (tls_want_write ? POLLOUT : 0); fds[nfds].revents = 0; nfds++; } { long long wait = pump_outq(sock); if (reconnect_at > 0 && sock < 0) { long long due = reconnect_at - now_ms(); if (due <= 0) { reconnect_at = 0; start_connection(&sock); continue; } if (wait < 0 || due < wait) wait = due; } ret = poll(fds, (nfds_t)nfds, wait < 0 ? -1 : (int)wait); } if (ret < 0) { if (errno == EINTR) continue; break; } if (fds[0].revents & (POLLIN | POLLHUP)) read_stdin(&frame, &sock); if (nfds > 1 && fds[1].revents != 0) { if (fds[1].revents & (POLLIN | POLLHUP | POLLERR)) { char buf[4096]; ssize_t n = connection_read(sock, buf, sizeof(buf)); if (n == -1 || n == -2) { tls_want_write = n == -2; } else if (n <= 0) { tls_teardown(); tls_want_write = 0; close(sock); sock = -1; inlen = 0; schedule_reconnect(); } else { char *start; char *nl; size_t used; if (inlen + (size_t)n >= sizeof(inbuf)) { inlen = 0; } memcpy(inbuf + inlen, buf, (size_t)n); inlen += (size_t)n; inbuf[inlen] = '\0'; start = inbuf; while ((nl = strstr(start, "\r\n")) != NULL) { *nl = '\0'; handle_line(sock, start); start = nl + 2; } used = (size_t)(start - inbuf); memmove(inbuf, start, inlen - used); inlen -= used; inbuf[inlen] = '\0'; } } } } tls_teardown(); if (sock >= 0) close(sock); dc_frame_free(&frame); return 0; }