From 476554d2cbd55dc142f0df47f4056ed664d040d0 Mon Sep 17 00:00:00 2001 From: hanez Date: Sun, 19 Jul 2026 01:29:22 +0200 Subject: [PATCH] v0.33.1: fix hot reload re-registration, add !hello, comprehensive docs - Fixed hot reload: after TLS session restore, the bot now does a fresh IRC connection and re-sends PASS/NICK/USER to re-register with the server, fixing the issue where channels were never re-joined after !reload or !restart. - Removed ZYNK_RESTORE_FD env var approach; reload_try_restore now restores settings and returns 1 to trigger a fresh connect. - Added !hello command for casual greeting. - Added atomic build rule in Makefile (compile to .tmp, then mv). - Added comprehensive function-level documentation across the entire codebase (~80 new doc comments). --- AGENTS.md | 1 + CHANGELOG.md | 16 + Makefile | 5 +- zynk.c | 1116 ++++++++++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 1093 insertions(+), 45 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 08a697c..23c4a37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,6 +75,7 @@ zynk/ | `zynk ` | Look up a stored value | | `zynk = ` | Store a value | | `!ping` | Responds with pong | +| `!hello` | Responds with hello and the user's name | | `!weather [city]` | Current weather (default: Berlin) | | `!forecast [city]` | 3-day forecast | | `!ai ` | Ask the AI a question | diff --git a/CHANGELOG.md b/CHANGELOG.md index 979c403..0be2b10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ +2026.07.19 – Hot reload re-registration fix. + +- Fixed hot reload: after TLS session restore, the bot now re-sends PASS/NICK/USER to re-register with the IRC server, fixing the issue where channels were never re-joined after `!reload` or `!restart`. +- Version bumped to 0.33.1. + +2026.07.19 – Hot reload, stock quotes, and auto-recompile. + +- Added hot reload: `!reload` and `!restart` commands (ops) save TLS session state, fork a new process with the inherited socket, and resume without dropping from IRC. +- Added `!stock [,SYMBOL...]` command to fetch real-time stock quotes from Yahoo Finance (up to 3 symbols). +- Added auto-compile and restart on `!code` changes: when the AI code change response is received, the bot runs `make` and reloads on success. +- Added User-Agent header to curl requests to avoid being blocked by servers that reject the default curl agent. +- Increased curl read buffer from 2 KiB to 32 KiB to handle larger API responses. +- Improved `!forecast` JSON parsing: returns a descriptive error message on parse failure instead of silently returning nothing. +- Increased AI_TIMEOUT from 240s to 600s and AI_REPLY_MAX from 400 to 2048 chars for longer AI interactions. +- Version bumped to 0.33.0. + 2026.07.16 – Security hardening. - Fixed buffer overflow in ai_child_task: plen unsigned underflow when history entries exceed prefix buffer size, causing out-of-bounds writes via snprintf. diff --git a/Makefile b/Makefile index 9ac2953..abe5edc 100644 --- a/Makefile +++ b/Makefile @@ -16,6 +16,10 @@ endif all: zynk +zynk: zynk.c + $(CC) $(CFLAGS) $(LDFLAGS) -o $@.tmp $< $(LDLIBS) + mv -f $@.tmp $@ + calc: zynk.c $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $< $(LDLIBS) @@ -28,4 +32,3 @@ install: calc uninstall: rm -vf $(DESTDIR)$(BINDIR)/zynk - diff --git a/zynk.c b/zynk.c index c86709b..ba2c8bc 100644 --- a/zynk.c +++ b/zynk.c @@ -29,7 +29,7 @@ int asprintf(char **, const char *, ...); /* ---- constants ---- */ -#define VERSION "0.33.0" +#define VERSION "0.33.1" #define DEFAULT_SERVER "irc.libera.chat" #define OPENCODE_BIN "/usr/bin/opencode" #define CLR_RESET "\033[0m" @@ -79,6 +79,16 @@ 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); @@ -125,6 +135,21 @@ typedef struct { void *ptr; } sqlite3; 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", @@ -166,6 +191,19 @@ static int sqlite_init_lib(void) { 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) { @@ -199,11 +237,42 @@ static int db_init(void) { 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)" @@ -219,6 +288,19 @@ static int db_set(const char *key, const char *value, const char *nick) { 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=?"; @@ -231,6 +313,19 @@ static char *db_get_raw(const char *key) { 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=?"; @@ -246,6 +341,17 @@ static char *db_get(const char *key) { 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" @@ -263,7 +369,21 @@ static char *db_get_random(void) { return r; } -/* Rotate recent history entries (prefix = "lastq" or "lasta") */ +/* + * 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]; @@ -300,6 +420,22 @@ static void db_rotate_history(const char *prefix, const char *value) { /* ---- 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')"; @@ -318,6 +454,18 @@ static int ai_start(const char *question, const char *target, const char *nick, 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=?"; @@ -330,6 +478,19 @@ static char *ai_get_question(long long id) { 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; @@ -341,6 +502,20 @@ static int ai_set_answer(long long id, const char *answer) { 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'"; @@ -355,6 +530,18 @@ static char *ai_get_answer(long long id) { 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=?"; @@ -367,6 +554,17 @@ static char *ai_get_nick(long long id) { 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; @@ -382,12 +580,37 @@ typedef struct { char name[64]; char ops[MAX_CHAN_OPS][32]; int nops; } ChanEntr 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) { @@ -398,6 +621,19 @@ static ChanEntry *chan_get_or_add(const char *name) { 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; @@ -406,6 +642,19 @@ static int chan_is_op(const char *name, const char *nick) { 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; @@ -417,6 +666,19 @@ static void chan_add_op(const char *name, const char *nick) { } } +/* + * 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; @@ -429,6 +691,19 @@ static void chan_del_op(const char *name, const char *nick) { } } +/* + * 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++) { @@ -442,6 +717,20 @@ static void chan_rename_op(const char *oldnick, const char *newnick) { /* ---- 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); @@ -463,6 +752,22 @@ static int net_connect(const char *host, int port) { 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); @@ -476,6 +781,20 @@ static int net_read(Session *s, char *buf, int size) { 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); @@ -487,6 +806,22 @@ static int net_write(Session *s, const char *buf, int size) { 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; @@ -514,6 +849,16 @@ static int net_send(Session *s, const char *fmt, ...) { 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(); @@ -524,6 +869,20 @@ static int tls_init(void) { 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); @@ -542,6 +901,18 @@ static int tls_handshake(Session *s) { 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); @@ -549,6 +920,14 @@ static void tls_cleanup(Session *s) { 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); @@ -560,6 +939,19 @@ static void tls_ctx_cleanup(void) { #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); @@ -567,6 +959,20 @@ static int reload_read_line(FILE *f, char *buf, size_t sz) { 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); @@ -590,6 +996,18 @@ static int reload_save(Session *s) { 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; @@ -628,41 +1046,32 @@ static int reload_try_restore(Session *s) { snprintf(s->auto_join, sizeof s->auto_join, "%s", auto_join); s->use_tls = use_tls_f; tls_verify = tls_verify_f; - if (!use_tls_f) { free(sbuf); return -1; } - if (tls_init() < 0) { free(sbuf); return -1; } - s->ssl = SSL_new(tls_ctx); - if (!s->ssl) { free(sbuf); return -1; } - const unsigned char *sp = sbuf; - SSL_SESSION *sess = d2i_SSL_SESSION(NULL, &sp, slen); free(sbuf); - if (!sess) { SSL_free(s->ssl); s->ssl = NULL; 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); - SSL_set_session(s->ssl, sess); - SSL_SESSION_free(sess); - int fl = fcntl(s->fd, F_GETFL, 0); - fcntl(s->fd, F_SETFL, fl & ~O_NONBLOCK); - int r = SSL_do_handshake(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; - } - s->connected = 1; 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 "TLS session resumed for %s:%d" CLR_RESET "\n", s->host, s->port); - return 0; + 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]) @@ -670,6 +1079,21 @@ static void irc_part_all(Session *s) { } } +/* + * 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"); @@ -688,7 +1112,6 @@ static void reload_do(Session *s, const char *reply_target) { net_send(s, "QUIT :restarting\r\n"); struct timespec ts_quit = { .tv_sec = 0, .tv_nsec = 500000000 }; nanosleep(&ts_quit, NULL); - fcntl(s->fd, F_SETFL, old_fl & ~O_CLOEXEC); pid_t pid = fork(); if (pid < 0) { unlink(ZYNK_RELOAD_FILE); @@ -696,12 +1119,15 @@ static void reload_do(Session *s, const char *reply_target) { return; } if (pid == 0) { - char fdstr[16]; - snprintf(fdstr, sizeof fdstr, "%d", s->fd); - setenv("ZYNK_RESTORE_FD", fdstr, 1); + close(s->fd); char self[4096]; ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1); - if (n > 0) { self[n] = 0; execl(self, "zynk", NULL); } + if (n > 0) { + self[n] = 0; + char *deleted = strstr(self, " (deleted)"); + if (deleted) *deleted = 0; + execl(self, "zynk", NULL); + } _exit(1); } _exit(0); @@ -710,12 +1136,38 @@ static void reload_do(Session *s, const char *reply_target) { /* ---- signal handling ---- */ static volatile sig_atomic_t running = 1; + +/* + * 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; @@ -736,6 +1188,20 @@ static int rate_limit_check(const char *nick) { /* ---- 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", @@ -768,6 +1234,21 @@ static void strip_ai_phrases(char *s) { *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; @@ -832,10 +1313,33 @@ static void strip_formatting(char *s) { *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++) @@ -881,6 +1385,21 @@ static void normalize_city(const char *in, char *display, size_t dsz, char *url, /* ---- 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; @@ -914,8 +1433,36 @@ static char *run_curl(const char *url) { 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); @@ -977,6 +1524,25 @@ 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); @@ -1083,6 +1649,26 @@ static void ai_child_task(Session *s, long long id, const char *agent) { 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) { @@ -1103,6 +1689,20 @@ static void ai_ask(Session *s, const char *question, const char *reply_target, c 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"); @@ -1133,6 +1733,23 @@ static int try_compile_and_restart(Session *s, const char *target) { } } +/* + * 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; @@ -1207,6 +1824,18 @@ static void ai_check_completion(Session *s) { /* ---- 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) { @@ -1219,6 +1848,22 @@ static void irc_join(Session *s, const char *chan) { 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) { @@ -1244,6 +1889,19 @@ static void irc_msg(Session *s, const char *t, const char *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) { @@ -1255,6 +1913,19 @@ static void irc_nick(Session *s, const char *nn) { 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; @@ -1272,6 +1943,24 @@ static void irc_pong(Session *s, const char *r) { /* ---- IRC command handlers ---- */ +/* + * cmd_zynk - Handle the "zynk" key-value store command. + * + * Processes three forms: bare "zynk" (returns random entry), + * "zynk " (looks up value), and "zynk = " (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; @@ -1355,6 +2044,14 @@ static int cmd_zynk(Session *s, const char *msg, const char *reply_target, const return 1; } +/* + * cmd_ping - Handle the "!ping" command. + * + * Responds with ": 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; @@ -1365,6 +2062,24 @@ static int cmd_ping(Session *s, const char *msg, const char *reply_target, const return 1; } +static int cmd_hello(Session *s, const char *msg, const char *reply_target, const char *src_nick) { + if (strncmp(msg, "!hello", 6) != 0) return 0; + if (msg[6] != ' ' && msg[6] != '\0') return 0; + if (rate_limit_check(src_nick) < 0) return 1; + char buf[96]; snprintf(buf, sizeof buf, "hello, %s!", src_nick); + irc_msg(s, reply_target, buf); + log_stamp(); fprintf(stderr, CLR_YELLOW "HELLO from %s in %s" CLR_RESET "\n", src_nick, reply_target); + return 1; +} + +/* + * cmd_version - Handle the "!version" command. + * + * Responds with "zynk " 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; @@ -1375,18 +2090,36 @@ static int cmd_version(Session *s, const char *msg, const char *reply_target, co 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, !weather [city], !forecast [city], !stock [,SYMBOL...], !ai , !code (ops), !reload (ops), !restart (ops), !quit/!die (ops)"); + "Commands: !help, !version, !ping, !hello, !weather [city], !forecast [city], !stock [,SYMBOL...], !ai , !code (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)) { @@ -1398,6 +2131,15 @@ static int cmd_quit(Session *s, const char *msg, const char *reply_target, const 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; @@ -1423,6 +2165,15 @@ static int cmd_weather(Session *s, const char *msg, const char *reply_target, co 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; @@ -1444,6 +2195,21 @@ static int cmd_forecast(Session *s, const char *msg, const char *reply_target, c 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; @@ -1454,6 +2220,17 @@ static const char *json_find(const char *haystack, const char *key) { return p; } +/* + * cmd_stock - Handle the "!stock [,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; @@ -1533,6 +2310,15 @@ static int cmd_stock(Session *s, const char *msg, const char *reply_target, cons return 1; } +/* + * cmd_ai - Handle the "!ai " 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; @@ -1551,6 +2337,18 @@ static int cmd_ai(Session *s, const char *msg, const char *reply_target, const c return 1; } +/* + * cmd_code - Handle the "!code " 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; @@ -1579,6 +2377,15 @@ static int cmd_code(Session *s, const char *msg, const char *reply_target, const 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_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)) { @@ -1590,6 +2397,14 @@ static int cmd_reload(Session *s, const char *msg, const char *reply_target, con 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)) { @@ -1602,6 +2417,24 @@ static int cmd_restart(Session *s, const char *msg, const char *reply_target, co 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; @@ -1641,6 +2474,23 @@ static void cmd_greeting_or_chat(Session *s, const char *msg, const char *reply_ /* ---- 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; @@ -1655,6 +2505,7 @@ static void handle_privmsg(Session *s, const char *params, const char *src_nick) 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_hello(s, msg, reply_target, src_nick)) return; if (cmd_version(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; @@ -1668,6 +2519,21 @@ static void handle_privmsg(Session *s, const char *params, const char *src_nick) 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]; @@ -1696,6 +2562,19 @@ static void handle_namreply(Session *s, const char *params) { } } +/* + * 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]; @@ -1708,6 +2587,19 @@ static void handle_mode(Session *s, const char *params) { } } +/* + * 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; @@ -1717,23 +2609,74 @@ static void handle_join(Session *s, const char *params) { 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, '!'); @@ -1750,6 +2693,21 @@ static void handle_nick_change(Session *s, const char *prefix, const char *param } } +/* + * 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; @@ -1772,6 +2730,23 @@ static void handle_error_codes(Session *s, const char *cmd_buf, const char *para /* ---- 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; @@ -1858,6 +2833,22 @@ static void irc_handle(Session *s, const char *raw) { /* ---- 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]; @@ -1874,6 +2865,19 @@ static void irc_feed(Session *s, const char *data, int len) { /* ---- 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" @@ -1894,6 +2898,21 @@ static void usage(const char *prog) { /* ---- 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); @@ -1930,6 +2949,26 @@ static int net_reconnect(Session *s) { /* ---- 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; @@ -2018,24 +3057,13 @@ int main(int argc, char **argv) { snprintf(s.real, sizeof s.real, "zynk"); snprintf(s.auto_join, sizeof s.auto_join, "%s", joinbuf); s.fd = -1; - const char *restore_fd_env = getenv("ZYNK_RESTORE_FD"); - if (restore_fd_env) { - s.fd = atoi(restore_fd_env); - unsetenv("ZYNK_RESTORE_FD"); - } 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); - int reloaded = 0; - if (use_tls) { - reloaded = (reload_try_restore(&s) == 0); - if (reloaded) { - log_stamp(); fprintf(stderr, CLR_GREEN "Hot reload: TLS session resumed" CLR_RESET "\n"); - } - } - if (!reloaded) { + 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();