2
0
Fork 0
forked from zynk/zynk

Numerous optimizations and fixes.

This commit is contained in:
Johannes Findeisen 2026-07-15 19:49:37 +02:00
commit 9b5d8df361

248
zynk.c
View file

@ -98,6 +98,8 @@ static int (*db_step)(void*);
static int (*db_finalize)(void*);
static const unsigned char *(*db_column_text)(void*,int);
static void (*db_free)(void*);
static int (*db_bind_int64)(void*,int,long long);
static long long (*db_last_rowid)(void*);
#define LOAD_FUNC(var, name) do { \
union { void *p; typeof(var) f; } _u; \
@ -119,6 +121,7 @@ static void (*db_free)(void*);
typedef struct { void *ptr; } sqlite3;
#define DB ((sqlite3*)db_handle)
static void *db_handle;
static void db_close_cleanup(void);
static int sqlite_init_lib(void) {
static const char *paths[] = {
@ -149,29 +152,43 @@ static int sqlite_init_lib(void) {
LOAD_FUNC(db_finalize, "sqlite3_finalize");
LOAD_FUNC(db_column_text,"sqlite3_column_text");
LOAD_FUNC(db_free, "sqlite3_free");
LOAD_FUNC(db_bind_int64, "sqlite3_bind_int64");
LOAD_FUNC(db_last_rowid, "sqlite3_last_insert_rowid");
if (!db_open || !db_exec || !db_close || !db_prepare ||
!db_bind_text || !db_step || !db_finalize || !db_column_text || !db_free)
!db_bind_text || !db_step || !db_finalize || !db_column_text ||
!db_free || !db_bind_int64 || !db_last_rowid) {
dlclose(sqlite_lib);
sqlite_lib = NULL;
return -1;
}
return 0;
}
static int db_init(void) {
if (sqlite_init_lib() < 0) { fprintf(stderr, CLR_RED "Cannot load libsqlite3" CLR_RESET "\n"); return -1; }
if (db_open("zynk.db", &db_handle) != SQLITE_OK) {
fprintf(stderr, CLR_RED "DB open failed" CLR_RESET "\n"); return -1;
fprintf(stderr, CLR_RED "DB open failed" CLR_RESET "\n");
if (db_handle) { db_close(DB); db_handle = NULL; }
return -1;
}
const char *sql_zynk = "CREATE TABLE IF NOT EXISTS zynk ("
"key TEXT PRIMARY KEY, value TEXT NOT NULL, "
"nick TEXT NOT NULL, updated_at TEXT DEFAULT (datetime('now')))";
char *err = NULL;
if (db_exec(DB, sql_zynk, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, CLR_RED "SQL: %s" CLR_RESET "\n", err); db_free(err); return -1;
fprintf(stderr, CLR_RED "SQL: %s" CLR_RESET "\n", err ? err : "unknown error");
if (err) db_free(err);
db_close_cleanup();
return -1;
}
const char *sql_ai = "CREATE TABLE IF NOT EXISTS ai_pending ("
"id INTEGER PRIMARY KEY, question TEXT, "
"answer TEXT, target TEXT, nick TEXT, status TEXT DEFAULT 'idle')";
if (db_exec(DB, sql_ai, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, CLR_RED "SQL: %s" CLR_RESET "\n", err); db_free(err); return -1;
fprintf(stderr, CLR_RED "SQL: %s" CLR_RESET "\n", err ? err : "unknown error");
if (err) db_free(err);
db_close_cleanup();
return -1;
}
const char *sql_clear_ai = "DELETE FROM ai_pending";
db_exec(DB, sql_clear_ai, NULL, NULL, NULL);
@ -181,6 +198,7 @@ static int db_init(void) {
}
static void db_close_cleanup(void) { if (db_handle) { db_close(DB); db_handle = NULL; } }
static void sqlite_cleanup(void) { if (sqlite_lib) { dlclose(sqlite_lib); sqlite_lib = NULL; } }
/* ---- DB key-value operations ---- */
@ -292,16 +310,7 @@ static int ai_start(const char *question, const char *target, const char *nick,
int rc = db_step(stmt);
db_finalize(stmt);
if (rc == SQLITE_DONE) {
void *stmt2;
if (db_prepare(DB, "SELECT last_insert_rowid()", -1, &stmt2, NULL) == SQLITE_OK) {
if (db_step(stmt2) == SQLITE_ROW) {
typedef long long (*f_last_rowid)(void*);
static f_last_rowid db_last_rowid = NULL;
if (!db_last_rowid) db_last_rowid = (f_last_rowid)dlsym(sqlite_lib, "sqlite3_last_insert_rowid");
if (db_last_rowid) *out_id = db_last_rowid(db_handle);
}
db_finalize(stmt2);
}
*out_id = db_last_rowid(db_handle);
return 0;
}
return -1;
@ -311,10 +320,7 @@ static char *ai_get_question(long long id) {
void *stmt;
const char *sql = "SELECT question FROM ai_pending WHERE id=?";
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
typedef int (*f_bind_int64)(void*, int, long long);
static f_bind_int64 db_bind_int64 = NULL;
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
if (db_bind_int64) db_bind_int64(stmt, 1, id);
db_bind_int64(stmt, 1, id);
if (db_step(stmt) != SQLITE_ROW) { db_finalize(stmt); return NULL; }
const char *q = (const char*)db_column_text(stmt, 0);
char *r = q ? strdup(q) : NULL;
@ -327,10 +333,7 @@ static int ai_set_answer(long long id, const char *answer) {
void *stmt;
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return -1;
db_bind_text(stmt, 1, answer, -1, SQLITE_STATIC);
typedef int (*f_bind_int64)(void*, int, long long);
static f_bind_int64 db_bind_int64 = NULL;
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
if (db_bind_int64) db_bind_int64(stmt, 2, id);
db_bind_int64(stmt, 2, id);
int rc = db_step(stmt);
db_finalize(stmt);
return rc == SQLITE_DONE ? 0 : -1;
@ -340,10 +343,7 @@ static char *ai_get_answer(long long id) {
void *stmt;
const char *sql = "SELECT answer,target FROM ai_pending WHERE id=? AND status='done'";
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
typedef int (*f_bind_int64)(void*, int, long long);
static f_bind_int64 db_bind_int64 = NULL;
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
if (db_bind_int64) db_bind_int64(stmt, 1, id);
db_bind_int64(stmt, 1, id);
if (db_step(stmt) != SQLITE_ROW) { db_finalize(stmt); return NULL; }
const char *a = (const char*)db_column_text(stmt, 0);
const char *t = (const char*)db_column_text(stmt, 1);
@ -357,10 +357,7 @@ static char *ai_get_nick(long long id) {
void *stmt;
const char *sql = "SELECT nick FROM ai_pending WHERE id=?";
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
typedef int (*f_bind_int64)(void*, int, long long);
static f_bind_int64 db_bind_int64 = NULL;
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
if (db_bind_int64) db_bind_int64(stmt, 1, id);
db_bind_int64(stmt, 1, id);
if (db_step(stmt) != SQLITE_ROW) { db_finalize(stmt); return NULL; }
const char *n = (const char*)db_column_text(stmt, 0);
char *r = n ? strdup(n) : NULL;
@ -372,10 +369,7 @@ static void ai_reset(long long id) {
const char *sql = "DELETE FROM ai_pending WHERE id=?";
void *stmt;
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return;
typedef int (*f_bind_int64)(void*, int, long long);
static f_bind_int64 db_bind_int64 = NULL;
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
if (db_bind_int64) db_bind_int64(stmt, 1, id);
db_bind_int64(stmt, 1, id);
db_step(stmt);
db_finalize(stmt);
}
@ -433,6 +427,17 @@ static void chan_del_op(const char *name, const char *nick) {
}
}
static void chan_rename_op(const char *oldnick, const char *newnick) {
for (int i = 0; i < nchans; i++) {
for (int j = 0; j < chans[i].nops; j++) {
if (strcasecmp(chans[i].ops[j], oldnick) == 0) {
snprintf(chans[i].ops[j], sizeof chans[i].ops[0], "%s", newnick);
break;
}
}
}
}
/* ---- network I/O ---- */
static int net_connect(const char *host, int port) {
@ -487,6 +492,7 @@ static int net_send(Session *s, const char *fmt, ...) {
int n = vsnprintf(buf, sizeof buf, fmt, ap);
va_end(ap);
if (n <= 0) return 0;
if ((size_t)n >= sizeof buf) return -1;
int left = n;
const char *p = buf;
while (left > 0) {
@ -495,6 +501,7 @@ static int net_send(Session *s, const char *fmt, ...) {
if (errno == EINTR || errno == EAGAIN) continue;
return -1;
}
if (w == 0) return -1;
left -= w; p += w;
}
return n;
@ -540,6 +547,13 @@ static void tls_cleanup(Session *s) {
s->ssl = NULL;
}
static void tls_ctx_cleanup(void) {
if (tls_ctx) {
SSL_CTX_free(tls_ctx);
tls_ctx = NULL;
}
}
/* ---- signal handling ---- */
static volatile sig_atomic_t running = 1;
@ -665,6 +679,46 @@ static void strip_formatting(char *s) {
*dst = 0;
}
static int has_crlf(const char *s) {
return s && strpbrk(s, "\r\n") != NULL;
}
static int valid_irc_word(const char *s) {
if (!s || !*s || has_crlf(s)) return 0;
for (const char *p = s; *p; p++)
if (*p == ' ' || *p == '\t') return 0;
return 1;
}
static void normalize_city(const char *in, char *display, size_t dsz, char *url, size_t usz) {
size_t dl = 0, ul = 0;
int pending_space = 0;
if (!in || !*in) in = "Berlin";
for (const unsigned char *p = (const unsigned char *)in; *p; p++) {
int word = isalnum(*p) || *p == '.' || *p == ',' || *p == '-' || *p == '_';
int space = *p == ' ' || *p == '\t' || *p == '+';
if (!word && !space) continue;
if (space) {
pending_space = dl > 0;
continue;
}
if (pending_space) {
if (dl + 1 < dsz) display[dl++] = ' ';
if (ul + 1 < usz) url[ul++] = '+';
pending_space = 0;
}
if (dl + 1 < dsz) display[dl++] = *p;
if (ul + 1 < usz) url[ul++] = *p;
}
if (dl == 0) {
snprintf(display, dsz, "Berlin");
snprintf(url, usz, "Berlin");
} else {
display[dl] = 0;
url[ul] = 0;
}
}
/* ---- curl helper ---- */
static char *run_curl(const char *url) {
@ -682,10 +736,17 @@ static char *run_curl(const char *url) {
_exit(127);
}
close(fd[1]);
char buf[2048];
char buf[2048], tmp[1024];
size_t len = 0;
ssize_t n;
while ((n = read(fd[0], buf + len, 2047 - len)) > 0) len += n;
while ((n = read(fd[0], tmp, sizeof tmp)) > 0) {
size_t avail = sizeof buf - 1 - len;
if (avail > 0) {
size_t copy = (size_t)n < avail ? (size_t)n : avail;
memcpy(buf + len, tmp, copy);
len += copy;
}
}
close(fd[0]);
int status;
waitpid(pid, &status, 0);
@ -741,9 +802,8 @@ static char *fetch_forecast(const char *city_url, const char *city_display) {
static volatile pid_t pending_ai_pid;
static volatile long long pending_ai_id;
static volatile const char *pending_ai_agent;
static void ai_child_task(Session *s, long long id) {
static void ai_child_task(Session *s, long long id, const char *agent) {
signal(SIGALRM, SIG_DFL);
alarm(AI_TIMEOUT);
/* Don't call tls_cleanup() — SSL_shutdown would send a close_notify on
@ -767,7 +827,7 @@ static void ai_child_task(Session *s, long long id) {
for (int i = 0; i < MAX_HISTORY; i++) { if (history[i]) { have_history = 1; break; } }
char prefix[2048];
int plen;
if (pending_ai_agent) {
if (agent) {
plen = snprintf(prefix, sizeof prefix,
"Your name is zynk. You are a coding assistant in a project. Execute code changes as requested. "
"Make real file edits and run commands as needed. Answer in English when asked in English, answer in German when asked in German. "
@ -804,17 +864,24 @@ static void ai_child_task(Session *s, long long id) {
close(ai_pipe[1]);
int dn = open("/dev/null", O_WRONLY);
if (dn >= 0) { dup2(dn, STDERR_FILENO); close(dn); }
if (pending_ai_agent)
execl(OPENCODE_BIN, "opencode", "run", "--dangerously-skip-permissions", "--agent", pending_ai_agent, combined, (char *)NULL);
if (agent)
execl(OPENCODE_BIN, "opencode", "run", "--dangerously-skip-permissions", "--agent", agent, combined, (char *)NULL);
else
execl(OPENCODE_BIN, "opencode", "run", "--dangerously-skip-permissions", "--agent", "plan", combined, (char *)NULL);
_exit(127);
}
close(ai_pipe[1]);
char out[6144];
char out[6144], tmp[1024];
size_t olen = 0;
ssize_t n;
while ((n = read(ai_pipe[0], out + olen, 6143 - olen)) > 0) olen += n;
while ((n = read(ai_pipe[0], tmp, sizeof tmp)) > 0) {
size_t avail = sizeof out - 1 - olen;
if (avail > 0) {
size_t copy = (size_t)n < avail ? (size_t)n : avail;
memcpy(out + olen, tmp, copy);
olen += copy;
}
}
close(ai_pipe[0]);
int status;
waitpid(cmd_pid, &status, 0);
@ -849,10 +916,9 @@ static void ai_ask(Session *s, const char *question, const char *reply_target, c
}
pid_t pid = fork();
if (pid == -1) { ai_reset(id); irc_msg(s, reply_target, "Error forking"); return; }
if (pid == 0) { ai_child_task(s, id); }
if (pid == 0) { ai_child_task(s, id, agent); }
pending_ai_pid = pid;
pending_ai_id = id;
pending_ai_agent = agent;
log_stamp(); fprintf(stderr, CLR_BLUE "AI started (PID %d, ID %lld) from %s:" CLR_RESET " %s\n", pid, id, src_nick, question);
}
@ -899,10 +965,7 @@ static void ai_check_completion(Session *s) {
char *target = NULL;
void *stmt;
if (db_prepare(DB, "SELECT target FROM ai_pending WHERE id=?", -1, &stmt, NULL) == SQLITE_OK) {
typedef int (*f_bind_int64)(void*, int, long long);
static f_bind_int64 db_bind_int64 = NULL;
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
if (db_bind_int64) db_bind_int64(stmt, 1, done_id);
db_bind_int64(stmt, 1, done_id);
if (db_step(stmt) == SQLITE_ROW) {
const char *t = (const char*)db_column_text(stmt, 0);
if (t) target = strdup(t);
@ -911,7 +974,9 @@ static void ai_check_completion(Session *s) {
}
if (WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGALRM) {
if (target) {
irc_msg(s, target, "AI query timed out after AI_TIMEOUT seconds.");
char msg[96];
snprintf(msg, sizeof msg, "AI query timed out after %d seconds.", AI_TIMEOUT);
irc_msg(s, target, msg);
log_stamp(); fprintf(stderr, CLR_RED "AI done PID %d from %s: timed out for %s" CLR_RESET "\n", done_pid, nick ? nick : "?", target);
}
} else if (target) {
@ -1051,20 +1116,12 @@ static int cmd_weather(Session *s, const char *msg, const char *reply_target, co
if (strncmp(msg, "!weather", 8) != 0) return 0;
if (msg[8] != ' ' && msg[8] != '\0') return 0;
if (rate_limit_check(src_nick) < 0) return 1;
char city[256];
char city[256], city_url[256];
const char *rest = msg[8] == ' ' ? msg + 9 : "";
while (*rest == ' ') rest++;
if (*rest) {
snprintf(city, sizeof city, "%s", rest);
char *end = city + strlen(city);
while (end > city && end[-1] == ' ') end--;
*end = 0;
} else {
snprintf(city, sizeof city, "Berlin");
}
for (char *p = city; *p; p++) if (*p == ' ') *p = '+';
normalize_city(rest, city, sizeof city, city_url, sizeof city_url);
char url[512];
snprintf(url, sizeof url, "https://wttr.in/%s?format=%%l:+%%t+%%C&m", city);
snprintf(url, sizeof url, "https://wttr.in/%s?format=%%l:+%%t+%%C&m", city_url);
char *body = fetch_url(url);
char resp[1024];
if (body) {
@ -1087,16 +1144,7 @@ static int cmd_forecast(Session *s, const char *msg, const char *reply_target, c
char city[256], city_url[256];
const char *rest = msg[9] == ' ' ? msg + 10 : "";
while (*rest == ' ') rest++;
if (*rest) {
snprintf(city, sizeof city, "%s", rest);
char *end = city + strlen(city);
while (end > city && end[-1] == ' ') end--;
*end = 0;
} else {
snprintf(city, sizeof city, "Berlin");
}
snprintf(city_url, sizeof city_url, "%s", city);
for (char *p = city_url; *p; p++) if (*p == ' ') *p = '+';
normalize_city(rest, city, sizeof city, city_url, sizeof city_url);
char *body = fetch_forecast(city_url, city);
char resp[1024];
if (body) {
@ -1236,7 +1284,10 @@ static void handle_namreply(Session *s, const char *params) {
p++;
}
int i = 0;
while (*p && *p != ' ' && i < 31) buf[i++] = *p++;
while (*p && *p != ' ') {
if (i < 31) buf[i++] = *p;
p++;
}
buf[i] = 0;
if (is_op && buf[0]) chan_add_op(_chan, buf);
}
@ -1258,7 +1309,9 @@ static void handle_join(Session *s, const char *params) {
(void)s;
const char *p = params;
if (*p == ':') p++;
chan_get_or_add(p);
char _chan[64];
if (sscanf(p, "%63s", _chan) == 1)
chan_get_or_add(_chan);
}
static void handle_part(const char *params, const char *src_nick) {
@ -1284,9 +1337,10 @@ static void handle_nick_change(Session *s, const char *prefix, const char *param
size_t nlen = ex ? (size_t)(ex - prefix) : strlen(prefix);
if (nlen >= sizeof src_nick) nlen = sizeof src_nick - 1;
memcpy(src_nick, prefix, nlen); src_nick[nlen] = 0;
const char *newnick = params;
if (*newnick == ':') newnick++;
chan_rename_op(src_nick, newnick);
if (strcasecmp(src_nick, s->nick) == 0) {
const char *newnick = params;
if (*newnick == ':') newnick++;
strncpy(s->nick, newnick, sizeof s->nick - 1);
s->nick[sizeof s->nick - 1] = 0;
}
@ -1510,7 +1564,19 @@ int main(int argc, char **argv) {
if (port <= 0 || port > 65535) port = DEF_PORT;
if ((port == 6697 || port == 7000) && !use_tls) use_tls = 1;
if (!nick) { snprintf(nickbuf, sizeof nickbuf, "zynk"); nick = nickbuf; }
if (db_init() < 0) { fprintf(stderr, CLR_RED "DB init failed" CLR_RESET "\n"); return 1; }
if (!valid_irc_word(nick)) {
fprintf(stderr, CLR_RED "Invalid nick" CLR_RESET "\n");
return 1;
}
if (has_crlf(passbuf) || has_crlf(joinbuf)) {
fprintf(stderr, CLR_RED "Invalid IRC argument" CLR_RESET "\n");
return 1;
}
if (db_init() < 0) {
fprintf(stderr, CLR_RED "DB init failed" CLR_RESET "\n");
sqlite_cleanup();
return 1;
}
Session s;
memset(&s, 0, sizeof s);
snprintf(s.host, sizeof s.host, "%s", sv);
@ -1522,14 +1588,30 @@ int main(int argc, char **argv) {
s.fd = -1;
s.use_tls = use_tls;
if (passbuf[0]) snprintf(s.pass, sizeof s.pass, "%s", passbuf);
if (use_tls && tls_init() < 0) { fprintf(stderr, CLR_RED "TLS init failed" CLR_RESET "\n"); return 1; }
if (use_tls && tls_init() < 0) {
fprintf(stderr, CLR_RED "TLS init failed" CLR_RESET "\n");
db_close_cleanup();
sqlite_cleanup();
return 1;
}
signal(SIGINT, handle_sigterm);
signal(SIGTERM, handle_sigterm);
signal(SIGPIPE, SIG_IGN);
s.fd = net_connect(s.host, s.port);
if (s.fd < 0) { fprintf(stderr, CLR_RED "Could not connect to %s:%d" CLR_RESET "\n", s.host, s.port); return 1; }
if (s.fd < 0) {
fprintf(stderr, CLR_RED "Could not connect to %s:%d" CLR_RESET "\n", s.host, s.port);
tls_ctx_cleanup();
db_close_cleanup();
sqlite_cleanup();
return 1;
}
if (s.use_tls && tls_handshake(&s) < 0) {
fprintf(stderr, CLR_RED "TLS handshake failed" CLR_RESET "\n"); close(s.fd); return 1;
fprintf(stderr, CLR_RED "TLS handshake failed" CLR_RESET "\n");
close(s.fd);
tls_ctx_cleanup();
db_close_cleanup();
sqlite_cleanup();
return 1;
}
int fl = fcntl(s.fd, F_GETFL, 0);
fcntl(s.fd, F_SETFL, fl | O_NONBLOCK);
@ -1556,6 +1638,12 @@ int main(int argc, char **argv) {
}
ai_check_completion(&s);
}
if (pending_ai_pid > 0) {
kill(pending_ai_pid, SIGTERM);
waitpid(pending_ai_pid, NULL, 0);
ai_reset(pending_ai_id);
pending_ai_pid = 0;
}
if (s.connected && s.fd >= 0) {
int old_fl = fcntl(s.fd, F_GETFL, 0);
fcntl(s.fd, F_SETFL, old_fl & ~O_NONBLOCK);
@ -1564,7 +1652,9 @@ int main(int argc, char **argv) {
nanosleep(&ts, NULL);
}
tls_cleanup(&s);
tls_ctx_cleanup();
if (s.fd >= 0) close(s.fd);
db_close_cleanup();
sqlite_cleanup();
return 0;
}