2
0
Fork 0
forked from zynk/zynk
zynk/zynk.c

3149 lines
109 KiB
C

/*
* Copyright (c) armin, hanez
*
* Licensed under the terms of the MIT License.
*/
#define _GNU_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <time.h>
#include <stdarg.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netdb.h>
/* #include <sys/utsname.h> */
#include <dlfcn.h>
#include <sys/wait.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
int asprintf(char **, const char *, ...);
/* ---- constants ---- */
#define VERSION "0.34.0"
#define DEFAULT_SERVER "irc.libera.chat"
#define OPENCODE_BIN "/usr/bin/opencode"
#define CLR_RESET "\033[0m"
#define CLR_DIM "\033[2m"
#define CLR_RED "\033[31m"
#define CLR_GREEN "\033[32m"
#define CLR_YELLOW "\033[33m"
#define CLR_BLUE "\033[34m"
#define CLR_MAGENTA "\033[35m"
#define CLR_CYAN "\033[36m"
enum {
RBUF_SZ = 16384,
DEF_PORT = 6697,
POLL_MS = 100,
AI_REPLY_MAX = 2048,
AI_TIMEOUT = 600,
MAX_CHANS = 32,
MAX_CHAN_OPS = 64,
RATE_LIMIT_WINDOW = 10,
RATE_LIMIT_MAX = 8,
MAX_HISTORY = 100,
};
/* ---- IRC session ---- */
typedef struct {
int fd;
char host[256];
int port;
char nick[32];
char user[32];
char real[256];
char pass[256];
char auto_join[256];
int connected;
char rbuf[16384];
int rlen;
SSL *ssl;
int use_tls;
int code_restart;
} Session;
/* ---- forward declarations ---- */
static void irc_msg(Session *, const char *, const char *);
/* ---- logging ---- */
/*
* log_stamp - Print a timestamped log prefix to stderr.
*
* Outputs the current local time in "[YY-MM-DD HH:MM:SS]" format using
* ANSI dim styling, followed by a space. Intended to be called before any
* log message on the same fprintf line. Uses localtime() and strftime()
* with a 64-byte stack buffer.
*
* Returns: void (output goes to stderr).
*/
static void log_stamp(void) {
struct tm *tm;
time_t t = time(NULL);
tm = localtime(&t);
char buf[64];
strftime(buf, sizeof buf, "%y-%m-%d %H:%M:%S", tm);
fprintf(stderr, CLR_DIM "[%s]" CLR_RESET " ", buf);
}
/* ---- SQLite3 dynamic loading ---- */
static void *sqlite_lib;
static int (*db_open)(const char*,void**);
static int (*db_exec)(void*,const char*,int(*)(void*,int,char**,char**),void*,char**);
static int (*db_close)(void*);
static int (*db_prepare)(void*,const char*,int,void**,const char**);
static int (*db_bind_text)(void*,int,const char*,int,void(*)(void*));
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; \
_u.p = dlsym(sqlite_lib, name); \
var = _u.f; \
} while(0)
#define SQLITE_OK 0
#define SQLITE_ERROR 1
#define SQLITE_DONE 101
#define SQLITE_ROW 100
#define SQLITE_INTEGER 1
#define SQLITE_FLOAT 2
#define SQLITE_TEXT 3
#define SQLITE_BLOB 4
#define SQLITE_NULL 5
#define SQLITE_STATIC ((void(*)(void*))0)
#define SQLITE_TRANSIENT ((void(*)(void*))-1)
typedef struct { void *ptr; } sqlite3;
#define DB ((sqlite3*)db_handle)
static void *db_handle;
static void db_close_cleanup(void);
/*
* sqlite_init_lib - Dynamically load libsqlite3 and resolve function symbols.
*
* Iterates through a list of well-known library paths (platform-dependent)
* attempting to dlopen() the SQLite3 shared object. Falls back to a generic
* dlopen() of "libsqlite3.so.0" and "libsqlite3.so" if none of the hardcoded
* paths succeed. On success, resolves all required SQLite3 function pointers
* (sqlite3_open, sqlite3_exec, sqlite3_close, sqlite3_prepare_v2,
* sqlite3_bind_text, sqlite3_step, sqlite3_finalize, sqlite3_column_text,
* sqlite3_free, sqlite3_bind_int64, sqlite3_last_insert_rowid) via dlsym
* using the LOAD_FUNC union trick for type-safe function pointer casts.
* Validates that all symbols were resolved; on failure, closes the handle.
*
* Returns: 0 on success, -1 on failure (library not found or missing symbols).
*/
static int sqlite_init_lib(void) {
static const char *paths[] = {
"/usr/lib/x86_64-linux-gnu/libsqlite3.so.0",
"/usr/lib/aarch64-linux-gnu/libsqlite3.so.0",
"/usr/lib/libsqlite3.so.0",
"/usr/lib64/libsqlite3.so.0",
"/lib/x86_64-linux-gnu/libsqlite3.so.0",
"/lib/aarch64-linux-gnu/libsqlite3.so.0",
"/lib/libsqlite3.so.0",
};
for (size_t i = 0; i < sizeof(paths)/sizeof(paths[0]); i++) {
sqlite_lib = dlopen(paths[i], RTLD_LAZY | RTLD_LOCAL);
if (sqlite_lib) break;
}
if (!sqlite_lib) {
sqlite_lib = dlopen("libsqlite3.so.0", RTLD_LAZY | RTLD_LOCAL);
if (!sqlite_lib)
sqlite_lib = dlopen("libsqlite3.so", RTLD_LAZY | RTLD_LOCAL);
}
if (!sqlite_lib) return -1;
LOAD_FUNC(db_open, "sqlite3_open");
LOAD_FUNC(db_exec, "sqlite3_exec");
LOAD_FUNC(db_close, "sqlite3_close");
LOAD_FUNC(db_prepare, "sqlite3_prepare_v2");
LOAD_FUNC(db_bind_text, "sqlite3_bind_text");
LOAD_FUNC(db_step, "sqlite3_step");
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_int64 || !db_last_rowid) {
dlclose(sqlite_lib);
sqlite_lib = NULL;
return -1;
}
return 0;
}
/*
* db_init - Initialize the SQLite3 database and create required tables.
*
* Calls sqlite_init_lib() to load the shared library, then opens (or creates)
* the "zynk.db" database file. Creates the "zynk" key-value table with columns
* (key TEXT PRIMARY KEY, value TEXT, nick TEXT, updated_at TEXT) and the
* "ai_pending" table for tracking in-flight AI queries with columns
* (id INTEGER PRIMARY KEY, question, answer, target, nick, status).
* Clears stale ai_pending rows and any lastq/lasta history entries from the
* previous session. On any error, logs to stderr and performs cleanup.
*
* Returns: 0 on success, -1 on failure.
*/
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");
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 ? 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 ? 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);
const char *sql_clear = "DELETE FROM zynk WHERE key LIKE 'lastq%' OR key LIKE 'lasta%'";
db_exec(DB, sql_clear, NULL, NULL, NULL);
return 0;
}
/*
* db_close_cleanup - Close the SQLite3 database handle if it is open.
*
* Checks if the global db_handle is non-NULL, and if so, calls sqlite3_close
* on it and resets the handle to NULL. Safe to call multiple times.
*
* Returns: void.
*/
static void db_close_cleanup(void) { if (db_handle) { db_close(DB); db_handle = NULL; } }
/*
* sqlite_cleanup - Unload the dynamically loaded SQLite3 shared library.
*
* Calls dlclose() on the sqlite_lib handle if non-NULL and resets it to NULL.
* Should be called after db_close_cleanup() during shutdown.
*
* Returns: void.
*/
static void sqlite_cleanup(void) { if (sqlite_lib) { dlclose(sqlite_lib); sqlite_lib = NULL; } }
/* ---- DB key-value operations ---- */
/*
* db_set - Insert or update a key-value pair in the zynk database.
*
* Uses an INSERT with ON CONFLICT upsert: if the key already exists, the
* value, nick (who set it), and updated_at timestamp are all replaced.
* The nick parameter records which IRC user created or last updated the entry.
*
* Parameters:
* key - The lookup key (stored lowercase by callers).
* value - The value string to store.
* nick - The IRC nick of the user who is setting this value.
*
* Returns: 0 on success, -1 on SQLite error.
*/
static int db_set(const char *key, const char *value, const char *nick) {
void *stmt;
const char *sql = "INSERT INTO zynk(key,value,nick,updated_at)"
" VALUES(?,?,?,datetime('now'))"
" ON CONFLICT(key) DO UPDATE SET value=excluded.value,"
" nick=excluded.nick, updated_at=datetime('now')";
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return -1;
db_bind_text(stmt, 1, key, -1, SQLITE_STATIC);
db_bind_text(stmt, 2, value, -1, SQLITE_STATIC);
db_bind_text(stmt, 3, nick, -1, SQLITE_STATIC);
int rc = db_step(stmt);
db_finalize(stmt);
return rc == SQLITE_DONE ? 0 : -1;
}
/*
* db_get_raw - Retrieve the raw value for a key without metadata.
*
* Queries the zynk table for the value associated with the given key.
* Unlike db_get(), does NOT append attribution info (nick, timestamp).
* Used internally for history rotation and existence checks.
*
* Parameters:
* key - The key to look up.
*
* Returns: A newly allocated string containing the value, or NULL if the
* key is not found. Caller must free() the result.
*/
static char *db_get_raw(const char *key) {
void *stmt;
const char *sql = "SELECT value FROM zynk WHERE key=?";
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
db_bind_text(stmt, 1, key, -1, SQLITE_STATIC);
if (db_step(stmt) != SQLITE_ROW) { db_finalize(stmt); return NULL; }
const char *v = (const char*)db_column_text(stmt, 0);
char *r = v ? strdup(v) : NULL;
db_finalize(stmt);
return r;
}
/*
* db_get - Retrieve a key's value with attribution metadata.
*
* Queries the zynk table for the value, nick, and updated_at timestamp
* for the given key. Returns a formatted string in the form
* "value (set by nick on timestamp)".
*
* Parameters:
* key - The key to look up.
*
* Returns: A newly allocated formatted string, or NULL if the key is not
* found. Caller must free() the result.
*/
static char *db_get(const char *key) {
void *stmt;
const char *sql = "SELECT value,nick,updated_at FROM zynk WHERE key=?";
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
db_bind_text(stmt, 1, key, -1, SQLITE_STATIC);
if (db_step(stmt) != SQLITE_ROW) { db_finalize(stmt); return NULL; }
const char *v = (const char*)db_column_text(stmt, 0);
const char *n = (const char*)db_column_text(stmt, 1);
const char *t = (const char*)db_column_text(stmt, 2);
char *r = NULL;
if (asprintf(&r, "%s (set by %s on %s)", v, n, t) < 0) r = NULL;
db_finalize(stmt);
return r;
}
/*
* db_get_random - Fetch a random key-value pair from the zynk database.
*
* Selects one random row from the zynk table, excluding internal history
* keys (those with prefix "lastq" or "lasta"). Returns a formatted string
* "key = value (by nick on timestamp)". Used when the user sends bare "zynk"
* without a key.
*
* Returns: A newly allocated formatted string, or NULL if the database is
* empty. Caller must free() the result.
*/
static char *db_get_random(void) {
void *stmt;
const char *sql = "SELECT key,value,nick,updated_at FROM zynk"
" WHERE key NOT LIKE 'lastq%' AND key NOT LIKE 'lasta%'"
" ORDER BY RANDOM() LIMIT 1";
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
if (db_step(stmt) != SQLITE_ROW) { db_finalize(stmt); return NULL; }
const char *k = (const char*)db_column_text(stmt, 0);
const char *v = (const char*)db_column_text(stmt, 1);
const char *n = (const char*)db_column_text(stmt, 2);
const char *t = (const char*)db_column_text(stmt, 3);
char *r = NULL;
if (asprintf(&r, "%s = %s (by %s on %s)", k, v, n, t) < 0) r = NULL;
db_finalize(stmt);
return r;
}
/*
* db_rotate_history - Rotate entries in the recent history ring buffer.
*
* Maintains a fixed-size (MAX_HISTORY) ring buffer of recent entries stored
* under keys "lastq01".."lastqN" or "lasta01".."lastaN". Shifts all existing
* entries by one position (N-1 <- N-2 <- ... <- 1 <- 0) and inserts the new
* value at position 0. Used to keep context for AI queries (lastq = questions,
* lasta = answers). Each entry is stored as-is without attribution metadata.
*
* Parameters:
* prefix - "lastq" for question history or "lasta" for answer history.
* value - The new entry to insert at position 0.
*
* Returns: void.
*/
static void db_rotate_history(const char *prefix, const char *value) {
char *old[MAX_HISTORY];
char kbuf[MAX_HISTORY][12];
for (int i = 0; i < MAX_HISTORY; i++) {
snprintf(kbuf[i], sizeof kbuf[i], "%s%02d", prefix, i + 1);
old[i] = db_get_raw(kbuf[i]);
}
void *stmt;
const char *sql = "INSERT INTO zynk(key,value,nick,updated_at)"
" VALUES(?,?,?,datetime('now'))"
" ON CONFLICT(key) DO UPDATE SET value=excluded.value,"
" nick=excluded.nick, updated_at=datetime('now')";
if (db_prepare(DB, sql, -1, &stmt, NULL) == SQLITE_OK) {
db_bind_text(stmt, 1, kbuf[0], -1, SQLITE_STATIC);
db_bind_text(stmt, 2, value, -1, SQLITE_STATIC);
db_bind_text(stmt, 3, "", -1, SQLITE_STATIC);
db_step(stmt);
db_finalize(stmt);
}
for (int i = 0; i < MAX_HISTORY - 1; i++) {
if (old[i] && db_prepare(DB, sql, -1, &stmt, NULL) == SQLITE_OK) {
db_bind_text(stmt, 1, kbuf[i + 1], -1, SQLITE_STATIC);
db_bind_text(stmt, 2, old[i], -1, SQLITE_STATIC);
db_bind_text(stmt, 3, "", -1, SQLITE_STATIC);
db_step(stmt);
db_finalize(stmt);
}
}
for (int i = 0; i < MAX_HISTORY; i++) free(old[i]);
}
#define db_update_lastq(v) db_rotate_history("lastq", v)
#define db_update_lasta(v) db_rotate_history("lasta", v)
/* ---- DB AI pending operations ---- */
/*
* ai_start - Create a new pending AI query record in the database.
*
* Inserts a new row into the ai_pending table with status 'pending',
* the question text, an empty answer, the target (channel or nick to
* reply to), and the requesting user's nick. Returns the auto-incremented
* row ID via the out_id parameter for later retrieval of the answer.
*
* Parameters:
* question - The user's question or code change request.
* target - The IRC target to send the reply to (channel or nick).
* nick - The IRC nick of the user who asked.
* out_id - Pointer to receive the new row's ID.
*
* Returns: 0 on success, -1 on error.
*/
static int ai_start(const char *question, const char *target, const char *nick, long long *out_id) {
const char *sql = "INSERT INTO ai_pending(question,answer,target,nick,status)"
" VALUES(?,?,?,?,'pending')";
void *stmt;
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return -1;
db_bind_text(stmt, 1, question, -1, SQLITE_STATIC);
db_bind_text(stmt, 2, "", -1, SQLITE_STATIC);
db_bind_text(stmt, 3, target, -1, SQLITE_STATIC);
db_bind_text(stmt, 4, nick, -1, SQLITE_STATIC);
int rc = db_step(stmt);
db_finalize(stmt);
if (rc == SQLITE_DONE) {
*out_id = db_last_rowid(db_handle);
return 0;
}
return -1;
}
/*
* ai_get_question - Retrieve the question text for a pending AI query.
*
* Queries ai_pending by row ID and returns the stored question string.
* Used by the child process to know what to ask opencode.
*
* Parameters:
* id - The row ID returned by ai_start().
*
* Returns: A newly allocated string with the question, or NULL on error.
* Caller must free() the result.
*/
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;
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;
db_finalize(stmt);
return r;
}
/*
* ai_set_answer - Store the AI response and mark the query as done.
*
* Updates the ai_pending row with the given ID, setting the answer text
* and changing status from 'pending' to 'done'. Called by the child process
* after opencode produces output (or an error message).
*
* Parameters:
* id - The row ID returned by ai_start().
* answer - The AI response text to store.
*
* Returns: 0 on success, -1 on error.
*/
static int ai_set_answer(long long id, const char *answer) {
const char *sql = "UPDATE ai_pending SET answer=?, status='done' WHERE id=?";
void *stmt;
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return -1;
db_bind_text(stmt, 1, answer, -1, SQLITE_STATIC);
db_bind_int64(stmt, 2, id);
int rc = db_step(stmt);
db_finalize(stmt);
return rc == SQLITE_DONE ? 0 : -1;
}
/*
* ai_get_answer - Retrieve the completed AI answer and its target.
*
* Queries ai_pending for a row with status='done' matching the given ID.
* Returns the answer text and the target channel/nick concatenated with
* a \x1f (unit separator) delimiter. The caller splits on this character
* to extract the answer and delivery target separately.
*
* Parameters:
* id - The row ID of the completed query.
*
* Returns: A newly allocated string "answer\x1ftarget", or NULL if the
* query is not yet done or not found. Caller must free() the result.
*/
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;
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);
char *r = NULL;
if (a && t) { if (asprintf(&r, "%s\037%s", a, t) < 0) r = NULL; }
db_finalize(stmt);
return r;
}
/*
* ai_get_nick - Retrieve the requesting user's nick for a pending AI query.
*
* Queries the ai_pending table for the nick associated with the given ID.
* Used for logging when the AI child process completes.
*
* Parameters:
* id - The row ID returned by ai_start().
*
* Returns: A newly allocated string with the nick, or NULL on error.
* Caller must free() the result.
*/
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;
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;
db_finalize(stmt);
return r;
}
/*
* ai_reset - Delete a completed or stale AI query record from the database.
*
* Removes the ai_pending row matching the given ID. Called after the answer
* has been delivered to IRC, or after a timeout/failure to clean up.
*
* Parameters:
* id - The row ID of the query to remove.
*
* Returns: void.
*/
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;
db_bind_int64(stmt, 1, id);
db_step(stmt);
db_finalize(stmt);
}
/* ---- channel op tracking ---- */
typedef struct { char name[64]; char ops[MAX_CHAN_OPS][32]; int nops; } ChanEntry;
static ChanEntry chans[MAX_CHANS];
static int nchans;
/*
* chan_get - Look up a channel entry by name.
*
* Searches the global chans[] array for a channel matching the given name
* (case-insensitive comparison). Used by all other chan_* functions to
* locate the channel record before modifying it.
*
* Parameters:
* name - The channel name (e.g. "#zynk") to look up.
*
* Returns: Pointer to the ChanEntry if found, NULL otherwise.
*/
static ChanEntry *chan_get(const char *name) {
for (int i = 0; i < nchans; i++)
if (strcasecmp(chans[i].name, name) == 0) return &chans[i];
return NULL;
}
/*
* chan_get_or_add - Look up a channel entry, creating it if it doesn't exist.
*
* First tries chan_get(). If not found and there is room in the chans[] array
* (up to MAX_CHANS), allocates a new entry with the given name and an empty
* ops list. Automatically called when a JOIN message or NAMREPLY is received.
*
* Parameters:
* name - The channel name to find or register.
*
* Returns: Pointer to the ChanEntry (existing or newly created), or NULL if
* the channel array is full.
*/
static ChanEntry *chan_get_or_add(const char *name) {
ChanEntry *c = chan_get(name);
if (!c && nchans < MAX_CHANS) {
c = &chans[nchans++];
snprintf(c->name, sizeof c->name, "%s", name);
c->nops = 0;
}
return c;
}
/*
* chan_is_op - Check whether a nick has operator status in a channel.
*
* Looks up the channel and searches its ops list for the given nick
* (case-insensitive). Used to gate privileged commands like !code,
* !reload, !restart, and zynk! overwrite.
*
* Parameters:
* name - The channel name.
* nick - The IRC nick to check.
*
* Returns: 1 if the nick is a channel op, 0 otherwise.
*/
static int chan_is_op(const char *name, const char *nick) {
ChanEntry *c = chan_get(name);
if (!c) return 0;
for (int i = 0; i < c->nops; i++)
if (strcasecmp(c->ops[i], nick) == 0) return 1;
return 0;
}
/*
* chan_add_op - Add a nick to the operator list for a channel.
*
* Gets or creates the channel entry, then checks for duplicates before
* appending the nick to the ops array. Called when a NAMREPLY shows the
* nick with @, ~, or & prefix, or when a MODE +o is received.
*
* Parameters:
* name - The channel name.
* nick - The IRC nick to add as op.
*
* Returns: void. Silently ignores duplicates and full ops arrays.
*/
static void chan_add_op(const char *name, const char *nick) {
ChanEntry *c = chan_get_or_add(name);
if (!c) return;
for (int i = 0; i < c->nops; i++)
if (strcasecmp(c->ops[i], nick) == 0) return;
if (c->nops < MAX_CHAN_OPS) {
snprintf(c->ops[c->nops], sizeof c->ops[0], "%s", nick);
c->nops++;
}
}
/*
* chan_del_op - Remove a nick from the operator list for a channel.
*
* Searches the channel's ops list for the nick (case-insensitive) and
* removes it by shifting subsequent entries down with memmove. Called on
* MODE -o, PART, KICK, and QUIT messages to keep the ops list current.
*
* Parameters:
* name - The channel name.
* nick - The IRC nick to remove from ops.
*
* Returns: void. Silently ignores if the nick is not found.
*/
static void chan_del_op(const char *name, const char *nick) {
ChanEntry *c = chan_get(name);
if (!c) return;
for (int i = 0; i < c->nops; i++) {
if (strcasecmp(c->ops[i], nick) == 0) {
memmove(c->ops + i, c->ops + i + 1, (c->nops - i - 1) * sizeof c->ops[0]);
c->nops--;
return;
}
}
}
/*
* chan_rename_op - Rename a nick across all channel operator lists.
*
* Iterates all channels and replaces oldnick with newnick in every ops
* array where a match is found. Called when a NICK change message is
* received so that op tracking stays consistent across renames.
*
* Parameters:
* oldnick - The previous IRC nick.
* newnick - The new IRC nick to substitute.
*
* Returns: void.
*/
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 ---- */
/*
* net_connect - Establish a TCP connection to a remote host.
*
* Performs DNS resolution via getaddrinfo() with AI_ADDRCONFIG (restricts
* to address families available on the local system), then iterates through
* resolved addresses trying socket()+connect() on each. The socket is
* non-blocking by default since this function doesn't set O_NONBLOCK.
*
* Parameters:
* host - The hostname or IP address to connect to.
* port - The TCP port number.
*
* Returns: A connected file descriptor on success, or -1 on failure.
*/
static int net_connect(const char *host, int port) {
struct addrinfo hints, *ai;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_ADDRCONFIG;
char pbuf[16];
snprintf(pbuf, sizeof pbuf, "%d", port);
int err = getaddrinfo(host, pbuf, &hints, &ai);
if (err) { fprintf(stderr, CLR_RED "DNS:" CLR_RESET " %s\n", gai_strerror(err)); return -1; }
int fd = -1;
for (struct addrinfo *rp = ai; rp; rp = rp->ai_next) {
fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (fd < 0) continue;
if (connect(fd, rp->ai_addr, rp->ai_addrlen) == 0) break;
close(fd); fd = -1;
}
freeaddrinfo(ai);
return fd;
}
/*
* net_read - Read data from the session's socket (TLS-aware).
*
* If the session has an active SSL connection, reads via SSL_read();
* otherwise uses plain read(). Translates SSL_ERROR_WANT_READ/WANT_WRITE
* into errno=EAGAIN for consistent non-blocking behavior. Returns 0 on
* clean TLS shutdown (SSL_ERROR_ZERO_RETURN).
*
* Parameters:
* s - The IRC session with fd and optional SSL context.
* buf - Destination buffer for the read data.
* size - Maximum number of bytes to read.
*
* Returns: Number of bytes read, 0 on EOF/shutdown, -1 on error (check
* errno for EAGAIN to distinguish transient from fatal errors).
*/
static int net_read(Session *s, char *buf, int size) {
if (s->ssl) {
int r = SSL_read(s->ssl, buf, size);
if (r > 0) return r;
int e = SSL_get_error(s->ssl, r);
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE) { errno = EAGAIN; return -1; }
if (e == SSL_ERROR_ZERO_RETURN) return 0;
errno = EIO;
return -1;
}
return read(s->fd, buf, size);
}
/*
* net_write - Write data to the session's socket (TLS-aware).
*
* If the session has an active SSL connection, writes via SSL_write();
* otherwise uses plain write(). Translates SSL_ERROR_WANT_READ/WANT_WRITE
* into errno=EAGAIN for consistent non-blocking behavior.
*
* Parameters:
* s - The IRC session with fd and optional SSL context.
* buf - Source buffer containing data to send.
* size - Number of bytes to write.
*
* Returns: Number of bytes written on success, -1 on error.
*/
static int net_write(Session *s, const char *buf, int size) {
if (s->ssl) {
int r = SSL_write(s->ssl, buf, size);
if (r > 0) return r;
int e = SSL_get_error(s->ssl, r);
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE) { errno = EAGAIN; return -1; }
return -1;
}
return write(s->fd, buf, size);
}
/*
* net_send - Format and send an IRC protocol message with retry logic.
*
* Uses vsnprintf to format the message into a 4096-byte stack buffer, then
* writes it via net_write() in a loop to handle partial writes. Retries on
* EINTR (signal interruption) and EAGAIN (would-block). The caller should
* include "\r\n" in the format string per IRC protocol requirements.
*
* Parameters:
* s - The IRC session.
* fmt - printf-style format string for the message.
* ... - Format arguments.
*
* Returns: Number of bytes sent on success, 0 if nothing to send,
* -1 on truncation or write failure.
*/
static int net_send(Session *s, const char *fmt, ...) {
char buf[4096];
va_list ap;
va_start(ap, 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) {
int w = net_write(s, p, left);
if (w < 0) {
if (errno == EINTR || errno == EAGAIN) continue;
return -1;
}
if (w == 0) return -1;
left -= w; p += w;
}
return n;
}
/* ---- TLS ---- */
static SSL_CTX *tls_ctx;
static int tls_verify = 1;
/*
* tls_init - Initialize the OpenSSL library and create a TLS context.
*
* Calls SSL_library_init() and SSL_load_error_strings() for OpenSSL setup,
* creates a new SSL_CTX using the TLS client method, loads default CA
* certificates for peer verification, and configures the verify mode
* based on the global tls_verify flag.
*
* Returns: 0 on success, -1 if context creation fails.
*/
static int tls_init(void) {
SSL_library_init();
SSL_load_error_strings();
tls_ctx = SSL_CTX_new(TLS_client_method());
if (!tls_ctx) return -1;
SSL_CTX_set_default_verify_paths(tls_ctx);
SSL_CTX_set_verify(tls_ctx, tls_verify ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
return 0;
}
/*
* tls_handshake - Perform a TLS handshake on an established TCP connection.
*
* Creates a new SSL object, associates it with the session's file descriptor
* and hostname (for SNI), then performs the handshake. Temporarily disables
* O_NONBLOCK on the fd since SSL_connect needs blocking I/O, then restores
* the original flags. If tls_verify is enabled, validates the server's
* certificate against the system CA store.
*
* Parameters:
* s - The IRC session with a valid fd and host.
*
* Returns: 0 on successful handshake, -1 on failure (SSL object is freed).
*/
static int tls_handshake(Session *s) {
if (!tls_ctx) return -1;
s->ssl = SSL_new(tls_ctx);
if (!s->ssl) return -1;
SSL_set_fd(s->ssl, s->fd);
SSL_set_tlsext_host_name(s->ssl, s->host);
if (tls_verify) SSL_set1_host(s->ssl, s->host);
int fl = fcntl(s->fd, F_GETFL, 0);
fcntl(s->fd, F_SETFL, fl & ~O_NONBLOCK);
int r = SSL_connect(s->ssl);
fcntl(s->fd, F_SETFL, fl | O_NONBLOCK);
if (r != 1) { SSL_free(s->ssl); s->ssl = NULL; return -1; }
if (tls_verify && SSL_get_verify_result(s->ssl) != X509_V_OK) {
SSL_free(s->ssl); s->ssl = NULL; return -1;
}
return 0;
}
/*
* tls_cleanup - Shut down and free the SSL connection for a session.
*
* Performs SSL_shutdown() to send the TLS close_notify alert (if the
* connection is still active), then frees the SSL object. Safe to call
* when s->ssl is NULL (no-op).
*
* Parameters:
* s - The IRC session whose SSL connection to tear down.
*
* Returns: void.
*/
static void tls_cleanup(Session *s) {
if (!s->ssl) return;
SSL_shutdown(s->ssl);
SSL_free(s->ssl);
s->ssl = NULL;
}
/*
* tls_ctx_cleanup - Free the global TLS context.
*
* Calls SSL_CTX_free() on the global tls_ctx and sets it to NULL.
* Should be called during shutdown after all sessions are cleaned up.
*
* Returns: void.
*/
static void tls_ctx_cleanup(void) {
if (tls_ctx) {
SSL_CTX_free(tls_ctx);
tls_ctx = NULL;
}
}
/* ---- hot reload ---- */
#define ZYNK_RELOAD_FILE "/tmp/zynk_reload"
/*
* reload_read_line - Read a single line from a file, stripping newlines.
*
* Helper for parsing the reload state file. Reads up to sz-1 bytes from
* the file handle, then strips trailing \n and \r characters.
*
* Parameters:
* f - The FILE handle to read from.
* buf - Destination buffer.
* sz - Size of the destination buffer.
*
* Returns: 0 on success, -1 on read failure or EOF.
*/
static int reload_read_line(FILE *f, char *buf, size_t sz) {
if (!fgets(buf, sz, f)) return -1;
size_t len = strlen(buf);
while (len > 0 && (buf[len-1] == '\n' || buf[len-1] == '\r')) buf[--len] = 0;
return 0;
}
/*
* reload_save - Save the current TLS session state to disk for hot reload.
*
* Serializes the SSL session (via i2d_SSL_SESSION) and all connection
* parameters (host, port, nick, user, real, pass, auto_join, tls settings)
* into the /tmp/zynk_reload file. The session data is hex-encoded. This
* allows the new process to resume the TLS connection without re-handshaking,
* avoiding a visible disconnect in the IRC channel.
*
* Parameters:
* s - The current IRC session to serialize.
*
* Returns: 0 on success, -1 on any failure.
*/
static int reload_save(Session *s) {
if (!s->ssl || s->fd < 0) return -1;
SSL_SESSION *sess = SSL_get1_session(s->ssl);
if (!sess) return -1;
int slen = i2d_SSL_SESSION(sess, NULL);
if (slen <= 0) { SSL_SESSION_free(sess); return -1; }
unsigned char *sbuf = malloc(slen);
if (!sbuf) { SSL_SESSION_free(sess); return -1; }
unsigned char *p = sbuf;
i2d_SSL_SESSION(sess, &p);
SSL_SESSION_free(sess);
FILE *f = fopen(ZYNK_RELOAD_FILE, "w");
if (!f) { free(sbuf); return -1; }
fprintf(f, "%d\n%s\n%d\n%s\n%s\n%s\n%s\n%s\n%d\n%d\n",
slen, s->host, s->port, s->nick, s->user, s->real,
s->pass, s->auto_join, s->use_tls, tls_verify);
for (int i = 0; i < slen; i++) fprintf(f, "%02x", sbuf[i]);
fprintf(f, "\n");
fclose(f);
free(sbuf);
return 0;
}
/*
* reload_try_restore - Restore previously saved connection settings from disk.
*
* Reads the /tmp/zynk_reload file, restores all connection parameters, and
* checks whether the restart was triggered by a code change. The caller then
* establishes a fresh IRC and TLS connection.
*
* Parameters:
* s - The IRC session to populate with restored state.
*
* Returns: 1 when settings were restored, -1 if no reload file or on error.
*/
static int reload_try_restore(Session *s) {
FILE *f = fopen(ZYNK_RELOAD_FILE, "r");
if (!f) return -1;
char line[1024];
int slen = 0, port = 0, use_tls_f = 0, tls_verify_f = 0;
char host[256] = "", nick[32] = "", user[32] = "", real[256] = "";
char pass[256] = "", auto_join[256] = "";
if (reload_read_line(f, line, sizeof line) < 0 || (slen = atoi(line)) <= 0 || slen > 65536) goto fail;
if (reload_read_line(f, host, sizeof host) < 0 || !host[0]) goto fail;
if (reload_read_line(f, line, sizeof line) < 0) goto fail;
port = atoi(line);
if (reload_read_line(f, nick, sizeof nick) < 0 || !nick[0]) goto fail;
if (reload_read_line(f, user, sizeof user) < 0 || !user[0]) goto fail;
if (reload_read_line(f, real, sizeof real) < 0) goto fail;
if (reload_read_line(f, pass, sizeof pass) < 0) goto fail;
if (reload_read_line(f, auto_join, sizeof auto_join) < 0) goto fail;
if (reload_read_line(f, line, sizeof line) < 0) goto fail;
use_tls_f = atoi(line);
if (reload_read_line(f, line, sizeof line) < 0) goto fail;
tls_verify_f = atoi(line);
unsigned char *sbuf = malloc(slen);
if (!sbuf) goto fail;
for (int i = 0; i < slen; i++) {
unsigned int byte;
if (fscanf(f, "%02x", &byte) != 1) { free(sbuf); goto fail; }
sbuf[i] = (unsigned char)byte;
}
fclose(f);
unlink(ZYNK_RELOAD_FILE);
snprintf(s->host, sizeof s->host, "%s", host);
s->port = port;
snprintf(s->nick, sizeof s->nick, "%s", nick);
snprintf(s->user, sizeof s->user, "%s", user);
snprintf(s->real, sizeof s->real, "%s", real);
if (pass[0]) snprintf(s->pass, sizeof s->pass, "%s", pass);
snprintf(s->auto_join, sizeof s->auto_join, "%s", auto_join);
s->use_tls = use_tls_f;
tls_verify = tls_verify_f;
free(sbuf);
FILE *cf = fopen("/tmp/zynk_code_restart", "r");
if (cf) {
fclose(cf);
unlink("/tmp/zynk_code_restart");
s->code_restart = 1;
}
log_stamp(); fprintf(stderr, CLR_GREEN "Restart state restored for %s:%d" CLR_RESET "\n", s->host, s->port);
return 1;
fail:
fclose(f);
return -1;
}
/*
* irc_part_all - Send IRC PART messages to all joined channels.
*
* Iterates the global chans[] array and sends a PART command for each
* non-empty channel name. Used during hot reload so the bot cleanly
* leaves channels before exec'ing a new instance.
*
* Parameters:
* s - The IRC session.
*
* Returns: void.
*/
static void irc_part_all(Session *s) {
for (int i = 0; i < nchans; i++) {
if (chans[i].name[0])
net_send(s, "PART %s\r\n", chans[i].name);
}
}
/*
* reload_do - Execute a hot reload: save state, part channels, fork+exec.
*
* Orchestrates the full hot reload sequence: saves TLS session state via
* reload_save(), waits briefly, parts all channels, sends QUIT, then
* fork()s and exec's the same binary. The child inherits the socket fd
* via ZYNK_RESTORE_FD environment variable and the parent exits. Requires
* an active TLS connection to preserve the session across the restart.
*
* Parameters:
* s - The IRC session.
* reply_target - Channel or nick to send status messages to.
*
* Returns: void (parent exits, child continues as new instance).
*/
static void reload_do(Session *s, const char *reply_target) {
if (!s->ssl || s->fd < 0) {
irc_msg(s, reply_target, "Cannot reload: not connected with TLS");
return;
}
if (reload_save(s) < 0) {
irc_msg(s, reply_target, "Failed to save session state");
return;
}
irc_msg(s, reply_target, "Reloading...");
struct timespec ts_short = { .tv_sec = 0, .tv_nsec = 100000000 };
nanosleep(&ts_short, NULL);
irc_part_all(s);
int old_fl = fcntl(s->fd, F_GETFL, 0);
fcntl(s->fd, F_SETFL, old_fl & ~O_NONBLOCK);
net_send(s, "QUIT :restarting\r\n");
struct timespec ts_quit = { .tv_sec = 0, .tv_nsec = 500000000 };
nanosleep(&ts_quit, NULL);
pid_t pid = fork();
if (pid < 0) {
unlink(ZYNK_RELOAD_FILE);
irc_msg(s, reply_target, "Fork failed, continuing");
return;
}
if (pid == 0) {
close(s->fd);
char self[4096];
ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
if (n > 0) {
self[n] = 0;
char *deleted = strstr(self, " (deleted)");
if (deleted) *deleted = 0;
execl(self, "zynk", NULL);
}
_exit(1);
}
_exit(0);
}
/* ---- signal handling ---- */
static volatile sig_atomic_t running = 1;
static time_t start_time;
/*
* handle_sigterm - Signal handler for SIGINT and SIGTERM.
*
* Sets the global running flag to 0, which causes the main poll loop to
* exit gracefully. Uses sig_atomic_t for async-signal-safety.
*
* Parameters:
* sig - The signal number (unused).
*
* Returns: void.
*/
static void handle_sigterm(int sig) { (void)sig; running = 0; }
/* ---- rate limiting ---- */
static struct { char nick[32]; time_t t; } rate_limits[RATE_LIMIT_MAX];
/*
* rate_limit_check - Enforce per-nick rate limiting on IRC commands.
*
* Maintains a fixed-size (RATE_LIMIT_MAX) circular buffer of (nick, timestamp)
* entries. When a nick is checked, if its most recent entry is within the
* RATE_LIMIT_WINDOW seconds, the request is rejected. Otherwise the nick's
* entry is updated (or the oldest slot is evicted). This prevents any single
* user from flooding the bot with commands.
*
* Parameters:
* nick - The IRC nick to check.
*
* Returns: 0 if the command is allowed, -1 if rate-limited.
*/
static int rate_limit_check(const char *nick) {
time_t now = time(NULL);
int slot = -1, oldest = 0;
for (int i = 0; i < RATE_LIMIT_MAX; i++) {
if (rate_limits[i].t == 0) { slot = i; break; }
if (rate_limits[i].t < rate_limits[oldest].t) oldest = i;
if (strcmp(rate_limits[i].nick, nick) == 0) {
if (now - rate_limits[i].t < RATE_LIMIT_WINDOW) return -1;
slot = i; break;
}
}
if (slot < 0) slot = oldest;
strncpy(rate_limits[slot].nick, nick, sizeof rate_limits[slot].nick - 1);
rate_limits[slot].nick[sizeof rate_limits[slot].nick - 1] = 0;
rate_limits[slot].t = now;
return 0;
}
/* ---- text utilities ---- */
/*
* strip_ai_phrases - Remove common AI disclaimer phrases from text.
*
* Scans the input string and removes occurrences of phrases like "as an AI",
* "I'm a large language model", "I don't have personal opinions", etc.
* Matching is case-insensitive. Also strips trailing punctuation and spaces
* left after phrase removal. Used to clean up opencode output before sending
* it to IRC, making responses more natural.
*
* Parameters:
* s - The string to clean in-place. Must be writable.
*
* Returns: void. The string is modified in-place.
*/
static void strip_ai_phrases(char *s) {
static const char *phrases[] = {
"as an ai", "as an ai language model", "as an ai assistant",
"i'm an ai", "i am an ai", "i'm just an ai", "i am just an ai",
"as a large language model", "as an llm",
"i'm an ai assistant", "i am an ai assistant",
"i don't have personal", "i do not have personal",
"i don't have emotions", "i do not have emotions",
"i'm a large language model", "i am a large language model",
"i'm an llm", "i am an llm",
};
char buf[6144];
size_t len = strlen(s);
if (len >= sizeof buf) return;
memcpy(buf, s, len + 1);
char *dst = s;
for (char *src = buf; *src; ) {
int skipped = 0;
for (size_t i = 0; i < sizeof phrases / sizeof phrases[0]; i++) {
size_t plen = strlen(phrases[i]);
if (strncasecmp(src, phrases[i], plen) == 0) {
src += plen;
while (*src == ' ' || *src == ',' || *src == '.' || *src == '!' || *src == '?') src++;
skipped = 1;
break;
}
}
if (!skipped) *dst++ = *src++;
}
*dst = 0;
}
/*
* strip_formatting - Strip markdown, ANSI escape codes, and IRC formatting.
*
* Removes: ANSI escape sequences, IRC mIRC color codes (\x03), bold/italic/
* underline/reverse/control characters, markdown code blocks (triple backticks
* kept as content), inline code backticks, bold (**), italic (*), and
* markdown links [text](url) -> text. Collapses excessive newlines (max 2
* consecutive) and double spaces. Processes in-place via a two-pointer
* approach for efficiency.
*
* Parameters:
* s - The string to strip in-place. Must be writable.
*
* Returns: void. The string is modified in-place.
*/
static void strip_formatting(char *s) {
char *r = s, *start = s;
int in_code_block = 0;
while (*s) {
if (*s == '\x1b') {
s++;
while (*s && (*s == '[' || (*s >= '0' && *s <= '?'))) s++;
if (*s && *s != 'm') while (*s && *s != 'm' && *s != '\x1b') s++;
if (*s == 'm') s++;
continue;
}
if (*s == '\x02' || *s == '\x0f' || *s == '\x16' || *s == '\x1d' || *s == '\x1f') { s++; continue; }
if (*s == '\x03') {
s++;
if (*s >= '0' && *s <= '9') { s++; if (*s >= '0' && *s <= '9') s++; }
if (*s == ',') { s++; if (*s >= '0' && *s <= '9') { s++; if (*s >= '0' && *s <= '9') s++; } }
continue;
}
if (s[0] == '`' && s[1] == '`' && s[2] == '`') {
in_code_block = !in_code_block;
s += 3;
if (*s == '\n') s++;
continue;
}
if (in_code_block) { *r++ = *s++; continue; }
if (*s == '`') { s++; continue; }
if (s[0] == '*' && s[1] == '*') {
s += 2;
while (*s && !(s[0] == '*' && s[1] == '*')) s++;
if (*s) s += 2;
continue;
}
if (*s == '*' && s[1] && s[1] != '*') {
s++;
while (*s && *s != '*') s++;
if (*s == '*') s++;
continue;
}
if (*s == '[') {
char *rb = strchr(s, ']');
if (rb && *(rb+1) == '(') {
char *lp = strchr(rb+2, ')');
if (lp) { s++; while (s < rb) *r++ = *s++; s = lp + 1; continue; }
}
}
*r++ = *s++;
}
*r = 0;
char *src = start, *dst = start;
int nlc = 0;
while (*src) {
if (*src == '\n') { nlc++; if (nlc > 2) { src++; continue; } }
else nlc = 0;
*dst++ = *src++;
}
*dst = 0;
src = start; dst = start;
while (*src) {
if (*src == ' ' && *(src+1) == ' ') { src++; continue; }
*dst++ = *src++;
}
*dst = 0;
}
/*
* has_crlf - Check if a string contains CR or LF characters.
*
* Used as a security check to prevent IRC protocol injection via
* embedded newlines in user-provided data.
*
* Parameters:
* s - The string to check (may be NULL).
*
* Returns: 1 if \r or \n is found, 0 if not found or s is NULL.
*/
static int has_crlf(const char *s) {
return s && strpbrk(s, "\r\n") != NULL;
}
/*
* has_ctl - Check if a string contains ASCII control characters.
*
* Scans for bytes below 0x20 (excluding common whitespace) or 0x7f (DEL).
* Used to validate IRC inputs and reject strings with embedded control
* codes that could disrupt the protocol.
*
* Parameters:
* s - The string to check (may be NULL).
*
* Returns: 1 if a control character is found, 0 otherwise.
*/
static int has_ctl(const char *s) {
if (!s) return 0;
for (const unsigned char *p = (const unsigned char*)s; *p; p++)
if (*p < 0x20 || *p == 0x7f) return 1;
return 0;
}
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 ---- */
/*
* run_curl - Execute curl to fetch a URL and capture stdout.
*
* Forks a child process that exec's curl with a 10-second timeout,
* suppresses stderr to /dev/null, and uses a fake Firefox User-Agent.
* The parent reads up to 32KB of output from the pipe, then waits for
* the child to exit. Used as a lightweight HTTP client without linking
* libcurl.
*
* Parameters:
* url - The URL to fetch.
*
* Returns: A newly allocated string with the response body on success,
* or NULL on failure. Caller must free() the result.
*/
static char *run_curl(const char *url) {
int fd[2];
if (pipe(fd) < 0) return NULL;
pid_t pid = fork();
if (pid < 0) { close(fd[0]); close(fd[1]); return NULL; }
if (pid == 0) {
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
close(fd[1]);
int dn = open("/dev/null", O_WRONLY);
if (dn >= 0) { dup2(dn, STDERR_FILENO); close(dn); }
execlp("curl", "curl", "-s", "--max-time", "10", "-A", "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", url, (char *)NULL);
_exit(127);
}
close(fd[1]);
char buf[32768], tmp[4096];
size_t len = 0;
ssize_t 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);
buf[len] = 0;
return status == 0 ? strdup(buf) : NULL;
}
/*
* fetch_url - Fetch content from a URL via curl.
*
* Thin wrapper around run_curl() for semantic clarity. Used by weather,
* forecast, and stock commands to fetch data from external APIs.
*
* Parameters:
* url - The URL to fetch.
*
* Returns: A newly allocated string with the response body, or NULL on
* failure. Caller must free() the result.
*/
static char *fetch_url(const char *url) { return run_curl(url); }
/*
* fetch_forecast - Fetch and parse a 3-day weather forecast from wttr.in.
*
* Fetches the JSON forecast (format=j1) from wttr.in for the given city,
* then manually parses the "weather" array to extract date, average
* temperature, and weather condition for up to 3 days. Dates are formatted
* as "Mon DD Mon" (e.g. "Mon 19 Jul"). Returns a single-line summary
* string like "Forecast for Berlin: Mon 19 Jul: 22°C Partly cloudy / ...".
*
* Parameters:
* city_url - URL-encoded city name for the API request.
* city_display - Human-readable city name for the response.
*
* Returns: A newly allocated forecast string, or NULL/ error message on
* failure. Caller must free() the result.
*/
static char *fetch_forecast(const char *city_url, const char *city_display) {
char url[512];
snprintf(url, sizeof url, "https://wttr.in/%s?format=j1", city_url);
char *json = fetch_url(url);
if (!json) return NULL;
char *p = strstr(json, "\"weather\"");
if (!p) {
char *err = NULL;
size_t jlen = strlen(json);
if (jlen > 400) jlen = 400;
asprintf(&err, "Forecast parse error (response: %.*s)", (int)jlen, json);
free(json);
return err;
}
p = strchr(p, '[');
if (!p) { free(json); return NULL; }
p++;
char line[3][256], fmt_date[3][32];
int ndays = 0;
for (int i = 0; i < 3; i++) {
p = strchr(p, '{');
if (!p) break;
const char *obj_end = p + 1;
int depth = 1;
while (*obj_end && depth > 0) { if (*obj_end == '{') depth++; else if (*obj_end == '}') depth--; obj_end++; }
char date[16]="", temp[8]="", cond[64]="";
char *db = strstr(p, "\"date\": \"");
if (db && db < obj_end) { db += 9; char *dq = strchr(db, '"'); if (dq && dq < obj_end) { size_t l = dq - db; if (l>15) l=15; memcpy(date,db,l); date[l]=0; } }
char *tb = strstr(p, "\"avgtempC\": \"");
if (tb && tb < obj_end) { tb += 13; char *tq = strchr(tb, '"'); if (tq && tq < obj_end) { size_t l = tq - tb; if (l>7) l=7; memcpy(temp,tb,l); temp[l]=0; } }
char *hb = strstr(p, "\"hourly\"");
if (hb && hb < obj_end) {
hb = strchr(hb, '[');
if (hb && hb < obj_end) {
hb++;
char *vb = strstr(hb, "\"value\": \"");
if (vb && vb < obj_end) { vb += 9; char *vq = strchr(vb, '"'); if (vq && vq < obj_end) { size_t l = vq - vb; if (l>63) l=63; memcpy(cond,vb,l); cond[l]=0; } }
}
}
struct tm tm = {0};
if (strptime(date, "%Y-%m-%d", &tm)) strftime(fmt_date[ndays], sizeof fmt_date[ndays], "%a %d %b", &tm);
else snprintf(fmt_date[ndays], sizeof fmt_date[ndays], "%s", date);
snprintf(line[ndays], sizeof line[ndays], "%s: %s\u00b0C %s", fmt_date[ndays], temp, cond);
ndays++;
p = (char*)obj_end;
}
free(json);
if (!ndays) return NULL;
char *out = NULL;
if (ndays == 1) { if (asprintf(&out, "Forecast for %s: %s", city_display, line[0]) < 0) out = NULL; }
else if (ndays == 2) { if (asprintf(&out, "Forecast for %s: %s / %s", city_display, line[0], line[1]) < 0) out = NULL; }
else { if (asprintf(&out, "Forecast for %s: %s / %s / %s", city_display, line[0], line[1], line[2]) < 0) out = NULL; }
return out;
}
/* ---- AI pipeline ---- */
static volatile pid_t pending_ai_pid;
static volatile long long pending_ai_id;
static const char *g_opencode_bin = OPENCODE_BIN;
/*
* ai_child_task - Child process entry point for running an AI query.
*
* Runs in a forked child process. Sets an alarm timeout (AI_TIMEOUT seconds),
* closes the parent's socket fd (but doesn't TLS-shutdown to avoid breaking
* the parent's connection), opens its own DB handle, retrieves the question
* and recent answer history, builds a prompt prefix with system instructions
* (different for "build" agent vs. "plan" agent), then fork+exec's opencode
* with the combined prompt. Reads up to 6KB of output, strips formatting
* and AI phrases, stores the result in the database, and exits. The parent
* polls for completion and delivers the answer to IRC.
*
* Parameters:
* s - The IRC session (only fd is used; ssl is intentionally not touched).
* id - The ai_pending row ID for this query.
* agent - The opencode agent name ("build" for code changes, NULL for plan mode).
*
* Returns: Does not return (calls exit(0) or exit(1)).
*/
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
* the shared fd, breaking the parent's connection. Just release our
* fd reference; the kernel will close it on exit. */
if (s->fd >= 0) close(s->fd);
s->fd = -1;
s->ssl = NULL;
db_close(DB);
db_handle = NULL;
if (db_open("zynk.db", &db_handle) != SQLITE_OK) exit(1);
char *q = ai_get_question(id);
if (!q) { db_close(DB); exit(1); }
char *history[MAX_HISTORY];
char hkey[MAX_HISTORY][12];
for (int i = 0; i < MAX_HISTORY; i++) {
snprintf(hkey[i], sizeof hkey[i], "lasta%02d", i + 1);
history[i] = db_get_raw(hkey[i]);
}
int have_history = 0;
for (int i = 0; i < MAX_HISTORY; i++) { if (history[i]) { have_history = 1; break; } }
char prefix[2048];
int plen;
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. "
"Max 2000 chars. No disclaimers or AI-sounding phrases. No markdown/formatting. "
"Just make the changes directly and confirm what you did.");
} else {
plen = snprintf(prefix, sizeof prefix,
"Your name is zynk. You are in plan mode - you can only answer questions and discuss code, "
"but you CANNOT make any changes to files or execute commands. If someone asks you to change or edit code, "
"tell them you are in plan mode and can only answer questions. Suggest they use !code <instruction> to make actual code changes. "
"Answer briefly. Answer in English when asked in English, answer in German when asked in German. Max 800 chars. "
"No disclaimers or AI-sounding phrases. No markdown/formatting. "
"Just answer directly.");
}
if (have_history) {
int space = (int)sizeof prefix - plen;
if (space > 0)
plen += snprintf(prefix + plen, space,
" My recent answers for context (only use if absolutely necessary): ");
if (plen >= (int)sizeof prefix) plen = (int)sizeof prefix - 1;
for (int i = 0; i < MAX_HISTORY; i++) {
space = (int)sizeof prefix - plen;
if (space <= 0) break;
if (history[i]) {
plen += snprintf(prefix + plen, space, "[%s] ", history[i]);
if (plen >= (int)sizeof prefix) plen = (int)sizeof prefix - 1;
}
}
}
for (int i = 0; i < MAX_HISTORY; i++) free(history[i]);
char combined[8192];
snprintf(combined, sizeof combined, "%s%s", prefix, q ? q : "");
free(q);
int ai_pipe[2];
if (pipe(ai_pipe) < 0) { ai_set_answer(id, "AI query failed (pipe error)"); db_close(DB); exit(0); }
pid_t cmd_pid = fork();
if (cmd_pid < 0) { close(ai_pipe[0]); close(ai_pipe[1]); ai_set_answer(id, "AI query failed (fork error)"); db_close(DB); exit(0); }
if (cmd_pid == 0) {
close(ai_pipe[0]);
dup2(ai_pipe[1], STDOUT_FILENO);
close(ai_pipe[1]);
int dn = open("/dev/null", O_WRONLY);
if (dn >= 0) { dup2(dn, STDERR_FILENO); close(dn); }
if (agent)
execl(g_opencode_bin, "opencode", "run", "--dangerously-skip-permissions", "--agent", agent, combined, (char *)NULL);
else
execl(g_opencode_bin, "opencode", "run", "--dangerously-skip-permissions", "--agent", "plan", combined, (char *)NULL);
_exit(127);
}
close(ai_pipe[1]);
char out[6144], tmp[1024];
size_t olen = 0;
ssize_t 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);
while (olen > 0 && (out[olen-1] == '\n' || out[olen-1] == '\r')) olen--;
out[olen] = 0;
int rc = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
if (rc != 0) {
ai_set_answer(id, "AI query failed (opencode exited with error)");
} else if (olen == 0) {
ai_set_answer(id, "AI returned an empty response");
} else {
strip_formatting(out);
strip_ai_phrases(out);
ai_set_answer(id, out);
db_update_lasta(out);
}
db_close(DB);
exit(0);
}
/*
* ai_ask - Queue a new AI query and spawn a child process to handle it.
*
* Rate-limits the requesting nick, checks that no other AI query is
* already in progress (only one concurrent query allowed), records the
* question in the history ring buffer, creates a database record via
* ai_start(), then fork()s a child to run ai_child_task(). Stores the
* child PID and query ID in global variables for polling in the main loop.
* Logs the query to stderr.
*
* Parameters:
* s - The IRC session.
* question - The user's question or instruction.
* reply_target - Channel or nick where the answer should be sent.
* src_nick - The IRC nick of the user who asked.
* agent - The opencode agent ("build" for code, NULL for plan), or
* "plan" passed as string for plan-mode queries.
*
* Returns: void. Sends error messages to IRC on failure.
*/
static void ai_ask(Session *s, const char *question, const char *reply_target, const char *src_nick, const char *agent) {
if (rate_limit_check(src_nick) < 0) return;
if (pending_ai_pid > 0) {
irc_msg(s, reply_target, "Already processing an AI query, please wait.");
return;
}
db_update_lastq(question);
long long id = 0;
if (ai_start(question, reply_target, src_nick, &id) != 0) {
irc_msg(s, reply_target, "Error starting AI query");
return;
}
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, agent); }
pending_ai_pid = pid;
pending_ai_id = id;
log_stamp(); fprintf(stderr, CLR_BLUE "AI started (PID %d, ID %lld) from %s:" CLR_RESET " %s\n", pid, id, src_nick, question);
}
/*
* try_compile_and_restart - Attempt to compile zynk and restart if successful.
*
* Runs "make" (with stderr redirected to /tmp/zynk_make_err). If compilation
* succeeds, notifies the IRC channel and triggers a hot reload via reload_do().
* If compilation fails, reads the first line of the error output and sends it
* to IRC as a notification. Used after code-change AI commands to auto-deploy.
*
* Parameters:
* s - The IRC session.
* target - The channel or nick to send compilation status to.
*
* Returns: 1 if the restart was triggered, 0 if compilation failed.
*/
static int try_compile_and_restart(Session *s, const char *target) {
log_stamp(); fprintf(stderr, CLR_GREEN "Code change detected, compiling..." CLR_RESET "\n");
int status = system("make 2>/tmp/zynk_make_err");
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
irc_msg(s, target, "Code compiled successfully, restarting...");
log_stamp(); fprintf(stderr, CLR_GREEN "Compilation successful, restarting..." CLR_RESET "\n");
FILE *cf = fopen("/tmp/zynk_code_restart", "w");
if (cf) { fprintf(cf, "%s\n", target); fclose(cf); }
reload_do(s, target);
return 1;
} else {
char errbuf[512];
FILE *f = fopen("/tmp/zynk_make_err", "r");
if (f) {
size_t n = fread(errbuf, 1, sizeof errbuf - 1, f);
errbuf[n] = 0;
fclose(f);
char *nl = strchr(errbuf, '\n');
if (nl) *nl = 0;
} else {
snprintf(errbuf, sizeof errbuf, "unknown error");
}
char msg[640];
snprintf(msg, sizeof msg, "Compilation failed: %s", errbuf);
irc_msg(s, target, msg);
log_stamp(); fprintf(stderr, CLR_RED "Compilation failed:" CLR_RESET " %s\n", errbuf);
return 0;
}
}
/*
* ai_check_completion - Poll for completed AI child processes.
*
* Called from the main poll loop on every iteration. Uses waitpid(WNOHANG)
* to check if the pending AI child has exited without blocking. If done,
* retrieves the answer from the database, splits on the \x1f separator to
* extract the delivery target, and sends the answer to IRC in chunks of
* up to AI_CHUNK_MAX characters (word-wrapped). Logs the result. If the
* query was a code change request (!code), triggers try_compile_and_restart()
* after delivering the answer. Handles timeouts (SIGALRM) and other failures
* with appropriate error messages.
*
* Parameters:
* s - The IRC session.
*
* Returns: void.
*/
static void ai_check_completion(Session *s) {
if (pending_ai_pid <= 0) return;
int wstatus;
pid_t done_pid = pending_ai_pid;
long long done_id = pending_ai_id;
if (waitpid(pending_ai_pid, &wstatus, WNOHANG) <= 0) return;
pending_ai_pid = 0;
char *nick = ai_get_nick(done_id);
char *result = ai_get_answer(done_id);
int is_code_change = 0;
char *question = ai_get_question(done_id);
if (question && strncmp(question, "[CODE CHANGE REQUEST", 20) == 0) is_code_change = 1;
free(question);
if (result) {
char *answer = result;
char *sep = strchr(result, '\037');
char *target = NULL;
if (sep) { *sep = 0; target = sep + 1; }
if (target) {
size_t alen = strlen(answer);
#define AI_CHUNK_MAX 450
size_t pos = 0;
int chunks = 0;
while (pos < alen) {
size_t end = pos + AI_CHUNK_MAX;
if (end >= alen) {
irc_msg(s, target, answer + pos);
chunks++;
break;
}
while (end > pos && answer[end] != ' ') end--;
if (end <= pos) end = pos + AI_CHUNK_MAX;
char save = answer[end];
answer[end] = 0;
irc_msg(s, target, answer + pos);
answer[end] = save;
pos = end + 1;
chunks++;
}
log_stamp(); fprintf(stderr, CLR_BLUE "AI done PID %d from %s: %zu chars sent as %d chunks to %s" CLR_RESET "\n", done_pid, nick ? nick : "?", alen, chunks, target);
if (is_code_change) try_compile_and_restart(s, target);
}
free(result);
ai_reset(done_id);
} else {
char *target = NULL;
void *stmt;
if (db_prepare(DB, "SELECT target FROM ai_pending WHERE id=?", -1, &stmt, NULL) == SQLITE_OK) {
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);
}
db_finalize(stmt);
}
if (WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGALRM) {
if (target) {
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) {
irc_msg(s, target, "AI query failed.");
log_stamp(); fprintf(stderr, CLR_RED "AI done PID %d from %s: failed for %s" CLR_RESET "\n", done_pid, nick ? nick : "?", target);
}
free(target);
ai_reset(done_id);
}
free(nick);
}
/* ---- IRC protocol helpers ---- */
/*
* irc_join - Send a JOIN command to join an IRC channel.
*
* Sanitizes the channel name by stopping at spaces, colons, or CRLF
* to prevent protocol injection. Sends "JOIN #channel\r\n" via net_send.
*
* Parameters:
* s - The IRC session.
* chan - The channel name to join (e.g. "#zynk").
*
* Returns: void.
*/
static void irc_join(Session *s, const char *chan) {
char tb[256]; size_t tl = 0;
if (chan) {
for (const unsigned char *p = (const unsigned char*)chan; *p && tl + 1 < sizeof tb; p++) {
if (*p == ' ' || *p == ':' || *p == '\r' || *p == '\n') break;
tb[tl++] = *p;
}
}
tb[tl] = 0;
if (tb[0]) net_send(s, "JOIN %s\r\n", tb);
}
/*
* irc_msg - Send a PRIVMSG to a target (channel or nick).
*
* Sanitizes the target name and message text. If the message contains
* any control characters (bytes < 0x20 or 0x7f), they are replaced with
* spaces to prevent IRC protocol injection. This is critical because
* AI-generated or user-provided text may contain embedded control codes.
* Sends "PRIVMSG target :text\r\n" via net_send.
*
* Parameters:
* s - The IRC session.
* t - The target (channel name or nick).
* txt - The message text to send.
*
* Returns: void.
*/
static void irc_msg(Session *s, const char *t, const char *txt) {
char tb[256]; size_t tl = 0;
if (t) {
for (const unsigned char *p = (const unsigned char*)t; *p && tl + 1 < sizeof tb; p++) {
if (*p == ' ' || *p == ':' || *p == '\r' || *p == '\n') break;
tb[tl++] = *p;
}
}
tb[tl] = 0;
const char *send_txt = txt ? txt : "";
char *clean = NULL;
int need_clean = 0;
for (const unsigned char *p = (const unsigned char*)send_txt; *p; p++) {
if (*p < 0x20 || *p == 0x7f) { need_clean = 1; break; }
}
if (need_clean) {
clean = strdup(send_txt);
if (!clean) return;
for (char *p = clean; *p; p++) if ((unsigned char)*p < 0x20 || (unsigned char)*p == 0x7f) *p = ' ';
send_txt = clean;
}
if (tb[0]) net_send(s, "PRIVMSG %s :%s\r\n", tb, send_txt);
free(clean);
}
/*
* irc_nick - Send a NICK command to change the bot's nickname.
*
* Sanitizes the nickname by stopping at spaces, colons, or CRLF.
* Sends "NICK newnick\r\n" via net_send. Also used on startup
* and when a nick collision (433/436) requires appending underscore.
*
* Parameters:
* s - The IRC session.
* nn - The new nickname to set.
*
* Returns: void.
*/
static void irc_nick(Session *s, const char *nn) {
char tb[64]; size_t tl = 0;
if (nn) {
for (const unsigned char *p = (const unsigned char*)nn; *p && tl + 1 < sizeof tb; p++) {
if (*p == ' ' || *p == ':' || *p == '\r' || *p == '\n') break;
tb[tl++] = *p;
}
}
tb[tl] = 0;
if (tb[0]) net_send(s, "NICK %s\r\n", tb);
}
/*
* irc_pong - Send a PONG response to a server PING.
*
* Strips the leading colon from the server's ping token, sanitizes
* any control characters to spaces, and sends "PONG :token\r\n".
* Required to keep the connection alive and respond to keepalives.
*
* Parameters:
* s - The IRC session.
* r - The ping token from the server (may start with ':').
*
* Returns: void.
*/
static void irc_pong(Session *s, const char *r) {
if (*r == ':') r++;
char pb[256]; size_t pl = 0;
if (r) {
for (const unsigned char *p = (const unsigned char*)r; *p && pl + 1 < sizeof pb; p++) {
if (*p == '\r' || *p == '\n') break;
unsigned char c = *p;
if (c < 0x20 || c == 0x7f) c = ' ';
pb[pl++] = (char)c;
}
}
pb[pl] = 0;
net_send(s, "PONG :%s\r\n", pb);
}
/* ---- IRC command handlers ---- */
/*
* cmd_zynk - Handle the "zynk" key-value store command.
*
* Processes three forms: bare "zynk" (returns random entry),
* "zynk <key>" (looks up value), and "zynk <key> = <value>" (stores value).
* Also handles "zynk!" prefix for overwriting existing keys (requires channel
* op). Keys are lowercased. Rate-limited. Blocked re-adds without "!" prefix
* to prevent accidental overwrites.
*
* Parameters:
* s - The IRC session.
* msg - The raw message text.
* reply_target - Channel or nick to reply to.
* src_nick - The nick of the user who sent the command.
* tgt - The message target (channel or nick).
*
* Returns: 1 if the command was matched (regardless of success), 0 otherwise.
*/
static int cmd_zynk(Session *s, const char *msg, const char *reply_target, const char *src_nick, const char *tgt) {
if (strncmp(msg, "zynk", 4) != 0) return 0;
if (msg[4] != '\0' && msg[4] != ' ' && msg[4] != '!') return 0;
if (rate_limit_check(src_nick) < 0) return 1;
/* zynk!foo without space after ! falls through to other commands */
if (msg[4] == '!' && msg[5] != '\0' && msg[5] != ' ') return 0;
int force = 0;
const char *rest;
if (msg[4] == '\0') {
char *rand = db_get_random();
if (rand) {
irc_msg(s, reply_target, rand);
log_stamp(); fprintf(stderr, CLR_MAGENTA "ZYNK %s from %s:" CLR_RESET " random %s\n", reply_target, src_nick, rand);
free(rand);
} else {
irc_msg(s, reply_target, "No zynkss saved yet.");
}
return 1;
} else if (msg[4] == '!') {
if (msg[5] == '\0') {
irc_msg(s, reply_target, "Usage: zynk! <key> = <value>");
return 1;
}
force = 1;
rest = msg + 6;
} else {
rest = msg + 5;
}
while (*rest == ' ') rest++;
if (!*rest) {
irc_msg(s, reply_target, "Usage: zynk <key> [= <value>]");
return 1;
}
const char *eq = strstr(rest, " = ");
char resp[1024];
if (eq) {
char key[256];
size_t kl = eq - rest;
if (kl == 0) { irc_msg(s, reply_target, "Key cannot be empty"); return 1; }
if (kl >= sizeof key) kl = sizeof key - 1;
memcpy(key, rest, kl); key[kl] = 0;
for (char *p = key; *p; p++) *p = tolower((unsigned char)*p);
if (!force) {
char *existing = db_get_raw(key);
if (existing) {
free(existing);
snprintf(resp, sizeof resp, "zynk already exists (use zynk! to overwrite)");
irc_msg(s, reply_target, resp);
log_stamp(); fprintf(stderr, CLR_MAGENTA "ZYNK %s from %s:" CLR_RESET " blocked re-add of %s\n", reply_target, src_nick, key);
return 1;
}
} else {
if (tgt[0] == '#' && !chan_is_op(tgt, src_nick)) {
irc_msg(s, reply_target, "You need op to overwrite a zynk");
return 1;
}
}
const char *val = eq + 3;
while (*val == ' ') val++;
if (db_set(key, val, src_nick) == 0)
snprintf(resp, sizeof resp, "%s = %s (saved)", key, val);
else
snprintf(resp, sizeof resp, "Error saving %s", key);
} else {
char key[256];
snprintf(key, sizeof key, "%s", rest);
for (char *p = key; *p; p++) *p = tolower((unsigned char)*p);
char *end = key + strlen(key);
while (end > key && end[-1] == ' ') end--;
*end = 0;
char *val = db_get(key);
if (val) {
snprintf(resp, sizeof resp, "%s: %s", key, val);
free(val);
} else {
snprintf(resp, sizeof resp, "%s: not found", key);
}
}
irc_msg(s, reply_target, resp);
log_stamp(); fprintf(stderr, CLR_MAGENTA "ZYNK %s from %s:" CLR_RESET " %s\n", reply_target, src_nick, resp);
return 1;
}
/*
* cmd_ping - Handle the "!ping" command.
*
* Responds with "<nick>: pong!" to confirm the bot is alive.
* Rate-limited to prevent flooding.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_ping(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
if (strncmp(msg, "!ping", 5) != 0) return 0;
if (msg[5] != ' ' && msg[5] != '\0') return 0;
if (rate_limit_check(src_nick) < 0) return 1;
char pong_buf[96]; snprintf(pong_buf, sizeof pong_buf, "%s: pong!", src_nick);
irc_msg(s, reply_target, pong_buf);
log_stamp(); fprintf(stderr, CLR_YELLOW "PING from %s in %s" CLR_RESET "\n", src_nick, reply_target);
return 1;
}
/*
* cmd_version - Handle the "!version" command.
*
* Responds with "zynk <VERSION>" to show the current bot version.
* Rate-limited.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_version(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
if (strncmp(msg, "!version", 8) != 0) return 0;
if (msg[8] != ' ' && msg[8] != '\0') return 0;
if (rate_limit_check(src_nick) < 0) return 1;
char buf[96]; snprintf(buf, sizeof buf, "zynk %s", VERSION);
irc_msg(s, reply_target, buf);
log_stamp(); fprintf(stderr, CLR_BLUE "VERSION from %s in %s" CLR_RESET "\n", src_nick, reply_target);
return 1;
}
/*
* cmd_help - Handle the "!help" command.
*
* Responds with a compact listing of all available bot commands and
* their usage. Includes zynk store/lookup, weather, forecast, stock,
* AI, code, reload, restart, and quit commands. Rate-limited.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_help(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
if (strncmp(msg, "!help", 5) != 0) return 0;
if (msg[5] != ' ' && msg[5] != '\0') return 0;
if (rate_limit_check(src_nick) < 0) return 1;
char buf[512];
snprintf(buf, sizeof buf,
"Commands: !help, !version, !ping, !uptime, !weather [city], !forecast [city], !stock <SYMBOL>[,SYMBOL...], !ai <question>, !code <change> (ops), !reload (ops), !restart (ops), !quit/!die (ops)");
irc_msg(s, reply_target, buf);
log_stamp(); fprintf(stderr, CLR_CYAN "HELP from %s in %s" CLR_RESET "\n", src_nick, reply_target);
return 1;
}
/*
* cmd_quit - Handle the "!quit" and "!die" shutdown commands.
*
* Requires channel op if used in a channel. Sets the global running flag
* to 0, causing the main loop to exit gracefully. Sends a farewell
* message before shutting down.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_quit(Session *s, const char *msg, const char *reply_target, const char *src_nick, const char *tgt) {
if (strcmp(msg, "!quit") != 0 && strcmp(msg, "!die") != 0) return 0;
if (tgt[0] == '#' && !chan_is_op(tgt, src_nick)) {
irc_msg(s, reply_target, "You need op to shut me down");
return 1;
}
irc_msg(s, reply_target, "pffffff, bye. :(");
running = 0;
return 1;
}
/*
* cmd_weather - Handle the "!weather [city]" command.
*
* Fetches current weather data from wttr.in for the specified city
* (defaults to Berlin). Normalizes the city name, fetches the one-line
* weather format, and sends the result to IRC. Rate-limited.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_weather(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
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], city_url[256];
const char *rest = msg[8] == ' ' ? msg + 9 : "";
while (*rest == ' ') rest++;
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_url);
char *body = fetch_url(url);
char resp[1024];
if (body) {
char *nl = strchr(body, '\n');
if (nl) *nl = 0;
snprintf(resp, sizeof resp, "%s", body);
free(body);
} else {
snprintf(resp, sizeof resp, "Weather: could not fetch data");
}
irc_msg(s, reply_target, resp);
log_stamp(); fprintf(stderr, CLR_MAGENTA "WEATHER %s from %s:" CLR_RESET " %s\n", reply_target, src_nick, resp);
return 1;
}
/*
* cmd_forecast - Handle the "!forecast [city]" command.
*
* Fetches a 3-day weather forecast from wttr.in using the JSON API.
* Delegates to fetch_forecast() for parsing. Defaults to Berlin if
* no city is specified. Rate-limited.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_forecast(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
if (strncmp(msg, "!forecast", 9) != 0) return 0;
if (msg[9] != ' ' && msg[9] != '\0') return 0;
if (rate_limit_check(src_nick) < 0) return 1;
char city[256], city_url[256];
const char *rest = msg[9] == ' ' ? msg + 10 : "";
while (*rest == ' ') rest++;
normalize_city(rest, city, sizeof city, city_url, sizeof city_url);
char *body = fetch_forecast(city_url, city);
char resp[1024];
if (body) {
snprintf(resp, sizeof resp, "%s", body);
free(body);
} else {
snprintf(resp, sizeof resp, "Forecast: could not fetch data");
}
irc_msg(s, reply_target, resp);
log_stamp(); fprintf(stderr, CLR_MAGENTA "FORECAST %s from %s:" CLR_RESET " %s\n", reply_target, src_nick, resp);
return 1;
}
/*
* json_find - Simple JSON value locator without a parser library.
*
* Searches for a key string in a JSON text blob and returns a pointer
* to the value that follows (after any whitespace and colon). Skips
* leading brackets/spaces. Not a full JSON parser - only works for
* flat key:value lookups in wttr.in/Yahoo Finance responses.
*
* Parameters:
* haystack - The JSON text to search.
* key - The key string to find (e.g. "\"regularMarketPrice\":").
*
* Returns: Pointer into haystack at the start of the value, or NULL if
* the key is not found.
*/
static const char *json_find(const char *haystack, const char *key) {
const char *p = strstr(haystack, key);
if (!p) return NULL;
p += strlen(key);
while (*p == ' ' || *p == '\t') p++;
if (*p == ':') { p++; while (*p == ' ' || *p == '\t') p++; }
while (*p == '[' || *p == ' ') p++;
return p;
}
/*
* cmd_stock - Handle the "!stock <SYMBOL>[,SYMBOL...]" command.
*
* Fetches real-time stock quotes from Yahoo Finance's chart API for up to
* 3 comma-separated ticker symbols. Parses the JSON response to extract
* current price, previous close, change/percent, day high/low, and volume.
* Formats each symbol as "SYMB (Name): $price +/-change (+/-pct%) H:high L:low Vol:volM".
* Multiple symbols are separated by " | ". Rate-limited.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_stock(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
if (strncmp(msg, "!stock", 6) != 0) return 0;
if (msg[6] != ' ' && msg[6] != '\0') return 0;
if (rate_limit_check(src_nick) < 0) return 1;
const char *rest = msg[6] == ' ' ? msg + 7 : "";
while (*rest == ' ') rest++;
if (!*rest) {
irc_msg(s, reply_target, "Usage: !stock <SYMBOL>[,SYMBOL...] (max 3, e.g. !stock AAPL or !stock AAPL,MSFT,GOOGL)");
return 1;
}
char buf[2048];
buf[0] = 0;
int count = 0;
char symbols[3][16];
const char *p = rest;
while (*p && count < 3) {
while (*p == ' ' || *p == ',') p++;
if (!*p) break;
int i = 0;
while (*p && *p != ' ' && *p != ',' && i < 15) symbols[count][i++] = toupper((unsigned char)*p++);
symbols[count][i] = 0;
count++;
}
for (int si = 0; si < count; si++) {
char url[512];
snprintf(url, sizeof url, "https://query1.finance.yahoo.com/v8/finance/chart/%s?interval=1d&range=1d", symbols[si]);
char *json = fetch_url(url);
if (!json) {
char tmp[128];
snprintf(tmp, sizeof tmp, "%s: fetch error", symbols[si]);
if (buf[0]) strncat(buf, " | ", sizeof buf - strlen(buf) - 1);
strncat(buf, tmp, sizeof buf - strlen(buf) - 1);
continue;
}
const char *rp_s = json_find(json, "\"regularMarketPrice\":");
const char *pc_s = json_find(json, "\"chartPreviousClose\":");
const char *hi_s = json_find(json, "\"high\":");
const char *lo_s = json_find(json, "\"low\":");
const char *vo_s = json_find(json, "\"volume\":");
const char *nm_s = json_find(json, "\"shortName\":");
if (!rp_s || !pc_s || !hi_s || !lo_s || !vo_s) {
char tmp[480];
size_t jlen = strlen(json);
if (jlen > 400) jlen = 400;
snprintf(tmp, sizeof tmp, "%s: parse error (response: %.*s)", symbols[si], (int)jlen, json);
if (buf[0]) strncat(buf, " | ", sizeof buf - strlen(buf) - 1);
strncat(buf, tmp, sizeof buf - strlen(buf) - 1);
free(json); continue;
}
double price = strtod(rp_s, NULL);
double prev_close = strtod(pc_s, NULL);
double high = strtod(hi_s, NULL);
double low = strtod(lo_s, NULL);
long volume = strtol(vo_s, NULL, 10);
double change = price - prev_close;
double pct = (prev_close != 0) ? (change / prev_close) * 100.0 : 0.0;
char name[32] = "";
if (nm_s && nm_s[0] == '"') {
nm_s++;
const char *nq = strchr(nm_s, '"');
if (nq) { size_t nl = nq - nm_s; if (nl > 31) nl = 31; memcpy(name, nm_s, nl); name[nl] = 0; }
}
char tmp[384];
if (name[0])
snprintf(tmp, sizeof tmp, "%s (%s): $%.2f %+.2f (%+.2f%%) H:%.2f L:%.2f Vol:%ldM",
symbols[si], name, price, change, pct, high, low, volume / 1000000);
else
snprintf(tmp, sizeof tmp, "%s: $%.2f %+.2f (%+.2f%%) H:%.2f L:%.2f Vol:%ldM",
symbols[si], price, change, pct, high, low, volume / 1000000);
if (buf[0]) strncat(buf, " | ", sizeof buf - strlen(buf) - 1);
strncat(buf, tmp, sizeof buf - strlen(buf) - 1);
free(json);
}
if (!buf[0]) snprintf(buf, sizeof buf, "Stock: could not fetch data");
irc_msg(s, reply_target, buf);
log_stamp(); fprintf(stderr, CLR_MAGENTA "STOCK %s from %s:" CLR_RESET " %s\n", reply_target, src_nick, buf);
return 1;
}
/*
* cmd_ai - Handle the "!ai <question>" command.
*
* Passes the question to ai_ask() in plan mode (agent=NULL), which means
* the AI can only discuss and answer questions but cannot modify files.
* Extracts the question text after "!ai ", trims trailing whitespace.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_ai(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
if (strncmp(msg, "!ai", 3) != 0) return 0;
if (msg[3] != ' ' && msg[3] != '\0') return 0;
const char *rest = msg[3] == ' ' ? msg + 4 : "";
while (*rest == ' ') rest++;
if (!*rest) {
irc_msg(s, reply_target, "Usage: !ai <question>");
return 1;
}
char question[2048];
snprintf(question, sizeof question, "%s", rest);
char *end = question + strlen(question);
while (end > question && end[-1] == ' ') end--;
*end = 0;
ai_ask(s, question, reply_target, src_nick, NULL);
return 1;
}
/*
* cmd_code - Handle the "!code <instruction>" command for AI code changes.
*
* Requires channel op and must be used in a channel (not PM). Wraps the
* instruction with context ("[CODE CHANGE REQUEST from op nick in #chan]")
* and passes it to ai_ask() with agent="build", which gives the AI full
* file-editing and command-execution capabilities. After the AI responds,
* try_compile_and_restart() is triggered to auto-deploy if compilation
* succeeds. Rate-limited.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_code(Session *s, const char *msg, const char *reply_target, const char *src_nick, const char *tgt) {
if (strncmp(msg, "!code", 5) != 0) return 0;
if (msg[5] != ' ' && msg[5] != '\0') return 0;
if (tgt[0] != '#') {
irc_msg(s, reply_target, "!code can only be used in a channel");
return 1;
}
if (!chan_is_op(tgt, src_nick)) {
irc_msg(s, reply_target, "You need to be a channel op to use !code");
return 1;
}
const char *rest = msg[5] == ' ' ? msg + 6 : "";
while (*rest == ' ') rest++;
if (!*rest) {
irc_msg(s, reply_target, "Usage: !code <instruction for code change>");
return 1;
}
char question[2048];
snprintf(question, sizeof question,
"[CODE CHANGE REQUEST from op %s in %s] %s", src_nick, tgt, rest);
char *end = question + strlen(question);
while (end > question && end[-1] == ' ') end--;
*end = 0;
ai_ask(s, question, reply_target, src_nick, "build");
log_stamp(); fprintf(stderr, CLR_RED "CODE %s from %s (op in %s):" CLR_RESET " %s\n", reply_target, src_nick, tgt, rest);
return 1;
}
/*
* cmd_reload - Handle the "!reload" hot-reload command.
*
* Requires channel op if used in a channel. Triggers reload_do() which
* saves TLS state, parts channels, sends QUIT, and fork/exec's a new
* instance. Only works with an active TLS connection. Rate-limited.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_uptime(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
if (strncmp(msg, "!uptime", 7) != 0) return 0;
if (msg[7] != ' ' && msg[7] != '\0') return 0;
if (rate_limit_check(src_nick) < 0) return 1;
time_t diff = time(NULL) - start_time;
long days = diff / 86400;
long hours = (diff % 86400) / 3600;
long mins = (diff % 3600) / 60;
long secs = diff % 60;
char buf[128];
if (days > 0)
snprintf(buf, sizeof buf, "%s: up %ldd %ldh %ldm %lds", src_nick, days, hours, mins, secs);
else if (hours > 0)
snprintf(buf, sizeof buf, "%s: up %ldh %ldm %lds", src_nick, hours, mins, secs);
else if (mins > 0)
snprintf(buf, sizeof buf, "%s: up %ldm %lds", src_nick, mins, secs);
else
snprintf(buf, sizeof buf, "%s: up %lds", src_nick, secs);
irc_msg(s, reply_target, buf);
log_stamp(); fprintf(stderr, CLR_YELLOW "UPTIME from %s in %s" CLR_RESET "\n", src_nick, reply_target);
return 1;
}
static int cmd_reload(Session *s, const char *msg, const char *reply_target, const char *src_nick, const char *tgt) {
if (strcmp(msg, "!reload") != 0) return 0;
if (tgt[0] == '#' && !chan_is_op(tgt, src_nick)) {
irc_msg(s, reply_target, "You need op to reload");
return 1;
}
if (rate_limit_check(src_nick) < 0) return 1;
reload_do(s, reply_target);
return 1;
}
/*
* cmd_restart - Handle the "!restart" command.
*
* Requires channel op. Functionally identical to cmd_reload: sends a
* "Restarting..." message then triggers reload_do(). Rate-limited.
*
* Returns: 1 if matched, 0 otherwise.
*/
static int cmd_restart(Session *s, const char *msg, const char *reply_target, const char *src_nick, const char *tgt) {
if (strcmp(msg, "!restart") != 0) return 0;
if (tgt[0] == '#' && !chan_is_op(tgt, src_nick)) {
irc_msg(s, reply_target, "You need op to restart me");
return 1;
}
if (rate_limit_check(src_nick) < 0) return 1;
irc_msg(s, reply_target, "Restarting...");
reload_do(s, reply_target);
return 1;
}
/*
* cmd_greeting_or_chat - Handle casual chat messages and direct address.
*
* Checks if the message starts with the bot's nick followed by ':', and
* if so strips that prefix to get the actual message. Matches known
* greeting/casual phrases (hi, hey, hello, bye, jojo, whatsup, waddup,
* German phrases) with hardcoded responses. If the message doesn't match
* any known phrase but was addressed to the bot by nick, forwards it to
* ai_ask() in plan mode for an AI-powered conversation response.
*
* Parameters:
* s - The IRC session.
* msg - The raw message text.
* reply_target - Channel or nick to reply to.
* src_nick - The nick of the sender.
*
* Returns: void.
*/
static void cmd_greeting_or_chat(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
int nicklen = strlen(s->nick);
const char *cmd = msg;
if (strncasecmp(msg, s->nick, nicklen) == 0 && msg[nicklen] == ':') {
cmd = msg + nicklen + 1;
while (*cmd == ' ') cmd++;
if (!*cmd) cmd = msg;
}
char resp[1024];
int matched = 0;
if (strcasecmp(cmd, "hi") == 0 || strcasecmp(cmd, "hey") == 0 || strcasecmp(cmd, "hello") == 0) {
snprintf(resp, sizeof resp, "Hi, %s!", src_nick); matched = 1;
} else if (strcasecmp(cmd, "bye") == 0 || strcasecmp(cmd, "goodbye") == 0) {
snprintf(resp, sizeof resp, "Bye, %s!", src_nick); matched = 1;
} else if (strcasecmp(cmd, "jojo") == 0) {
snprintf(resp, sizeof resp, "Jo, %s!", src_nick); matched = 1;
} else if (strcasecmp(cmd, "whatsup") == 0) {
snprintf(resp, sizeof resp, "Not much, %s!", src_nick); matched = 1;
} else if (strcasecmp(cmd, "waddup") == 0) {
snprintf(resp, sizeof resp, "Yo %s!", src_nick); matched = 1;
} else if (strcasecmp(cmd, "waddup yo") == 0) {
snprintf(resp, sizeof resp, "Yo!"); matched = 1;
} else if (strcasecmp(cmd, "deine muddi") == 0 || strcasecmp(cmd, "deine mutter") == 0) {
snprintf(resp, sizeof resp, "Ey, %s, lass das!", src_nick); matched = 1;
} else if (strcasecmp(cmd, "penis") == 0) {
snprintf(resp, sizeof resp, "..."); matched = 1;
}
if (matched) {
irc_msg(s, reply_target, resp);
log_stamp(); fprintf(stderr, CLR_CYAN "CHAT %s from %s:" CLR_RESET " %s\n", reply_target, src_nick, resp);
return;
}
if (cmd != msg) {
ai_ask(s, cmd, reply_target, src_nick, NULL);
}
}
/* ---- IRC protocol handlers ---- */
/*
* handle_privmsg - Dispatch incoming PRIVMSG to the appropriate command handler.
*
* Parses the PRIVMSG params to extract the target channel/nick and the message
* text. Ignores messages from the bot itself. Sets reply_target to the channel
* if it's a channel message, or to the sender's nick for PMs. Then tries each
* command handler in order: zynk, ping, version, help, quit, weather, forecast,
* stock, ai, code, reload, restart. If no command matches and the message was
* addressed to the bot by nick, falls through to cmd_greeting_or_chat.
*
* Parameters:
* s - The IRC session.
* params - The raw IRC params (target :message).
* src_nick - The nick of the message sender.
*
* Returns: void.
*/
static void handle_privmsg(Session *s, const char *params, const char *src_nick) {
const char *p = params;
const char *target = p;
p = strchr(p, ' '); if (!p) return;
char tgt[256]; size_t tl = p - target;
if (tl >= sizeof tgt) tl = sizeof tgt - 1;
memcpy(tgt, target, tl); tgt[tl] = 0;
while (*p == ' ') p++;
if (*p == ':') p++;
const char *msg = p;
if (strcasecmp(src_nick, s->nick) == 0) return;
const char *reply_target = (tgt[0] == '#') ? tgt : src_nick;
if (cmd_zynk(s, msg, reply_target, src_nick, tgt)) return;
if (cmd_ping(s, msg, reply_target, src_nick)) return;
if (cmd_version(s, msg, reply_target, src_nick)) return;
if (cmd_uptime(s, msg, reply_target, src_nick)) return;
if (cmd_help(s, msg, reply_target, src_nick)) return;
if (cmd_quit(s, msg, reply_target, src_nick, tgt)) return;
if (cmd_weather(s, msg, reply_target, src_nick)) return;
if (cmd_forecast(s, msg, reply_target, src_nick)) return;
if (cmd_stock(s, msg, reply_target, src_nick)) return;
if (cmd_ai(s, msg, reply_target, src_nick)) return;
if (cmd_code(s, msg, reply_target, src_nick, tgt)) return;
if (cmd_reload(s, msg, reply_target, src_nick, tgt)) return;
if (cmd_restart(s, msg, reply_target, src_nick, tgt)) return;
cmd_greeting_or_chat(s, msg, reply_target, src_nick);
}
/*
* handle_namreply - Process RPL_NAMREPLY (353) to populate channel op lists.
*
* Parses the names list from the server's NAMREPLY, which contains nicks
* prefixed with status symbols: @ = channel op, ~ = owner, & = admin,
* % = halfop. For each nick with op-like prefix, adds it to the channel's
* op tracking list via chan_add_op(). This is how the bot discovers existing
* ops when it first joins a channel.
*
* Parameters:
* s - The IRC session.
* params - The raw IRC params (nick type #channel :names...).
*
* Returns: void.
*/
static void handle_namreply(Session *s, const char *params) {
(void)s;
char our[32], _chan[64];
const char *p = params;
/* params: "<nick> <type> <chan> :<nicks>" */
if (sscanf(p, "%31s %*s %63s", our, _chan) < 2) return;
p = strchr(p, ':');
if (!p) return;
p++;
char buf[32];
while (*p) {
while (*p == ' ') p++;
if (!*p) break;
int is_op = 0;
while (*p && (*p == '@' || *p == '~' || *p == '&' || *p == '%')) {
if (*p == '@' || *p == '~' || *p == '&') is_op = 1;
p++;
}
int i = 0;
while (*p && *p != ' ') {
if (i < 31) buf[i++] = *p;
p++;
}
buf[i] = 0;
if (is_op && buf[0]) chan_add_op(_chan, buf);
}
}
/*
* handle_mode - Process MODE changes to track channel op additions/removals.
*
* Parses MODE messages like "#chan +o nick" or "#chan -o nick". When +o is
* set, adds the nick to the channel's op list. When -o is set, removes it.
* Only processes channel modes that affect operator status.
*
* Parameters:
* s - The IRC session.
* params - The raw IRC params (channel modes [nick]).
*
* Returns: void.
*/
static void handle_mode(Session *s, const char *params) {
(void)s;
char _chan[64], _modes[32], _nick[32];
if (sscanf(params, "%63s %31s %31s", _chan, _modes, _nick) < 3) return;
if (_chan[0] == '#') {
if (_modes[0] == '+' && strchr(_modes, 'o'))
chan_add_op(_chan, _nick);
else if (_modes[0] == '-' && strchr(_modes, 'o'))
chan_del_op(_chan, _nick);
}
}
/*
* handle_join - Process JOIN messages to register new channels.
*
* When any user (including the bot) joins a channel, registers the channel
* in the tracking array via chan_get_or_add(). This ensures the channel
* exists in the ops tracking structure even before NAMREPLY arrives.
*
* Parameters:
* s - The IRC session.
* params - The raw IRC params (:#channel).
*
* Returns: void.
*/
static void handle_join(Session *s, const char *params) {
(void)s;
const char *p = params;
if (*p == ':') p++;
char _chan[64];
if (sscanf(p, "%63s", _chan) == 1)
chan_get_or_add(_chan);
}
/*
* handle_part - Process PART messages to clean up channel op tracking.
*
* When a user parts a channel, removes them from that channel's op list
* via chan_del_op(). Prevents stale op entries from accumulating.
*
* Parameters:
* params - The raw IRC params (#channel [message]).
* src_nick - The nick of the user who parted.
*
* Returns: void.
*/
static void handle_part(const char *params, const char *src_nick) {
char _chan[64];
if (sscanf(params, "%63s", _chan) >= 1)
chan_del_op(_chan, src_nick);
}
/*
* handle_kick - Process KICK messages to remove kicked users from op lists.
*
* When a user is kicked from a channel, removes them from that channel's
* op list via chan_del_op(). Prevents tracking a user who is no longer
* in the channel.
*
* Parameters:
* params - The raw IRC params (#channel victim [message]).
*
* Returns: void.
*/
static void handle_kick(const char *params) {
char _chan[64], _victim[32];
if (sscanf(params, "%63s %31s", _chan, _victim) >= 2)
chan_del_op(_chan, _victim);
}
/*
* handle_quit_net - Process QUIT messages to clean up op tracking.
*
* When any user quits the network, removes them from all channel op lists
* via chan_del_op(). Iterates all tracked channels.
*
* Parameters:
* src_nick - The nick of the user who quit.
*
* Returns: void.
*/
static void handle_quit_net(const char *src_nick) {
for (int i = 0; i < nchans; i++)
chan_del_op(chans[i].name, src_nick);
}
/*
* handle_nick_change - Process NICK changes to update op tracking and bot state.
*
* Extracts the old nick from the message prefix, gets the new nick from
* params, then renames the nick across all channel op lists via
* chan_rename_op(). If the bot itself changed its nick (e.g. after a
* 433 collision), updates s->nick to match. Validates the new nick for
* safety (no CRLF, no control characters).
*
* Parameters:
* s - The IRC session.
* prefix - The IRC prefix containing the old nick (nick!user@host).
* params - The IRC params (:newnick).
*
* Returns: void.
*/
static void handle_nick_change(Session *s, const char *prefix, const char *params) {
char src_nick[64] = "";
const char *ex = strchr(prefix, '!');
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++;
if (!*newnick || has_crlf(newnick) || has_ctl(newnick)) return;
chan_rename_op(src_nick, newnick);
if (strcasecmp(src_nick, s->nick) == 0) {
strncpy(s->nick, newnick, sizeof s->nick - 1);
s->nick[sizeof s->nick - 1] = 0;
}
}
/*
* handle_error_codes - Handle numeric IRC error codes and ERROR messages.
*
* Handles: 464 (password rejected - shuts down), 433/436 (nick collision -
* appends underscore to nick and retries), and ERROR (logs the message).
* These are server-level errors that require special handling beyond normal
* command dispatch.
*
* Parameters:
* s - The IRC session.
* cmd_buf - The IRC command/numeric as a string.
* params - The IRC params.
*
* Returns: void.
*/
static void handle_error_codes(Session *s, const char *cmd_buf, const char *params) {
if (strcmp(cmd_buf, "464") == 0) {
log_stamp(); fprintf(stderr, CLR_RED "Password rejected" CLR_RESET "\n"); running = 0; return;
}
if (strcmp(cmd_buf, "433") == 0 || strcmp(cmd_buf, "436") == 0) {
char newnick[33];
snprintf(newnick, sizeof newnick, "%s_", s->nick);
irc_nick(s, newnick);
strncpy(s->nick, newnick, sizeof s->nick - 1);
s->nick[sizeof s->nick - 1] = 0;
return;
}
if (strcmp(cmd_buf, "ERROR") == 0) {
const char *m = params;
if (*m == ':') m++;
log_stamp(); fprintf(stderr, CLR_RED "ERROR:" CLR_RESET " %s\n", m);
return;
}
}
/* ---- IRC dispatcher ---- */
/*
* irc_handle - Parse and dispatch a single complete IRC protocol message.
*
* Parses the IRC message format (:prefix COMMAND params :trailing) into
* its components. Handles server keepalives (PING/PONG), connection
* establishment (001), MOTD end (376/422 triggers channel joins), and
* routes numeric replies and commands to their respective handler
* functions. Extracts the source nick from the prefix for PRIVMSG,
* JOIN, PART, KICK, QUIT, and NICK commands. Also handles the code
* restart notification on MOTD end.
*
* Parameters:
* s - The IRC session.
* raw - The complete IRC line (without trailing \r\n).
*
* Returns: void.
*/
static void irc_handle(Session *s, const char *raw) {
if (!raw || !*raw) return;
const char *prefix = NULL, *cmd = raw;
char pfx_buf[512], cmd_buf[64];
pfx_buf[0] = cmd_buf[0] = 0;
if (*raw == ':') {
raw++;
const char *sp = strchr(raw, ' ');
if (!sp) return;
size_t plen = sp - raw;
if (plen >= sizeof pfx_buf) plen = sizeof pfx_buf - 1;
memcpy(pfx_buf, raw, plen); pfx_buf[plen] = 0;
prefix = pfx_buf;
cmd = sp + 1;
while (*cmd == ' ') cmd++;
if (!*cmd) return;
}
const char *params = strchr(cmd, ' ');
if (params) {
size_t clen = params - cmd;
if (clen >= sizeof cmd_buf) clen = sizeof cmd_buf - 1;
memcpy(cmd_buf, cmd, clen); cmd_buf[clen] = 0;
while (*params == ' ') params++;
} else {
size_t cl2 = strlen(cmd);
if (cl2 >= sizeof cmd_buf) cl2 = sizeof cmd_buf - 1;
memcpy(cmd_buf, cmd, cl2); cmd_buf[cl2] = 0;
params = "";
}
if (strcmp(cmd_buf, "PING") == 0) { irc_pong(s, params); return; }
char src_nick[64] = "";
if (prefix) {
const char *ex = strchr(prefix, '!');
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;
}
if (strcmp(cmd_buf, "001") == 0) {
s->connected = 1;
log_stamp(); fprintf(stderr, CLR_GREEN "Connected to %s" CLR_RESET "\n", s->host);
return;
}
if (strcmp(cmd_buf, "376") == 0 || strcmp(cmd_buf, "422") == 0) {
log_stamp(); fprintf(stderr, CLR_GREEN "MOTD end, joining channels..." CLR_RESET "\n");
char *copy = strdup(s->auto_join);
if (copy) {
char *save;
for (char *tok = strtok_r(copy, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) {
while (*tok == ' ') tok++;
char *end = tok + strlen(tok);
while (end > tok && end[-1] == ' ') end--;
*end = 0;
if (*tok) { irc_join(s, tok); log_stamp(); fprintf(stderr, CLR_GREEN "Joining %s" CLR_RESET "\n", tok); }
}
free(copy);
}
if (s->code_restart) {
s->code_restart = 0;
char *c2 = strdup(s->auto_join);
if (c2) {
char *sv;
for (char *t = strtok_r(c2, ",", &sv); t; t = strtok_r(NULL, ",", &sv)) {
while (*t == ' ') t++;
char *e = t + strlen(t);
while (e > t && e[-1] == ' ') e--;
*e = 0;
if (*t) irc_msg(s, t, "Code update done, I'm back!");
}
free(c2);
}
}
return;
}
if (strcmp(cmd_buf, "PRIVMSG") == 0) { handle_privmsg(s, params, src_nick); return; }
if (strcmp(cmd_buf, "353") == 0) { handle_namreply(s, params); return; }
if (strcmp(cmd_buf, "MODE") == 0) { handle_mode(s, params); return; }
if (strcmp(cmd_buf, "JOIN") == 0 && prefix) { handle_join(s, params); return; }
if (strcmp(cmd_buf, "PART") == 0 && prefix) { handle_part(params, src_nick); return; }
if (strcmp(cmd_buf, "KICK") == 0 && prefix) { handle_kick(params); return; }
if (strcmp(cmd_buf, "QUIT") == 0 && prefix) { handle_quit_net(src_nick); return; }
if (strcmp(cmd_buf, "NICK") == 0 && prefix) { handle_nick_change(s, prefix, params); return; }
handle_error_codes(s, cmd_buf, params);
}
/* ---- IRC line parser ---- */
/*
* irc_feed - Buffer incoming data and dispatch complete IRC lines.
*
* Accumulates raw bytes into the session's read buffer (s->rbuf) until
* a newline is found. On \n, NUL-terminates the buffer and passes the
* complete line to irc_handle(). Skips \r characters. Prevents buffer
* overflow by checking against RBUF_SZ. This implements the line-based
* protocol parsing required by IRC.
*
* Parameters:
* s - The IRC session with rbuf and rlen state.
* data - Raw bytes from the network read.
* len - Number of bytes in data.
*
* Returns: void.
*/
static void irc_feed(Session *s, const char *data, int len) {
for (int i = 0; i < len; i++) {
char c = data[i];
if (c == '\r') continue;
if (c == '\n') {
s->rbuf[s->rlen] = 0;
if (s->rlen > 0) irc_handle(s, s->rbuf);
s->rlen = 0;
} else {
if (s->rlen < RBUF_SZ - 1) s->rbuf[s->rlen++] = c;
}
}
}
/* ---- usage ---- */
/*
* usage - Print command-line usage information to stderr.
*
* Displays all available command-line options (-ssl, -server, -port, -pass,
* -nick, -join, -opencode, -noverify, -h) with descriptions and defaults.
* Also lists the basic zynk store/lookup commands. Called when -h/--help
* is passed or when invalid arguments are detected.
*
* Parameters:
* prog - The program name (argv[0]).
*
* Returns: void (output goes to stderr).
*/
static void usage(const char *prog) {
fprintf(stderr,
"Usage: %s [-ssl] [-server host] [-port p] [-nick n] [-join c] [-opencode path]\n"
" -h This help\n"
" -noverify Skip TLS certificate verification\n"
" -server host IRC server (default: %s)\n"
" -port p Port (default: %d)\n"
" -pass p Server password\n"
" -nick n Nickname (default: zynk<PID>)\n"
" -join c Auto-join channels (comma-sep, default: #zynk)\n"
" -opencode p Path to opencode binary (default: %s)\n"
"\n"
"Zynk commands:\n"
" zynk foo = bar Store 'bar' under key 'foo'\n"
" zynk foo Retrieve value for 'foo'\n",
prog, DEFAULT_SERVER, DEF_PORT, OPENCODE_BIN);
}
/* ---- reconnect ---- */
/*
* net_reconnect - Attempt to reconnect to the IRC server after disconnection.
*
* Cleans up the existing TLS session and socket, then tries up to 10 times
* to reconnect with increasing delays (5s, 7s, 9s, ...). For each attempt,
* creates a new TCP connection, performs TLS handshake if enabled, sets
* non-blocking mode, sends PASS/NICK/USER to re-authenticate. Logs each
* attempt and gives up after 10 failures. Used by the main loop when a
* read returns 0 (clean disconnect) or a fatal error.
*
* Parameters:
* s - The IRC session to reconnect (host, port, nick, etc. are reused).
*
* Returns: 0 on successful reconnection, -1 after exhausting all attempts.
*/
static int net_reconnect(Session *s) {
tls_cleanup(s);
if (s->fd >= 0) close(s->fd);
s->fd = -1;
s->connected = 0;
s->rlen = 0;
for (int attempt = 0; attempt < 10; attempt++) {
if (attempt > 0) {
log_stamp(); fprintf(stderr, CLR_YELLOW "Reconnecting in %ds (attempt %d/10)..." CLR_RESET "\n",
5 + attempt * 2, attempt + 1);
sleep(5 + attempt * 2);
}
s->fd = net_connect(s->host, s->port);
if (s->fd < 0) {
log_stamp(); fprintf(stderr, CLR_RED "Reconnect attempt %d/10: connect failed" CLR_RESET "\n", attempt + 1);
continue;
}
if (s->use_tls && tls_handshake(s) < 0) {
log_stamp(); fprintf(stderr, CLR_RED "Reconnect attempt %d/10: TLS failed" CLR_RESET "\n", attempt + 1);
close(s->fd); s->fd = -1;
continue;
}
int fl = fcntl(s->fd, F_GETFL, 0);
fcntl(s->fd, F_SETFL, fl | O_NONBLOCK);
if (s->pass[0]) net_send(s, "PASS %s\r\n", s->pass);
irc_nick(s, s->nick);
net_send(s, "USER %s 0 * :%s\r\n", s->user, s->real);
log_stamp(); fprintf(stderr, CLR_GREEN "Reconnected to %s:%d" CLR_RESET "\n", s->host, s->port);
return 0;
}
log_stamp(); fprintf(stderr, CLR_RED "Giving up after 10 reconnect attempts" CLR_RESET "\n");
return -1;
}
/* ---- main ---- */
/*
* main - Entry point: parse arguments, initialize, connect, and run the event loop.
*
* Parses command-line arguments (server, port, nick, channels, TLS options,
* opencode path). Validates inputs (IRC-safe strings, valid port, etc.).
* Initializes the SQLite database. Attempts hot-reload restoration if TLS
* is enabled; otherwise establishes a fresh connection with TLS handshake.
* Sets up signal handlers (SIGINT/SIGTERM for graceful shutdown, SIGPIPE
* ignored). Runs the main event loop using poll() with a 100ms timeout:
* reads incoming IRC data and feeds it through irc_feed/irc_handle, and
* checks for completed AI child processes via ai_check_completion(). On
* shutdown, kills any pending AI process, sends QUIT, cleans up TLS/DB,
* and exits cleanly.
*
* Parameters:
* argc - Argument count.
* argv - Argument vector.
*
* Returns: 0 on clean shutdown, 1 on error.
*/
int main(int argc, char **argv) {
const char *sv = DEFAULT_SERVER;
int use_tls = 0;
int port = DEF_PORT;
char nickbuf[32];
const char *nick = NULL;
char passbuf[256] = "";
char joinbuf[256] = "#zynk";
g_opencode_bin = OPENCODE_BIN;
int pos = 0;
log_stamp(); fprintf(stderr, CLR_CYAN "[zynk] starting up" CLR_RESET "\n");
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
usage(argv[0]); return 0;
}
if (argv[i][0] == '-') {
if (strcmp(argv[i], "-ssl") == 0 || strcmp(argv[i], "-tls") == 0)
use_tls = 1;
else if (strcmp(argv[i], "-pass") == 0) {
if (++i >= argc) { usage(argv[0]); return 1; }
snprintf(passbuf, sizeof passbuf, "%s", argv[i]);
} else if (strcmp(argv[i], "-nick") == 0) {
if (++i >= argc) { usage(argv[0]); return 1; }
nick = argv[i];
} else if (strcmp(argv[i], "-port") == 0) {
if (++i >= argc) { usage(argv[0]); return 1; }
port = atoi(argv[i]);
} else if (strcmp(argv[i], "-server") == 0) {
if (++i >= argc) { usage(argv[0]); return 1; }
sv = argv[i];
} else if (strcmp(argv[i], "-join") == 0) {
if (++i >= argc) { usage(argv[0]); return 1; }
snprintf(joinbuf, sizeof joinbuf, "%s", argv[i]);
} else if (strcmp(argv[i], "-opencode") == 0) {
if (++i >= argc) { usage(argv[0]); return 1; }
g_opencode_bin = argv[i];
} else if (strcmp(argv[i], "-noverify") == 0) {
tls_verify = 0;
} else {
usage(argv[0]); return 1;
}
} else switch (pos++) {
case 0: sv = argv[i]; break;
case 1: {
const char *p = argv[i];
if (p[0] == '+') { use_tls = 1; p++; }
port = atoi(p);
break;
}
case 2: nick = argv[i]; break;
default:
fprintf(stderr, CLR_RED "Unexpected arg:" CLR_RESET " %s\n", argv[i]);
return 1;
}
}
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 (!valid_irc_word(nick)) {
fprintf(stderr, CLR_RED "Invalid nick" CLR_RESET "\n");
return 1;
}
if (has_crlf(passbuf) || has_crlf(joinbuf) || has_ctl(passbuf)) {
fprintf(stderr, CLR_RED "Invalid IRC argument" CLR_RESET "\n");
return 1;
}
if (!g_opencode_bin || !*g_opencode_bin) {
fprintf(stderr, CLR_RED "Invalid opencode path" CLR_RESET "\n");
return 1;
}
if (has_ctl(g_opencode_bin)) {
fprintf(stderr, CLR_RED "Invalid opencode path (control chars)" CLR_RESET "\n");
return 1;
}
if (db_init() < 0) {
fprintf(stderr, CLR_RED "DB init failed" CLR_RESET "\n");
sqlite_cleanup();
return 1;
}
start_time = time(NULL);
Session s;
memset(&s, 0, sizeof s);
snprintf(s.host, sizeof s.host, "%s", sv);
s.port = port;
snprintf(s.nick, sizeof s.nick, "%s", nick);
snprintf(s.user, sizeof s.user, "%s", nick);
snprintf(s.real, sizeof s.real, "zynk");
snprintf(s.auto_join, sizeof s.auto_join, "%s", joinbuf);
s.fd = -1;
s.use_tls = use_tls;
if (passbuf[0]) snprintf(s.pass, sizeof s.pass, "%s", passbuf);
signal(SIGINT, handle_sigterm);
signal(SIGTERM, handle_sigterm);
signal(SIGPIPE, SIG_IGN);
if (use_tls) reload_try_restore(&s);
{
if (use_tls && tls_init() < 0) {
fprintf(stderr, CLR_RED "TLS init failed" CLR_RESET "\n");
db_close_cleanup();
sqlite_cleanup();
return 1;
}
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);
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);
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);
log_stamp(); fprintf(stderr, CLR_GREEN "Connecting to %s:%d as %s..." CLR_RESET "\n", s.host, s.port, s.nick);
if (s.pass[0]) net_send(&s, "PASS %s\r\n", s.pass);
irc_nick(&s, s.nick);
net_send(&s, "USER %s 0 * :%s\r\n", s.user, s.real);
}
running = 1;
pending_ai_pid = 0;
while (running) {
struct pollfd pfd = { .fd = s.fd, .events = POLLIN };
int ret = poll(&pfd, 1, POLL_MS);
if (ret < 0) { if (errno == EINTR) continue; break; }
if (pfd.revents & (POLLIN | POLLHUP)) {
char buf[4096];
int n = net_read(&s, buf, sizeof buf);
if (n > 0) { irc_feed(&s, buf, n); }
else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EINTR)) {
log_stamp(); fprintf(stderr, CLR_YELLOW "Disconnected" CLR_RESET "\n");
s.connected = 0;
if (net_reconnect(&s) < 0) break;
continue;
}
}
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);
net_send(&s, "QUIT :zynk\r\n");
struct timespec ts = { .tv_sec = 0, .tv_nsec = 500000000 };
nanosleep(&ts, NULL);
}
tls_cleanup(&s);
tls_ctx_cleanup();
if (s.fd >= 0) close(s.fd);
db_close_cleanup();
sqlite_cleanup();
return 0;
}