diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..50229a7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# Build artifacts +/irc9 +*.o +*.a +*.so +*.d +*.dSYM/ + +# Local configuration (use irc9rc-example as the template) +/irc9rc +/config + +# Editor and IDE files +*~ +*.swp +*.swo +.idea/ +.vscode/ + +# OS junk +.DS_Store +Thumbs.db + +# Debugging leftovers +core +core.* +*.log diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0a777ca --- /dev/null +++ b/Makefile @@ -0,0 +1,17 @@ +CC ?= cc +CFLAGS ?= -O2 -Wall -Wextra -Wpedantic -pthread $(shell pkg-config --cflags ncurses 2>/dev/null) +LDLIBS ?= -pthread $(shell pkg-config --libs ncurses 2>/dev/null || echo -lncurses) + +HAVE_OPENSSL := $(shell pkg-config --exists openssl && echo yes) +ifeq ($(HAVE_OPENSSL),yes) +CFLAGS += -DUSE_OPENSSL $(shell pkg-config --cflags openssl) +LDLIBS += $(shell pkg-config --libs openssl) +endif + +irc9: irc9.c + $(CC) $(CFLAGS) -D_DARWIN_C_SOURCE -o $@ $< $(LDLIBS) + +clean: + rm -f irc9 + +.PHONY: clean diff --git a/irc9.c b/irc9.c new file mode 100644 index 0000000..2664252 --- /dev/null +++ b/irc9.c @@ -0,0 +1,2295 @@ +/* + * 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. + */ + +#include +#include +#ifdef __APPLE__ +#include +#endif +#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 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]; + 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; + +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]; +#ifdef USE_OPENSSL + SSL *ssl; +#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 WINDOW *titlewin, *treewin, *mainwin, *inputwin; +static int treew = TREEW, mainh = 1; +static int sel_attr = A_REVERSE; /* opaque highlight only when default colours are unsupported */ +static int ui_attr = A_REVERSE; /* title and status bar emphasis */ +static int transparent_bg = 0; /* terminal default background, i.e. transparent where supported */ + +#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 *xmalloc(size_t n) +{ + void *p = malloc(n); + if (!p) { endwin(); fprintf(stderr, "irc9: out of memory\n"); exit(1); } + return p; +} + +static char *dupstr(const char *s) +{ + size_t n = 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(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 = xmalloc(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(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] "); + line = xmalloc(strlen(stamp) + strlen(clean) + 1); + snprintf(line, strlen(stamp) + strlen(clean) + 1, "%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 void member_add(Window *w, const char *nick) +{ + if (member_find(w, nick)) return; + Member *m = xmalloc(sizeof *m); + snprintf(m->nick, sizeof m->nick, "%s", nick); + m->next = w->members; + w->members = m; +} + +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; + } + + int count = 0; + for (Member *m = w->members; m; m = m->next) count++; + + char line[MAXLINE * 2]; + int len = snprintf(line, sizeof line, "* %d 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", m->nick); + if (add <= 0 || (size_t)add >= room) break; + len += add; + } + line[len] = 0; + win_append_raw(w, line); +} + +/* ------------------------------------------------------------------ */ +/* config */ + +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; + 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 ? atoi(a2) : 6667; + if (s->port < 1 || s->port > 65535) s->port = 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); + s->fd = -1; + s->retry_at = 0; + if (!servers) servers = s; else last->next = s; + last = s; + 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) { + /* Accepted for compatibility; join channels manually with /join. */ + } 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) +{ +#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) +{ +#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) return; + 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 cap = 4 * ((len + 2) / 3); + char *out = xmalloc(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 = 1 + ulen + 1 + plen; + unsigned char *raw = xmalloc(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 (!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 = sizeof s->caps - used - 1; + 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 (!is_channel(arg[0]) && 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, "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); + while (len && (*p == '@' || *p == '+' || *p == '%')) { 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); + } + 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; + 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) { + memmove(history[0], history[1], (MAXHIST - 1) * MAXINPUT); + 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", 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", 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 == ERR) return; + 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 || c == KEY_BACKSPACE) { + 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) { curwin->scroll += mainh > 1 ? mainh - 1 : 1; 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) +{ + if (titlewin) delwin(titlewin); + if (treewin) delwin(treewin); + if (mainwin) delwin(mainwin); + if (inputwin) delwin(inputwin); + + treew = COLS >= 60 ? TREEW : (COLS >= 30 ? 16 : 8); + if (treew > COLS / 2) treew = COLS / 2; + mainh = LINES - 4; + if (mainh < 1) mainh = 1; + + titlewin = newwin(1, COLS, 0, 0); + treewin = newwin(mainh, treew, 1, 0); + mainwin = newwin(mainh, COLS - treew, 1, treew); + inputwin = newwin(3, COLS, LINES - 3, 0); +} + +static int ircfmt_vislen(const char *s) +{ + int n = 0; + 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; + } + n++; + } + return n; +} + +static size_t ircfmt_bytes_for_vis(const char *s, int vis) +{ + int n = 0; + size_t i = 0; + for (; s[i] && n < vis; 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; + } + n++; + } + return i; +} + +static void push_wrapped(char **rows, int *nr, int maxrows, const char *s, int width) +{ + if (width < 1) width = 1; + if (*nr >= maxrows) return; + + char *copy = dupstr(s); + char *segs[128]; + int nseg = 0; + char cur[MAXLINE * 2]; + int clen = 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) { + size_t b = ircfmt_bytes_for_vis(tok, width); + if (nseg < 128) segs[nseg++] = dupnstr(tok, b); + tok += b; tlvis -= width; tlbytes -= b; + } + memcpy(cur, tok, tlbytes); cur[tlbytes] = 0; clen = (int)tlbytes; curvis = tlvis; + } else if (curvis + 1 + tlvis <= width) { + cur[clen++] = ' '; + memcpy(cur + clen, tok, tlbytes); + clen += (int)tlbytes; + cur[clen] = 0; + curvis += 1 + tlvis; + } else { + if (nseg < 128) segs[nseg++] = dupstr(cur); + while (tlvis > width) { + size_t b = ircfmt_bytes_for_vis(tok, width); + if (nseg < 128) segs[nseg++] = dupnstr(tok, b); + tok += b; tlvis -= width; tlbytes -= b; + } + memcpy(cur, tok, tlbytes); cur[tlbytes] = 0; clen = (int)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(copy); +} + +static void draw_tree(void) +{ + werase(treewin); + wborder(treewin, 0, ACS_VLINE, 0, 0, 0, 0, 0, 0); + int y = 1; + for (Server *s = servers; s; s = s->next) { + if (y >= mainh - 1) break; + int selected = (serverwin(s) == curwin); + if (selected) wattron(treewin, sel_attr); + else wattron(treewin, A_BOLD); + mvwprintw(treewin, y++, 1, "%c %-.*s", s->connected ? '*' : ' ', + treew - 4, s->host); + if (selected) wattroff(treewin, sel_attr); + else wattroff(treewin, A_BOLD); + 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 (w == curwin) wattron(treewin, sel_attr); + mvwprintw(treewin, y++, 3, "%-.*s", treew - 5, label); + if (w == curwin) wattroff(treewin, sel_attr); + } + } + wnoutrefresh(treewin); +} + +static int irc_to_curses_color(int c) +{ + static const int map[16] = { + COLOR_WHITE, COLOR_BLACK, COLOR_BLUE, COLOR_GREEN, + COLOR_RED, COLOR_RED, COLOR_MAGENTA, COLOR_YELLOW, + COLOR_YELLOW, COLOR_GREEN, COLOR_CYAN, COLOR_CYAN, + COLOR_BLUE, COLOR_MAGENTA, COLOR_BLACK, COLOR_WHITE + }; + if (c < 0 || c > 15) return -1; + return map[c]; +} + +static int ircfmt_color_pair(int fg, int bg) +{ + static short pair_fg[256]; + static short pair_bg[256]; + static int init; + static int next = 16; + if (!has_colors()) return 0; + if (!init) { + for (int i = 0; i < 256; i++) { pair_fg[i] = -2; pair_bg[i] = -2; } + init = 1; + } + for (int i = 16; i < next; i++) + if (pair_fg[i] == fg && pair_bg[i] == bg) return i; + if (next >= COLOR_PAIRS || next >= 256) return 0; + short pfg = fg < 0 ? (transparent_bg ? -1 : COLOR_WHITE) : (short)irc_to_curses_color(fg); + short pbg = bg < 0 ? (transparent_bg ? -1 : COLOR_BLACK) : (short)irc_to_curses_color(bg); + init_pair((short)next, pfg, pbg); + pair_fg[next] = (short)fg; + pair_bg[next] = (short)bg; + return next++; +} + +static void waddnstr_ircfmt(WINDOW *w, int y, int x, const char *s, int maxvis) +{ + int vis = 0; + int bold = 0, ul = 0, rev = 0; + int fg = -1, bg = -1; + wmove(w, y, x); + for (size_t i = 0; s[i] && vis < maxvis; i++) { + unsigned char c = (unsigned char)s[i]; + if (c == 0x02) { bold = !bold; continue; } + if (c == 0x1f) { ul = !ul; continue; } + if (c == 0x16) { rev = !rev; continue; } + if (c == 0x1d) { continue; } /* italic - not widely supported in ncurses */ + if (c == 0x0f) { bold = ul = rev = 0; fg = bg = -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; } + continue; + } + attr_t attr = A_NORMAL; + if (bold) attr |= A_BOLD; + if (ul) attr |= A_UNDERLINE; + if (rev) attr |= A_REVERSE; + int cp = (fg >= 0 || bg >= 0) ? ircfmt_color_pair(fg, bg) : 0; + wattr_set(w, attr, (short)cp, NULL); + waddch(w, c); + vis++; + } + wattr_set(w, A_NORMAL, 0, NULL); +} + +static void draw_title(void) +{ + werase(titlewin); + wattron(titlewin, ui_attr); + wmove(titlewin, 0, 0); + whline(titlewin, ' ', COLS); + if (curwin) { + 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]" : ""); + mvwaddnstr(titlewin, 0, 0, head, COLS); + } + wattroff(titlewin, ui_attr); + wnoutrefresh(titlewin); +} + +static void draw_main(void) +{ + werase(mainwin); + int width = COLS - treew; + + if (curwin && mainh > 0) { + int ww = width - 2; + int h = mainh; + int need = h + curwin->scroll; + if (need < 0) need = 0; + int cap = need + curwin->nlines * 8 + 64; + char **rows = xmalloc((size_t)cap * sizeof *rows); + int nr = 0; + for (int i = curwin->nlines - 1; i >= 0 && nr < need; i--) + push_wrapped(rows, &nr, need, curwin->lines[i], ww); + if (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]) + waddnstr_ircfmt(mainwin, r, 1, rows[idx], ww); + } + for (int i = 0; i < nr; i++) free(rows[i]); + free(rows); + } + wnoutrefresh(mainwin); +} + +static void draw_input(void) +{ + werase(inputwin); + mvwhline(inputwin, 0, 0, ACS_HLINE, COLS); + + wattron(inputwin, ui_attr); + wmove(inputwin, 1, 0); + whline(inputwin, ' ', 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); + mvwaddnstr(inputwin, 1, 1, status, COLS - 2); + } + wattroff(inputwin, ui_attr); + + mvwaddch(inputwin, 2, 0, '>'); + mvwaddch(inputwin, 2, 1, ' '); + mvwaddnstr(inputwin, 2, 2, input, COLS - 3); + int x = 2 + input_pos; + if (x >= COLS) x = COLS - 1; + wmove(inputwin, 2, x); + wnoutrefresh(inputwin); +} + +static void redraw(void) +{ + draw_title(); + draw_tree(); + draw_main(); + draw_input(); + doupdate(); + dirty = 0; +} + +static void check_resize(void) +{ + if (is_term_resized(LINES, COLS)) { + resize_term(0, 0); + layout(); + dirty = 1; + } +} + +/* ------------------------------------------------------------------ */ +/* 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); + + initscr(); + cbreak(); + noecho(); + keypad(stdscr, TRUE); + nodelay(stdscr, TRUE); + curs_set(1); + if (has_colors()) { + start_color(); + if (use_default_colors() == OK) { + /* -1 = terminal default: foot's transparent background stays visible. */ + transparent_bg = 1; + init_pair(1, -1, -1); + sel_attr = A_BOLD | A_UNDERLINE | COLOR_PAIR(1); + ui_attr = A_BOLD | COLOR_PAIR(1); + } else { + /* No default-colour support: keep the old opaque highlight. */ + init_pair(1, COLOR_BLACK, COLOR_WHITE); + sel_attr = COLOR_PAIR(1); + } + } + layout(); + curwin = servers->windows; + redraw(); + + while (!quit_flag) { + int c; + while ((c = getch()) != ERR) { + if (c == KEY_RESIZE) { resize_term(0, 0); layout(); dirty = 1; continue; } + handle_key(c); + if (quit_flag) break; + } + 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++; + } + if (nf) poll(fds, (nfds_t)nf, 50); + else napms(50); + + for (int i = 0; i < nf; i++) + if (fds[i].revents & (POLLIN | POLLHUP | POLLERR)) + read_server(owner[i]); + + if (dirty) redraw(); + } + + endwin(); + +#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); + 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; +} diff --git a/irc9rc-example b/irc9rc-example new file mode 100644 index 0000000..971d11e --- /dev/null +++ b/irc9rc-example @@ -0,0 +1,21 @@ +# irc9 config: keywords and arguments, one line each. +# Comments are whole lines starting with '#'. + +nick armin +user armin +real Armin +# strip_formatting off # default on; off renders IRC bold/color/etc. + +# Libera and OFTC use TLS on 6697. Use port 6667 without the ssl keyword for +# plain TCP. The optional sasl line applies to the server above it; the SASL +# user is your account name. +server irc.libera.chat 6697 ssl +# sasl armin my-sasl-password + +server irc.oftc.net 6697 ssl +# sasl armin my-sasl-password + +# channel lines are accepted for compatibility but ignored. Join manually. +# channel #linux +# channel #c +# channel #irc9