/* * irc9 - a deliberately minimal console IRC client. * * No networks, no settings commands, no plugins. Just servers, windows, * and ctrl-n / ctrl-p to walk through them. */ #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE 700 #endif #include #ifdef __APPLE__ #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef USE_OPENSSL #include #include #include #endif #define HOSTLEN 128 #define NICKLEN 64 #define CHANLEN 128 #define INBUF 4096 #define MAXLINE 512 #define MAXINPUT 512 #define MAXHIST 64 #define MAXSCROLL 500 #define MAXSCROLLROWS (MAXSCROLL * 128) /* push_wrapped emits at most 128 rows per line */ #define TREEW 24 #define RETRY 5 #define CAP_NONE 0 #define CAP_LS 1 #define CAP_REQ 2 #define CAP_AUTH 3 typedef enum { W_SERVER, W_CHANNEL, W_QUERY } Wintype; typedef struct Member { char nick[NICKLEN]; uint32_t status; struct Member *next; } Member; typedef struct Window { char name[CHANLEN]; char hostmask[128]; Wintype type; struct Server *srv; struct Window *next; char **lines; int nlines; int unread; int scroll; int syncing; struct timespec join_ts; Member *members; } Window; #ifdef USE_AUTOJOIN typedef struct AutojoinChannel { char name[CHANLEN]; struct AutojoinChannel *next; } AutojoinChannel; #endif typedef struct Server { char host[HOSTLEN]; int port; char nick[NICKLEN]; char user[NICKLEN]; char real[128]; int fd; int connected; int connecting; unsigned long connect_gen; time_t retry_at; char inbuf[INBUF]; size_t inlen; Window *windows; Window *reply_win; /* where command replies are printed */ int tls; int sasl; char sasl_user[NICKLEN]; char sasl_pass[128]; int cap_state; char caps[512]; /* accumulated multi-line CAP LS reply */ char umode[32]; char prefix_modes[32], prefix_symbols[32], chanmodes[128]; #ifdef USE_OPENSSL SSL *ssl; #endif #ifdef USE_AUTOJOIN AutojoinChannel *autojoin; #endif struct Server *next; } Server; /* A finished connection attempt, handed from the worker to the UI thread. */ typedef struct ConnectResult { Server *s; unsigned long gen; int fd; char err[128]; #ifdef USE_OPENSSL SSL *ssl; #endif } ConnectResult; /* Immutable snapshot passed to a worker; the UI may change the Server meanwhile. */ typedef struct ConnectJob { Server *s; char host[HOSTLEN]; int port; #ifdef USE_OPENSSL int tls; #endif unsigned long gen; } ConnectJob; static Server *servers; static int connect_pipe[2] = { -1, -1 }; static Window *curwin; static volatile sig_atomic_t quit_flag; static int dirty = 1; static int cols = 80, lines = 24; static int treew = TREEW, mainh = 1; static struct termios saved_terminal; static int terminal_active; static int terminal_color; enum { KEY_UP = 256, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_HOME, KEY_END, KEY_PPAGE, KEY_NPAGE }; #ifdef USE_OPENSSL static SSL_CTX *tls_ctx; static int tls_verify; #endif static char g_nick[NICKLEN] = "irc9"; static char g_user[NICKLEN] = "irc9"; static char g_real[128] = "irc9 user"; static int strip_formatting = 1; static char input[MAXINPUT]; static int input_len, input_pos; static char history[MAXHIST][MAXINPUT]; static int hist_n, hist_cur = -1; static int comp_active, comp_index; static char comp_prefix[MAXINPUT], comp_last[NICKLEN]; #define MAXRECENT 16 #define MAXCAND 128 static char recent_nicks[MAXRECENT][NICKLEN]; static int nrecent; static char comp_cands[MAXCAND][NICKLEN]; static int comp_count, comp_start, comp_end; /* ------------------------------------------------------------------ */ /* small helpers */ static void terminal_finish(void) { if (!terminal_active) return; fputs("\033[0m\033[?25h\033[?1l\033>\033[?1049l", stdout); fflush(stdout); tcsetattr(STDIN_FILENO, TCSANOW, &saved_terminal); terminal_active = 0; } static void fatal(const char *msg) { terminal_finish(); fprintf(stderr, "irc9: %s\n", msg); exit(1); } static void *xmalloc(size_t n) { void *p = malloc(n); if (!p) fatal("out of memory"); return p; } static size_t size_add(size_t a, size_t b) { if (a > SIZE_MAX - b) fatal("integer overflow"); return a + b; } static size_t size_mul(size_t a, size_t b) { if (a && b > SIZE_MAX / a) fatal("integer overflow"); return a * b; } static void *xalloc_array(size_t n, size_t size) { return xmalloc(size_mul(n, size)); } static char *dupstr(const char *s) { size_t n = size_add(strlen(s), 1); char *p = xmalloc(n); memcpy(p, s, n); return p; } static char *dupnstr(const char *s, size_t n) { char *p = xmalloc(size_add(n, 1)); memcpy(p, s, n); p[n] = 0; return p; } static void fmttime(char *buf, size_t sz, const char *fmt) { time_t t = time(NULL); struct tm tm; localtime_r(&t, &tm); strftime(buf, sz, fmt, &tm); } static int is_channel(const char *s) { return s && (*s == '#' || *s == '&' || *s == '+' || *s == '!'); } static Server *server_window_owner(void) { return servers; } static Window *serverwin(Server *s) { return s->windows; /* created first for every server */ } static Window *reply_window(Server *s) { return s->reply_win ? s->reply_win : serverwin(s); } /* ------------------------------------------------------------------ */ /* windows and scrollback */ static Window *window_new(Server *s, const char *name, Wintype type) { Window *w = xmalloc(sizeof *w); Window **tail = &s->windows; memset(w, 0, sizeof *w); snprintf(w->name, sizeof w->name, "%s", name); w->type = type; w->srv = s; w->lines = xalloc_array(MAXSCROLL, sizeof *w->lines); while (*tail) tail = &(*tail)->next; *tail = w; return w; } static Window *window_find(Server *s, const char *name) { for (Window *w = s->windows; w; w = w->next) if (strcasecmp(w->name, name) == 0) return w; return NULL; } static Window *window_get(Server *s, const char *name, Wintype type) { Window *w = window_find(s, name); if (!w) w = window_new(s, name, type); return w; } static void focus_window(Window *w) { if (!w || w == curwin) return; curwin = w; curwin->scroll = 0; curwin->unread = 0; dirty = 1; } static void window_clear(Window *w) { if (!w) return; for (int i = 0; i < w->nlines; i++) free(w->lines[i]); w->nlines = 0; w->scroll = 0; w->unread = 0; dirty = 1; } static void window_close(Server *s, Window *w) { if (!w || w == s->windows) return; /* never close the server window */ Window **p = &s->windows; while (*p && *p != w) p = &(*p)->next; if (!*p) return; *p = w->next; for (int i = 0; i < w->nlines; i++) free(w->lines[i]); free(w->lines); for (Member *m = w->members; m; ) { Member *mn = m->next; free(m); m = mn; } if (s->reply_win == w) s->reply_win = NULL; if (curwin == w) focus_window(s->windows); free(w); dirty = 1; } static char *strip_ircfmt(const char *s) { size_t n = strlen(s); char *out = xmalloc(size_add(n, 1)); size_t j = 0; for (size_t i = 0; i < n; i++) { unsigned char c = (unsigned char)s[i]; if (c == 0x02 || c == 0x1d || c == 0x1f || c == 0x16 || c == 0x0f) continue; if (c == 0x03) { i++; if (i < n && isdigit((unsigned char)s[i])) { i++; if (i < n && isdigit((unsigned char)s[i])) i++; if (i < n && s[i] == ',' && i + 1 < n && isdigit((unsigned char)s[i + 1])) { i += 2; if (i < n && isdigit((unsigned char)s[i])) i++; } } i--; continue; } out[j++] = (char)c; } out[j] = 0; return out; } static void win_append_raw(Window *w, const char *text) { if (w->nlines == MAXSCROLL) { free(w->lines[0]); memmove(w->lines, w->lines + 1, (MAXSCROLL - 1) * sizeof *w->lines); w->nlines--; } char stamp[16], *line; char *clean = strip_formatting ? strip_ircfmt(text) : dupstr(text); fmttime(stamp, sizeof stamp, "[%H:%M] "); size_t sz = size_add(size_add(strlen(stamp), strlen(clean)), 1); line = xmalloc(sz); snprintf(line, sz, "%s%s", stamp, clean); free(clean); w->lines[w->nlines++] = line; if (w->scroll > 0) w->scroll++; if (w != curwin) w->unread++; dirty = 1; } static void appendf(Window *w, const char *fmt, ...) { char buf[MAXLINE * 2]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); win_append_raw(w, buf); } static void switch_window(int dir) { if (!curwin) return; Window *target = NULL; if (dir > 0) { target = curwin->next; if (!target) for (Server *s = curwin->srv->next; s; s = s->next) if (s->windows) { target = s->windows; break; } if (!target) for (Server *t = servers; t; t = t->next) if (t->windows) { target = t->windows; break; } } else { for (Server *s = servers; s; s = s->next) for (Window *w = s->windows; w; w = w->next) { if (w == curwin) goto found; target = w; } found:; if (!target) for (Server *s = servers; s; s = s->next) if (s->windows) { Window *last = s->windows; while (last->next) last = last->next; target = last; } } if (target && target != curwin) { curwin = target; curwin->scroll = 0; curwin->unread = 0; dirty = 1; } } /* ------------------------------------------------------------------ */ /* channel members (only used to route QUIT / NICK notices) */ static Member *member_find(Window *w, const char *nick) { for (Member *m = w->members; m; m = m->next) if (strcasecmp(m->nick, nick) == 0) return m; return NULL; } static Member *member_add(Window *w, const char *nick) { Member *existing = member_find(w, nick); if (existing) return existing; Member *m = xmalloc(sizeof *m); snprintf(m->nick, sizeof m->nick, "%s", nick); m->status = 0; m->next = w->members; w->members = m; return m; } static void member_modes(Window *w, const char *modes, char **args, int count) { Server *s = w->srv; int adding = 1; int param = 0; for (const char *p = modes; *p; p++) { if (*p == '+' || *p == '-') { adding = *p == '+'; continue; } const char *prefix = strchr(s->prefix_modes, *p); if (prefix) { if (param >= count) break; Member *m = member_find(w, args[param++]); if (m) { uint32_t bit = UINT32_C(1) << (prefix - s->prefix_modes); if (adding) m->status |= bit; else m->status &= ~bit; } } else { int group = 0; for (const char *c = s->chanmodes; *c; c++) { if (*c == ',') group++; else if (*c == *p) { if (group < 2 || (group == 2 && adding)) param++; break; } } } } } static void member_remove(Window *w, const char *nick) { Member **p = &w->members; while (*p) { if (strcasecmp((*p)->nick, nick) == 0) { Member *old = *p; *p = old->next; free(old); return; } p = &(*p)->next; } } static void member_rename(Window *w, const char *oldnick, const char *newnick) { Member *m = member_find(w, oldnick); if (m) snprintf(m->nick, sizeof m->nick, "%s", newnick); } /* Print the locally tracked nicklist in a channel's scrollback. */ static void show_names(Window *w) { if (!w) return; if (w->type != W_CHANNEL) { appendf(w, "* no nicklist here; select a channel"); return; } size_t count = 0; for (Member *m = w->members; m; m = m->next) count++; char line[MAXLINE * 2]; int len = snprintf(line, sizeof line, "* %zu on %s:", count, w->name); if (len < 0) len = 0; if ((size_t)len >= sizeof line) len = (int)sizeof line - 1; for (Member *m = w->members; m; m = m->next) { size_t room = sizeof line - (size_t)len - 1; int add = snprintf(line + len, room, " %s%s", m->nick, m->status ? "*" : ""); if (add <= 0 || (size_t)add >= room) break; len += add; } line[len] = 0; win_append_raw(w, line); } /* ------------------------------------------------------------------ */ /* config */ static int parse_port(const char *str) { char *end = NULL; errno = 0; long v = strtol(str, &end, 10); if (errno == ERANGE || end == str || *end != '\0' || v < 1 || v > 65535) return 6667; return (int)v; } static void load_config(const char *path) { FILE *f = fopen(path, "r"); if (!f) { fprintf(stderr, "irc9: cannot open config %s: %s\n", path, strerror(errno)); exit(1); } char line[1024]; Server *last = NULL; #ifdef USE_AUTOJOIN AutojoinChannel **channel_tail = NULL; #endif while (fgets(line, sizeof line, f)) { size_t n = strlen(line); while (n && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = 0; char *p = line; while (isspace((unsigned char)*p)) p++; if (!*p || *p == '#') continue; /* whole-line comments only */ char *key = NULL, *a1 = NULL, *a2 = NULL, *a3 = NULL; char *save = NULL; key = strtok_r(p, " \t", &save); if (!key) continue; a1 = strtok_r(NULL, " \t", &save); a2 = strtok_r(NULL, " \t", &save); a3 = strtok_r(NULL, " \t", &save); if (strcasecmp(key, "nick") == 0 && a1) { snprintf(g_nick, sizeof g_nick, "%s", a1); } else if (strcasecmp(key, "user") == 0 && a1) { snprintf(g_user, sizeof g_user, "%s", a1); } else if (strcasecmp(key, "real") == 0 && a1) { if (a2) snprintf(g_real, sizeof g_real, "%s %s", a1, a2); else snprintf(g_real, sizeof g_real, "%s", a1); } else if (strcasecmp(key, "server") == 0 && a1) { Server *s = xmalloc(sizeof *s); memset(s, 0, sizeof *s); snprintf(s->host, sizeof s->host, "%s", a1); s->port = a2 ? parse_port(a2) : 6667; if (a3 && (strcasecmp(a3, "ssl") == 0 || strcasecmp(a3, "tls") == 0)) s->tls = 1; snprintf(s->nick, sizeof s->nick, "%s", g_nick); snprintf(s->user, sizeof s->user, "%s", g_user); snprintf(s->real, sizeof s->real, "%s", g_real); strcpy(s->prefix_modes, "qaohv"); strcpy(s->prefix_symbols, "~&@%+"); strcpy(s->chanmodes, "beI,k,l,imnst"); s->fd = -1; s->retry_at = 0; if (!servers) servers = s; else last->next = s; last = s; #ifdef USE_AUTOJOIN channel_tail = &s->autojoin; #endif window_new(s, s->host, W_SERVER); } else if (strcasecmp(key, "sasl") == 0 && a1 && a2 && last) { snprintf(last->sasl_user, sizeof last->sasl_user, "%s", a1); snprintf(last->sasl_pass, sizeof last->sasl_pass, "%s", a2); last->sasl = 1; } else if ((strcasecmp(key, "strip_formatting") == 0 || strcasecmp(key, "stripfmt") == 0) && a1) { strip_formatting = !strcasecmp(a1, "on") || !strcasecmp(a1, "true") || !strcasecmp(a1, "yes") || strcmp(a1, "1") == 0; } else if (strcasecmp(key, "channel") == 0) { #ifdef USE_AUTOJOIN if (channel_tail && a1 && strlen(a1) < CHANLEN) { AutojoinChannel *channel = xmalloc(sizeof *channel); strcpy(channel->name, a1); channel->next = NULL; *channel_tail = channel; channel_tail = &channel->next; } #endif } else { fprintf(stderr, "irc9: ignoring config line: %s\n", line); } } fclose(f); if (!servers) { fprintf(stderr, "irc9: config has no server lines\n"); exit(1); } } /* ------------------------------------------------------------------ */ /* network */ static ssize_t net_read(Server *s, void *buf, size_t len) { if (len > INT_MAX) len = INT_MAX; /* SSL_read/write take int */ #ifdef USE_OPENSSL if (s->ssl) return SSL_read(s->ssl, buf, (int)len); #endif return recv(s->fd, buf, len, 0); } static ssize_t net_write(Server *s, const void *buf, size_t len) { if (len > INT_MAX) len = INT_MAX; /* SSL_read/write take int */ #ifdef USE_OPENSSL if (s->ssl) return SSL_write(s->ssl, buf, (int)len); #endif return send(s->fd, buf, len, 0); } static void send_all(Server *s, const char *buf, size_t len) { size_t off = 0; while (off < len) { ssize_t n = net_write(s, buf + off, len - off); if (n > 0) { off += (size_t)n; continue; } #ifdef USE_OPENSSL if (s->ssl) { int err = SSL_get_error(s->ssl, (int)n); if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { struct pollfd pfd = { .fd = s->fd, .events = err == SSL_ERROR_WANT_READ ? POLLIN : POLLOUT }; poll(&pfd, 1, 1000); continue; } break; } #endif if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) continue; break; } } static void sendf(Server *s, const char *fmt, ...) { if (s->fd < 0) return; char buf[MAXLINE * 2]; va_list ap; va_start(ap, fmt); int n = vsnprintf(buf, sizeof buf - 2, fmt, ap); va_end(ap); if (n < 0 || (size_t)n >= sizeof buf - 2) return; /* encoding error or truncation */ size_t len = strlen(buf); buf[len] = '\r'; buf[len + 1] = '\n'; buf[len + 2] = 0; send_all(s, buf, len + 2); } static void connect_fail(Server *s, const char *why) { appendf(serverwin(s), "* cannot connect to %s:%d (%s)", s->host, s->port, why); s->retry_at = time(NULL) + RETRY; } static void errno_string(int e, char *buf, size_t sz) { strerror_r(e, buf, sz); buf[sz - 1] = 0; } #ifdef USE_OPENSSL static int tls_connect(SSL *ssl, int fd) { for (;;) { int r = SSL_connect(ssl); if (r == 1) return 0; int err = SSL_get_error(ssl, r); if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { struct pollfd pfd = { .fd = fd, .events = err == SSL_ERROR_WANT_READ ? POLLIN : POLLOUT }; if (poll(&pfd, 1, 3000) <= 0) return -1; continue; } return -1; } } #endif /* DNS, connect and TLS handshake all happen here, never on the UI thread. */ static void *connect_thread(void *arg) { ConnectJob *job = arg; const char *host = job->host; int port = job->port; #ifdef USE_OPENSSL int tls = job->tls; #endif ConnectResult r; memset(&r, 0, sizeof r); r.s = job->s; r.gen = job->gen; r.fd = -1; char portstr[16]; snprintf(portstr, sizeof portstr, "%d", port); struct addrinfo hints, *res = NULL, *rp; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if (getaddrinfo(host, portstr, &hints, &res) != 0) { snprintf(r.err, sizeof r.err, "host not found"); goto done; } int fd = -1; for (rp = res; rp; rp = rp->ai_next) { fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (fd < 0) continue; int fl = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, fl | O_NONBLOCK); if (connect(fd, rp->ai_addr, rp->ai_addrlen) == 0 || errno == EINPROGRESS) break; close(fd); fd = -1; } int saved_errno = errno; freeaddrinfo(res); if (fd < 0) { errno_string(saved_errno, r.err, sizeof r.err); goto done; } struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0 }; int rc = poll(&pfd, 1, 3000); int err = 0; socklen_t elen = sizeof err; if (rc <= 0) err = ETIMEDOUT; else if (pfd.revents & POLLOUT) getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &elen); else err = ECONNREFUSED; if (err) { close(fd); errno_string(err, r.err, sizeof r.err); goto done; } #ifdef USE_OPENSSL SSL *ssl = NULL; if (tls) { if (!tls_ctx) { close(fd); snprintf(r.err, sizeof r.err, "TLS unavailable"); goto done; } ssl = SSL_new(tls_ctx); if (!ssl || SSL_set_fd(ssl, fd) != 1 || SSL_set_tlsext_host_name(ssl, host) != 1) { if (ssl) SSL_free(ssl); close(fd); snprintf(r.err, sizeof r.err, "TLS setup failed"); goto done; } if (tls_verify) X509_VERIFY_PARAM_set1_host(SSL_get0_param(ssl), host, 0); if (tls_connect(ssl, fd) != 0) { char ebuf[256]; unsigned long e = ERR_get_error(); snprintf(r.err, sizeof r.err, "%s", e ? ERR_error_string(e, ebuf) : "TLS handshake failed"); SSL_free(ssl); close(fd); goto done; } r.ssl = ssl; } #endif r.fd = fd; done: free(job); for (;;) { ssize_t n = write(connect_pipe[1], &r, sizeof r); if (n == (ssize_t)sizeof r) break; if (n < 0 && errno == EINTR) continue; break; /* pipe is full or closed; nothing useful we can do here */ } return NULL; } static void connect_server(Server *s) { if (!s || s->connecting) return; s->connecting = 1; ConnectJob *job = xmalloc(sizeof *job); job->s = s; snprintf(job->host, sizeof job->host, "%s", s->host); job->port = s->port; #ifdef USE_OPENSSL job->tls = s->tls; #endif job->gen = s->connect_gen; pthread_t th; if (pthread_create(&th, NULL, connect_thread, job) != 0) { free(job); s->connecting = 0; connect_fail(s, "cannot start connection thread"); return; } pthread_detach(th); } /* Pick up completed attempts and apply them to server state on this thread. */ static void handle_connect_results(void) { ConnectResult r; while (read(connect_pipe[0], &r, sizeof r) == (ssize_t)sizeof r) { Server *s = r.s; if (!s || r.gen != s->connect_gen) { #ifdef USE_OPENSSL if (r.ssl) SSL_free(r.ssl); #endif if (r.fd >= 0) close(r.fd); continue; } s->connecting = 0; if (r.fd < 0) { connect_fail(s, r.err[0] ? r.err : "connection failed"); continue; } s->fd = r.fd; #ifdef USE_OPENSSL s->ssl = r.ssl; #endif s->connected = 0; s->inlen = 0; s->cap_state = CAP_NONE; s->caps[0] = 0; #ifdef USE_OPENSSL if (s->tls) appendf(serverwin(s), "* TLS connected to %s:%d", s->host, s->port); else #endif appendf(serverwin(s), "* connected to %s:%d", s->host, s->port); sendf(s, "CAP LS 302"); sendf(s, "NICK %s", s->nick); sendf(s, "USER %s 0 * :%s", s->user, s->real); if (s->sasl) s->cap_state = CAP_LS; } } static void disconnect_server(Server *s) { s->connect_gen++; s->connecting = 0; appendf(serverwin(s), "* disconnected from %s", s->host); #ifdef USE_OPENSSL if (s->ssl) { SSL_shutdown(s->ssl); SSL_free(s->ssl); s->ssl = NULL; } #endif close(s->fd); s->fd = -1; s->connected = 0; s->inlen = 0; s->cap_state = CAP_NONE; s->caps[0] = 0; s->retry_at = time(NULL) + RETRY; } /* ------------------------------------------------------------------ */ /* IRC protocol */ static char *base64_encode(const unsigned char *in, size_t len) { static const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; size_t groups = size_add(len, 2) / 3; size_t cap = size_mul(groups, 4); char *out = xmalloc(size_add(cap, 1)); size_t i = 0, j = 0; while (i + 2 < len) { unsigned v = (unsigned)in[i] << 16 | (unsigned)in[i + 1] << 8 | in[i + 2]; out[j++] = tbl[(v >> 18) & 63]; out[j++] = tbl[(v >> 12) & 63]; out[j++] = tbl[(v >> 6) & 63]; out[j++] = tbl[v & 63]; i += 3; } if (i < len) { unsigned v = (unsigned)in[i] << 16; if (i + 1 < len) v |= (unsigned)in[i + 1] << 8; out[j++] = tbl[(v >> 18) & 63]; out[j++] = tbl[(v >> 12) & 63]; out[j++] = i + 1 < len ? tbl[(v >> 6) & 63] : '='; out[j++] = '='; } out[j] = 0; return out; } static void sasl_authenticate(Server *s) { size_t ulen = strlen(s->sasl_user), plen = strlen(s->sasl_pass); size_t rawlen = size_add(size_add(ulen, plen), 2); /* NUL user NUL pass */ unsigned char *raw = xmalloc(size_add(rawlen, 1)); raw[0] = 0; memcpy(raw + 1, s->sasl_user, ulen); raw[1 + ulen] = 0; memcpy(raw + 2 + ulen, s->sasl_pass, plen); char *b64 = base64_encode(raw, rawlen); sendf(s, "AUTHENTICATE %s", b64); free(b64); free(raw); } static void prefix_nick(const char *prefix, char *out, size_t outsz) { if (!outsz) return; if (!prefix) { out[0] = 0; return; } const char *p = prefix; while (*p && *p != '!' && *p != '@') p++; size_t n = (size_t)(p - prefix); if (n >= outsz) n = outsz - 1; memcpy(out, prefix, n); out[n] = 0; } /* Splits a raw IRC line in place. Returns the number of params. */ static int parse_irc(char *line, char **prefix, char **cmd, char **argv, int maxargv) { char *p = line; *prefix = NULL; if (*p == ':') { *prefix = ++p; p = strchr(p, ' '); if (!p) return -1; *p++ = 0; } while (*p == ' ') p++; *cmd = p; p = strchr(p, ' '); if (!p) return 0; *p++ = 0; int n = 0; while (*p) { while (*p == ' ') p++; if (!*p) break; if (*p == ':') { if (n < maxargv) argv[n++] = p + 1; break; } if (n < maxargv) argv[n++] = p; p = strchr(p, ' '); if (!p) break; *p++ = 0; } return n; } /* Returns 1 when the message was CTCP and has been dealt with. */ static int handle_ctcp(Server *s, const char *nick, char *text, Window *w, int is_reply) { size_t len = strlen(text); if (!*nick || len < 2 || text[0] != '\001') return 0; char *end = strrchr(text, '\001'); if (!end || end == text) return 0; *end = 0; char *cmd = text + 1; char *argp = strchr(cmd, ' '); if (argp) { *argp++ = 0; while (*argp == ' ') argp++; } const char *arg = argp ? argp : ""; if (is_reply) { appendf(w, "* %s CTCP %s: %s", nick, cmd, arg); } else if (strcasecmp(cmd, "ACTION") == 0) { appendf(w, "* %s %s", nick, arg); } else if (strcasecmp(cmd, "VERSION") == 0) { sendf(s, "NOTICE %s :\001VERSION irc9\001", nick); } else if (strcasecmp(cmd, "PING") == 0) { sendf(s, "NOTICE %s :\001PING %s\001", nick, arg); } else if (strcasecmp(cmd, "TIME") == 0) { char now[64]; fmttime(now, sizeof now, "%Y-%m-%d %H:%M:%S"); sendf(s, "NOTICE %s :\001TIME %s\001", nick, now); } else if (strcasecmp(cmd, "USERINFO") == 0) { sendf(s, "NOTICE %s :\001USERINFO %s\001", nick, g_real); } else { appendf(w, "* %s CTCP %s", nick, cmd); } return 1; } static void handle_line(Server *s, char *line) { char *prefix, *cmd; char *arg[16]; int narg = parse_irc(line, &prefix, &cmd, arg, 16); if (narg < 0 || !*cmd) return; char nick[NICKLEN]; prefix_nick(prefix, nick, sizeof nick); const char *hostmask = (prefix && *prefix) ? prefix : NULL; Window *sw = serverwin(s); if (strcasecmp(cmd, "PING") == 0) { sendf(s, "PONG :%s", narg > 0 ? arg[0] : ""); return; } if (strcasecmp(cmd, "CAP") == 0 && narg >= 3) { if (strcasecmp(arg[1], "LS") == 0) { /* LS [ * ] :; keep collecting until the final line. */ int more = narg >= 4 && strcmp(arg[2], "*") == 0; const char *part = more ? arg[3] : arg[2]; size_t used = strlen(s->caps); size_t room = used < sizeof s->caps ? sizeof s->caps - used - 1 : 0; if (part && room) strncat(s->caps, part, room - 1); if (more) return; if (s->sasl && strstr(s->caps, "sasl")) { sendf(s, "CAP REQ :sasl"); s->cap_state = CAP_REQ; } else { sendf(s, "CAP END"); s->cap_state = CAP_NONE; } s->caps[0] = 0; } else if (strcasecmp(arg[1], "ACK") == 0 && strstr(arg[2], "sasl")) { sendf(s, "AUTHENTICATE PLAIN"); s->cap_state = CAP_AUTH; } else if (strcasecmp(arg[1], "NAK") == 0 && strstr(arg[2], "sasl")) { appendf(sw, "* server does not support SASL"); sendf(s, "CAP END"); s->cap_state = CAP_NONE; } return; } if (strcasecmp(cmd, "AUTHENTICATE") == 0) { if (s->cap_state == CAP_AUTH && narg > 0 && strcmp(arg[0], "+") == 0) sasl_authenticate(s); return; } if (strcmp(cmd, "903") == 0) { appendf(sw, "* SASL authentication successful"); sendf(s, "CAP END"); s->cap_state = CAP_NONE; return; } if (strcmp(cmd, "902") == 0 || strcmp(cmd, "904") == 0 || strcmp(cmd, "905") == 0 || strcmp(cmd, "906") == 0 || strcmp(cmd, "907") == 0) { if (narg > 0) appendf(sw, "* SASL authentication failed: %s", arg[narg - 1]); else appendf(sw, "* SASL authentication failed"); sendf(s, "CAP END"); s->cap_state = CAP_NONE; return; } if (strcasecmp(cmd, "PRIVMSG") == 0 || strcasecmp(cmd, "NOTICE") == 0) { int notice = (strcasecmp(cmd, "NOTICE") == 0); const char *text = narg > 1 ? arg[1] : ""; if (narg < 1) return; Window *w; if (is_channel(arg[0])) w = window_get(s, arg[0], W_CHANNEL); else if (*nick && hostmask && !strchr(hostmask, '!') && !strchr(hostmask, '@')) w = sw; else if (*nick) w = window_get(s, nick, W_QUERY); else w = sw; if (w->type == W_QUERY && hostmask && strchr(hostmask, '!')) snprintf(w->hostmask, sizeof w->hostmask, "%s", hostmask); if (narg > 1 && handle_ctcp(s, nick, arg[1], w, notice)) return; if (notice) appendf(w, "-%s- %s", *nick ? nick : "server", text); else appendf(w, "<%s> %s", *nick ? nick : "server", text); return; } if (strcasecmp(cmd, "JOIN") == 0) { if (narg < 1) return; Window *w = window_get(s, arg[0], W_CHANNEL); member_add(w, nick); appendf(w, "* %s joined %s", hostmask ? hostmask : "someone", arg[0]); return; } if (strcasecmp(cmd, "PART") == 0) { if (narg < 1) return; Window *w = window_get(s, arg[0], W_CHANNEL); member_remove(w, nick); char why[MAXLINE]; if (narg > 1) snprintf(why, sizeof why, " (%s)", arg[1]); else why[0] = 0; appendf(w, "* %s left %s%s", hostmask ? hostmask : "someone", arg[0], why); return; } if (strcasecmp(cmd, "QUIT") == 0) { char why[MAXLINE]; if (narg > 0) snprintf(why, sizeof why, " (%s)", arg[0]); else why[0] = 0; int shown = 0; for (Window *w = s->windows; w; w = w->next) if (w->type == W_CHANNEL && member_find(w, nick)) { appendf(w, "* %s quit%s", hostmask ? hostmask : nick, why); member_remove(w, nick); shown = 1; } if (!shown) appendf(sw, "* %s quit%s", hostmask ? hostmask : nick, why); return; } if (strcasecmp(cmd, "NICK") == 0) { if (narg < 1) return; int shown = 0; for (Window *w = s->windows; w; w = w->next) { if (w->type == W_CHANNEL && member_find(w, nick)) { member_rename(w, nick, arg[0]); appendf(w, "* %s is now known as %s", nick, arg[0]); shown = 1; } else if (w->type == W_QUERY && strcasecmp(w->name, nick) == 0) { snprintf(w->name, sizeof w->name, "%s", arg[0]); } } if (strcasecmp(nick, s->nick) == 0) snprintf(s->nick, sizeof s->nick, "%s", arg[0]); if (!shown) appendf(sw, "* %s is now known as %s", nick, arg[0]); return; } if (strcasecmp(cmd, "KICK") == 0 && narg >= 2) { Window *w = window_get(s, arg[0], W_CHANNEL); char why[MAXLINE]; if (narg > 2) snprintf(why, sizeof why, " (%s)", arg[2]); else why[0] = 0; appendf(w, "* %s was kicked from %s by %s%s", arg[1], arg[0], *nick ? nick : "server", why); member_remove(w, arg[1]); return; } if (strcasecmp(cmd, "MODE") == 0 && narg >= 2) { Window *w = window_find(s, arg[0]); if (!w) w = is_channel(arg[0]) ? window_get(s, arg[0], W_CHANNEL) : sw; char params[MAXLINE]; params[0] = 0; for (int i = 1; i < narg; i++) { if (i > 1) strncat(params, " ", sizeof params - strlen(params) - 1); strncat(params, arg[i], sizeof params - strlen(params) - 1); } if (w->type == W_CHANNEL) member_modes(w, arg[1], arg + 2, narg - 2); else if (strcasecmp(arg[0], s->nick) == 0) snprintf(s->umode, sizeof s->umode, "%s", arg[1]); appendf(w, "* %s sets mode %s on %s", *nick ? nick : "server", params, arg[0]); return; } if (strcasecmp(cmd, "TOPIC") == 0 && narg >= 2) { Window *w = window_get(s, arg[0], W_CHANNEL); appendf(w, "* %s changed topic of %s: %s", *nick ? nick : "server", arg[0], arg[1]); return; } if (strcasecmp(cmd, "INVITE") == 0 && narg >= 2) { appendf(sw, "* %s invited you to %s", *nick ? nick : "server", arg[1]); return; } if (strcasecmp(cmd, "PONG") == 0) { appendf(sw, "* pong from %s", *nick ? nick : "server"); return; } if (strcmp(cmd, "005") == 0) { for (int i = 1; i < narg; i++) { if (strncmp(arg[i], "PREFIX=(", 8) == 0) { const char *modes = arg[i] + 8; const char *end = strchr(modes, ')'); if (end && (size_t)(end - modes) == strlen(end + 1) && (size_t)(end - modes) < sizeof s->prefix_modes) { size_t len = (size_t)(end - modes); memcpy(s->prefix_modes, modes, len); s->prefix_modes[len] = 0; strcpy(s->prefix_symbols, end + 1); } } else if (strncmp(arg[i], "CHANMODES=", 10) == 0 && strlen(arg[i] + 10) < sizeof s->chanmodes) { strcpy(s->chanmodes, arg[i] + 10); } } } if (strcmp(cmd, "353") == 0) { /* 353 : */ if (narg < 4) return; Window *w = window_get(s, arg[2], W_CHANNEL); char *p = arg[3]; while (*p) { while (*p == ' ') p++; if (!*p) break; char *e = strchr(p, ' '); size_t len = e ? (size_t)(e - p) : strlen(p); uint32_t status = 0; while (len) { const char *prefix = strchr(s->prefix_symbols, *p); if (!prefix) break; status |= UINT32_C(1) << (prefix - s->prefix_symbols); p++; len--; } if (len) { char tmp[NICKLEN]; size_t cp = len < sizeof tmp - 1 ? len : sizeof tmp - 1; memcpy(tmp, p, cp); tmp[cp] = 0; member_add(w, tmp)->status = status; } p = e ? e + 1 : p + len; } return; } if (strcmp(cmd, "366") == 0) { /* End of /NAMES: show the complete nicklist for the channel. */ if (narg >= 2) { Window *w = window_find(s, arg[1]); if (!w) w = window_get(s, arg[1], W_CHANNEL); if (w->type == W_CHANNEL) { show_names(w); if (w->syncing) { struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); double dt = (now.tv_sec - w->join_ts.tv_sec) + (now.tv_nsec - w->join_ts.tv_nsec) / 1e9; appendf(w, "* synced %s in %.2fs", w->name, dt); w->syncing = 0; } else { appendf(w, "* synced %s", w->name); } } } return; } /* WHOIS replies go back to the window where /whois was issued. */ /* Numeric replies start with our own nick: ... */ if (strcmp(cmd, "311") == 0 && narg >= 6) { appendf(reply_window(s), "* %s is %s@%s (%s)", arg[1], arg[2], arg[3], arg[5]); return; } if (strcmp(cmd, "301") == 0 && narg >= 3) { appendf(reply_window(s), "* %s is away: %s", arg[1], arg[2]); return; } if (strcmp(cmd, "312") == 0 && narg >= 4) { appendf(reply_window(s), "* %s is on server %s (%s)", arg[1], arg[2], arg[3]); return; } if (strcmp(cmd, "317") == 0 && narg >= 3) { appendf(reply_window(s), "* %s idle %ss", arg[1], arg[2]); return; } if (strcmp(cmd, "319") == 0 && narg >= 3) { appendf(reply_window(s), "* %s is on: %s", arg[1], arg[2]); return; } if (strcmp(cmd, "318") == 0) { if (narg >= 2) appendf(reply_window(s), "* end of whois for %s", arg[1]); s->reply_win = NULL; return; } if (strcmp(cmd, "401") == 0) { if (narg >= 3) appendf(reply_window(s), "* %s: %s", arg[1], arg[2]); s->reply_win = NULL; return; } /* Replies for /topic, /who, /list and the informational commands. */ if (strcmp(cmd, "331") == 0 && narg >= 3) { appendf(reply_window(s), "* no topic for %s", arg[1]); return; } if (strcmp(cmd, "332") == 0 && narg >= 3) { appendf(reply_window(s), "* topic for %s: %s", arg[1], arg[2]); return; } if (strcmp(cmd, "333") == 0 && narg >= 4) { appendf(reply_window(s), "* topic for %s set by %s", arg[1], arg[2]); return; } if (strcmp(cmd, "352") == 0 && narg >= 8) { appendf(reply_window(s), "* %s is %s@%s on %s (%s)", arg[5], arg[2], arg[3], arg[1], arg[7]); return; } if (strcmp(cmd, "315") == 0) { if (narg >= 2) appendf(reply_window(s), "* end of who list: %s", arg[1]); s->reply_win = NULL; return; } if (strcmp(cmd, "322") == 0 && narg >= 4) { appendf(reply_window(s), "* %s (%s users): %s", arg[1], arg[2], arg[3]); return; } if (strcmp(cmd, "323") == 0) { appendf(reply_window(s), "* end of channel list"); s->reply_win = NULL; return; } if (strcmp(cmd, "371") == 0 || strcmp(cmd, "372") == 0 || strcmp(cmd, "257") == 0 || strcmp(cmd, "258") == 0 || strcmp(cmd, "259") == 0 || strcmp(cmd, "212") == 0) { if (narg > 0) appendf(reply_window(s), "%s", arg[narg - 1]); return; } if (strcmp(cmd, "375") == 0) return; /* MOTD start */ if (strcmp(cmd, "376") == 0 || strcmp(cmd, "369") == 0 || strcmp(cmd, "219") == 0 || strcmp(cmd, "255") == 0) { s->reply_win = NULL; return; } if (strcmp(cmd, "251") == 0) { /* The counts are part of the trailing text for RPL_LUSERCLIENT. */ if (narg > 0) appendf(reply_window(s), "%s", arg[narg - 1]); return; } if (strcmp(cmd, "252") == 0 || strcmp(cmd, "253") == 0 || strcmp(cmd, "254") == 0) { /* RPL_LUSEROP/UNKNOWN/CHANNELS: :. */ if (narg >= 3) appendf(reply_window(s), "%s %s", arg[narg - 2], arg[narg - 1]); else if (narg > 0) appendf(reply_window(s), "%s", arg[narg - 1]); return; } if (strcmp(cmd, "391") == 0 && narg >= 3) { appendf(reply_window(s), "* time at %s: %s", arg[1], arg[2]); return; } if (strcmp(cmd, "351") == 0 && narg >= 2) { appendf(reply_window(s), "* server version: %s", arg[narg - 1]); return; } if (strcmp(cmd, "341") == 0 && narg >= 4) { appendf(reply_window(s), "* invited %s to %s", arg[1], arg[2]); return; } if (strcmp(cmd, "221") == 0 && narg >= 2) { snprintf(s->umode, sizeof s->umode, "%s", arg[1]); return; } if (strcmp(cmd, "305") == 0 || strcmp(cmd, "306") == 0) { if (narg > 0) appendf(sw, "* %s", arg[narg - 1]); return; } if (strcmp(cmd, "461") == 0 || strcmp(cmd, "403") == 0 || strcmp(cmd, "404") == 0 || strcmp(cmd, "482") == 0 || strcmp(cmd, "471") == 0 || strcmp(cmd, "473") == 0 || strcmp(cmd, "474") == 0 || strcmp(cmd, "475") == 0) { if (narg > 0) appendf(reply_window(s), "* error: %s", arg[narg - 1]); return; } if (strcmp(cmd, "001") == 0) { s->connected = 1; #ifdef USE_AUTOJOIN while (s->autojoin) { AutojoinChannel *channel = s->autojoin; sendf(s, "JOIN %s", channel->name); s->autojoin = channel->next; free(channel); } #endif appendf(sw, "%s", narg > 0 ? arg[narg - 1] : cmd); return; } if (strcmp(cmd, "433") == 0) { appendf(sw, "* nickname %s is in use, trying another", s->nick); size_t len = strlen(s->nick); if (len + 1 < sizeof s->nick) { s->nick[len] = '_'; s->nick[len + 1] = 0; sendf(s, "NICK %s", s->nick); } return; } if (strcasecmp(cmd, "ERROR") == 0) { appendf(sw, "* %s", narg > 0 ? arg[0] : "error from server"); return; } /* Everything else (welcome numerics, MOTD, unknown commands). */ if (narg > 0) appendf(sw, "%s", arg[narg - 1]); else appendf(sw, "%s", cmd); } static void read_server(Server *s) { char buf[INBUF]; for (;;) { ssize_t n = net_read(s, buf, sizeof buf); if (n > 0) { for (ssize_t i = 0; i < n; i++) { char c = buf[i]; if (c == '\n') { while (s->inlen && s->inbuf[s->inlen - 1] == '\r') s->inlen--; s->inbuf[s->inlen] = 0; if (s->inlen) handle_line(s, s->inbuf); s->inlen = 0; } else if (s->inlen < sizeof s->inbuf - 1) { s->inbuf[s->inlen++] = c; } else { s->inlen = 0; /* give up on an absurdly long line */ } } continue; } #ifdef USE_OPENSSL if (s->ssl) { int err = SSL_get_error(s->ssl, (int)n); if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) return; } #endif if (n == 0) { disconnect_server(s); return; } if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) return; disconnect_server(s); return; } } /* ------------------------------------------------------------------ */ /* input line and commands */ static void history_add(const char *s) { if (!*s) return; if (hist_n == MAXHIST) { for (int i = 1; i < MAXHIST; i++) memcpy(history[i - 1], history[i], sizeof history[i]); hist_n--; } snprintf(history[hist_n++], MAXINPUT, "%s", s); hist_cur = -1; } static void history_browse(int dir) { if (dir > 0 && hist_cur < 0) { /* Down on a freshly typed line saves it, then clears the input. */ history_add(input); input[0] = 0; input_len = input_pos = 0; return; } if (hist_n == 0) return; if (hist_cur < 0) { /* dir < 0: start at the most recent entry. */ hist_cur = hist_n - 1; } else { hist_cur += dir; if (hist_cur < 0) hist_cur = 0; if (hist_cur >= hist_n) hist_cur = -1; } if (hist_cur < 0) input[0] = 0; else snprintf(input, MAXINPUT, "%s", history[hist_cur]); input_len = input_pos = (int)strlen(input); } static const char *const command_names[] = { "admin", "away", "ban", "clear", "close", "ctcp", "deop", "devoice", "help", "info", "invite", "join", "kick", "links", "list", "lusers", "me", "mode", "motd", "msg", "n", "names", "nick", "notice", "op", "part", "ping", "query", "quit", "raw", "reconnect", "stats", "time", "topic", "unban", "version", "voice", "wc", "who", "whois" }; /* Most recently tab-completed nick goes first (MRU). */ static void remember_nick(const char *nick) { for (int i = 0; i < nrecent; i++) { if (strcasecmp(recent_nicks[i], nick) == 0) { char tmp[NICKLEN]; snprintf(tmp, sizeof tmp, "%s", recent_nicks[i]); memmove(recent_nicks + 1, recent_nicks, (size_t)i * sizeof *recent_nicks); snprintf(recent_nicks[0], NICKLEN, "%s", tmp); return; } } if (nrecent < MAXRECENT) nrecent++; memmove(recent_nicks + 1, recent_nicks, (size_t)(MAXRECENT - 1) * sizeof *recent_nicks); snprintf(recent_nicks[0], NICKLEN, "%s", nick); } /* Matching nicks from the current window, recently completed ones first. */ static int nick_candidates(char out[][NICKLEN], int cap, const char *prefix) { int n = 0; size_t plen = strlen(prefix); if (!curwin) return 0; if (curwin->type == W_QUERY) { if (strncasecmp(curwin->name, prefix, plen) == 0 && n < cap) snprintf(out[n++], NICKLEN, "%.*s", NICKLEN - 1, curwin->name); return n; } if (curwin->type != W_CHANNEL) return 0; for (int i = 0; i < nrecent && n < cap; i++) { if (strncasecmp(recent_nicks[i], prefix, plen) == 0 && member_find(curwin, recent_nicks[i])) snprintf(out[n++], NICKLEN, "%.*s", NICKLEN - 1, recent_nicks[i]); } for (Member *m = curwin->members; m && n < cap; m = m->next) { if (strncasecmp(m->nick, prefix, plen) != 0) continue; int dup = 0; for (int j = 0; j < n; j++) if (strcasecmp(out[j], m->nick) == 0) { dup = 1; break; } if (!dup) snprintf(out[n++], NICKLEN, "%s", m->nick); } return n; } /* Start or advance the cycle when a tab was pressed for the same word. */ static int completion_slot(const char *word, int *restart) { if (comp_active && strcmp(word, comp_last) == 0) { *restart = 0; return comp_index; } snprintf(comp_prefix, sizeof comp_prefix, "%s", word); *restart = 1; return 0; } static void replace_completion(int start, int tail_at, const char *chosen, const char *sep) { char buf[MAXINPUT]; snprintf(buf, sizeof buf, "%.*s%s%s%s", start, input, chosen, sep, input + tail_at); snprintf(input, sizeof input, "%s", buf); input_len = input_pos = (int)strlen(input); comp_start = start; comp_end = start + (int)strlen(chosen) + (int)strlen(sep); dirty = 1; } /* Complete the command word after '/'; repeated tabs cycle the matches. */ static void complete_command(const char *word, int start, int tail_at) { int restart; int slot = completion_slot(word, &restart); (void)restart; size_t ncmd = sizeof command_names / sizeof *command_names; size_t plen = strlen(comp_prefix); int count = 0; for (size_t i = 0; i < ncmd; i++) if (strncmp(command_names[i], comp_prefix, plen) == 0) count++; if (count == 0) { comp_active = 0; return; } int want = slot % count; const char *chosen = NULL; int seen = 0; for (size_t i = 0; i < ncmd; i++) { if (strncmp(command_names[i], comp_prefix, plen) == 0) { if (seen++ == want) { chosen = command_names[i]; break; } } } if (!chosen) { comp_active = 0; return; } comp_index = (want + 1) % count; snprintf(comp_last, sizeof comp_last, "%s", chosen); comp_active = 1; replace_completion(start, tail_at, chosen, " "); } /* Complete the word at the cursor against nicks in the current window. */ static void complete_nick(const char *word, int start, int tail_at) { int restart; int slot = completion_slot(word, &restart); if (restart) comp_count = nick_candidates(comp_cands, MAXCAND, comp_prefix); if (comp_count == 0) { comp_active = 0; return; } int want = slot % comp_count; const char *chosen = comp_cands[want]; comp_index = (want + 1) % comp_count; snprintf(comp_last, sizeof comp_last, "%s", chosen); comp_active = 1; remember_nick(chosen); replace_completion(start, tail_at, chosen, start == 0 ? ": " : " "); } static void complete_input(void) { if (input_len < 1) return; int pos = input_pos > input_len ? input_len : input_pos; int start = pos; while (start > 0 && input[start - 1] != ' ') start--; if (input[0] == '/' && start <= 1) start = 1; /* skip the slash for commands */ char word[MAXINPUT]; snprintf(word, sizeof word, "%.*s", pos - start, input + start); /* After a completion the cursor sits past its separator: keep cycling. */ if (!*word && comp_active) { snprintf(word, sizeof word, "%s", comp_last); start = comp_start; pos = comp_end; } if (input[0] == '/' && start <= 1) complete_command(word, start, pos); else complete_nick(word, start, pos); } static char *next_word(char **p) { char *s = *p; while (*s == ' ' || *s == '\t') s++; if (!*s) { *p = s; return NULL; } char *e = s; while (*e && *e != ' ' && *e != '\t') e++; if (*e) *e++ = 0; *p = e; return s; } static Window *input_target(void) { if (!curwin || curwin->type == W_SERVER) return NULL; return curwin; } static void do_command(char *line) { char *p = line + 1; while (*p == ' ' || *p == '\t') p++; char *cmd = next_word(&p); if (!cmd) return; char rest[MAXINPUT]; snprintf(rest, sizeof rest, "%s", p); char *q = rest; if (strcasecmp(cmd, "join") == 0 || strcasecmp(cmd, "j") == 0) { char *chan = next_word(&q); char chanbuf[CHANLEN]; if (!chan || !curwin) return; if (!is_channel(chan)) { snprintf(chanbuf, sizeof chanbuf, "#%s", chan); chan = chanbuf; } Window *w = window_get(curwin->srv, chan, W_CHANNEL); w->syncing = 1; clock_gettime(CLOCK_MONOTONIC, &w->join_ts); focus_window(w); sendf(curwin->srv, "JOIN %s", chan); } else if (strcasecmp(cmd, "n") == 0 || strcasecmp(cmd, "names") == 0) { Window *t = curwin; char *name = next_word(&q); if (name && curwin) { t = window_find(curwin->srv, name); if (!t) appendf(curwin, "* no such window: %s", name); } if (t) show_names(t); } else if (strcasecmp(cmd, "part") == 0) { Window *t = input_target(); char *chan = next_word(&q); if (!t || !t->srv) return; if (!chan && t->type == W_CHANNEL) chan = t->name; if (!chan) return; if (*q) sendf(t->srv, "PART %s :%s", chan, q); else sendf(t->srv, "PART %s", chan); } else if (strcasecmp(cmd, "nick") == 0) { char *newnick = next_word(&q); if (!newnick || !curwin) return; sendf(curwin->srv, "NICK %s", newnick); appendf(serverwin(curwin->srv), "* changing nick to %s", newnick); } else if (strcasecmp(cmd, "msg") == 0) { char *target = next_word(&q); if (!target || !curwin || !*q) return; sendf(curwin->srv, "PRIVMSG %s :%s", target, q); Window *w = window_get(curwin->srv, target, is_channel(target) ? W_CHANNEL : W_QUERY); appendf(w, "<%s> %s", curwin->srv->nick, q); } else if (strcasecmp(cmd, "whois") == 0) { char *nick = next_word(&q); if (!curwin) return; if (!nick) { appendf(curwin, "* usage: /whois nick"); return; } curwin->srv->reply_win = curwin; sendf(curwin->srv, "WHOIS %s", nick); appendf(curwin, "* whois %s", nick); } else if (strcasecmp(cmd, "me") == 0) { Window *t = input_target(); if (!t || !*q) return; sendf(t->srv, "PRIVMSG %s :\001ACTION %s\001", t->name, q); appendf(t, "* %s %s", t->srv->nick, q); } else if (strcasecmp(cmd, "away") == 0) { if (!curwin) return; sendf(curwin->srv, "AWAY :%s", *q ? q : ""); if (*q) appendf(curwin, "* away: %s", q); else appendf(curwin, "* not away"); } else if (strcasecmp(cmd, "topic") == 0) { Window *t = input_target(); if (!t || t->type != W_CHANNEL) { if (curwin) appendf(curwin, "* no channel here"); return; } t->srv->reply_win = t; if (*q) sendf(t->srv, "TOPIC %s :%s", t->name, q); else sendf(t->srv, "TOPIC %s", t->name); } else if (strcasecmp(cmd, "invite") == 0) { char *nick = next_word(&q); if (!nick || !curwin) return; char *chan = next_word(&q); if (!chan && curwin->type == W_CHANNEL) chan = curwin->name; if (!chan) { appendf(curwin, "* usage: /invite nick [#chan]"); return; } curwin->srv->reply_win = curwin; sendf(curwin->srv, "INVITE %s %s", nick, chan); appendf(curwin, "* inviting %s to %s", nick, chan); } else if (strcasecmp(cmd, "kick") == 0) { Window *t = input_target(); char *nick = next_word(&q); if (!t || t->type != W_CHANNEL || !nick) { if (curwin) appendf(curwin, "* usage: /kick nick [reason] in a channel"); return; } if (*q) sendf(t->srv, "KICK %s %s :%s", t->name, nick, q); else sendf(t->srv, "KICK %s %s", t->name, nick); } else if (strcasecmp(cmd, "mode") == 0) { char *target = next_word(&q); if (!target && curwin && curwin->type != W_SERVER) target = curwin->name; if (!target || !curwin) return; curwin->srv->reply_win = curwin; if (*q) sendf(curwin->srv, "MODE %s %s", target, q); else sendf(curwin->srv, "MODE %s", target); } else if (strcasecmp(cmd, "op") == 0 || strcasecmp(cmd, "deop") == 0 || strcasecmp(cmd, "voice") == 0 || strcasecmp(cmd, "devoice") == 0 || strcasecmp(cmd, "ban") == 0 || strcasecmp(cmd, "unban") == 0) { Window *t = input_target(); char *who = next_word(&q); if (!t || t->type != W_CHANNEL || !who) { if (curwin) appendf(curwin, "* usage: /%s nick|mask in a channel", cmd); return; } const char *flag = !strcasecmp(cmd, "op") ? "+o" : !strcasecmp(cmd, "deop") ? "-o" : !strcasecmp(cmd, "voice") ? "+v" : !strcasecmp(cmd, "devoice") ? "-v" : !strcasecmp(cmd, "ban") ? "+b" : "-b"; sendf(t->srv, "MODE %s %s %s", t->name, flag, who); appendf(t, "* mode %s %s %s", t->name, flag, who); } else if (strcasecmp(cmd, "notice") == 0) { char *target = next_word(&q); if (!target || !curwin || !*q) return; sendf(curwin->srv, "NOTICE %s :%s", target, q); Window *w = window_get(curwin->srv, target, is_channel(target) ? W_CHANNEL : W_QUERY); appendf(w, "-%s- %s", curwin->srv->nick, q); } else if (strcasecmp(cmd, "query") == 0) { char *nick = next_word(&q); if (!nick || !curwin) return; focus_window(window_get(curwin->srv, nick, W_QUERY)); } else if (strcasecmp(cmd, "who") == 0) { if (!curwin) return; curwin->srv->reply_win = curwin; sendf(curwin->srv, "WHO%s%s", *q ? " " : "", q); } else if (strcasecmp(cmd, "list") == 0) { if (!curwin) return; curwin->srv->reply_win = curwin; sendf(curwin->srv, "LIST%s%s", *q ? " " : "", q); } else if (strcasecmp(cmd, "motd") == 0 || strcasecmp(cmd, "time") == 0 || strcasecmp(cmd, "version") == 0 || strcasecmp(cmd, "admin") == 0 || strcasecmp(cmd, "info") == 0 || strcasecmp(cmd, "links") == 0 || strcasecmp(cmd, "lusers") == 0 || strcasecmp(cmd, "stats") == 0) { if (!curwin) return; curwin->srv->reply_win = curwin; sendf(curwin->srv, "%s%s%s", cmd, *q ? " " : "", q); appendf(curwin, "* %s", cmd); } else if (strcasecmp(cmd, "ping") == 0) { char *nick = next_word(&q); if (!nick || !curwin) return; sendf(curwin->srv, "PING %s", nick); appendf(curwin, "* pinging %s", nick); } else if (strcasecmp(cmd, "ctcp") == 0) { char *nick = next_word(&q); if (!nick || !curwin || !*q) return; sendf(curwin->srv, "PRIVMSG %s :\001%s\001", nick, q); appendf(curwin, "* ctcp %s %s", nick, q); } else if (strcasecmp(cmd, "raw") == 0) { if (!curwin || !*q) return; sendf(curwin->srv, "%s", q); appendf(curwin, "* -> %s", q); } else if (strcasecmp(cmd, "close") == 0 || strcasecmp(cmd, "wc") == 0) { if (!curwin) return; if (curwin == curwin->srv->windows) { appendf(curwin, "* cannot close the server window"); return; } window_close(curwin->srv, curwin); } else if (strcasecmp(cmd, "clear") == 0) { window_clear(curwin); } else if (strcasecmp(cmd, "reconnect") == 0) { if (!curwin) return; Server *s = curwin->srv; appendf(serverwin(s), "* reconnecting to %s:%d", s->host, s->port); disconnect_server(s); s->retry_at = 0; connect_server(s); } else if (strcasecmp(cmd, "quit") == 0) { for (Server *s = servers; s; s = s->next) sendf(s, "QUIT :%s", *q ? q : "irc9"); quit_flag = 1; } else if (strcasecmp(cmd, "help") == 0) { Window *t = curwin ? curwin : server_window_owner()->windows; appendf(t, "commands: /join /part /nick /msg /me /whois /n /names"); appendf(t, " /away /topic /invite /kick /mode /notice /query"); appendf(t, " /who /list /motd /time /version /admin /info"); appendf(t, " /links /lusers /stats /ping /ctcp /op /deop"); appendf(t, " /voice /devoice /ban /unban /raw /close /wc /clear"); appendf(t, " /reconnect /quit /help"); appendf(t, "keys: ctrl-n / ctrl-p switch windows, pgup/pgdn scroll, ctrl-l clear screen"); } else { if (curwin) appendf(curwin, "* unknown command: /%s", cmd); } } static void submit_input(void) { char line[MAXINPUT]; snprintf(line, sizeof line, "%s", input); history_add(line); if (*line == '/') { do_command(line); } else if (*line) { Window *t = input_target(); if (!t) { if (curwin) appendf(curwin, "* no target here; use /join or /msg"); } else { sendf(t->srv, "PRIVMSG %s :%s", t->name, line); appendf(t, "<%s> %s", t->srv->nick, line); } } input[0] = 0; input_len = input_pos = 0; if (curwin) { curwin->scroll = 0; curwin->unread = 0; } dirty = 1; } static void handle_key(int c) { if (c != '\t') comp_active = 0; if (c == '\t') { complete_input(); return; } if (c == 0x0e) { switch_window(1); return; } /* ctrl-n */ if (c == 0x10) { switch_window(-1); return; } /* ctrl-p */ if (c == 0x0c) { /* ctrl-l */ if (curwin) { curwin->scroll = -mainh; dirty = 1; } return; } if (c == '\n' || c == '\r') { submit_input(); return; } if (c == 127 || c == 8) { if (input_pos > 0) { memmove(input + input_pos - 1, input + input_pos, (size_t)(input_len - input_pos) + 1); input_pos--; input_len--; } dirty = 1; return; } if (c == KEY_LEFT) { if (input_pos > 0) input_pos--; dirty = 1; return; } if (c == KEY_RIGHT) { if (input_pos < input_len) input_pos++; dirty = 1; return; } if (c == KEY_HOME) { input_pos = 0; dirty = 1; return; } if (c == KEY_END) { input_pos = input_len; dirty = 1; return; } if (c == KEY_UP) { history_browse(-1); dirty = 1; return; } if (c == KEY_DOWN) { history_browse(1); dirty = 1; return; } if (c == KEY_PPAGE) { if (curwin) { int step = mainh > 1 ? mainh - 1 : 1; if (curwin->scroll < 0) curwin->scroll = 0; if (curwin->scroll > MAXSCROLLROWS - step) curwin->scroll = MAXSCROLLROWS; else curwin->scroll += step; dirty = 1; } return; } if (c == KEY_NPAGE) { if (curwin) { curwin->scroll -= mainh > 1 ? mainh - 1 : 1; if (curwin->scroll < 0) curwin->scroll = 0; dirty = 1; } return; } if (((c >= 32 && c < 127) || (c >= 0x80 && c < 0x100)) && input_len < MAXINPUT - 1) { memmove(input + input_pos + 1, input + input_pos, (size_t)(input_len - input_pos) + 1); input[input_pos++] = (char)c; input_len++; dirty = 1; } } /* ------------------------------------------------------------------ */ /* drawing */ static void layout(void) { treew = cols >= 60 ? TREEW : (cols >= 30 ? 16 : 8); if (treew > cols / 2) treew = cols / 2; mainh = lines > 4 ? lines - 4 : 0; } static void terminal_move(int row, int col) { printf("\033[%d;%dH", row + 1, col + 1); } static void terminal_repeat(int c, int count) { for (int i = 0; i < count; i++) putchar(c); } /* Consume complete printable characters without forwarding terminal controls. */ static size_t terminal_character(const char *s, size_t available, int *width) { mbstate_t state = {0}; wchar_t wc; size_t len = mbrtowc(&wc, s, available, &state); *width = 1; if (len == 0 || len > available) return 0; if (iswcntrl(wc)) return 0; *width = wcwidth(wc); if (*width < 0) { *width = 1; return 0; } return len; } static void terminal_text(const char *s, int columns) { size_t remaining = strlen(s); while (remaining && columns >= 0) { int width; size_t len = terminal_character(s, remaining, &width); if (width > columns) break; if (len) fwrite(s, 1, len, stdout); else { putchar('?'); len = 1; } columns -= width; remaining -= len; s += len; } } static int ircfmt_vislen(const char *s) { int n = 0; size_t length = strlen(s); for (size_t i = 0; s[i]; i++) { unsigned char c = (unsigned char)s[i]; if (c == 0x02 || c == 0x1d || c == 0x1f || c == 0x16 || c == 0x0f) continue; if (c == 0x03) { i++; if (s[i] && isdigit((unsigned char)s[i])) { i++; if (s[i] && isdigit((unsigned char)s[i])) i++; if (s[i] == ',' && s[i + 1] && isdigit((unsigned char)s[i + 1])) { i += 2; if (s[i] && isdigit((unsigned char)s[i])) i++; } } i--; continue; } int width; size_t len = terminal_character(s + i, length - i, &width); if (len) i += len - 1; n += width; } return n; } static size_t ircfmt_bytes_for_vis(const char *s, int vis, int *used) { int n = 0; size_t length = strlen(s); size_t i = 0; for (; s[i]; i++) { unsigned char c = (unsigned char)s[i]; if (c == 0x02 || c == 0x1d || c == 0x1f || c == 0x16 || c == 0x0f) continue; if (c == 0x03) { size_t j = i + 1; if (s[j] && isdigit((unsigned char)s[j])) { j++; if (s[j] && isdigit((unsigned char)s[j])) j++; if (s[j] == ',' && s[j + 1] && isdigit((unsigned char)s[j + 1])) { j += 2; if (s[j] && isdigit((unsigned char)s[j])) j++; } } i = j - 1; continue; } int width; size_t len = terminal_character(s + i, length - i, &width); if (n && width > vis - n) break; if (len) i += len - 1; n += width; } *used = n; return i; } static void push_wrapped(char **rows, int *nr, int maxrows, const char *s, int width) { if (width < 1) width = 1; if (width > MAXLINE * 2 - 1) width = MAXLINE * 2 - 1; if (*nr >= maxrows) return; char *copy = dupstr(s); char *segs[128]; /* Tokens plus the single spaces we reinsert never exceed the source line. */ char *cur = xmalloc(size_add(strlen(s), 2)); size_t clen = 0; int nseg = 0; int curvis = 0; cur[0] = 0; for (char *tok = strtok(copy, " \t"); tok; tok = strtok(NULL, " \t")) { int tlvis = ircfmt_vislen(tok); size_t tlbytes = strlen(tok); if (curvis == 0) { while (tlvis > width) { int used; size_t b = ircfmt_bytes_for_vis(tok, width, &used); if (nseg < 128) segs[nseg++] = dupnstr(tok, b); tok += b; tlvis -= used; tlbytes -= b; } memcpy(cur, tok, tlbytes); cur[tlbytes] = 0; clen = tlbytes; curvis = tlvis; } else if (curvis + 1 + tlvis <= width) { cur[clen++] = ' '; memcpy(cur + clen, tok, tlbytes); clen += tlbytes; cur[clen] = 0; curvis += 1 + tlvis; } else { if (nseg < 128) segs[nseg++] = dupstr(cur); while (tlvis > width) { int used; size_t b = ircfmt_bytes_for_vis(tok, width, &used); if (nseg < 128) segs[nseg++] = dupnstr(tok, b); tok += b; tlvis -= used; tlbytes -= b; } memcpy(cur, tok, tlbytes); cur[tlbytes] = 0; clen = tlbytes; curvis = tlvis; } } if (clen || nseg == 0) { if (nseg < 128) segs[nseg++] = dupstr(cur); } for (int i = nseg - 1; i >= 0; i--) { if (*nr < maxrows) rows[(*nr)++] = segs[i]; else free(segs[i]); } free(cur); free(copy); } static void draw_tree(void) { if (treew < 2 || mainh < 2) return; if (terminal_color) fputs("\033[36m", stdout); terminal_move(1, 0); putchar('/'); terminal_repeat('-', treew - 2); putchar('\\'); for (int row = 2; row < mainh; row++) { terminal_move(row, 0); putchar('|'); terminal_move(row, treew - 1); putchar('|'); } terminal_move(mainh, 0); putchar('\\'); terminal_repeat('_', treew - 2); putchar('/'); fputs("\033[0m", stdout); int y = 1; for (Server *s = servers; s; s = s->next) { if (y >= mainh - 1) break; int selected = (serverwin(s) == curwin); if (treew > 4) { terminal_move(y, 1); fputs(selected ? (terminal_color ? "\033[1;4m" : "\033[7m") : "\033[1m", stdout); printf("%c ", s->connected ? '*' : ' '); terminal_text(s->host, treew - 4); fputs("\033[0m", stdout); } y++; for (Window *w = s->windows->next; w; w = w->next) { if (y >= mainh - 1) break; char label[CHANLEN + 16]; if (w->unread) snprintf(label, sizeof label, "%s(%d)", w->name, w->unread); else snprintf(label, sizeof label, "%s", w->name); if (treew > 5) { terminal_move(y, 2); if (terminal_color) fputs("\033[36m", stdout); fputs(w->next ? "|-" : "\\-", stdout); fputs("\033[0m", stdout); if (w == curwin) fputs(terminal_color ? "\033[1;4m" : "\033[7m", stdout); terminal_text(label, treew - 6); fputs("\033[0m", stdout); } y++; } } } static int irc_to_ansi_color(int color) { static const int map[] = {7, 0, 4, 2, 1, 1, 5, 3, 3, 2, 6, 6, 4, 5, 0, 7}; return color >= 0 && color < 16 ? map[color] : 9; } static void draw_irc_text(int y, int x, const char *s, int maxvis) { int vis = 0; int bold = 0, ul = 0, rev = 0; int fg = -1, bg = -1; terminal_move(y, x); size_t length = strlen(s); int style_dirty = 1; for (size_t i = 0; s[i]; i++) { unsigned char c = (unsigned char)s[i]; if (c == 0x02) { bold = !bold; style_dirty = 1; continue; } if (c == 0x1f) { ul = !ul; style_dirty = 1; continue; } if (c == 0x16) { rev = !rev; style_dirty = 1; continue; } if (c == 0x1d) { continue; } if (c == 0x0f) { bold = ul = rev = 0; fg = bg = -1; style_dirty = 1; continue; } if (c == 0x03) { int nfg = -1, nbg = -1, saw = 0; i++; if (s[i] && isdigit((unsigned char)s[i])) { saw = 1; nfg = s[i] - '0'; i++; if (s[i] && isdigit((unsigned char)s[i])) { nfg = nfg * 10 + (s[i] - '0'); i++; } if (s[i] == ',' && s[i + 1] && isdigit((unsigned char)s[i + 1])) { i++; nbg = s[i] - '0'; i++; if (s[i] && isdigit((unsigned char)s[i])) { nbg = nbg * 10 + (s[i] - '0'); i++; } } } i--; if (saw) { fg = nfg; bg = nbg; } else { fg = bg = -1; } style_dirty = 1; continue; } if (style_dirty) { printf("\033[0%s%s%s", bold ? ";1" : "", ul ? ";4" : "", rev ? ";7" : ""); if (terminal_color) printf(";%d;%d", 30 + irc_to_ansi_color(fg), 40 + irc_to_ansi_color(bg)); putchar('m'); style_dirty = 0; } int width; size_t len = terminal_character(s + i, length - i, &width); if (width > maxvis - vis) { if (vis == 0 && maxvis == 1) putchar('?'); break; } if (len) { fwrite(s + i, 1, len, stdout); i += len - 1; } else { putchar('?'); } vis += width; } fputs("\033[0m", stdout); } static void draw_title(void) { fputs(terminal_color ? "\033[1m" : "\033[7m", stdout); terminal_move(0, 0); terminal_repeat(' ', cols); if (curwin) { int margin = cols > 24; terminal_move(0, margin); char head[MAXLINE]; if (curwin->type == W_SERVER) snprintf(head, sizeof head, "[irc9] (status) %s%s", curwin->srv->host, curwin->scroll > 0 ? " [scroll]" : ""); else if (curwin->type == W_QUERY && curwin->hostmask[0]) snprintf(head, sizeof head, "[irc9] %s / %s (%s)%s", curwin->srv->host, curwin->name, curwin->hostmask, curwin->scroll > 0 ? " [scroll]" : ""); else snprintf(head, sizeof head, "[irc9] %s / %s%s", curwin->srv->host, curwin->name, curwin->scroll > 0 ? " [scroll]" : ""); terminal_text(head, cols - margin); } fputs("\033[0m", stdout); } static void draw_main(void) { int width = cols - treew; if (curwin && mainh > 0 && width >= 3) { int ww = width - 2; if (ww < 1) ww = 1; int h = mainh; long long need_ll = (long long)h + curwin->scroll; if (need_ll < 0) need_ll = 0; size_t need = (size_t)need_ll; size_t cap = size_add(need, size_add(size_mul((size_t)curwin->nlines, 8), 64)); char **rows = xalloc_array(cap, sizeof *rows); int nr = 0; int maxrows = need > INT_MAX ? INT_MAX : (int)need; for (int i = curwin->nlines - 1; i >= 0 && nr < maxrows; i--) push_wrapped(rows, &nr, maxrows, curwin->lines[i], ww); if ((size_t)nr < need) { int maxscroll = nr - h; if (maxscroll < 0) maxscroll = 0; if (curwin->scroll > maxscroll) curwin->scroll = maxscroll; } for (int r = 0; r < h; r++) { int idx = curwin->scroll + (h - 1 - r); if (idx >= 0 && idx < nr && rows[idx]) draw_irc_text(r + 1, treew + 1, rows[idx], ww); } for (int i = 0; i < nr; i++) free(rows[i]); free(rows); } } static void draw_input(void) { if (lines < 4) return; terminal_move(lines - 3, 0); if (terminal_color) fputs("\033[36m", stdout); terminal_repeat('-', cols); fputs("\033[0m", stdout); fputs(terminal_color ? "\033[1m" : "\033[7m", stdout); terminal_move(lines - 2, 0); terminal_repeat(' ', cols); if (curwin) { char now[16], status[MAXLINE], umode[40]; fmttime(now, sizeof now, "%H:%M"); if (curwin->srv->umode[0]) snprintf(umode, sizeof umode, "[%s]", curwin->srv->umode); else umode[0] = 0; snprintf(status, sizeof status, "[%s] (%s@%s:%d%s)%s%s", now, curwin->srv->nick, curwin->srv->host, curwin->srv->port, curwin->srv->tls ? " [TLS]" : "", umode[0] ? " " : "", umode); if (cols > 2) { terminal_move(lines - 2, 1); terminal_text(status, cols - 2); } } fputs("\033[0m", stdout); terminal_move(lines - 1, 0); if (cols > 1) fputs("> ", stdout); terminal_text(input, cols - 3); int x = 2; for (int i = 0; i < input_pos; ) { int width; size_t len = terminal_character(input + i, (size_t)(input_pos - i), &width); x += width; i += len ? (int)len : 1; } if (x >= cols) x = cols - 1; terminal_move(lines - 1, x); } static void redraw(void) { fputs("\033[?25l\033[0m\033[2J", stdout); draw_title(); draw_tree(); draw_main(); draw_input(); fputs("\033[?25h", stdout); fflush(stdout); dirty = 0; } static void check_resize(void) { struct winsize size; if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0 && size.ws_row && size.ws_col && (lines != size.ws_row || cols != size.ws_col)) { lines = size.ws_row; cols = size.ws_col; layout(); dirty = 1; } } static void terminal_start(void) { const char *term = getenv("TERM"); if (!isatty(STDOUT_FILENO) || tcgetattr(STDIN_FILENO, &saved_terminal) < 0) fatal("a terminal is required"); struct termios mode = saved_terminal; mode.c_lflag &= ~(ICANON | ECHO | IEXTEN); mode.c_iflag &= ~(ICRNL | INLCR | IGNCR | ISTRIP | IXON | IXOFF); mode.c_cc[VMIN] = 0; mode.c_cc[VTIME] = 0; if (tcsetattr(STDIN_FILENO, TCSANOW, &mode) < 0) fatal("cannot configure terminal"); terminal_active = 1; terminal_color = term && strcmp(term, "dumb") != 0 && strncmp(term, "vt", 2) != 0; fputs("\033[?1049h\033[?1h\033=", stdout); check_resize(); layout(); } /* Decode both normal and application cursor keys, including split reads. */ static void terminal_read_keys(void) { static int state, number, parameters; static struct timespec last_escape; struct timespec now = {0}; clock_gettime(CLOCK_MONOTONIC, &now); if (state && (now.tv_sec - last_escape.tv_sec) * 1000LL + (now.tv_nsec - last_escape.tv_nsec) / 1000000 >= 1000) state = 0; unsigned char bytes[256]; ssize_t count = read(STDIN_FILENO, bytes, sizeof bytes); for (ssize_t i = 0; i < count && !quit_flag; i++) { int c = bytes[i]; if (c == 27) { state = 1; last_escape = now; continue; } if (state == 1) { if (c == '[' || c == 'O') { state = c; number = parameters = 0; continue; } state = 0; } else if (state) { if (c >= '0' && c <= '9') { if (!parameters && number < 100) number = number * 10 + c - '0'; continue; } if (c >= 0x20 && c <= 0x3f) { parameters = 1; continue; } int sequence = state; state = 0; if (sequence == 'O' && c == 'M') { handle_key('\n'); continue; } if (sequence == '[' && c == '[') { state = -1; /* Linux console function-key prefix */ continue; } if (sequence == -1) continue; switch (c) { case 'A': c = KEY_UP; break; case 'B': c = KEY_DOWN; break; case 'C': c = KEY_RIGHT; break; case 'D': c = KEY_LEFT; break; case 'H': c = KEY_HOME; break; case 'F': c = KEY_END; break; case '~': switch (number) { case 1: case 7: c = KEY_HOME; break; case 4: case 8: c = KEY_END; break; case 5: c = KEY_PPAGE; break; case 6: c = KEY_NPAGE; break; default: continue; } break; default: continue; } } handle_key(c); } } /* ------------------------------------------------------------------ */ /* main */ static void on_signal(int sig) { if (sig == SIGTERM) quit_flag = 1; } /* Explicit argument wins; otherwise look next to the executable first. */ static const char *find_config(void) { static const char *names[] = { "irc9rc", "config" }; static char exe[1024], dir[1024], path[1200], home_path[512]; exe[0] = 0; #ifdef __APPLE__ uint32_t size = sizeof exe; if (_NSGetExecutablePath(exe, &size) != 0) exe[0] = 0; #elif defined(__linux__) ssize_t n = readlink("/proc/self/exe", exe, sizeof exe - 1); if (n > 0) exe[n] = 0; else exe[0] = 0; #endif char *slash = *exe ? strrchr(exe, '/') : NULL; if (slash) { size_t dlen = (size_t)(slash - exe) + 1; memcpy(dir, exe, dlen); dir[dlen] = 0; for (size_t i = 0; i < sizeof names / sizeof *names; i++) { snprintf(path, sizeof path, "%s%s", dir, names[i]); if (access(path, R_OK) == 0) return path; } } const char *home = getenv("HOME"); snprintf(home_path, sizeof home_path, "%s/.irc9rc", home ? home : "."); return home_path; } int main(int argc, char **argv) { const char *path = argc > 1 ? argv[1] : find_config(); signal(SIGPIPE, SIG_IGN); signal(SIGINT, on_signal); signal(SIGTERM, on_signal); setlocale(LC_ALL, ""); load_config(path); #ifdef USE_OPENSSL tls_ctx = SSL_CTX_new(TLS_client_method()); if (tls_ctx) { static const char *const cas[] = { "/etc/ssl/cert.pem", "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", NULL }; const char *ca = NULL; for (int i = 0; cas[i]; i++) if (access(cas[i], R_OK) == 0) { ca = cas[i]; break; } if (ca && SSL_CTX_load_verify_locations(tls_ctx, ca, NULL) == 1) { SSL_CTX_set_verify(tls_ctx, SSL_VERIFY_PEER, NULL); tls_verify = 1; } else { SSL_CTX_set_verify(tls_ctx, SSL_VERIFY_NONE, NULL); } } else { fprintf(stderr, "irc9: TLS unavailable (OpenSSL init failed)\n"); } #endif if (pipe(connect_pipe) != 0) { fprintf(stderr, "irc9: cannot create connection pipe: %s\n", strerror(errno)); return 1; } int fl = fcntl(connect_pipe[0], F_GETFL, 0); fcntl(connect_pipe[0], F_SETFL, fl | O_NONBLOCK); terminal_start(); curwin = servers->windows; redraw(); while (!quit_flag) { terminal_read_keys(); if (quit_flag) break; handle_connect_results(); check_resize(); time_t now = time(NULL); for (Server *s = servers; s; s = s->next) if (s->fd < 0 && !s->connecting && now >= s->retry_at) connect_server(s); struct pollfd fds[64]; Server *owner[64]; int nf = 0; for (Server *s = servers; s && nf < 64; s = s->next) { if (s->fd < 0) continue; fds[nf].fd = s->fd; fds[nf].events = POLLIN; fds[nf].revents = 0; owner[nf] = s; nf++; } poll(fds, (nfds_t)nf, 50); for (int i = 0; i < nf; i++) if (fds[i].revents & (POLLIN | POLLHUP | POLLERR)) read_server(owner[i]); if (dirty) redraw(); } terminal_finish(); #ifdef USE_OPENSSL /* A worker may still be using the SSL_CTX; leave it to process exit. */ int pending = 0; for (Server *s = servers; s; s = s->next) if (s->connecting) pending = 1; #endif for (Server *s = servers; s; ) { Server *sn = s->next; for (Window *w = s->windows; w; ) { Window *wn = w->next; for (int i = 0; i < w->nlines; i++) free(w->lines[i]); free(w->lines); for (Member *m = w->members; m; ) { Member *mn = m->next; free(m); m = mn; } free(w); w = wn; } #ifdef USE_OPENSSL if (s->ssl) SSL_free(s->ssl); #endif if (s->fd >= 0) close(s->fd); #ifdef USE_AUTOJOIN while (s->autojoin) { AutojoinChannel *channel = s->autojoin; s->autojoin = channel->next; free(channel); } #endif free(s); s = sn; } #ifdef USE_OPENSSL if (tls_ctx && !pending) SSL_CTX_free(tls_ctx); #endif close(connect_pipe[0]); close(connect_pipe[1]); return 0; }