2026-07-14 22:37:37 +02:00
/*
* Copyright ( c ) armin , hanez
*
* Licensed under the terms of the MIT License .
*/
2026-06-07 01:50:05 +02:00
# 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 <dlfcn.h>
# include <sys/wait.h>
# include <openssl/ssl.h>
# include <openssl/err.h>
2026-06-29 16:57:31 +02:00
int asprintf ( char * * , const char * , . . . ) ;
2026-06-29 17:31:17 +02:00
/* ---- constants ---- */
2026-07-21 14:08:53 +02:00
# define VERSION "0.38.2"
2026-06-07 01:50:05 +02:00
# define DEFAULT_SERVER "irc.libera.chat"
2026-07-15 21:19:28 +02:00
# 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"
2026-06-29 17:31:17 +02:00
enum {
RBUF_SZ = 16384 ,
DEF_PORT = 6697 ,
POLL_MS = 100 ,
2026-07-18 23:26:57 +02:00
AI_TIMEOUT = 600 ,
2026-06-29 17:31:17 +02:00
MAX_CHANS = 32 ,
MAX_CHAN_OPS = 64 ,
2026-07-14 21:44:07 +02:00
RATE_LIMIT_WINDOW = 10 ,
2026-06-29 17:31:17 +02:00
RATE_LIMIT_MAX = 8 ,
2026-07-14 21:53:14 +02:00
MAX_HISTORY = 100 ,
2026-07-21 14:08:53 +02:00
GITLOG_COUNT = 1 ,
GITLOG_MAX = 5 ,
CHANGELOG_COUNT = 1 ,
2026-07-21 02:44:54 +02:00
CHANGELOG_MAX = 10 ,
2026-06-29 17:31:17 +02:00
} ;
/* ---- 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 ;
2026-07-19 00:14:30 +02:00
int code_restart ;
2026-06-29 17:31:17 +02:00
} Session ;
/* ---- forward declarations ---- */
static void irc_msg ( Session * , const char * , const char * ) ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
static void seen_update ( const char * , const char * , const char * ) ;
static void tell_deliver ( Session * , const char * , const char * ) ;
2026-06-29 17:31:17 +02:00
/* ---- logging ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 ) .
*/
2026-06-07 01:50:05 +02:00
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 ) ;
}
2026-06-29 17:31:17 +02:00
/* ---- SQLite3 dynamic loading ---- */
2026-06-07 01:50:05 +02:00
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 * ) ;
2026-07-15 19:49:37 +02:00
static int ( * db_bind_int64 ) ( void * , int , long long ) ;
static long long ( * db_last_rowid ) ( void * ) ;
2026-06-29 17:31:17 +02:00
2026-06-07 01:50:05 +02:00
# define LOAD_FUNC(var, name) do { \
union { void * p ; typeof ( var ) f ; } _u ; \
_u . p = dlsym ( sqlite_lib , name ) ; \
var = _u . f ; \
} while ( 0 )
2026-06-29 17:31:17 +02:00
2026-06-07 01:50:05 +02:00
# 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 ;
2026-07-15 19:49:37 +02:00
static void db_close_cleanup ( void ) ;
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 ) .
*/
2026-06-07 01:50:05 +02:00
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 " ) ;
2026-07-15 19:49:37 +02:00
LOAD_FUNC ( db_bind_int64 , " sqlite3_bind_int64 " ) ;
LOAD_FUNC ( db_last_rowid , " sqlite3_last_insert_rowid " ) ;
2026-06-07 01:50:05 +02:00
if ( ! db_open | | ! db_exec | | ! db_close | | ! db_prepare | |
2026-07-15 19:49:37 +02:00
! db_bind_text | | ! db_step | | ! db_finalize | | ! db_column_text | |
! db_free | | ! db_bind_int64 | | ! db_last_rowid ) {
dlclose ( sqlite_lib ) ;
sqlite_lib = NULL ;
2026-06-07 01:50:05 +02:00
return - 1 ;
2026-07-15 19:49:37 +02:00
}
2026-06-07 01:50:05 +02:00
return 0 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
static int db_init ( void ) {
if ( sqlite_init_lib ( ) < 0 ) { fprintf ( stderr , CLR_RED " Cannot load libsqlite3 " CLR_RESET " \n " ) ; return - 1 ; }
2026-07-14 23:52:56 +02:00
if ( db_open ( " zynk.db " , & db_handle ) ! = SQLITE_OK ) {
2026-07-15 19:49:37 +02:00
fprintf ( stderr , CLR_RED " DB open failed " CLR_RESET " \n " ) ;
if ( db_handle ) { db_close ( DB ) ; db_handle = NULL ; }
return - 1 ;
2026-06-07 01:50:05 +02:00
}
2026-07-14 23:52:56 +02:00
const char * sql_zynk = " CREATE TABLE IF NOT EXISTS zynk ( "
2026-06-07 01:50:05 +02:00
" key TEXT PRIMARY KEY, value TEXT NOT NULL, "
" nick TEXT NOT NULL, updated_at TEXT DEFAULT (datetime('now'))) " ;
char * err = NULL ;
2026-07-14 23:52:56 +02:00
if ( db_exec ( DB , sql_zynk , NULL , NULL , & err ) ! = SQLITE_OK ) {
2026-07-15 19:49:37 +02:00
fprintf ( stderr , CLR_RED " SQL: %s " CLR_RESET " \n " , err ? err : " unknown error " ) ;
if ( err ) db_free ( err ) ;
db_close_cleanup ( ) ;
return - 1 ;
2026-06-07 01:50:05 +02:00
}
const char * sql_ai = " CREATE TABLE IF NOT EXISTS ai_pending ( "
2026-06-29 18:38:05 +02:00
" id INTEGER PRIMARY KEY, question TEXT, "
2026-06-07 01:50:05 +02:00
" answer TEXT, target TEXT, nick TEXT, status TEXT DEFAULT 'idle') " ;
if ( db_exec ( DB , sql_ai , NULL , NULL , & err ) ! = SQLITE_OK ) {
2026-07-15 19:49:37 +02:00
fprintf ( stderr , CLR_RED " SQL: %s " CLR_RESET " \n " , err ? err : " unknown error " ) ;
if ( err ) db_free ( err ) ;
db_close_cleanup ( ) ;
return - 1 ;
2026-06-07 01:50:05 +02:00
}
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
const char * sql_seen = " CREATE TABLE IF NOT EXISTS seen ( "
" nick TEXT PRIMARY KEY, last_seen TEXT, last_channel TEXT, last_action TEXT) " ;
db_exec ( DB , sql_seen , NULL , NULL , NULL ) ;
const char * sql_tell = " CREATE TABLE IF NOT EXISTS tell ( "
" id INTEGER PRIMARY KEY, from_nick TEXT, to_nick TEXT, "
" message TEXT, created_at TEXT DEFAULT (datetime('now'))) " ;
db_exec ( DB , sql_tell , NULL , NULL , NULL ) ;
2026-06-29 18:38:05 +02:00
const char * sql_clear_ai = " DELETE FROM ai_pending " ;
db_exec ( DB , sql_clear_ai , NULL , NULL , NULL ) ;
2026-07-14 23:52:56 +02:00
const char * sql_clear = " DELETE FROM zynk WHERE key LIKE 'lastq%' OR key LIKE 'lasta%' " ;
2026-06-21 03:20:11 +02:00
db_exec ( DB , sql_clear , NULL , NULL , NULL ) ;
2026-06-07 01:50:05 +02:00
return 0 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
static void db_close_cleanup ( void ) { if ( db_handle ) { db_close ( DB ) ; db_handle = NULL ; } }
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-15 19:49:37 +02:00
static void sqlite_cleanup ( void ) { if ( sqlite_lib ) { dlclose ( sqlite_lib ) ; sqlite_lib = NULL ; } }
2026-06-29 17:31:17 +02:00
/* ---- DB key-value operations ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
static int db_set ( const char * key , const char * value , const char * nick ) {
void * stmt ;
2026-07-14 23:52:56 +02:00
const char * sql = " INSERT INTO zynk(key,value,nick,updated_at) "
2026-06-07 01:50:05 +02:00
" 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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
static char * db_get_raw ( const char * key ) {
void * stmt ;
2026-07-14 23:52:56 +02:00
const char * sql = " SELECT value FROM zynk WHERE key=? " ;
2026-06-07 01:50:05 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
static char * db_get ( const char * key ) {
2026-06-07 01:50:05 +02:00
void * stmt ;
2026-07-14 23:52:56 +02:00
const char * sql = " SELECT value,nick,updated_at FROM zynk WHERE key=? " ;
2026-06-29 17:31:17 +02:00
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 ;
2026-06-07 01:50:05 +02:00
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-21 03:20:11 +02:00
static char * db_get_random ( void ) {
void * stmt ;
2026-07-14 23:52:56 +02:00
const char * sql = " SELECT key,value,nick,updated_at FROM zynk "
2026-06-21 03:20:11 +02:00
" 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 ;
2026-06-29 16:57:31 +02:00
if ( asprintf ( & r , " %s = %s (by %s on %s) " , k , v , n , t ) < 0 ) r = NULL ;
2026-06-21 03:20:11 +02:00
db_finalize ( stmt ) ;
return r ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
static void db_rotate_history ( const char * prefix , const char * value ) {
2026-07-14 21:44:07 +02:00
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 ] ) ;
}
2026-06-07 01:50:05 +02:00
void * stmt ;
2026-07-14 23:52:56 +02:00
const char * sql = " INSERT INTO zynk(key,value,nick,updated_at) "
2026-06-29 17:31:17 +02:00
" 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 ) {
2026-07-14 21:44:07 +02:00
db_bind_text ( stmt , 1 , kbuf [ 0 ] , - 1 , SQLITE_STATIC ) ;
2026-06-29 17:31:17 +02:00
db_bind_text ( stmt , 2 , value , - 1 , SQLITE_STATIC ) ;
db_bind_text ( stmt , 3 , " " , - 1 , SQLITE_STATIC ) ;
db_step ( stmt ) ;
db_finalize ( stmt ) ;
}
2026-07-14 21:44:07 +02:00
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 ) ;
}
2026-06-29 17:31:17 +02:00
}
2026-07-14 21:44:07 +02:00
for ( int i = 0 ; i < MAX_HISTORY ; i + + ) free ( old [ i ] ) ;
2026-06-07 01:50:05 +02:00
}
2026-06-29 17:31:17 +02:00
# define db_update_lastq(v) db_rotate_history("lastq", v)
# define db_update_lasta(v) db_rotate_history("lasta", v)
/* ---- DB AI pending operations ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 18:38:05 +02:00
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') " ;
2026-06-07 01:50:05 +02:00
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 ) ;
2026-06-29 18:38:05 +02:00
if ( rc = = SQLITE_DONE ) {
2026-07-15 19:49:37 +02:00
* out_id = db_last_rowid ( db_handle ) ;
2026-06-29 18:38:05 +02:00
return 0 ;
}
return - 1 ;
2026-06-07 01:50:05 +02:00
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 18:38:05 +02:00
static char * ai_get_question ( long long id ) {
2026-06-07 01:50:05 +02:00
void * stmt ;
2026-06-29 18:38:05 +02:00
const char * sql = " SELECT question FROM ai_pending WHERE id=? " ;
2026-06-07 01:50:05 +02:00
if ( db_prepare ( DB , sql , - 1 , & stmt , NULL ) ! = SQLITE_OK ) return NULL ;
2026-07-15 19:49:37 +02:00
db_bind_int64 ( stmt , 1 , id ) ;
2026-06-07 01:50:05 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 18:38:05 +02:00
static int ai_set_answer ( long long id , const char * answer ) {
const char * sql = " UPDATE ai_pending SET answer=?, status='done' WHERE id=? " ;
2026-06-07 01:50:05 +02:00
void * stmt ;
if ( db_prepare ( DB , sql , - 1 , & stmt , NULL ) ! = SQLITE_OK ) return - 1 ;
db_bind_text ( stmt , 1 , answer , - 1 , SQLITE_STATIC ) ;
2026-07-15 19:49:37 +02:00
db_bind_int64 ( stmt , 2 , id ) ;
2026-06-07 01:50:05 +02:00
int rc = db_step ( stmt ) ;
db_finalize ( stmt ) ;
return rc = = SQLITE_DONE ? 0 : - 1 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 \x1f target " , or NULL if the
* query is not yet done or not found . Caller must free ( ) the result .
*/
2026-06-29 18:38:05 +02:00
static char * ai_get_answer ( long long id ) {
2026-06-07 01:50:05 +02:00
void * stmt ;
2026-06-29 18:38:05 +02:00
const char * sql = " SELECT answer,target FROM ai_pending WHERE id=? AND status='done' " ;
2026-06-07 01:50:05 +02:00
if ( db_prepare ( DB , sql , - 1 , & stmt , NULL ) ! = SQLITE_OK ) return NULL ;
2026-07-15 19:49:37 +02:00
db_bind_int64 ( stmt , 1 , id ) ;
2026-06-07 01:50:05 +02:00
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 ;
2026-06-29 16:57:31 +02:00
if ( a & & t ) { if ( asprintf ( & r , " %s \037 %s " , a , t ) < 0 ) r = NULL ; }
2026-06-07 01:50:05 +02:00
db_finalize ( stmt ) ;
return r ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 18:38:05 +02:00
static char * ai_get_nick ( long long id ) {
2026-06-07 01:50:05 +02:00
void * stmt ;
2026-06-29 18:38:05 +02:00
const char * sql = " SELECT nick FROM ai_pending WHERE id=? " ;
2026-06-07 01:50:05 +02:00
if ( db_prepare ( DB , sql , - 1 , & stmt , NULL ) ! = SQLITE_OK ) return NULL ;
2026-07-15 19:49:37 +02:00
db_bind_int64 ( stmt , 1 , id ) ;
2026-06-07 01:50:05 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 18:38:05 +02:00
static void ai_reset ( long long id ) {
const char * sql = " DELETE FROM ai_pending WHERE id=? " ;
2026-06-07 01:50:05 +02:00
void * stmt ;
if ( db_prepare ( DB , sql , - 1 , & stmt , NULL ) ! = SQLITE_OK ) return ;
2026-07-15 19:49:37 +02:00
db_bind_int64 ( stmt , 1 , id ) ;
2026-06-07 01:50:05 +02:00
db_step ( stmt ) ;
db_finalize ( stmt ) ;
}
2026-06-29 17:31:17 +02:00
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
/* ---- DB seen/tell operations ---- */
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* seen_update - Record a nick ' s last - seen timestamp and context .
*
* Upserts a row in the seen table : inserts a new record if the nick has
* never been seen , or updates the existing record with the current UTC
* timestamp , channel , and action . Uses INSERT . . . ON CONFLICT DO UPDATE .
*
* Parameters :
* nick - The IRC nick to record .
* channel - The channel where the nick was seen ( or " " for DMs / QUIT ) .
* action - A short description of what the nick did ( e . g . " spoke " ,
* " joined " , " left " ) . Defaults to " spoke " if NULL .
*
* Returns : void .
*/
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
static void seen_update ( const char * nick , const char * channel , const char * action ) {
void * stmt ;
const char * sql = " INSERT INTO seen(nick,last_seen,last_channel,last_action) "
2026-07-20 22:24:21 +02:00
" VALUES(?,datetime('now','localtime'),?,?) "
" ON CONFLICT(nick) DO UPDATE SET last_seen=datetime('now','localtime'), "
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
" last_channel=excluded.last_channel, last_action=excluded.last_action " ;
if ( db_prepare ( DB , sql , - 1 , & stmt , NULL ) ! = SQLITE_OK ) return ;
db_bind_text ( stmt , 1 , nick , - 1 , SQLITE_STATIC ) ;
db_bind_text ( stmt , 2 , channel ? channel : " " , - 1 , SQLITE_STATIC ) ;
db_bind_text ( stmt , 3 , action ? action : " spoke " , - 1 , SQLITE_STATIC ) ;
db_step ( stmt ) ;
db_finalize ( stmt ) ;
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* seen_lookup - Retrieve last - seen info for a given nick .
*
* Queries the seen table for the most recent timestamp , channel , and
* action recorded for the given nick . Returns a human - readable string
* suitable for sending directly to IRC .
*
* Parameters :
* nick - The IRC nick to look up .
*
* Returns : A newly allocated string like " <nick> was last seen <action>
* < channel > < timestamp > " , or NULL if the nick was never seen.
* Caller must free ( ) the result .
*/
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
static char * seen_lookup ( const char * nick ) {
void * stmt ;
const char * sql = " SELECT last_seen, last_channel, last_action FROM seen WHERE nick=? " ;
if ( db_prepare ( DB , sql , - 1 , & stmt , NULL ) ! = SQLITE_OK ) return NULL ;
db_bind_text ( stmt , 1 , nick , - 1 , SQLITE_STATIC ) ;
if ( db_step ( stmt ) ! = SQLITE_ROW ) { db_finalize ( stmt ) ; return NULL ; }
const char * t = ( const char * ) db_column_text ( stmt , 0 ) ;
const char * c = ( const char * ) db_column_text ( stmt , 1 ) ;
const char * a = ( const char * ) db_column_text ( stmt , 2 ) ;
char * r = NULL ;
if ( asprintf ( & r , " %s was last seen %s %s %s " , nick , a ? a : " in " , c ? c : " ? " , t ? t : " unknown " ) < 0 ) r = NULL ;
db_finalize ( stmt ) ;
return r ;
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* tell_add - Queue a message for later delivery to a nick .
*
* Inserts a pending message into the tell table , recording the sender ,
* recipient , and message text . The message will be delivered the next
* time the recipient speaks ( via tell_deliver ) .
*
* Parameters :
* from - The IRC nick of the sender .
* to - The IRC nick of the intended recipient .
* msg - The message text to deliver .
*
* Returns : void .
*/
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
static void tell_add ( const char * from , const char * to , const char * msg ) {
void * stmt ;
const char * sql = " INSERT INTO tell(from_nick,to_nick,message) VALUES(?,?,?) " ;
if ( db_prepare ( DB , sql , - 1 , & stmt , NULL ) ! = SQLITE_OK ) return ;
db_bind_text ( stmt , 1 , from , - 1 , SQLITE_STATIC ) ;
db_bind_text ( stmt , 2 , to , - 1 , SQLITE_STATIC ) ;
db_bind_text ( stmt , 3 , msg , - 1 , SQLITE_STATIC ) ;
db_step ( stmt ) ;
db_finalize ( stmt ) ;
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* tell_deliver - Deliver all pending tell messages for a nick .
*
* Queries the tell table for all messages addressed to the given nick ,
* sends each one to the specified channel via irc_msg in the format
* " <nick>: message from <sender>: <text> " , and deletes each row after
* delivery . Messages are delivered in insertion order ( lowest ID first ) .
*
* Parameters :
* s - The IRC session .
* nick - The nick whose pending messages should be delivered .
* channel - The channel to send the delivery messages to .
*
* Returns : void .
*/
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
static void tell_deliver ( Session * s , const char * nick , const char * channel ) {
void * stmt ;
const char * sql = " SELECT id, from_nick, message FROM tell WHERE to_nick=? ORDER BY id ASC " ;
if ( db_prepare ( DB , sql , - 1 , & stmt , NULL ) ! = SQLITE_OK ) return ;
db_bind_text ( stmt , 1 , nick , - 1 , SQLITE_STATIC ) ;
while ( db_step ( stmt ) = = SQLITE_ROW ) {
long long id = 0 ;
const void * idcol = db_column_text ( stmt , 0 ) ;
if ( idcol ) id = atoll ( ( const char * ) idcol ) ;
const char * from = ( const char * ) db_column_text ( stmt , 1 ) ;
const char * msg = ( const char * ) db_column_text ( stmt , 2 ) ;
char buf [ 1024 ] ;
snprintf ( buf , sizeof buf , " %s: message from %s: %s " , nick , from ? from : " ? " , msg ? msg : " " ) ;
irc_msg ( s , channel , buf ) ;
char dsql [ 128 ] ;
snprintf ( dsql , sizeof dsql , " DELETE FROM tell WHERE id=%lld " , id ) ;
void * dstmt ;
if ( db_prepare ( DB , dsql , - 1 , & dstmt , NULL ) = = SQLITE_OK ) { db_step ( dstmt ) ; db_finalize ( dstmt ) ; }
}
db_finalize ( stmt ) ;
}
2026-06-21 03:20:11 +02:00
/* ---- channel op tracking ---- */
2026-06-29 17:31:17 +02:00
2026-06-21 03:20:11 +02:00
typedef struct { char name [ 64 ] ; char ops [ MAX_CHAN_OPS ] [ 32 ] ; int nops ; } ChanEntry ;
static ChanEntry chans [ MAX_CHANS ] ;
static int nchans ;
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-21 03:20:11 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-21 03:20:11 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-21 03:20:11 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-21 03:20:11 +02:00
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 + + ;
}
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-21 03:20:11 +02:00
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 ;
}
}
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-15 19:49:37 +02:00
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 ;
}
}
}
}
2026-06-29 17:31:17 +02:00
/* ---- network I/O ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 ) .
*/
2026-06-07 01:50:05 +02:00
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 ) ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
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 ) ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
static int net_send ( Session * s , const char * fmt , . . . ) {
2026-07-14 21:44:07 +02:00
char buf [ 4096 ] ;
2026-06-07 01:50:05 +02:00
va_list ap ;
va_start ( ap , fmt ) ;
int n = vsnprintf ( buf , sizeof buf , fmt , ap ) ;
va_end ( ap ) ;
if ( n < = 0 ) return 0 ;
2026-07-15 19:49:37 +02:00
if ( ( size_t ) n > = sizeof buf ) return - 1 ;
2026-06-07 01:50:05 +02:00
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 ;
}
2026-07-15 19:49:37 +02:00
if ( w = = 0 ) return - 1 ;
2026-06-07 01:50:05 +02:00
left - = w ; p + = w ;
}
return n ;
}
2026-06-29 17:31:17 +02:00
/* ---- TLS ---- */
2026-06-07 01:50:05 +02:00
static SSL_CTX * tls_ctx ;
static int tls_verify = 1 ;
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 ) .
*/
2026-06-07 01:50:05 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
static void tls_cleanup ( Session * s ) {
if ( ! s - > ssl ) return ;
SSL_shutdown ( s - > ssl ) ;
SSL_free ( s - > ssl ) ;
s - > ssl = NULL ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-15 19:49:37 +02:00
static void tls_ctx_cleanup ( void ) {
if ( tls_ctx ) {
SSL_CTX_free ( tls_ctx ) ;
tls_ctx = NULL ;
}
}
2026-07-19 00:14:30 +02:00
/* ---- hot reload ---- */
# define ZYNK_RELOAD_FILE " / tmp / zynk_reload"
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-19 00:14:30 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-19 00:14:30 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-19 00:14:30 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
log_stamp ( ) ; fprintf ( stderr , CLR_GREEN " Restart state restored for %s:%d " CLR_RESET " \n " , s - > host , s - > port ) ;
return 1 ;
2026-07-19 00:14:30 +02:00
fail :
fclose ( f ) ;
return - 1 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-19 00:14:30 +02:00
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 ) ;
}
}
2026-07-19 01:29:22 +02:00
/*
* 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 ) .
*/
2026-07-19 00:14:30 +02:00
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 ) {
2026-07-19 01:29:22 +02:00
close ( s - > fd ) ;
2026-07-19 00:14:30 +02:00
char self [ 4096 ] ;
ssize_t n = readlink ( " /proc/self/exe " , self , sizeof self - 1 ) ;
2026-07-19 01:29:22 +02:00
if ( n > 0 ) {
self [ n ] = 0 ;
char * deleted = strstr ( self , " (deleted) " ) ;
if ( deleted ) * deleted = 0 ;
execl ( self , " zynk " , NULL ) ;
}
2026-07-19 00:14:30 +02:00
_exit ( 1 ) ;
}
_exit ( 0 ) ;
}
2026-06-29 17:31:17 +02:00
/* ---- signal handling ---- */
2026-06-07 01:50:05 +02:00
static volatile sig_atomic_t running = 1 ;
2026-07-19 02:06:32 +02:00
static time_t start_time ;
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
static void handle_sigterm ( int sig ) { ( void ) sig ; running = 0 ; }
2026-06-29 17:31:17 +02:00
/* ---- rate limiting ---- */
2026-06-07 01:50:05 +02:00
static struct { char nick [ 32 ] ; time_t t ; } rate_limits [ RATE_LIMIT_MAX ] ;
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*
2026-07-21 03:16:19 +02:00
* Channel operators are exempt from rate limiting . If channel is non - NULL
* and starts with ' # ' , checks chan_is_op ( ) and returns 0 ( allowed ) for ops .
*
2026-07-19 01:29:22 +02:00
* Parameters :
2026-07-21 03:16:19 +02:00
* nick - The IRC nick to check .
* channel - The channel name ( or NULL for DMs ) . Ops in this channel
* are exempt from rate limiting .
2026-07-19 01:29:22 +02:00
*
* Returns : 0 if the command is allowed , - 1 if rate - limited .
*/
2026-07-21 03:16:19 +02:00
static int rate_limit_check ( const char * nick , const char * channel ) {
if ( channel & & channel [ 0 ] = = ' # ' & & chan_is_op ( channel , nick ) ) return 0 ;
2026-06-07 01:50:05 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
/* ---- text utilities ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
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 ;
2026-07-15 16:10:09 +02:00
src = start ; dst = start ;
while ( * src ) {
if ( * src = = ' ' & & * ( src + 1 ) = = ' ' ) { src + + ; continue ; }
* dst + + = * src + + ;
}
* dst = 0 ;
2026-06-07 01:50:05 +02:00
}
2026-06-29 17:31:17 +02:00
2026-07-20 00:53:17 +02:00
// This needs to be tested more.
/*static void strip_opencode_header(char *s) {
2026-07-20 00:19:27 +02:00
if ( ! s | | s [ 0 ] ! = ' > ' | | s [ 1 ] ! = ' ' ) return ;
char * sep = strstr ( s , " \xc2 \xb7 " ) ;
if ( ! sep ) sep = strstr ( s , " · " ) ;
if ( ! sep ) return ;
char * nl = strchr ( s , ' \n ' ) ;
if ( nl ) {
nl + + ;
memmove ( s , nl , strlen ( nl ) + 1 ) ;
} else {
s [ 0 ] = 0 ;
}
2026-07-20 00:53:17 +02:00
} */
2026-07-20 00:19:27 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-15 19:49:37 +02:00
static int has_crlf ( const char * s ) {
return s & & strpbrk ( s , " \r \n " ) ! = NULL ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-16 03:07:33 +02:00
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 ;
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* valid_irc_word - Check if a string is a single valid IRC word .
*
* A valid IRC word is non - NULL , non - empty , contains no CRLF characters ,
* and contains no spaces or tabs . Used to validate IRC nicknames ,
* channel names , and command arguments before database operations .
*
* Parameters :
* s - The string to validate .
*
* Returns : 1 if the string is a valid single word , 0 otherwise .
*/
2026-07-15 19:49:37 +02:00
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 ;
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* normalize_city - Normalize a user - provided city name for display and URLs .
*
* Produces two output forms : a display form with spaces , and a URL form
* with ' + ' replacing spaces . Strips non - alphanumeric characters except
* dots , commas , hyphens , and underscores . Collapses multiple spaces into
* single spaces . Defaults to " Berlin " if the input is empty or results
* in an empty string after sanitization .
*
* Parameters :
* in - The raw city name from the user .
* display - Output buffer for the display form ( e . g . " New York " ) .
* dsz - Size of the display buffer .
* url - Output buffer for the URL form ( e . g . " New+York " ) .
* usz - Size of the URL buffer .
*
* Returns : void .
*/
2026-07-15 19:49:37 +02:00
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 ;
}
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* collapse_spaces - Collapse runs of whitespace into single spaces .
*
* Modifies a string in place , replacing each run of one or more spaces
* with a single space . Leading and trailing spaces are also removed .
* No - op if the string is NULL or empty .
*
* Parameters :
* s - The string to modify in place .
*
* Returns : void .
*/
2026-07-19 19:54:36 +02:00
static void collapse_spaces ( char * s ) {
char * r = s , * w = s ;
int space = 0 ;
while ( * r ) {
if ( * r = = ' ' ) { if ( ! space ) * w + + = ' ' ; space = 1 ; }
else { * w + + = * r ; space = 0 ; }
r + + ;
}
* w = 0 ;
}
2026-06-29 17:31:17 +02:00
/* ---- curl helper ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 32 KB 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 .
*/
2026-06-29 16:57:51 +02:00
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 ) ; }
2026-07-19 16:47:49 +02:00
execlp ( " curl " , " curl " , " -s " , " --max-time " , " 10 " , " -A " , " zynk/ " VERSION , url , ( char * ) NULL ) ;
2026-06-29 16:57:51 +02:00
_exit ( 127 ) ;
2026-06-21 03:20:11 +02:00
}
2026-06-29 16:57:51 +02:00
close ( fd [ 1 ] ) ;
2026-07-18 23:26:57 +02:00
char buf [ 32768 ] , tmp [ 4096 ] ;
2026-06-07 01:50:05 +02:00
size_t len = 0 ;
2026-06-29 16:57:51 +02:00
ssize_t n ;
2026-07-15 19:49:37 +02:00
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 ;
}
}
2026-06-29 16:57:51 +02:00
close ( fd [ 0 ] ) ;
int status ;
waitpid ( pid , & status , 0 ) ;
2026-06-07 01:50:05 +02:00
buf [ len ] = 0 ;
2026-06-29 16:57:51 +02:00
return status = = 0 ? strdup ( buf ) : NULL ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
static char * fetch_url ( const char * url ) { return run_curl ( url ) ; }
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
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 ;
2026-07-18 23:26:57 +02:00
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 , ' [ ' ) ;
2026-06-07 01:50:05 +02:00
if ( ! p ) { free ( json ) ; return NULL ; }
2026-07-18 23:26:57 +02:00
p + + ;
2026-06-07 01:50:05 +02:00
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 ; } }
2026-07-18 23:26:57 +02:00
char * hb = strstr ( p , " \" hourly \" " ) ;
2026-06-07 01:50:05 +02:00
if ( hb & & hb < obj_end ) {
2026-07-18 23:26:57 +02:00
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 ; } }
}
2026-06-07 01:50:05 +02:00
}
struct tm tm = { 0 } ;
2026-07-19 18:39:30 +02:00
if ( strptime ( date , " %Y-%m-%d " , & tm ) ) { mktime ( & tm ) ; strftime ( fmt_date [ ndays ] , sizeof fmt_date [ ndays ] , " %a %d %b " , & tm ) ; }
2026-06-07 01:50:05 +02:00
else snprintf ( fmt_date [ ndays ] , sizeof fmt_date [ ndays ] , " %s " , date ) ;
2026-06-29 17:31:17 +02:00
snprintf ( line [ ndays ] , sizeof line [ ndays ] , " %s: %s \u00b0 C %s " , fmt_date [ ndays ] , temp , cond ) ;
2026-06-07 01:50:05 +02:00
ndays + + ;
p = ( char * ) obj_end ;
}
free ( json ) ;
if ( ! ndays ) return NULL ;
char * out = NULL ;
2026-06-29 16:57:31 +02:00
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 ; }
2026-07-19 19:54:36 +02:00
if ( out ) collapse_spaces ( out ) ;
2026-06-07 01:50:05 +02:00
return out ;
}
2026-06-29 17:31:17 +02:00
/* ---- AI pipeline ---- */
2026-06-29 18:38:05 +02:00
static volatile pid_t pending_ai_pid ;
static volatile long long pending_ai_id ;
2026-07-15 21:19:28 +02:00
static const char * g_opencode_bin = OPENCODE_BIN ;
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 6 KB 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 ) ) .
*/
2026-07-15 19:49:37 +02:00
static void ai_child_task ( Session * s , long long id , const char * agent ) {
2026-06-29 17:31:17 +02:00
signal ( SIGALRM , SIG_DFL ) ;
2026-07-14 22:07:18 +02:00
alarm ( AI_TIMEOUT ) ;
2026-06-29 17:31:17 +02:00
/* 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 ;
2026-07-14 23:52:56 +02:00
if ( db_open ( " zynk.db " , & db_handle ) ! = SQLITE_OK ) exit ( 1 ) ;
2026-06-29 18:38:05 +02:00
char * q = ai_get_question ( id ) ;
2026-06-29 17:31:17 +02:00
if ( ! q ) { db_close ( DB ) ; exit ( 1 ) ; }
2026-07-14 21:44:07 +02:00
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 ; } }
2026-06-29 17:31:17 +02:00
char prefix [ 2048 ] ;
2026-07-14 22:25:56 +02:00
int plen ;
2026-07-15 19:49:37 +02:00
if ( agent ) {
2026-07-14 22:25:56 +02:00
plen = snprintf ( prefix , sizeof prefix ,
2026-07-14 23:52:56 +02:00
" Your name is zynk. You are a coding assistant in a project. Execute code changes as requested. "
2026-07-14 22:25:56 +02:00
" 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 ,
2026-07-14 23:52:56 +02:00
" Your name is zynk. You are in plan mode - you can only answer questions and discuss code, "
2026-07-14 23:04:48 +02:00
" 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. "
2026-07-14 22:25:56 +02:00
" No disclaimers or AI-sounding phrases. No markdown/formatting. "
" Just answer directly. " ) ;
}
2026-07-14 21:44:07 +02:00
if ( have_history ) {
2026-07-16 03:43:00 +02:00
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 ;
2026-07-14 21:44:07 +02:00
for ( int i = 0 ; i < MAX_HISTORY ; i + + ) {
2026-07-16 03:43:00 +02:00
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 ;
}
2026-07-14 21:44:07 +02:00
}
2026-06-29 17:31:17 +02:00
}
2026-07-14 21:44:07 +02:00
for ( int i = 0 ; i < MAX_HISTORY ; i + + ) free ( history [ i ] ) ;
2026-06-29 18:38:05 +02:00
char combined [ 8192 ] ;
2026-06-29 17:31:17 +02:00
snprintf ( combined , sizeof combined , " %s%s " , prefix , q ? q : " " ) ;
free ( q ) ;
int ai_pipe [ 2 ] ;
2026-06-29 18:38:05 +02:00
if ( pipe ( ai_pipe ) < 0 ) { ai_set_answer ( id , " AI query failed (pipe error) " ) ; db_close ( DB ) ; exit ( 0 ) ; }
2026-06-29 17:31:17 +02:00
pid_t cmd_pid = fork ( ) ;
2026-06-29 18:38:05 +02:00
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 ) ; }
2026-06-29 17:31:17 +02:00
if ( cmd_pid = = 0 ) {
close ( ai_pipe [ 0 ] ) ;
dup2 ( ai_pipe [ 1 ] , STDOUT_FILENO ) ;
2026-07-19 23:01:55 +02:00
dup2 ( ai_pipe [ 1 ] , STDERR_FILENO ) ;
2026-06-29 17:31:17 +02:00
close ( ai_pipe [ 1 ] ) ;
2026-07-15 19:49:37 +02:00
if ( agent )
2026-07-15 21:19:28 +02:00
execl ( g_opencode_bin , " opencode " , " run " , " --dangerously-skip-permissions " , " --agent " , agent , combined , ( char * ) NULL ) ;
2026-07-14 22:25:56 +02:00
else
2026-07-15 21:19:28 +02:00
execl ( g_opencode_bin , " opencode " , " run " , " --dangerously-skip-permissions " , " --agent " , " plan " , combined , ( char * ) NULL ) ;
2026-06-29 17:31:17 +02:00
_exit ( 127 ) ;
}
close ( ai_pipe [ 1 ] ) ;
2026-07-15 19:49:37 +02:00
char out [ 6144 ] , tmp [ 1024 ] ;
2026-06-29 17:31:17 +02:00
size_t olen = 0 ;
ssize_t n ;
2026-07-15 19:49:37 +02:00
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 ;
}
}
2026-06-29 17:31:17 +02:00
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 ) {
2026-07-19 23:01:55 +02:00
char errmsg [ 4200 ] ;
strip_formatting ( out ) ;
if ( olen > 0 )
snprintf ( errmsg , sizeof errmsg , " AI error (exit %d): %.4000s " , rc , out ) ;
else
snprintf ( errmsg , sizeof errmsg , " AI error (exit %d, no output) " , rc ) ;
ai_set_answer ( id , errmsg ) ;
2026-06-29 17:31:17 +02:00
} else if ( olen = = 0 ) {
2026-06-29 18:38:05 +02:00
ai_set_answer ( id , " AI returned an empty response " ) ;
2026-06-29 17:31:17 +02:00
} else {
2026-07-20 00:53:17 +02:00
// Needs more testing.
//strip_opencode_header(out);
2026-06-29 17:31:17 +02:00
strip_formatting ( out ) ;
strip_ai_phrases ( out ) ;
2026-06-29 18:38:05 +02:00
ai_set_answer ( id , out ) ;
2026-06-29 17:31:17 +02:00
db_update_lasta ( out ) ;
}
db_close ( DB ) ;
exit ( 0 ) ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-14 22:25:56 +02:00
static void ai_ask ( Session * s , const char * question , const char * reply_target , const char * src_nick , const char * agent ) {
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return ;
2026-06-29 17:31:17 +02:00
if ( pending_ai_pid > 0 ) {
irc_msg ( s , reply_target , " Already processing an AI query, please wait. " ) ;
return ;
}
db_update_lastq ( question ) ;
2026-06-29 18:38:05 +02:00
long long id = 0 ;
if ( ai_start ( question , reply_target , src_nick , & id ) ! = 0 ) {
2026-06-29 17:31:17 +02:00
irc_msg ( s , reply_target , " Error starting AI query " ) ;
return ;
}
pid_t pid = fork ( ) ;
2026-06-29 18:38:05 +02:00
if ( pid = = - 1 ) { ai_reset ( id ) ; irc_msg ( s , reply_target , " Error forking " ) ; return ; }
2026-07-15 19:49:37 +02:00
if ( pid = = 0 ) { ai_child_task ( s , id , agent ) ; }
2026-06-29 17:31:17 +02:00
pending_ai_pid = pid ;
2026-06-29 18:38:05 +02:00
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 ) ;
2026-06-29 17:31:17 +02:00
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-19 00:14:30 +02:00
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 ;
}
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
static void ai_check_completion ( Session * s ) {
if ( pending_ai_pid < = 0 ) return ;
int wstatus ;
pid_t done_pid = pending_ai_pid ;
2026-06-29 18:38:05 +02:00
long long done_id = pending_ai_id ;
2026-06-29 17:31:17 +02:00
if ( waitpid ( pending_ai_pid , & wstatus , WNOHANG ) < = 0 ) return ;
pending_ai_pid = 0 ;
2026-06-29 18:38:05 +02:00
char * nick = ai_get_nick ( done_id ) ;
char * result = ai_get_answer ( done_id ) ;
2026-07-19 00:14:30 +02:00
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 ) ;
2026-06-29 17:31:17 +02:00
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 ) ;
2026-07-14 21:44:07 +02:00
# 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 ;
2026-06-29 17:31:17 +02:00
}
2026-07-14 21:44:07 +02:00
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 + + ;
2026-06-29 17:31:17 +02:00
}
2026-07-14 21:44:07 +02:00
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 ) ;
2026-07-19 00:14:30 +02:00
if ( is_code_change ) try_compile_and_restart ( s , target ) ;
2026-06-29 17:31:17 +02:00
}
free ( result ) ;
2026-06-29 18:38:05 +02:00
ai_reset ( done_id ) ;
2026-06-29 17:31:17 +02:00
} else {
2026-06-29 18:38:05 +02:00
char * target = NULL ;
void * stmt ;
if ( db_prepare ( DB , " SELECT target FROM ai_pending WHERE id=? " , - 1 , & stmt , NULL ) = = SQLITE_OK ) {
2026-07-15 19:49:37 +02:00
db_bind_int64 ( stmt , 1 , done_id ) ;
2026-06-29 18:38:05 +02:00
if ( db_step ( stmt ) = = SQLITE_ROW ) {
const char * t = ( const char * ) db_column_text ( stmt , 0 ) ;
if ( t ) target = strdup ( t ) ;
}
db_finalize ( stmt ) ;
}
2026-06-29 17:31:17 +02:00
if ( WIFSIGNALED ( wstatus ) & & WTERMSIG ( wstatus ) = = SIGALRM ) {
if ( target ) {
2026-07-15 19:49:37 +02:00
char msg [ 96 ] ;
snprintf ( msg , sizeof msg , " AI query timed out after %d seconds. " , AI_TIMEOUT ) ;
irc_msg ( s , target , msg ) ;
2026-06-29 17:31:17 +02:00
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 ) ;
}
2026-06-29 18:38:05 +02:00
free ( target ) ;
ai_reset ( done_id ) ;
2026-06-29 17:31:17 +02:00
}
free ( nick ) ;
}
/* ---- IRC protocol helpers ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-16 03:07:33 +02:00
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 ) ;
}
2026-06-29 17:31:17 +02:00
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
static void irc_msg ( Session * s , const char * t , const char * txt ) {
2026-07-16 03:07:33 +02:00
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 ;
}
2026-06-29 17:31:17 +02:00
}
2026-07-16 03:07:33 +02:00
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 ) ;
2026-07-16 03:43:00 +02:00
if ( ! clean ) return ;
for ( char * p = clean ; * p ; p + + ) if ( ( unsigned char ) * p < 0x20 | | ( unsigned char ) * p = = 0x7f ) * p = ' ' ;
send_txt = clean ;
2026-07-16 03:07:33 +02:00
}
if ( tb [ 0 ] ) net_send ( s , " PRIVMSG %s :%s \r \n " , tb , send_txt ) ;
2026-06-29 17:31:17 +02:00
free ( clean ) ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-16 03:07:33 +02:00
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 ) ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-16 03:07:33 +02:00
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 ) ;
}
2026-06-29 17:31:17 +02:00
/* ---- IRC command handlers ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-14 23:52:56 +02:00
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 ;
2026-06-29 17:31:17 +02:00
if ( msg [ 4 ] ! = ' \0 ' & & msg [ 4 ] ! = ' ' & & msg [ 4 ] ! = ' ! ' ) return 0 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-14 23:52:56 +02:00
/* zynk!foo without space after ! falls through to other commands */
2026-06-29 17:31:17 +02:00
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 ) ;
2026-07-14 23:52:56 +02:00
log_stamp ( ) ; fprintf ( stderr , CLR_MAGENTA " ZYNK %s from %s: " CLR_RESET " random %s \n " , reply_target , src_nick , rand ) ;
2026-06-29 17:31:17 +02:00
free ( rand ) ;
} else {
2026-07-14 23:52:56 +02:00
irc_msg ( s , reply_target , " No zynkss saved yet. " ) ;
2026-06-29 17:31:17 +02:00
}
return 1 ;
} else if ( msg [ 4 ] = = ' ! ' ) {
if ( msg [ 5 ] = = ' \0 ' ) {
2026-07-14 23:52:56 +02:00
irc_msg ( s , reply_target , " Usage: zynk! <key> = <value> " ) ;
2026-06-29 17:31:17 +02:00
return 1 ;
}
force = 1 ;
rest = msg + 6 ;
} else {
rest = msg + 5 ;
}
while ( * rest = = ' ' ) rest + + ;
if ( ! * rest ) {
2026-07-14 23:52:56 +02:00
irc_msg ( s , reply_target , " Usage: zynk <key> [= <value>] " ) ;
2026-06-29 17:31:17 +02:00
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 ) ;
2026-07-14 23:52:56 +02:00
snprintf ( resp , sizeof resp , " zynk already exists (use zynk! to overwrite) " ) ;
2026-06-29 17:31:17 +02:00
irc_msg ( s , reply_target , resp ) ;
2026-07-14 23:52:56 +02:00
log_stamp ( ) ; fprintf ( stderr , CLR_MAGENTA " ZYNK %s from %s: " CLR_RESET " blocked re-add of %s \n " , reply_target , src_nick , key ) ;
2026-06-29 17:31:17 +02:00
return 1 ;
}
} else {
if ( tgt [ 0 ] = = ' # ' & & ! chan_is_op ( tgt , src_nick ) ) {
2026-07-14 23:52:56 +02:00
irc_msg ( s , reply_target , " You need op to overwrite a zynk " ) ;
2026-06-29 17:31:17 +02:00
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 ) ;
2026-07-14 23:52:56 +02:00
log_stamp ( ) ; fprintf ( stderr , CLR_MAGENTA " ZYNK %s from %s: " CLR_RESET " %s \n " , reply_target , src_nick , resp ) ;
2026-06-29 17:31:17 +02:00
return 1 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-06-29 17:31:17 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* cmd_version - Handle the " !version " command .
*
* Responds with " zynk <VERSION> " to show the current bot version .
* Rate - limited .
*
* Returns : 1 if matched , 0 otherwise .
*/
2026-07-15 21:03:42 +02:00
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 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-15 21:03:42 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-15 21:12:29 +02:00
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 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-15 21:12:29 +02:00
char buf [ 512 ] ;
snprintf ( buf , sizeof buf ,
2026-07-21 14:08:53 +02:00
" Commands: !help, !version, !ping, !uptime, !weather [city], !forecast [city], !stock <SYMBOL>, !calc <expr>, !time [tz], !seen <nick>, !tell <nick> <msg>, !gitlog [count] [full], !changelog [count] [full], !ai <question>, !code <change> (ops), !rebuild [pull] (ops), !reload (ops), !restart (ops), !quit/!die (ops) " ) ;
2026-07-15 21:12:29 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-15 19:49:37 +02:00
char city [ 256 ] , city_url [ 256 ] ;
2026-06-29 17:31:17 +02:00
const char * rest = msg [ 8 ] = = ' ' ? msg + 9 : " " ;
while ( * rest = = ' ' ) rest + + ;
2026-07-15 19:49:37 +02:00
normalize_city ( rest , city , sizeof city , city_url , sizeof city_url ) ;
2026-06-29 17:31:17 +02:00
char url [ 512 ] ;
2026-07-15 19:49:37 +02:00
snprintf ( url , sizeof url , " https://wttr.in/%s?format=%%l:+%%t+%%C&m " , city_url ) ;
2026-06-29 17:31:17 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-06-29 17:31:17 +02:00
char city [ 256 ] , city_url [ 256 ] ;
const char * rest = msg [ 9 ] = = ' ' ? msg + 10 : " " ;
while ( * rest = = ' ' ) rest + + ;
2026-07-15 19:49:37 +02:00
normalize_city ( rest , city , sizeof city , city_url , sizeof city_url ) ;
2026-06-29 17:31:17 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-18 23:26:57 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-18 23:26:57 +02:00
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 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-18 23:26:57 +02:00
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 " ) ;
2026-07-19 19:54:36 +02:00
collapse_spaces ( buf ) ;
2026-07-18 23:26:57 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ;
2026-07-14 22:25:56 +02:00
ai_ask ( s , question , reply_target , src_nick , NULL ) ;
2026-06-29 17:31:17 +02:00
return 1 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-14 22:07:18 +02:00
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 ;
2026-07-14 22:25:56 +02:00
ai_ask ( s , question , reply_target , src_nick , " build " ) ;
2026-07-14 22:07:18 +02:00
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 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-19 02:06:32 +02:00
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 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-19 02:06:32 +02:00
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 ;
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* cmd_reload - Handle the " !reload " command .
*
* Requires channel op if used in a channel . Rate - limited . Triggers
* reload_do ( ) which serializes bot state , exec ' s a fresh copy of the
* binary , and restores state . This allows updating the bot without
* disconnecting from IRC .
*
* Parameters :
* s - The IRC session .
* msg - The raw IRC message text .
* reply_target - Channel or nick to send the response to .
* src_nick - The nick of the user who issued the command .
* tgt - The channel or nick the message was sent to .
*
* Returns : 1 if the command was matched , 0 otherwise .
*/
2026-07-19 00:14:30 +02:00
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 ;
}
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-19 00:14:30 +02:00
reload_do ( s , reply_target ) ;
return 1 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-07-19 00:14:30 +02:00
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 ;
}
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-19 00:14:30 +02:00
irc_msg ( s , reply_target , " Restarting... " ) ;
reload_do ( s , reply_target ) ;
return 1 ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
static int cmd_calc ( Session * s , const char * msg , const char * reply_target , const char * src_nick ) {
if ( strncmp ( msg , " !calc " , 5 ) ! = 0 ) return 0 ;
if ( msg [ 5 ] ! = ' ' & & msg [ 5 ] ! = ' \0 ' ) return 0 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
const char * rest = msg [ 5 ] = = ' ' ? msg + 6 : " " ;
while ( * rest = = ' ' ) rest + + ;
if ( ! * rest ) {
irc_msg ( s , reply_target , " Usage: !calc <expression> (e.g. !calc 2+2, !calc (3*7)+1) " ) ;
return 1 ;
}
2026-07-20 02:49:53 +02:00
int in_pipe [ 2 ] , out_pipe [ 2 ] ;
if ( pipe ( in_pipe ) < 0 | | pipe ( out_pipe ) < 0 ) { irc_msg ( s , reply_target , " Calc: internal error " ) ; return 1 ; }
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
pid_t pid = fork ( ) ;
2026-07-20 02:49:53 +02:00
if ( pid < 0 ) { close ( in_pipe [ 0 ] ) ; close ( in_pipe [ 1 ] ) ; close ( out_pipe [ 0 ] ) ; close ( out_pipe [ 1 ] ) ; irc_msg ( s , reply_target , " Calc: fork failed " ) ; return 1 ; }
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
if ( pid = = 0 ) {
2026-07-20 02:49:53 +02:00
close ( in_pipe [ 1 ] ) ;
close ( out_pipe [ 0 ] ) ;
dup2 ( in_pipe [ 0 ] , STDIN_FILENO ) ;
close ( in_pipe [ 0 ] ) ;
dup2 ( out_pipe [ 1 ] , STDOUT_FILENO ) ;
close ( out_pipe [ 1 ] ) ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
execlp ( " bc " , " bc " , " -l " , ( char * ) NULL ) ;
_exit ( 127 ) ;
}
2026-07-20 02:49:53 +02:00
close ( in_pipe [ 0 ] ) ;
close ( out_pipe [ 1 ] ) ;
2026-07-20 03:32:44 +02:00
const char * pidef = " define pi() { return 3.14159265358979323844; } \n " ;
write ( in_pipe [ 1 ] , pidef , strlen ( pidef ) ) ;
2026-07-20 02:49:53 +02:00
write ( in_pipe [ 1 ] , rest , strlen ( rest ) ) ;
write ( in_pipe [ 1 ] , " \n " , 1 ) ;
close ( in_pipe [ 1 ] ) ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
char buf [ 512 ] , tmp [ 256 ] ;
size_t len = 0 ;
ssize_t n ;
2026-07-20 02:49:53 +02:00
while ( ( n = read ( out_pipe [ 0 ] , tmp , sizeof tmp - 1 ) ) > 0 ) {
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
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 ;
}
}
2026-07-20 02:49:53 +02:00
close ( out_pipe [ 0 ] ) ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
int status ;
waitpid ( pid , & status , 0 ) ;
while ( len > 0 & & ( buf [ len - 1 ] = = ' \n ' | | buf [ len - 1 ] = = ' \r ' ) ) len - - ;
buf [ len ] = 0 ;
char * nl = strchr ( buf , ' \n ' ) ;
if ( nl ) * nl = 0 ;
if ( len = = 0 ) {
irc_msg ( s , reply_target , " Calc: no result (check expression syntax) " ) ;
} else {
char resp [ 640 ] ;
snprintf ( resp , sizeof resp , " %s: %s " , src_nick , buf ) ;
irc_msg ( s , reply_target , resp ) ;
}
log_stamp ( ) ; fprintf ( stderr , CLR_YELLOW " CALC %s from %s: " CLR_RESET " %s \n " , reply_target , src_nick , rest ) ;
return 1 ;
}
2026-07-20 03:56:25 +02:00
typedef struct { const char * name ; int off ; int dst_off ; int dst_north ; } TzEntry ;
static const TzEntry tz_table [ ] = {
{ " UTC " , 0 , 0 , 0 } ,
{ " GMT " , 0 , 0 , 0 } ,
{ " EST " , - 5 * 3600 , - 5 * 3600 , 0 } ,
{ " CST " , - 6 * 3600 , - 6 * 3600 , 0 } ,
{ " MST " , - 7 * 3600 , - 7 * 3600 , 0 } ,
{ " PST " , - 8 * 3600 , - 8 * 3600 , 0 } ,
{ " HST " , - 10 * 3600 , - 10 * 3600 , 0 } ,
{ " US/Eastern " , - 5 * 3600 , - 4 * 3600 , 1 } ,
{ " US/Central " , - 6 * 3600 , - 5 * 3600 , 1 } ,
{ " US/Mountain " , - 7 * 3600 , - 6 * 3600 , 1 } ,
{ " US/Pacific " , - 8 * 3600 , - 7 * 3600 , 1 } ,
{ " US/Alaska " , - 9 * 3600 , - 8 * 3600 , 1 } ,
{ " US/Honolulu " , - 10 * 3600 , - 10 * 3600 , 0 } ,
{ " Europe/London " , 0 , 1 * 3600 , 1 } ,
{ " Europe/Berlin " , 1 * 3600 , 2 * 3600 , 1 } ,
{ " Europe/Paris " , 1 * 3600 , 2 * 3600 , 1 } ,
{ " Europe/Moscow " , 3 * 3600 , 3 * 3600 , 0 } ,
{ " Europe/Istanbul " , 3 * 3600 , 3 * 3600 , 0 } ,
{ " Asia/Tokyo " , 9 * 3600 , 9 * 3600 , 0 } ,
{ " Asia/Shanghai " , 8 * 3600 , 8 * 3600 , 0 } ,
{ " Asia/Kolkata " , 19800 , 19800 , 0 } ,
{ " Asia/Dubai " , 4 * 3600 , 4 * 3600 , 0 } ,
{ " Asia/Singapore " , 8 * 3600 , 8 * 3600 , 0 } ,
{ " Asia/Seoul " , 9 * 3600 , 9 * 3600 , 0 } ,
{ " Asia/Hong_Kong " , 8 * 3600 , 8 * 3600 , 0 } ,
{ " Asia/Taipei " , 8 * 3600 , 8 * 3600 , 0 } ,
{ " Australia/Sydney " , 10 * 3600 , 11 * 3600 , 2 } ,
{ " Australia/Melbourne " , 10 * 3600 , 11 * 3600 , 2 } ,
{ " Australia/Brisbane " , 10 * 3600 , 10 * 3600 , 0 } ,
{ " Australia/Perth " , 8 * 3600 , 8 * 3600 , 0 } ,
{ " Australia/Adelaide " , 930 * 60 , 1030 * 60 , 2 } ,
{ " Australia/Darwin " , 930 * 60 , 930 * 60 , 0 } ,
{ " Pacific/Auckland " , 12 * 3600 , 13 * 3600 , 2 } ,
{ " Pacific/Honolulu " , - 10 * 3600 , - 10 * 3600 , 0 } ,
{ " Pacific/Fiji " , 12 * 3600 , 13 * 3600 , 2 } ,
{ " Canada/Toronto " , - 5 * 3600 , - 4 * 3600 , 1 } ,
{ " Canada/Vancouver " , - 8 * 3600 , - 7 * 3600 , 1 } ,
{ " America/Sao_Paulo " , - 3 * 3600 , - 2 * 3600 , 2 } ,
{ " America/Mexico_City " , - 6 * 3600 , - 5 * 3600 , 1 } ,
{ " America/Argentina/Buenos_Aires " , - 3 * 3600 , - 3 * 3600 , 0 } ,
{ " Africa/Cairo " , 2 * 3600 , 2 * 3600 , 0 } ,
{ " Africa/Johannesburg " , 2 * 3600 , 2 * 3600 , 0 } ,
{ " Africa/Lagos " , 1 * 3600 , 1 * 3600 , 0 } ,
{ " Africa/Nairobi " , 3 * 3600 , 3 * 3600 , 0 } ,
{ " Atlantic/Reykjavik " , 0 , 0 , 0 } ,
} ;
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* tz_lookup - Look up a timezone entry by IANA name .
*
* Searches the static tz_table [ ] array for a matching timezone name
* using case - insensitive comparison . Used as a fallback when the system
* lacks tzdata and cannot resolve IANA timezone names via localtime_r .
*
* Parameters :
* name - The IANA timezone name to look up ( e . g . " Europe/Berlin " ) .
*
* Returns : A pointer to the matching TzEntry , or NULL if not found .
*/
2026-07-20 03:56:25 +02:00
static const TzEntry * tz_lookup ( const char * name ) {
for ( size_t i = 0 ; i < sizeof tz_table / sizeof tz_table [ 0 ] ; i + + )
if ( strcasecmp ( tz_table [ i ] . name , name ) = = 0 ) return & tz_table [ i ] ;
return NULL ;
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
2026-07-20 06:59:46 +02:00
* tz_format - Format a timestamp with a given UTC offset .
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
*
* Converts a Unix epoch timestamp plus UTC offset into a human - readable
2026-07-20 06:59:46 +02:00
* string like " 2025-07-20 14:30:00 " . Used as a fallback when the system
* lacks tzdata and cannot resolve IANA timezone names via localtime_r .
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
*
* Parameters :
* epoch - The Unix epoch timestamp to format .
* offset - The UTC offset in seconds ( positive for east of UTC ) .
2026-07-20 06:59:46 +02:00
* tzname - The IANA timezone name ( unused , kept for API compatibility ) .
* is_dst - Whether DST is currently in effect ( unused ) .
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
* buf - Output buffer for the formatted string .
* buflen - Size of the output buffer .
*
* Returns : void ( result written to buf ) .
*/
2026-07-20 03:56:25 +02:00
static void tz_format ( time_t epoch , int offset , const char * tzname , int is_dst , char * buf , size_t buflen ) {
2026-07-20 06:59:46 +02:00
( void ) tzname ; ( void ) is_dst ;
2026-07-20 03:56:25 +02:00
time_t local = epoch + offset ;
struct tm tm ;
gmtime_r ( & local , & tm ) ;
2026-07-20 06:59:46 +02:00
snprintf ( buf , buflen , " %04d-%02d-%02d %02d:%02d:%02d " ,
2026-07-20 03:56:25 +02:00
tm . tm_year + 1900 , tm . tm_mon + 1 , tm . tm_mday ,
2026-07-20 06:59:46 +02:00
tm . tm_hour , tm . tm_min , tm . tm_sec ) ;
2026-07-20 03:56:25 +02:00
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* cmd_time - Handle the " !time [timezone] " command .
*
* Without arguments , returns the bot ' s local time . With a timezone
* argument , first tries the system setenv ( " TZ " ) / localtime_r ( ) approach .
* If the system returns UTC for a non - UTC timezone ( indicating missing
* tzdata ) , falls back to the built - in tz_table with hemisphere - aware
* DST rules . Rate - limited .
*
* Parameters :
* s - The IRC session .
* msg - The raw IRC message text .
* reply_target - Channel or nick to send the response to .
* src_nick - The nick of the user who issued the command .
*
* Returns : 1 if the command was matched , 0 otherwise .
*/
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
static int cmd_time ( Session * s , const char * msg , const char * reply_target , const char * src_nick ) {
if ( strncmp ( msg , " !time " , 5 ) ! = 0 ) return 0 ;
if ( msg [ 5 ] ! = ' ' & & msg [ 5 ] ! = ' \0 ' ) return 0 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
char resp [ 256 ] ;
const char * rest = msg [ 5 ] = = ' ' ? msg + 6 : " " ;
while ( * rest = = ' ' ) rest + + ;
if ( * rest ) {
char tzname [ 64 ] ;
size_t tl = 0 ;
for ( const char * p = rest ; * p & & tl < sizeof tzname - 1 & & * p ! = ' ' ; p + + )
tzname [ tl + + ] = * p ;
tzname [ tl ] = 0 ;
2026-07-20 03:56:25 +02:00
time_t now = time ( NULL ) ;
struct tm utc_tm ;
gmtime_r ( & now , & utc_tm ) ;
char * old_tz = getenv ( " TZ " ) ;
char old_tz_buf [ 256 ] = " " ;
if ( old_tz ) { strncpy ( old_tz_buf , old_tz , sizeof old_tz_buf - 1 ) ; old_tz_buf [ sizeof old_tz_buf - 1 ] = 0 ; }
setenv ( " TZ " , tzname , 1 ) ;
tzset ( ) ;
struct tm local_tm ;
localtime_r ( & now , & local_tm ) ;
if ( old_tz_buf [ 0 ] ) setenv ( " TZ " , old_tz_buf , 1 ) ; else unsetenv ( " TZ " ) ;
tzset ( ) ;
int sys_offset = ( local_tm . tm_hour - utc_tm . tm_hour ) * 3600 + ( local_tm . tm_min - utc_tm . tm_min ) * 60 ;
if ( sys_offset > 12 * 3600 ) sys_offset - = 24 * 3600 ;
if ( sys_offset < - 12 * 3600 ) sys_offset + = 24 * 3600 ;
int system_works = ( sys_offset ! = 0 | | strcasecmp ( tzname , " UTC " ) = = 0 | | strcasecmp ( tzname , " GMT " ) = = 0 ) ;
if ( system_works ) {
char buf [ 64 ] ;
2026-07-20 06:59:46 +02:00
strftime ( buf , sizeof buf , " %Y-%m-%d %H:%M:%S " , & local_tm ) ;
snprintf ( resp , sizeof resp , " %s: %s " , src_nick , buf ) ;
2026-07-20 03:56:25 +02:00
} else {
const TzEntry * tz = tz_lookup ( tzname ) ;
if ( tz ) {
int off = tz - > off ;
if ( tz - > dst_north & & tz - > off ! = tz - > dst_off ) {
int mon = utc_tm . tm_mon + 1 ;
if ( tz - > dst_north = = 1 )
off = ( mon > = 4 & & mon < = 10 ) ? tz - > dst_off : tz - > off ;
else
off = ( mon > = 10 | | mon < = 3 ) ? tz - > dst_off : tz - > off ;
}
char buf [ 128 ] ;
tz_format ( now , off , tzname , off ! = tz - > off , buf , sizeof buf ) ;
snprintf ( resp , sizeof resp , " %s: %s " , src_nick , buf ) ;
} else {
snprintf ( resp , sizeof resp , " %s: Unknown timezone: %s " , src_nick , tzname ) ;
}
}
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
} else {
2026-07-20 03:16:01 +02:00
time_t now = time ( NULL ) ;
struct tm * tm = localtime ( & now ) ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
char buf [ 64 ] ;
2026-07-20 06:59:46 +02:00
strftime ( buf , sizeof buf , " %Y-%m-%d %H:%M:%S " , tm ) ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
snprintf ( resp , sizeof resp , " %s: %s " , src_nick , buf ) ;
}
irc_msg ( s , reply_target , resp ) ;
log_stamp ( ) ; fprintf ( stderr , CLR_YELLOW " TIME from %s in %s " CLR_RESET " \n " , src_nick , reply_target ) ;
return 1 ;
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* cmd_seen - Handle the " !seen <nick> " command .
*
* Looks up the given nick in the seen database and reports when they
* were last seen , in which channel , and what action they were performing .
* Special - cases : checking yourself returns " You are right here, duh! " ,
* checking the bot returns " I am right here! " , and unknown nicks return
* " I have never seen <nick> " . Rate - limited .
*
* Parameters :
* s - The IRC session .
* msg - The raw IRC message text .
* reply_target - Channel or nick to send the response to .
* src_nick - The nick of the user who issued the command .
*
* Returns : 1 if the command was matched , 0 otherwise .
*/
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
static int cmd_seen ( Session * s , const char * msg , const char * reply_target , const char * src_nick ) {
if ( strncmp ( msg , " !seen " , 5 ) ! = 0 ) return 0 ;
if ( msg [ 5 ] ! = ' ' ) return 0 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
const char * rest = msg + 6 ;
while ( * rest = = ' ' ) rest + + ;
if ( ! * rest ) {
irc_msg ( s , reply_target , " Usage: !seen <nick> " ) ;
return 1 ;
}
char target [ 32 ] ;
int i = 0 ;
while ( * rest & & * rest ! = ' ' & & i < 31 ) target [ i + + ] = * rest + + ;
target [ i ] = 0 ;
if ( strcasecmp ( target , src_nick ) = = 0 ) {
irc_msg ( s , reply_target , " You are right here, duh! " ) ;
return 1 ;
}
if ( strcasecmp ( target , s - > nick ) = = 0 ) {
irc_msg ( s , reply_target , " I am right here! " ) ;
return 1 ;
}
char * result = seen_lookup ( target ) ;
if ( result ) {
irc_msg ( s , reply_target , result ) ;
free ( result ) ;
} else {
char resp [ 128 ] ;
snprintf ( resp , sizeof resp , " I have never seen %s " , target ) ;
irc_msg ( s , reply_target , resp ) ;
}
log_stamp ( ) ; fprintf ( stderr , CLR_CYAN " SEEN %s from %s in %s " CLR_RESET " \n " , target , src_nick , reply_target ) ;
return 1 ;
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* cmd_tell - Handle the " !tell <nick> <message> " command .
*
* Stores a pending message in the tell table to be delivered to the
* target nick when they next speak . Validates that the sender is not
* trying to tell themselves something . Confirms with " Ok, I'll tell
* < nick > when they ' re around . " Rate-limited.
*
* Parameters :
* s - The IRC session .
* msg - The raw IRC message text .
* reply_target - Channel or nick to send the response to .
* src_nick - The nick of the user who issued the command .
*
* Returns : 1 if the command was matched , 0 otherwise .
*/
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
static int cmd_tell ( Session * s , const char * msg , const char * reply_target , const char * src_nick ) {
if ( strncmp ( msg , " !tell " , 5 ) ! = 0 ) return 0 ;
if ( msg [ 5 ] ! = ' ' ) return 0 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
const char * rest = msg + 6 ;
while ( * rest = = ' ' ) rest + + ;
if ( ! * rest ) {
irc_msg ( s , reply_target , " Usage: !tell <nick> <message> " ) ;
return 1 ;
}
char target [ 32 ] ;
int i = 0 ;
while ( * rest & & * rest ! = ' ' & & i < 31 ) target [ i + + ] = * rest + + ;
target [ i ] = 0 ;
while ( * rest = = ' ' ) rest + + ;
if ( ! * rest ) {
irc_msg ( s , reply_target , " Usage: !tell <nick> <message> " ) ;
return 1 ;
}
if ( strcasecmp ( target , src_nick ) = = 0 ) {
irc_msg ( s , reply_target , " You can't tell yourself something! " ) ;
return 1 ;
}
tell_add ( src_nick , target , rest ) ;
char resp [ 256 ] ;
snprintf ( resp , sizeof resp , " Ok, I'll tell %s when they're around. " , target ) ;
irc_msg ( s , reply_target , resp ) ;
log_stamp ( ) ; fprintf ( stderr , CLR_CYAN " TELL %s from %s in %s: " CLR_RESET " -> %s: %s \n " , reply_target , src_nick , reply_target , target , rest ) ;
return 1 ;
}
2026-07-20 18:36:46 +02:00
/*
* cmd_gitlog - Handle the " !gitlog [count] " command .
*
* Displays recent git commits of the zynk project by forking a child
* process that runs " git log --oneline -n <count> " . Each commit line
* is sent as a separate IRC PRIVMSG to the reply target . The commit
* count defaults to GITLOG_COUNT ( 5 ) when no argument is provided ,
* and is clamped to GITLOG_MAX ( 20 ) if the user requests more .
* Rate - limited per - nick . If git is not installed or the working
* directory is not a git repository , an appropriate error message is
* sent . If no commits exist ( e . g . fresh repo ) , reports that no commits
* were found .
*
* Parameters :
* s - The IRC session .
* msg - The raw IRC message text .
* reply_target - Channel or nick to send the response to .
* src_nick - The IRC nick of the user who issued the command .
*
* Returns : 1 if the command was matched , 0 otherwise .
*/
2026-07-20 18:28:06 +02:00
static int cmd_gitlog ( Session * s , const char * msg , const char * reply_target , const char * src_nick ) {
if ( strncmp ( msg , " !gitlog " , 7 ) ! = 0 ) return 0 ;
if ( msg [ 7 ] ! = ' ' & & msg [ 7 ] ! = ' \0 ' ) return 0 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-20 18:28:06 +02:00
int count = GITLOG_COUNT ;
2026-07-21 14:08:53 +02:00
int full = 0 ;
2026-07-20 18:28:06 +02:00
const char * rest = msg [ 7 ] = = ' ' ? msg + 8 : " " ;
while ( * rest = = ' ' ) rest + + ;
if ( * rest ) {
2026-07-21 14:08:53 +02:00
if ( isdigit ( ( unsigned char ) * rest ) ) {
count = atoi ( rest ) ;
if ( count < = 0 ) count = GITLOG_COUNT ;
if ( count > GITLOG_MAX ) count = GITLOG_MAX ;
while ( * rest & & isdigit ( ( unsigned char ) * rest ) ) rest + + ;
while ( * rest = = ' ' ) rest + + ;
}
if ( strncasecmp ( rest , " full " , 4 ) = = 0 & & ( rest [ 4 ] = = ' \0 ' | | rest [ 4 ] = = ' ' ) )
full = 1 ;
2026-07-20 18:28:06 +02:00
}
int out_pipe [ 2 ] ;
if ( pipe ( out_pipe ) < 0 ) { irc_msg ( s , reply_target , " gitlog: internal error " ) ; return 1 ; }
pid_t pid = fork ( ) ;
if ( pid < 0 ) { close ( out_pipe [ 0 ] ) ; close ( out_pipe [ 1 ] ) ; irc_msg ( s , reply_target , " gitlog: fork failed " ) ; return 1 ; }
if ( pid = = 0 ) {
close ( out_pipe [ 0 ] ) ;
dup2 ( out_pipe [ 1 ] , STDOUT_FILENO ) ;
close ( out_pipe [ 1 ] ) ;
int dn = open ( " /dev/null " , O_WRONLY ) ;
if ( dn > = 0 ) { dup2 ( dn , STDERR_FILENO ) ; close ( dn ) ; }
char cnt [ 8 ] ;
snprintf ( cnt , sizeof cnt , " %d " , count ) ;
2026-07-21 14:08:53 +02:00
if ( full )
execlp ( " git " , " git " , " log " , " -n " , cnt , ( char * ) NULL ) ;
else
execlp ( " git " , " git " , " log " , " --oneline " , " -n " , cnt , ( char * ) NULL ) ;
2026-07-20 18:28:06 +02:00
_exit ( 127 ) ;
}
close ( out_pipe [ 1 ] ) ;
2026-07-21 14:08:53 +02:00
char buf [ 8192 ] , tmp [ 512 ] ;
2026-07-20 18:28:06 +02:00
size_t len = 0 ;
ssize_t n ;
while ( ( n = read ( out_pipe [ 0 ] , tmp , sizeof tmp - 1 ) ) > 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 ( out_pipe [ 0 ] ) ;
int status ;
waitpid ( pid , & status , 0 ) ;
while ( len > 0 & & ( buf [ len - 1 ] = = ' \n ' | | buf [ len - 1 ] = = ' \r ' ) ) len - - ;
buf [ len ] = 0 ;
if ( len = = 0 ) {
irc_msg ( s , reply_target , " gitlog: no commits found " ) ;
return 1 ;
}
2026-07-21 14:08:53 +02:00
if ( full ) {
struct timespec ts_msg = { . tv_sec = 0 , . tv_nsec = 200000000 } ;
char * p = buf ;
while ( * p ) {
char * end = strstr ( p , " \n \n " ) ;
size_t elen = end ? ( size_t ) ( end - p ) : strlen ( p ) ;
while ( elen > 0 & & ( p [ elen - 1 ] = = ' \n ' | | p [ elen - 1 ] = = ' \r ' ) ) elen - - ;
if ( elen > 0 ) {
p [ elen ] = 0 ;
char * out = p ;
char * src = p ;
while ( * src ) {
while ( * src = = ' ' ) src + + ;
while ( * src & & * src ! = ' \n ' ) * out + + = * src + + ;
if ( * src = = ' \n ' ) * out + + = * src + + ;
}
* out = 0 ;
collapse_spaces ( p ) ;
irc_msg ( s , reply_target , p ) ;
nanosleep ( & ts_msg , NULL ) ;
}
if ( end ) p = end + 2 ; else break ;
}
} else {
char * line = strtok ( buf , " \n " ) ;
while ( line ) {
while ( * line = = ' ' ) line + + ;
collapse_spaces ( line ) ;
if ( * line ) irc_msg ( s , reply_target , line ) ;
line = strtok ( NULL , " \n " ) ;
}
2026-07-20 18:28:06 +02:00
}
2026-07-21 14:08:53 +02:00
log_stamp ( ) ; fprintf ( stderr , CLR_YELLOW " GITLOG %s from %s (count=%d%s) " CLR_RESET " \n " , reply_target , src_nick , count , full ? " , full " : " " ) ;
2026-07-20 18:28:06 +02:00
return 1 ;
}
2026-07-21 02:44:54 +02:00
/*
* cmd_changelog - Handle the " !changelog " command .
*
* Reads CHANGELOG . md from the project root and displays the last N date / title
* lines ( default : CHANGELOG_COUNT ) . Lines starting with a date ( YYYY . MM . DD )
* are treated as entries . Accepts an optional count argument ( 1 – CHANGELOG_MAX ) .
* Rate - limited .
*
* Returns : 1 if the command was matched , 0 otherwise .
*/
static int cmd_changelog ( Session * s , const char * msg , const char * reply_target , const char * src_nick ) {
if ( strncmp ( msg , " !changelog " , 10 ) ! = 0 ) return 0 ;
if ( msg [ 10 ] ! = ' ' & & msg [ 10 ] ! = ' \0 ' ) return 0 ;
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-21 02:44:54 +02:00
int count = CHANGELOG_COUNT ;
2026-07-21 14:08:53 +02:00
int full = 0 ;
2026-07-21 02:44:54 +02:00
const char * rest = msg [ 10 ] = = ' ' ? msg + 11 : " " ;
while ( * rest = = ' ' ) rest + + ;
if ( * rest ) {
2026-07-21 14:08:53 +02:00
if ( isdigit ( ( unsigned char ) * rest ) ) {
count = atoi ( rest ) ;
if ( count < = 0 ) count = CHANGELOG_COUNT ;
if ( count > CHANGELOG_MAX ) count = CHANGELOG_MAX ;
while ( * rest & & isdigit ( ( unsigned char ) * rest ) ) rest + + ;
while ( * rest = = ' ' ) rest + + ;
}
if ( strncasecmp ( rest , " full " , 4 ) = = 0 & & ( rest [ 4 ] = = ' \0 ' | | rest [ 4 ] = = ' ' ) )
full = 1 ;
2026-07-21 02:44:54 +02:00
}
FILE * f = fopen ( " CHANGELOG.md " , " r " ) ;
if ( ! f ) { irc_msg ( s , reply_target , " changelog: CHANGELOG.md not found " ) ; return 1 ; }
char * line = NULL ;
size_t cap = 0 ;
2026-07-21 14:08:53 +02:00
if ( ! full ) {
const char * headers [ 256 ] ;
int total = 0 ;
while ( getline ( & line , & cap , f ) ! = - 1 ) {
size_t len = strlen ( line ) ;
while ( len > 0 & & ( line [ len - 1 ] = = ' \n ' | | line [ len - 1 ] = = ' \r ' ) ) line [ - - len ] = 0 ;
if ( len > 10 & & isdigit ( ( unsigned char ) line [ 0 ] ) & & isdigit ( ( unsigned char ) line [ 1 ] ) & &
isdigit ( ( unsigned char ) line [ 2 ] ) & & isdigit ( ( unsigned char ) line [ 3 ] ) & &
line [ 4 ] = = ' . ' & & isdigit ( ( unsigned char ) line [ 5 ] ) & & isdigit ( ( unsigned char ) line [ 6 ] ) & &
line [ 7 ] = = ' . ' & & isdigit ( ( unsigned char ) line [ 8 ] ) & & isdigit ( ( unsigned char ) line [ 9 ] ) & &
line [ 10 ] = = ' ' ) {
if ( total < 256 ) headers [ total + + ] = strdup ( line ) ;
}
2026-07-21 02:44:54 +02:00
}
2026-07-21 14:08:53 +02:00
free ( line ) ;
fclose ( f ) ;
int showed = count < total ? count : total ;
struct timespec ts_msg = { . tv_sec = 0 , . tv_nsec = 200000000 } ;
for ( int i = 0 ; i < showed ; i + + ) {
irc_msg ( s , reply_target , headers [ i ] ) ;
free ( ( void * ) headers [ i ] ) ;
if ( i + 1 < showed ) nanosleep ( & ts_msg , NULL ) ;
}
for ( int i = showed ; i < total ; i + + ) free ( ( void * ) headers [ i ] ) ;
if ( total = = 0 ) { irc_msg ( s , reply_target , " changelog: no entries found " ) ; return 1 ; }
log_stamp ( ) ; fprintf ( stderr , CLR_YELLOW " CHANGELOG %s from %s (count=%d, showed=%d) " CLR_RESET " \n " , reply_target , src_nick , count , showed ) ;
} else {
char * entries [ 256 ] ;
int total = 0 ;
int showed = 0 ;
size_t entry_cap = 0 ;
size_t entry_len = 0 ;
char * entry = NULL ;
struct timespec ts_msg = { . tv_sec = 0 , . tv_nsec = 200000000 } ;
while ( getline ( & line , & cap , f ) ! = - 1 ) {
size_t len = strlen ( line ) ;
while ( len > 0 & & ( line [ len - 1 ] = = ' \n ' | | line [ len - 1 ] = = ' \r ' ) ) line [ - - len ] = 0 ;
int is_header = ( len > 10 & & isdigit ( ( unsigned char ) line [ 0 ] ) & & isdigit ( ( unsigned char ) line [ 1 ] ) & &
isdigit ( ( unsigned char ) line [ 2 ] ) & & isdigit ( ( unsigned char ) line [ 3 ] ) & &
line [ 4 ] = = ' . ' & & isdigit ( ( unsigned char ) line [ 5 ] ) & & isdigit ( ( unsigned char ) line [ 6 ] ) & &
line [ 7 ] = = ' . ' & & isdigit ( ( unsigned char ) line [ 8 ] ) & & isdigit ( ( unsigned char ) line [ 9 ] ) & &
line [ 10 ] = = ' ' ) ;
if ( is_header ) {
if ( entry ) {
while ( entry_len > 0 & & ( entry [ entry_len - 1 ] = = ' \n ' | | entry [ entry_len - 1 ] = = ' \r ' ) ) entry [ - - entry_len ] = 0 ;
entries [ total + + ] = entry ;
entry = NULL ; entry_len = 0 ; entry_cap = 0 ;
}
entry_cap = len + 256 ;
entry = malloc ( entry_cap ) ;
memcpy ( entry , line , len ) ;
entry_len = len ;
entry [ entry_len ] = 0 ;
} else if ( entry ) {
if ( entry_len + len + 2 > entry_cap ) {
entry_cap = entry_len + len + 256 ;
entry = realloc ( entry , entry_cap ) ;
}
if ( entry_len > 0 & & line [ 0 ] ) entry [ entry_len + + ] = ' \n ' ;
if ( line [ 0 ] ) {
memcpy ( entry + entry_len , line , len ) ;
entry_len + = len ;
}
entry [ entry_len ] = 0 ;
}
}
if ( entry ) {
while ( entry_len > 0 & & ( entry [ entry_len - 1 ] = = ' \n ' | | entry [ entry_len - 1 ] = = ' \r ' ) ) entry [ - - entry_len ] = 0 ;
entries [ total + + ] = entry ;
}
free ( line ) ;
fclose ( f ) ;
if ( total = = 0 ) { irc_msg ( s , reply_target , " changelog: no entries found " ) ; return 1 ; }
int showed_n = count < total ? count : total ;
for ( int i = 0 ; i < showed_n ; i + + ) {
irc_msg ( s , reply_target , entries [ i ] ) ;
showed + + ;
free ( entries [ i ] ) ;
if ( i + 1 < showed_n ) nanosleep ( & ts_msg , NULL ) ;
}
for ( int i = showed_n ; i < total ; i + + ) free ( entries [ i ] ) ;
log_stamp ( ) ; fprintf ( stderr , CLR_YELLOW " CHANGELOG %s from %s (count=%d, showed=%d, full) " CLR_RESET " \n " , reply_target , src_nick , count , showed ) ;
2026-07-21 02:44:54 +02:00
}
return 1 ;
}
2026-07-20 23:14:26 +02:00
/*
* cmd_rebuild - Handle the " !rebuild " command .
*
2026-07-21 14:08:53 +02:00
* Requires channel op and must be used in a channel . Optionally runs
* " git pull " if the argument " pull " is provided ( e . g . " !rebuild pull " ) .
* Always runs " make clean " and " make " in sequence . If all steps succeed ,
* triggers a hot reload via reload_do ( ) . If any step fails , reports the
* error from the build output . Rate - limited .
2026-07-20 23:14:26 +02:00
*
* Returns : 1 if matched , 0 otherwise .
*/
static int cmd_rebuild ( Session * s , const char * msg , const char * reply_target , const char * src_nick , const char * tgt ) {
2026-07-21 14:08:53 +02:00
int do_pull = ( strcmp ( msg , " !rebuild pull " ) = = 0 ) ;
if ( strcmp ( msg , " !rebuild " ) ! = 0 & & ! do_pull ) return 0 ;
2026-07-20 23:14:26 +02:00
if ( tgt [ 0 ] ! = ' # ' ) {
irc_msg ( s , reply_target , " !rebuild can only be used in a channel " ) ;
return 1 ;
}
if ( ! chan_is_op ( tgt , src_nick ) ) {
irc_msg ( s , reply_target , " You need op to rebuild " ) ;
return 1 ;
}
2026-07-21 03:16:19 +02:00
if ( rate_limit_check ( src_nick , reply_target ) < 0 ) return 1 ;
2026-07-21 14:08:53 +02:00
irc_msg ( s , reply_target , do_pull ? " Pulling and rebuilding... " : " Rebuilding... " ) ;
log_stamp ( ) ; fprintf ( stderr , CLR_GREEN " REBUILD from %s in %s (pull=%d) " CLR_RESET " \n " , src_nick , reply_target , do_pull ) ;
2026-07-20 23:14:26 +02:00
int status ;
char errbuf [ 512 ] ;
2026-07-21 14:08:53 +02:00
if ( do_pull ) {
status = system ( " git pull 2>/tmp/zynk_rebuild_err " ) ;
if ( ! WIFEXITED ( status ) | | WEXITSTATUS ( status ) ! = 0 ) {
char msg_buf [ 640 ] ;
FILE * f = fopen ( " /tmp/zynk_rebuild_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 " ) ;
snprintf ( msg_buf , sizeof msg_buf , " Rebuild failed (git pull): %s " , errbuf ) ;
irc_msg ( s , reply_target , msg_buf ) ;
log_stamp ( ) ; fprintf ( stderr , CLR_RED " REBUILD git pull failed: " CLR_RESET " %s \n " , errbuf ) ;
return 1 ;
}
2026-07-20 23:14:26 +02:00
}
status = system ( " make clean 2>/tmp/zynk_rebuild_err " ) ;
if ( ! WIFEXITED ( status ) | | WEXITSTATUS ( status ) ! = 0 ) {
char msg_buf [ 640 ] ;
FILE * f = fopen ( " /tmp/zynk_rebuild_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 " ) ;
snprintf ( msg_buf , sizeof msg_buf , " Rebuild failed (make clean): %s " , errbuf ) ;
irc_msg ( s , reply_target , msg_buf ) ;
log_stamp ( ) ; fprintf ( stderr , CLR_RED " REBUILD make clean failed: " CLR_RESET " %s \n " , errbuf ) ;
return 1 ;
}
status = system ( " make 2>/tmp/zynk_rebuild_err " ) ;
if ( WIFEXITED ( status ) & & WEXITSTATUS ( status ) = = 0 ) {
irc_msg ( s , reply_target , " Build successful, restarting... " ) ;
log_stamp ( ) ; fprintf ( stderr , CLR_GREEN " REBUILD successful, restarting... " CLR_RESET " \n " ) ;
FILE * cf = fopen ( " /tmp/zynk_code_restart " , " w " ) ;
if ( cf ) { fprintf ( cf , " %s \n " , reply_target ) ; fclose ( cf ) ; }
reload_do ( s , reply_target ) ;
} else {
FILE * f = fopen ( " /tmp/zynk_rebuild_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_buf [ 640 ] ;
snprintf ( msg_buf , sizeof msg_buf , " Rebuild failed (make): %s " , errbuf ) ;
irc_msg ( s , reply_target , msg_buf ) ;
log_stamp ( ) ; fprintf ( stderr , CLR_RED " REBUILD make failed: " CLR_RESET " %s \n " , errbuf ) ;
}
return 1 ;
}
docs: document all undocumented functions, add built-in timezone table to README
- Added doc comments (/* ... */) to all 14 undocumented static functions in
zynk.c matching the existing documentation style (function name, description,
Parameters, Returns sections):
* DB ops: seen_update, seen_lookup, tell_add, tell_deliver
* String utils: valid_irc_word, normalize_city, collapse_spaces
* Command handlers: cmd_reload, cmd_time, cmd_seen, cmd_tell, cmd_greeting_or_chat
* Timezone helpers: tz_lookup, tz_format
- Added complete reference table of all 45 built-in timezones to README.md
with region, UTC offset, and DST support status, so users know which
timezones work without tzdata installed.
- Updated CHANGELOG.md v0.35.5 entry to reflect these additions.
- Clean build, zero warnings.
2026-07-20 05:06:50 +02:00
/*
* cmd_greeting_or_chat - Handle informal greetings and chat messages .
*
* Strips the bot ' s nick prefix if present ( e . g . " zynk: hello " ) and
* matches against a fixed set of greetings / phrases : " hi " , " hey " ,
* " hello " , " bye " , " goodbye " , " jojo " , " whatsup " , " waddup " , and a few
* German phrases . Responds with a canned reply for each . If no fixed
* phrase matches but the message was addressed by nick , forwards it
* to the AI as a chat question via ai_ask .
*
* Parameters :
* s - The IRC session .
* msg - The raw IRC message text .
* reply_target - Channel or nick to send the response to .
* src_nick - The nick of the user who sent the message .
*
* Returns : void .
*/
2026-06-29 17:31:17 +02:00
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 ) {
2026-07-14 22:25:56 +02:00
ai_ask ( s , cmd , reply_target , src_nick , NULL ) ;
2026-06-29 17:31:17 +02:00
}
}
/* ---- IRC protocol handlers ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
seen_update ( src_nick , tgt , " spoke " ) ;
tell_deliver ( s , src_nick , ( tgt [ 0 ] = = ' # ' ) ? tgt : src_nick ) ;
2026-06-29 17:31:17 +02:00
const char * reply_target = ( tgt [ 0 ] = = ' # ' ) ? tgt : src_nick ;
2026-07-14 23:52:56 +02:00
if ( cmd_zynk ( s , msg , reply_target , src_nick , tgt ) ) return ;
2026-06-29 17:31:17 +02:00
if ( cmd_ping ( s , msg , reply_target , src_nick ) ) return ;
2026-07-15 21:03:42 +02:00
if ( cmd_version ( s , msg , reply_target , src_nick ) ) return ;
2026-07-19 02:06:32 +02:00
if ( cmd_uptime ( s , msg , reply_target , src_nick ) ) return ;
2026-07-15 21:12:29 +02:00
if ( cmd_help ( s , msg , reply_target , src_nick ) ) return ;
2026-06-29 17:31:17 +02:00
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 ;
2026-07-18 23:26:57 +02:00
if ( cmd_stock ( s , msg , reply_target , src_nick ) ) return ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
if ( cmd_calc ( s , msg , reply_target , src_nick ) ) return ;
if ( cmd_time ( s , msg , reply_target , src_nick ) ) return ;
if ( cmd_seen ( s , msg , reply_target , src_nick ) ) return ;
if ( cmd_tell ( s , msg , reply_target , src_nick ) ) return ;
2026-07-20 18:28:06 +02:00
if ( cmd_gitlog ( s , msg , reply_target , src_nick ) ) return ;
2026-07-21 02:44:54 +02:00
if ( cmd_changelog ( s , msg , reply_target , src_nick ) ) return ;
2026-06-29 17:31:17 +02:00
if ( cmd_ai ( s , msg , reply_target , src_nick ) ) return ;
2026-07-14 22:07:18 +02:00
if ( cmd_code ( s , msg , reply_target , src_nick , tgt ) ) return ;
2026-07-20 23:14:26 +02:00
if ( cmd_rebuild ( s , msg , reply_target , src_nick , tgt ) ) return ;
2026-07-19 00:14:30 +02:00
if ( cmd_reload ( s , msg , reply_target , src_nick , tgt ) ) return ;
if ( cmd_restart ( s , msg , reply_target , src_nick , tgt ) ) return ;
2026-06-29 17:31:17 +02:00
cmd_greeting_or_chat ( s , msg , reply_target , src_nick ) ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
static void handle_namreply ( Session * s , const char * params ) {
2026-06-29 18:38:05 +02:00
( 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 + + ;
2026-06-29 17:31:17 +02:00
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 ;
2026-07-15 19:49:37 +02:00
while ( * p & & * p ! = ' ' ) {
if ( i < 31 ) buf [ i + + ] = * p ;
p + + ;
}
2026-06-29 17:31:17 +02:00
buf [ i ] = 0 ;
if ( is_op & & buf [ 0 ] ) chan_add_op ( _chan , buf ) ;
}
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ) ;
}
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
static void handle_join ( Session * s , const char * params ) {
2026-06-29 18:38:05 +02:00
( void ) s ;
2026-06-29 17:31:17 +02:00
const char * p = params ;
if ( * p = = ' : ' ) p + + ;
2026-07-15 19:49:37 +02:00
char _chan [ 64 ] ;
if ( sscanf ( p , " %63s " , _chan ) = = 1 )
chan_get_or_add ( _chan ) ;
2026-06-29 17:31:17 +02:00
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ) ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
seen_update ( src_nick , _chan , " left " ) ;
2026-06-29 17:31:17 +02:00
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ) ;
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
static void handle_quit_net ( const char * src_nick ) {
for ( int i = 0 ; i < nchans ; i + + )
chan_del_op ( chans [ i ] . name , src_nick ) ;
v0.35.0: add !calc, !time, !seen, !tell commands
New IRC commands:
- !calc <expr>: evaluate math via bc -l (arithmetic, powers, trig, log, vars)
- !time [tz]: show current time in any IANA timezone
- !seen <nick>: track/query last-seen activity (auto-updated on speak/part/quit)
- !tell <nick> <msg>: leave offline messages, delivered when target speaks
Database:
- Added 'seen' table for user activity tracking (nick, timestamp, channel, action)
- Added 'tell' table for pending offline messages
Other changes:
- Updated !help to list all new commands
- Updated README.md with detailed docs for all commands including !calc
expression syntax and !time timezone examples
- Bumped version to 0.35.0
2026-07-20 02:43:21 +02:00
seen_update ( src_nick , NULL , " quit " ) ;
2026-06-29 17:31:17 +02:00
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ;
2026-07-15 19:49:37 +02:00
const char * newnick = params ;
if ( * newnick = = ' : ' ) newnick + + ;
2026-07-16 03:43:00 +02:00
if ( ! * newnick | | has_crlf ( newnick ) | | has_ctl ( newnick ) ) return ;
2026-07-15 19:49:37 +02:00
chan_rename_op ( src_nick , newnick ) ;
2026-06-29 17:31:17 +02:00
if ( strcasecmp ( src_nick , s - > nick ) = = 0 ) {
strncpy ( s - > nick , newnick , sizeof s - > nick - 1 ) ;
s - > nick [ sizeof s - > nick - 1 ] = 0 ;
}
}
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-29 17:31:17 +02:00
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 ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
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 ;
2026-06-29 18:38:05 +02:00
while ( * cmd = = ' ' ) cmd + + ;
if ( ! * cmd ) return ;
2026-06-07 01:50:05 +02:00
}
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 ;
2026-06-29 17:31:17 +02:00
if ( * tok ) { irc_join ( s , tok ) ; log_stamp ( ) ; fprintf ( stderr , CLR_GREEN " Joining %s " CLR_RESET " \n " , tok ) ; }
2026-06-07 01:50:05 +02:00
}
free ( copy ) ;
}
2026-07-19 00:14:30 +02:00
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 ) ;
}
}
2026-06-07 01:50:05 +02:00
return ;
}
2026-06-29 17:31:17 +02:00
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 ) ;
2026-06-07 01:50:05 +02:00
}
2026-06-29 17:31:17 +02:00
/* ---- IRC line parser ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 .
*/
2026-06-07 01:50:05 +02:00
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 ' ) {
2026-06-29 18:38:05 +02:00
s - > rbuf [ s - > rlen ] = 0 ;
if ( s - > rlen > 0 ) irc_handle ( s , s - > rbuf ) ;
2026-06-07 01:50:05 +02:00
s - > rlen = 0 ;
} else {
if ( s - > rlen < RBUF_SZ - 1 ) s - > rbuf [ s - > rlen + + ] = c ;
}
}
}
2026-06-29 17:31:17 +02:00
/* ---- usage ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 ) .
*/
2026-06-07 01:50:05 +02:00
static void usage ( const char * prog ) {
fprintf ( stderr ,
2026-07-15 21:19:28 +02:00
" Usage: %s [-ssl] [-server host] [-port p] [-nick n] [-join c] [-opencode path] \n "
2026-06-21 03:20:11 +02:00
" -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 "
2026-07-14 23:52:56 +02:00
" -nick n Nickname (default: zynk<PID>) \n "
" -join c Auto-join channels (comma-sep, default: #zynk) \n "
2026-07-15 21:19:28 +02:00
" -opencode p Path to opencode binary (default: %s) \n "
2026-06-07 01:50:05 +02:00
" \n "
2026-07-14 23:52:56 +02:00
" Zynk commands: \n "
" zynk foo = bar Store 'bar' under key 'foo' \n "
" zynk foo Retrieve value for 'foo' \n " ,
2026-07-15 21:19:28 +02:00
prog , DEFAULT_SERVER , DEF_PORT , OPENCODE_BIN ) ;
2026-06-07 01:50:05 +02:00
}
2026-06-29 17:31:17 +02:00
/* ---- reconnect ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 ( 5 s , 7 s , 9 s , . . . ) . 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 .
*/
2026-06-29 17:31:17 +02:00
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 ---- */
2026-07-19 01:29:22 +02:00
/*
* 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 100 ms 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 .
*/
2026-06-07 01:50:05 +02:00
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 ] = " " ;
2026-07-14 23:52:56 +02:00
char joinbuf [ 256 ] = " #zynk " ;
2026-07-15 21:19:28 +02:00
g_opencode_bin = OPENCODE_BIN ;
2026-06-07 01:50:05 +02:00
int pos = 0 ;
2026-07-14 23:52:56 +02:00
log_stamp ( ) ; fprintf ( stderr , CLR_CYAN " [zynk] starting up " CLR_RESET " \n " ) ;
2026-06-07 01:50:05 +02:00
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 ] ) ;
2026-07-15 21:19:28 +02:00
} else if ( strcmp ( argv [ i ] , " -opencode " ) = = 0 ) {
if ( + + i > = argc ) { usage ( argv [ 0 ] ) ; return 1 ; }
g_opencode_bin = argv [ i ] ;
2026-06-07 01:50:05 +02:00
} 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 ;
2026-07-14 23:52:56 +02:00
if ( ! nick ) { snprintf ( nickbuf , sizeof nickbuf , " zynk " ) ; nick = nickbuf ; }
2026-07-15 19:49:37 +02:00
if ( ! valid_irc_word ( nick ) ) {
fprintf ( stderr , CLR_RED " Invalid nick " CLR_RESET " \n " ) ;
return 1 ;
}
2026-07-16 03:43:00 +02:00
if ( has_crlf ( passbuf ) | | has_crlf ( joinbuf ) | | has_ctl ( passbuf ) ) {
2026-07-15 19:49:37 +02:00
fprintf ( stderr , CLR_RED " Invalid IRC argument " CLR_RESET " \n " ) ;
return 1 ;
}
2026-07-15 21:19:28 +02:00
if ( ! g_opencode_bin | | ! * g_opencode_bin ) {
fprintf ( stderr , CLR_RED " Invalid opencode path " CLR_RESET " \n " ) ;
return 1 ;
}
2026-07-16 03:07:33 +02:00
if ( has_ctl ( g_opencode_bin ) ) {
fprintf ( stderr , CLR_RED " Invalid opencode path (control chars) " CLR_RESET " \n " ) ;
return 1 ;
}
2026-07-15 19:49:37 +02:00
if ( db_init ( ) < 0 ) {
fprintf ( stderr , CLR_RED " DB init failed " CLR_RESET " \n " ) ;
sqlite_cleanup ( ) ;
return 1 ;
}
2026-07-19 02:06:32 +02:00
start_time = time ( NULL ) ;
2026-06-07 01:50:05 +02:00
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 ) ;
2026-07-14 23:52:56 +02:00
snprintf ( s . real , sizeof s . real , " zynk " ) ;
2026-06-29 17:31:17 +02:00
snprintf ( s . auto_join , sizeof s . auto_join , " %s " , joinbuf ) ;
2026-06-07 01:50:05 +02:00
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 ) ;
2026-07-19 01:29:22 +02:00
if ( use_tls ) reload_try_restore ( & s ) ;
{
2026-07-19 00:14:30 +02:00
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 ) ;
2026-06-07 01:50:05 +02:00
}
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 ) ) {
2026-06-29 17:31:17 +02:00
log_stamp ( ) ; fprintf ( stderr , CLR_YELLOW " Disconnected " CLR_RESET " \n " ) ;
s . connected = 0 ;
if ( net_reconnect ( & s ) < 0 ) break ;
continue ;
2026-06-07 01:50:05 +02:00
}
}
2026-06-29 17:31:17 +02:00
ai_check_completion ( & s ) ;
2026-06-07 01:50:05 +02:00
}
2026-07-15 19:49:37 +02:00
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 ;
}
2026-06-07 01:50:05 +02:00
if ( s . connected & & s . fd > = 0 ) {
2026-06-29 17:31:17 +02:00
int old_fl = fcntl ( s . fd , F_GETFL , 0 ) ;
fcntl ( s . fd , F_SETFL , old_fl & ~ O_NONBLOCK ) ;
2026-07-14 23:52:56 +02:00
net_send ( & s , " QUIT :zynk \r \n " ) ;
2026-06-07 01:50:05 +02:00
struct timespec ts = { . tv_sec = 0 , . tv_nsec = 500000000 } ;
nanosleep ( & ts , NULL ) ;
}
tls_cleanup ( & s ) ;
2026-07-15 19:49:37 +02:00
tls_ctx_cleanup ( ) ;
2026-06-07 01:50:05 +02:00
if ( s . fd > = 0 ) close ( s . fd ) ;
db_close_cleanup ( ) ;
2026-07-15 19:49:37 +02:00
sqlite_cleanup ( ) ;
2026-06-07 01:50:05 +02:00
return 0 ;
}