1564 lines
54 KiB
C
1564 lines
54 KiB
C
/*
|
|
* Copyright (c) armin, hanez
|
|
*
|
|
* Licensed under the terms of the MIT License.
|
|
*/
|
|
|
|
#define _GNU_SOURCE
|
|
#define _POSIX_C_SOURCE 200809L
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <strings.h>
|
|
#include <unistd.h>
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <poll.h>
|
|
#include <signal.h>
|
|
#include <time.h>
|
|
#include <stdarg.h>
|
|
#include <ctype.h>
|
|
#include <sys/socket.h>
|
|
#include <netdb.h>
|
|
#include <sys/utsname.h>
|
|
#include <dlfcn.h>
|
|
#include <sys/wait.h>
|
|
#include <openssl/ssl.h>
|
|
#include <openssl/err.h>
|
|
int asprintf(char **, const char *, ...);
|
|
|
|
/* ---- constants ---- */
|
|
|
|
#define DEFAULT_SERVER "irc.libera.chat"
|
|
#define OPENCODE_BIN "/home/hanez/bin/opencode"
|
|
#define CLR_RESET "\033[0m"
|
|
#define CLR_DIM "\033[2m"
|
|
#define CLR_RED "\033[31m"
|
|
#define CLR_GREEN "\033[32m"
|
|
#define CLR_YELLOW "\033[33m"
|
|
#define CLR_BLUE "\033[34m"
|
|
#define CLR_MAGENTA "\033[35m"
|
|
#define CLR_CYAN "\033[36m"
|
|
|
|
enum {
|
|
RBUF_SZ = 16384,
|
|
DEF_PORT = 6697,
|
|
POLL_MS = 100,
|
|
AI_REPLY_MAX = 2048,
|
|
AI_TIMEOUT = 240,
|
|
MAX_CHANS = 32,
|
|
MAX_CHAN_OPS = 64,
|
|
RATE_LIMIT_WINDOW = 10,
|
|
RATE_LIMIT_MAX = 8,
|
|
MAX_HISTORY = 100,
|
|
};
|
|
|
|
/* ---- IRC session ---- */
|
|
|
|
typedef struct {
|
|
int fd;
|
|
char host[256];
|
|
int port;
|
|
char nick[32];
|
|
char user[32];
|
|
char real[256];
|
|
char pass[256];
|
|
char auto_join[256];
|
|
int connected;
|
|
char rbuf[16384];
|
|
int rlen;
|
|
SSL *ssl;
|
|
int use_tls;
|
|
} Session;
|
|
|
|
/* ---- forward declarations ---- */
|
|
|
|
static void irc_msg(Session *, const char *, const char *);
|
|
|
|
/* ---- logging ---- */
|
|
|
|
static void log_stamp(void) {
|
|
struct tm *tm;
|
|
time_t t = time(NULL);
|
|
tm = localtime(&t);
|
|
char buf[64];
|
|
strftime(buf, sizeof buf, "%y-%m-%d %H:%M:%S", tm);
|
|
fprintf(stderr, CLR_DIM "[%s]" CLR_RESET " ", buf);
|
|
}
|
|
|
|
/* ---- SQLite3 dynamic loading ---- */
|
|
|
|
static void *sqlite_lib;
|
|
static int (*db_open)(const char*,void**);
|
|
static int (*db_exec)(void*,const char*,int(*)(void*,int,char**,char**),void*,char**);
|
|
static int (*db_close)(void*);
|
|
static int (*db_prepare)(void*,const char*,int,void**,const char**);
|
|
static int (*db_bind_text)(void*,int,const char*,int,void(*)(void*));
|
|
static int (*db_step)(void*);
|
|
static int (*db_finalize)(void*);
|
|
static const unsigned char *(*db_column_text)(void*,int);
|
|
static void (*db_free)(void*);
|
|
|
|
#define LOAD_FUNC(var, name) do { \
|
|
union { void *p; typeof(var) f; } _u; \
|
|
_u.p = dlsym(sqlite_lib, name); \
|
|
var = _u.f; \
|
|
} while(0)
|
|
|
|
#define SQLITE_OK 0
|
|
#define SQLITE_ERROR 1
|
|
#define SQLITE_DONE 101
|
|
#define SQLITE_ROW 100
|
|
#define SQLITE_INTEGER 1
|
|
#define SQLITE_FLOAT 2
|
|
#define SQLITE_TEXT 3
|
|
#define SQLITE_BLOB 4
|
|
#define SQLITE_NULL 5
|
|
#define SQLITE_STATIC ((void(*)(void*))0)
|
|
#define SQLITE_TRANSIENT ((void(*)(void*))-1)
|
|
typedef struct { void *ptr; } sqlite3;
|
|
#define DB ((sqlite3*)db_handle)
|
|
static void *db_handle;
|
|
|
|
static 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");
|
|
if (!db_open || !db_exec || !db_close || !db_prepare ||
|
|
!db_bind_text || !db_step || !db_finalize || !db_column_text || !db_free)
|
|
return -1;
|
|
return 0;
|
|
}
|
|
|
|
static int db_init(void) {
|
|
if (sqlite_init_lib() < 0) { fprintf(stderr, CLR_RED "Cannot load libsqlite3" CLR_RESET "\n"); return -1; }
|
|
if (db_open("zynk.db", &db_handle) != SQLITE_OK) {
|
|
fprintf(stderr, CLR_RED "DB open failed" CLR_RESET "\n"); return -1;
|
|
}
|
|
const char *sql_zynk = "CREATE TABLE IF NOT EXISTS zynk ("
|
|
"key TEXT PRIMARY KEY, value TEXT NOT NULL, "
|
|
"nick TEXT NOT NULL, updated_at TEXT DEFAULT (datetime('now')))";
|
|
char *err = NULL;
|
|
if (db_exec(DB, sql_zynk, NULL, NULL, &err) != SQLITE_OK) {
|
|
fprintf(stderr, CLR_RED "SQL: %s" CLR_RESET "\n", err); db_free(err); return -1;
|
|
}
|
|
const char *sql_ai = "CREATE TABLE IF NOT EXISTS ai_pending ("
|
|
"id INTEGER PRIMARY KEY, question TEXT, "
|
|
"answer TEXT, target TEXT, nick TEXT, status TEXT DEFAULT 'idle')";
|
|
if (db_exec(DB, sql_ai, NULL, NULL, &err) != SQLITE_OK) {
|
|
fprintf(stderr, CLR_RED "SQL: %s" CLR_RESET "\n", err); db_free(err); return -1;
|
|
}
|
|
const char *sql_clear_ai = "DELETE FROM ai_pending";
|
|
db_exec(DB, sql_clear_ai, NULL, NULL, NULL);
|
|
const char *sql_clear = "DELETE FROM zynk WHERE key LIKE 'lastq%' OR key LIKE 'lasta%'";
|
|
db_exec(DB, sql_clear, NULL, NULL, NULL);
|
|
return 0;
|
|
}
|
|
|
|
static void db_close_cleanup(void) { if (db_handle) { db_close(DB); db_handle = NULL; } }
|
|
|
|
/* ---- DB key-value operations ---- */
|
|
|
|
static int db_set(const char *key, const char *value, const char *nick) {
|
|
void *stmt;
|
|
const char *sql = "INSERT INTO zynk(key,value,nick,updated_at)"
|
|
" VALUES(?,?,?,datetime('now'))"
|
|
" ON CONFLICT(key) DO UPDATE SET value=excluded.value,"
|
|
" nick=excluded.nick, updated_at=datetime('now')";
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return -1;
|
|
db_bind_text(stmt, 1, key, -1, SQLITE_STATIC);
|
|
db_bind_text(stmt, 2, value, -1, SQLITE_STATIC);
|
|
db_bind_text(stmt, 3, nick, -1, SQLITE_STATIC);
|
|
int rc = db_step(stmt);
|
|
db_finalize(stmt);
|
|
return rc == SQLITE_DONE ? 0 : -1;
|
|
}
|
|
|
|
static char *db_get_raw(const char *key) {
|
|
void *stmt;
|
|
const char *sql = "SELECT value FROM zynk WHERE key=?";
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
|
|
db_bind_text(stmt, 1, key, -1, SQLITE_STATIC);
|
|
if (db_step(stmt) != SQLITE_ROW) { db_finalize(stmt); return NULL; }
|
|
const char *v = (const char*)db_column_text(stmt, 0);
|
|
char *r = v ? strdup(v) : NULL;
|
|
db_finalize(stmt);
|
|
return r;
|
|
}
|
|
|
|
static char *db_get(const char *key) {
|
|
void *stmt;
|
|
const char *sql = "SELECT value,nick,updated_at FROM zynk WHERE key=?";
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
|
|
db_bind_text(stmt, 1, key, -1, SQLITE_STATIC);
|
|
if (db_step(stmt) != SQLITE_ROW) { db_finalize(stmt); return NULL; }
|
|
const char *v = (const char*)db_column_text(stmt, 0);
|
|
const char *n = (const char*)db_column_text(stmt, 1);
|
|
const char *t = (const char*)db_column_text(stmt, 2);
|
|
char *r = NULL;
|
|
if (asprintf(&r, "%s (set by %s on %s)", v, n, t) < 0) r = NULL;
|
|
db_finalize(stmt);
|
|
return r;
|
|
}
|
|
|
|
static char *db_get_random(void) {
|
|
void *stmt;
|
|
const char *sql = "SELECT key,value,nick,updated_at FROM zynk"
|
|
" WHERE key NOT LIKE 'lastq%' AND key NOT LIKE 'lasta%'"
|
|
" ORDER BY RANDOM() LIMIT 1";
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
|
|
if (db_step(stmt) != SQLITE_ROW) { db_finalize(stmt); return NULL; }
|
|
const char *k = (const char*)db_column_text(stmt, 0);
|
|
const char *v = (const char*)db_column_text(stmt, 1);
|
|
const char *n = (const char*)db_column_text(stmt, 2);
|
|
const char *t = (const char*)db_column_text(stmt, 3);
|
|
char *r = NULL;
|
|
if (asprintf(&r, "%s = %s (by %s on %s)", k, v, n, t) < 0) r = NULL;
|
|
db_finalize(stmt);
|
|
return r;
|
|
}
|
|
|
|
/* Rotate recent history entries (prefix = "lastq" or "lasta") */
|
|
static void db_rotate_history(const char *prefix, const char *value) {
|
|
char *old[MAX_HISTORY];
|
|
char kbuf[MAX_HISTORY][12];
|
|
for (int i = 0; i < MAX_HISTORY; i++) {
|
|
snprintf(kbuf[i], sizeof kbuf[i], "%s%02d", prefix, i + 1);
|
|
old[i] = db_get_raw(kbuf[i]);
|
|
}
|
|
void *stmt;
|
|
const char *sql = "INSERT INTO zynk(key,value,nick,updated_at)"
|
|
" VALUES(?,?,?,datetime('now'))"
|
|
" ON CONFLICT(key) DO UPDATE SET value=excluded.value,"
|
|
" nick=excluded.nick, updated_at=datetime('now')";
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) == SQLITE_OK) {
|
|
db_bind_text(stmt, 1, kbuf[0], -1, SQLITE_STATIC);
|
|
db_bind_text(stmt, 2, value, -1, SQLITE_STATIC);
|
|
db_bind_text(stmt, 3, "", -1, SQLITE_STATIC);
|
|
db_step(stmt);
|
|
db_finalize(stmt);
|
|
}
|
|
for (int i = 0; i < MAX_HISTORY - 1; i++) {
|
|
if (old[i] && db_prepare(DB, sql, -1, &stmt, NULL) == SQLITE_OK) {
|
|
db_bind_text(stmt, 1, kbuf[i + 1], -1, SQLITE_STATIC);
|
|
db_bind_text(stmt, 2, old[i], -1, SQLITE_STATIC);
|
|
db_bind_text(stmt, 3, "", -1, SQLITE_STATIC);
|
|
db_step(stmt);
|
|
db_finalize(stmt);
|
|
}
|
|
}
|
|
for (int i = 0; i < MAX_HISTORY; i++) free(old[i]);
|
|
}
|
|
|
|
#define db_update_lastq(v) db_rotate_history("lastq", v)
|
|
#define db_update_lasta(v) db_rotate_history("lasta", v)
|
|
|
|
/* ---- DB AI pending operations ---- */
|
|
|
|
static int ai_start(const char *question, const char *target, const char *nick, long long *out_id) {
|
|
const char *sql = "INSERT INTO ai_pending(question,answer,target,nick,status)"
|
|
" VALUES(?,?,?,?,'pending')";
|
|
void *stmt;
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return -1;
|
|
db_bind_text(stmt, 1, question, -1, SQLITE_STATIC);
|
|
db_bind_text(stmt, 2, "", -1, SQLITE_STATIC);
|
|
db_bind_text(stmt, 3, target, -1, SQLITE_STATIC);
|
|
db_bind_text(stmt, 4, nick, -1, SQLITE_STATIC);
|
|
int rc = db_step(stmt);
|
|
db_finalize(stmt);
|
|
if (rc == SQLITE_DONE) {
|
|
void *stmt2;
|
|
if (db_prepare(DB, "SELECT last_insert_rowid()", -1, &stmt2, NULL) == SQLITE_OK) {
|
|
if (db_step(stmt2) == SQLITE_ROW) {
|
|
typedef long long (*f_last_rowid)(void*);
|
|
static f_last_rowid db_last_rowid = NULL;
|
|
if (!db_last_rowid) db_last_rowid = (f_last_rowid)dlsym(sqlite_lib, "sqlite3_last_insert_rowid");
|
|
if (db_last_rowid) *out_id = db_last_rowid(db_handle);
|
|
}
|
|
db_finalize(stmt2);
|
|
}
|
|
return 0;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
static char *ai_get_question(long long id) {
|
|
void *stmt;
|
|
const char *sql = "SELECT question FROM ai_pending WHERE id=?";
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
|
|
typedef int (*f_bind_int64)(void*, int, long long);
|
|
static f_bind_int64 db_bind_int64 = NULL;
|
|
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
|
|
if (db_bind_int64) db_bind_int64(stmt, 1, id);
|
|
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;
|
|
}
|
|
|
|
static int ai_set_answer(long long id, const char *answer) {
|
|
const char *sql = "UPDATE ai_pending SET answer=?, status='done' WHERE id=?";
|
|
void *stmt;
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return -1;
|
|
db_bind_text(stmt, 1, answer, -1, SQLITE_STATIC);
|
|
typedef int (*f_bind_int64)(void*, int, long long);
|
|
static f_bind_int64 db_bind_int64 = NULL;
|
|
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
|
|
if (db_bind_int64) db_bind_int64(stmt, 2, id);
|
|
int rc = db_step(stmt);
|
|
db_finalize(stmt);
|
|
return rc == SQLITE_DONE ? 0 : -1;
|
|
}
|
|
|
|
static char *ai_get_answer(long long id) {
|
|
void *stmt;
|
|
const char *sql = "SELECT answer,target FROM ai_pending WHERE id=? AND status='done'";
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
|
|
typedef int (*f_bind_int64)(void*, int, long long);
|
|
static f_bind_int64 db_bind_int64 = NULL;
|
|
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
|
|
if (db_bind_int64) db_bind_int64(stmt, 1, id);
|
|
if (db_step(stmt) != SQLITE_ROW) { db_finalize(stmt); return NULL; }
|
|
const char *a = (const char*)db_column_text(stmt, 0);
|
|
const char *t = (const char*)db_column_text(stmt, 1);
|
|
char *r = NULL;
|
|
if (a && t) { if (asprintf(&r, "%s\037%s", a, t) < 0) r = NULL; }
|
|
db_finalize(stmt);
|
|
return r;
|
|
}
|
|
|
|
static char *ai_get_nick(long long id) {
|
|
void *stmt;
|
|
const char *sql = "SELECT nick FROM ai_pending WHERE id=?";
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return NULL;
|
|
typedef int (*f_bind_int64)(void*, int, long long);
|
|
static f_bind_int64 db_bind_int64 = NULL;
|
|
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
|
|
if (db_bind_int64) db_bind_int64(stmt, 1, id);
|
|
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;
|
|
}
|
|
|
|
static void ai_reset(long long id) {
|
|
const char *sql = "DELETE FROM ai_pending WHERE id=?";
|
|
void *stmt;
|
|
if (db_prepare(DB, sql, -1, &stmt, NULL) != SQLITE_OK) return;
|
|
typedef int (*f_bind_int64)(void*, int, long long);
|
|
static f_bind_int64 db_bind_int64 = NULL;
|
|
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
|
|
if (db_bind_int64) db_bind_int64(stmt, 1, id);
|
|
db_step(stmt);
|
|
db_finalize(stmt);
|
|
}
|
|
|
|
/* ---- channel op tracking ---- */
|
|
|
|
typedef struct { char name[64]; char ops[MAX_CHAN_OPS][32]; int nops; } ChanEntry;
|
|
static ChanEntry chans[MAX_CHANS];
|
|
static int nchans;
|
|
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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++;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* ---- network I/O ---- */
|
|
|
|
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;
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
static int net_send(Session *s, const char *fmt, ...) {
|
|
char buf[4096];
|
|
va_list ap;
|
|
va_start(ap, fmt);
|
|
int n = vsnprintf(buf, sizeof buf, fmt, ap);
|
|
va_end(ap);
|
|
if (n <= 0) return 0;
|
|
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;
|
|
}
|
|
left -= w; p += w;
|
|
}
|
|
return n;
|
|
}
|
|
|
|
/* ---- TLS ---- */
|
|
|
|
static SSL_CTX *tls_ctx;
|
|
static int tls_verify = 1;
|
|
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
static void tls_cleanup(Session *s) {
|
|
if (!s->ssl) return;
|
|
SSL_shutdown(s->ssl);
|
|
SSL_free(s->ssl);
|
|
s->ssl = NULL;
|
|
}
|
|
|
|
/* ---- signal handling ---- */
|
|
|
|
static volatile sig_atomic_t running = 1;
|
|
static void handle_sigterm(int sig) { (void)sig; running = 0; }
|
|
|
|
/* ---- rate limiting ---- */
|
|
|
|
static struct { char nick[32]; time_t t; } rate_limits[RATE_LIMIT_MAX];
|
|
|
|
static int rate_limit_check(const char *nick) {
|
|
time_t now = time(NULL);
|
|
int slot = -1, oldest = 0;
|
|
for (int i = 0; i < RATE_LIMIT_MAX; i++) {
|
|
if (rate_limits[i].t == 0) { slot = i; break; }
|
|
if (rate_limits[i].t < rate_limits[oldest].t) oldest = i;
|
|
if (strcmp(rate_limits[i].nick, nick) == 0) {
|
|
if (now - rate_limits[i].t < RATE_LIMIT_WINDOW) return -1;
|
|
slot = i; break;
|
|
}
|
|
}
|
|
if (slot < 0) slot = oldest;
|
|
strncpy(rate_limits[slot].nick, nick, sizeof rate_limits[slot].nick - 1);
|
|
rate_limits[slot].nick[sizeof rate_limits[slot].nick - 1] = 0;
|
|
rate_limits[slot].t = now;
|
|
return 0;
|
|
}
|
|
|
|
/* ---- text utilities ---- */
|
|
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
/* ---- curl helper ---- */
|
|
|
|
static char *run_curl(const char *url) {
|
|
int fd[2];
|
|
if (pipe(fd) < 0) return NULL;
|
|
pid_t pid = fork();
|
|
if (pid < 0) { close(fd[0]); close(fd[1]); return NULL; }
|
|
if (pid == 0) {
|
|
close(fd[0]);
|
|
dup2(fd[1], STDOUT_FILENO);
|
|
close(fd[1]);
|
|
int dn = open("/dev/null", O_WRONLY);
|
|
if (dn >= 0) { dup2(dn, STDERR_FILENO); close(dn); }
|
|
execlp("curl", "curl", "-s", "--max-time", "10", url, (char *)NULL);
|
|
_exit(127);
|
|
}
|
|
close(fd[1]);
|
|
char buf[2048];
|
|
size_t len = 0;
|
|
ssize_t n;
|
|
while ((n = read(fd[0], buf + len, 2047 - len)) > 0) len += n;
|
|
close(fd[0]);
|
|
int status;
|
|
waitpid(pid, &status, 0);
|
|
buf[len] = 0;
|
|
return status == 0 ? strdup(buf) : NULL;
|
|
}
|
|
|
|
static char *fetch_url(const char *url) { return run_curl(url); }
|
|
|
|
static char *fetch_forecast(const char *city_url, const char *city_display) {
|
|
char url[512];
|
|
snprintf(url, sizeof url, "https://wttr.in/%s?format=j1", city_url);
|
|
char *json = fetch_url(url);
|
|
if (!json) return NULL;
|
|
char *p = strstr(json, "\"weather\":[");
|
|
if (!p) { free(json); return NULL; }
|
|
p += 11;
|
|
char line[3][256], fmt_date[3][32];
|
|
int ndays = 0;
|
|
for (int i = 0; i < 3; i++) {
|
|
p = strchr(p, '{');
|
|
if (!p) break;
|
|
const char *obj_end = p + 1;
|
|
int depth = 1;
|
|
while (*obj_end && depth > 0) { if (*obj_end == '{') depth++; else if (*obj_end == '}') depth--; obj_end++; }
|
|
char date[16]="", temp[8]="", cond[64]="";
|
|
char *db = strstr(p, "\"date\": \"");
|
|
if (db && db < obj_end) { db += 9; char *dq = strchr(db, '"'); if (dq && dq < obj_end) { size_t l = dq - db; if (l>15) l=15; memcpy(date,db,l); date[l]=0; } }
|
|
char *tb = strstr(p, "\"avgtempC\": \"");
|
|
if (tb && tb < obj_end) { tb += 13; char *tq = strchr(tb, '"'); if (tq && tq < obj_end) { size_t l = tq - tb; if (l>7) l=7; memcpy(temp,tb,l); temp[l]=0; } }
|
|
char *hb = strstr(p, "\"hourly\":[");
|
|
if (hb && hb < obj_end) {
|
|
char *vb = strstr(hb, "\"value\": \"");
|
|
if (vb && vb < obj_end) { vb += 9; char *vq = strchr(vb, '"'); if (vq && vq < obj_end) { size_t l = vq - vb; if (l>63) l=63; memcpy(cond,vb,l); cond[l]=0; } }
|
|
}
|
|
struct tm tm = {0};
|
|
if (strptime(date, "%Y-%m-%d", &tm)) strftime(fmt_date[ndays], sizeof fmt_date[ndays], "%a %d %b", &tm);
|
|
else snprintf(fmt_date[ndays], sizeof fmt_date[ndays], "%s", date);
|
|
snprintf(line[ndays], sizeof line[ndays], "%s: %s\u00b0C %s", fmt_date[ndays], temp, cond);
|
|
ndays++;
|
|
p = (char*)obj_end;
|
|
}
|
|
free(json);
|
|
if (!ndays) return NULL;
|
|
char *out = NULL;
|
|
if (ndays == 1) { if (asprintf(&out, "Forecast for %s: %s", city_display, line[0]) < 0) out = NULL; }
|
|
else if (ndays == 2) { if (asprintf(&out, "Forecast for %s: %s / %s", city_display, line[0], line[1]) < 0) out = NULL; }
|
|
else { if (asprintf(&out, "Forecast for %s: %s / %s / %s", city_display, line[0], line[1], line[2]) < 0) out = NULL; }
|
|
return out;
|
|
}
|
|
|
|
/* ---- AI pipeline ---- */
|
|
|
|
static volatile pid_t pending_ai_pid;
|
|
static volatile long long pending_ai_id;
|
|
static volatile const char *pending_ai_agent;
|
|
|
|
static void ai_child_task(Session *s, long long id) {
|
|
signal(SIGALRM, SIG_DFL);
|
|
alarm(AI_TIMEOUT);
|
|
/* Don't call tls_cleanup() — SSL_shutdown would send a close_notify on
|
|
* the shared fd, breaking the parent's connection. Just release our
|
|
* fd reference; the kernel will close it on exit. */
|
|
if (s->fd >= 0) close(s->fd);
|
|
s->fd = -1;
|
|
s->ssl = NULL;
|
|
db_close(DB);
|
|
db_handle = NULL;
|
|
if (db_open("zynk.db", &db_handle) != SQLITE_OK) exit(1);
|
|
char *q = ai_get_question(id);
|
|
if (!q) { db_close(DB); exit(1); }
|
|
char *history[MAX_HISTORY];
|
|
char hkey[MAX_HISTORY][12];
|
|
for (int i = 0; i < MAX_HISTORY; i++) {
|
|
snprintf(hkey[i], sizeof hkey[i], "lasta%02d", i + 1);
|
|
history[i] = db_get_raw(hkey[i]);
|
|
}
|
|
int have_history = 0;
|
|
for (int i = 0; i < MAX_HISTORY; i++) { if (history[i]) { have_history = 1; break; } }
|
|
char prefix[2048];
|
|
int plen;
|
|
if (pending_ai_agent) {
|
|
plen = snprintf(prefix, sizeof prefix,
|
|
"Your name is zynk. You are a coding assistant in a project. Execute code changes as requested. "
|
|
"Make real file edits and run commands as needed. Answer in English when asked in English, answer in German when asked in German. "
|
|
"Max 2000 chars. No disclaimers or AI-sounding phrases. No markdown/formatting. "
|
|
"Just make the changes directly and confirm what you did.");
|
|
} else {
|
|
plen = snprintf(prefix, sizeof prefix,
|
|
"Your name is zynk. You are in plan mode - you can only answer questions and discuss code, "
|
|
"but you CANNOT make any changes to files or execute commands. If someone asks you to change or edit code, "
|
|
"tell them you are in plan mode and can only answer questions. Suggest they use !code <instruction> to make actual code changes. "
|
|
"Answer briefly. Answer in English when asked in English, answer in German when asked in German. Max 800 chars. "
|
|
"No disclaimers or AI-sounding phrases. No markdown/formatting. "
|
|
"Just answer directly.");
|
|
}
|
|
if (have_history) {
|
|
plen += snprintf(prefix + plen, sizeof prefix - plen,
|
|
" My recent answers for context (only use if absolutely necessary): ");
|
|
for (int i = 0; i < MAX_HISTORY; i++) {
|
|
if (history[i])
|
|
plen += snprintf(prefix + plen, sizeof prefix - plen, "[%s] ", history[i]);
|
|
}
|
|
}
|
|
for (int i = 0; i < MAX_HISTORY; i++) free(history[i]);
|
|
char combined[8192];
|
|
snprintf(combined, sizeof combined, "%s%s", prefix, q ? q : "");
|
|
free(q);
|
|
int ai_pipe[2];
|
|
if (pipe(ai_pipe) < 0) { ai_set_answer(id, "AI query failed (pipe error)"); db_close(DB); exit(0); }
|
|
pid_t cmd_pid = fork();
|
|
if (cmd_pid < 0) { close(ai_pipe[0]); close(ai_pipe[1]); ai_set_answer(id, "AI query failed (fork error)"); db_close(DB); exit(0); }
|
|
if (cmd_pid == 0) {
|
|
close(ai_pipe[0]);
|
|
dup2(ai_pipe[1], STDOUT_FILENO);
|
|
close(ai_pipe[1]);
|
|
int dn = open("/dev/null", O_WRONLY);
|
|
if (dn >= 0) { dup2(dn, STDERR_FILENO); close(dn); }
|
|
if (pending_ai_agent)
|
|
execl(OPENCODE_BIN, "opencode", "run", "--dangerously-skip-permissions", "--agent", pending_ai_agent, combined, (char *)NULL);
|
|
else
|
|
execl(OPENCODE_BIN, "opencode", "run", "--dangerously-skip-permissions", "--agent", "plan", combined, (char *)NULL);
|
|
_exit(127);
|
|
}
|
|
close(ai_pipe[1]);
|
|
char out[6144];
|
|
size_t olen = 0;
|
|
ssize_t n;
|
|
while ((n = read(ai_pipe[0], out + olen, 6143 - olen)) > 0) olen += n;
|
|
close(ai_pipe[0]);
|
|
int status;
|
|
waitpid(cmd_pid, &status, 0);
|
|
while (olen > 0 && (out[olen-1] == '\n' || out[olen-1] == '\r')) olen--;
|
|
out[olen] = 0;
|
|
int rc = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
|
|
if (rc != 0) {
|
|
ai_set_answer(id, "AI query failed (opencode exited with error)");
|
|
} else if (olen == 0) {
|
|
ai_set_answer(id, "AI returned an empty response");
|
|
} else {
|
|
strip_formatting(out);
|
|
strip_ai_phrases(out);
|
|
ai_set_answer(id, out);
|
|
db_update_lasta(out);
|
|
}
|
|
db_close(DB);
|
|
exit(0);
|
|
}
|
|
|
|
static void ai_ask(Session *s, const char *question, const char *reply_target, const char *src_nick, const char *agent) {
|
|
if (rate_limit_check(src_nick) < 0) return;
|
|
if (pending_ai_pid > 0) {
|
|
irc_msg(s, reply_target, "Already processing an AI query, please wait.");
|
|
return;
|
|
}
|
|
db_update_lastq(question);
|
|
long long id = 0;
|
|
if (ai_start(question, reply_target, src_nick, &id) != 0) {
|
|
irc_msg(s, reply_target, "Error starting AI query");
|
|
return;
|
|
}
|
|
pid_t pid = fork();
|
|
if (pid == -1) { ai_reset(id); irc_msg(s, reply_target, "Error forking"); return; }
|
|
if (pid == 0) { ai_child_task(s, id); }
|
|
pending_ai_pid = pid;
|
|
pending_ai_id = id;
|
|
pending_ai_agent = agent;
|
|
log_stamp(); fprintf(stderr, CLR_BLUE "AI started (PID %d, ID %lld) from %s:" CLR_RESET " %s\n", pid, id, src_nick, question);
|
|
}
|
|
|
|
static void ai_check_completion(Session *s) {
|
|
if (pending_ai_pid <= 0) return;
|
|
int wstatus;
|
|
pid_t done_pid = pending_ai_pid;
|
|
long long done_id = pending_ai_id;
|
|
if (waitpid(pending_ai_pid, &wstatus, WNOHANG) <= 0) return;
|
|
pending_ai_pid = 0;
|
|
char *nick = ai_get_nick(done_id);
|
|
char *result = ai_get_answer(done_id);
|
|
if (result) {
|
|
char *answer = result;
|
|
char *sep = strchr(result, '\037');
|
|
char *target = NULL;
|
|
if (sep) { *sep = 0; target = sep + 1; }
|
|
if (target) {
|
|
size_t alen = strlen(answer);
|
|
#define AI_CHUNK_MAX 450
|
|
size_t pos = 0;
|
|
int chunks = 0;
|
|
while (pos < alen) {
|
|
size_t end = pos + AI_CHUNK_MAX;
|
|
if (end >= alen) {
|
|
irc_msg(s, target, answer + pos);
|
|
chunks++;
|
|
break;
|
|
}
|
|
while (end > pos && answer[end] != ' ') end--;
|
|
if (end <= pos) end = pos + AI_CHUNK_MAX;
|
|
char save = answer[end];
|
|
answer[end] = 0;
|
|
irc_msg(s, target, answer + pos);
|
|
answer[end] = save;
|
|
pos = end + 1;
|
|
chunks++;
|
|
}
|
|
log_stamp(); fprintf(stderr, CLR_BLUE "AI done PID %d from %s: %zu chars sent as %d chunks to %s" CLR_RESET "\n", done_pid, nick ? nick : "?", alen, chunks, target);
|
|
}
|
|
free(result);
|
|
ai_reset(done_id);
|
|
} else {
|
|
char *target = NULL;
|
|
void *stmt;
|
|
if (db_prepare(DB, "SELECT target FROM ai_pending WHERE id=?", -1, &stmt, NULL) == SQLITE_OK) {
|
|
typedef int (*f_bind_int64)(void*, int, long long);
|
|
static f_bind_int64 db_bind_int64 = NULL;
|
|
if (!db_bind_int64) db_bind_int64 = (f_bind_int64)dlsym(sqlite_lib, "sqlite3_bind_int64");
|
|
if (db_bind_int64) db_bind_int64(stmt, 1, done_id);
|
|
if (db_step(stmt) == SQLITE_ROW) {
|
|
const char *t = (const char*)db_column_text(stmt, 0);
|
|
if (t) target = strdup(t);
|
|
}
|
|
db_finalize(stmt);
|
|
}
|
|
if (WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGALRM) {
|
|
if (target) {
|
|
irc_msg(s, target, "AI query timed out after AI_TIMEOUT seconds.");
|
|
log_stamp(); fprintf(stderr, CLR_RED "AI done PID %d from %s: timed out for %s" CLR_RESET "\n", done_pid, nick ? nick : "?", target);
|
|
}
|
|
} else if (target) {
|
|
irc_msg(s, target, "AI query failed.");
|
|
log_stamp(); fprintf(stderr, CLR_RED "AI done PID %d from %s: failed for %s" CLR_RESET "\n", done_pid, nick ? nick : "?", target);
|
|
}
|
|
free(target);
|
|
ai_reset(done_id);
|
|
}
|
|
free(nick);
|
|
}
|
|
|
|
/* ---- IRC protocol helpers ---- */
|
|
|
|
static void irc_join(Session *s, const char *chan) { net_send(s, "JOIN %s\r\n", chan); }
|
|
|
|
static void irc_msg(Session *s, const char *t, const char *txt) {
|
|
char *clean = NULL;
|
|
if (strpbrk(txt, "\r\n")) {
|
|
clean = strdup(txt);
|
|
if (clean) { for (char *p = clean; *p; p++) if (*p == '\r' || *p == '\n') *p = ' '; txt = clean; }
|
|
}
|
|
net_send(s, "PRIVMSG %s :%s\r\n", t, txt);
|
|
free(clean);
|
|
}
|
|
|
|
static void irc_nick(Session *s, const char *nn) { net_send(s, "NICK %s\r\n", nn); }
|
|
static void irc_pong(Session *s, const char *r) { if (*r == ':') r++; net_send(s, "PONG :%s\r\n", r); }
|
|
|
|
/* ---- IRC command handlers ---- */
|
|
|
|
static int cmd_zynk(Session *s, const char *msg, const char *reply_target, const char *src_nick, const char *tgt) {
|
|
if (strncmp(msg, "zynk", 4) != 0) return 0;
|
|
if (msg[4] != '\0' && msg[4] != ' ' && msg[4] != '!') return 0;
|
|
if (rate_limit_check(src_nick) < 0) return 1;
|
|
/* zynk!foo without space after ! falls through to other commands */
|
|
if (msg[4] == '!' && msg[5] != '\0' && msg[5] != ' ') return 0;
|
|
int force = 0;
|
|
const char *rest;
|
|
if (msg[4] == '\0') {
|
|
char *rand = db_get_random();
|
|
if (rand) {
|
|
irc_msg(s, reply_target, rand);
|
|
log_stamp(); fprintf(stderr, CLR_MAGENTA "ZYNK %s from %s:" CLR_RESET " random %s\n", reply_target, src_nick, rand);
|
|
free(rand);
|
|
} else {
|
|
irc_msg(s, reply_target, "No zynkss saved yet.");
|
|
}
|
|
return 1;
|
|
} else if (msg[4] == '!') {
|
|
if (msg[5] == '\0') {
|
|
irc_msg(s, reply_target, "Usage: zynk! <key> = <value>");
|
|
return 1;
|
|
}
|
|
force = 1;
|
|
rest = msg + 6;
|
|
} else {
|
|
rest = msg + 5;
|
|
}
|
|
while (*rest == ' ') rest++;
|
|
if (!*rest) {
|
|
irc_msg(s, reply_target, "Usage: zynk <key> [= <value>]");
|
|
return 1;
|
|
}
|
|
const char *eq = strstr(rest, " = ");
|
|
char resp[1024];
|
|
if (eq) {
|
|
char key[256];
|
|
size_t kl = eq - rest;
|
|
if (kl == 0) { irc_msg(s, reply_target, "Key cannot be empty"); return 1; }
|
|
if (kl >= sizeof key) kl = sizeof key - 1;
|
|
memcpy(key, rest, kl); key[kl] = 0;
|
|
for (char *p = key; *p; p++) *p = tolower((unsigned char)*p);
|
|
if (!force) {
|
|
char *existing = db_get_raw(key);
|
|
if (existing) {
|
|
free(existing);
|
|
snprintf(resp, sizeof resp, "zynk already exists (use zynk! to overwrite)");
|
|
irc_msg(s, reply_target, resp);
|
|
log_stamp(); fprintf(stderr, CLR_MAGENTA "ZYNK %s from %s:" CLR_RESET " blocked re-add of %s\n", reply_target, src_nick, key);
|
|
return 1;
|
|
}
|
|
} else {
|
|
if (tgt[0] == '#' && !chan_is_op(tgt, src_nick)) {
|
|
irc_msg(s, reply_target, "You need op to overwrite a zynk");
|
|
return 1;
|
|
}
|
|
}
|
|
const char *val = eq + 3;
|
|
while (*val == ' ') val++;
|
|
if (db_set(key, val, src_nick) == 0)
|
|
snprintf(resp, sizeof resp, "%s = %s (saved)", key, val);
|
|
else
|
|
snprintf(resp, sizeof resp, "Error saving %s", key);
|
|
} else {
|
|
char key[256];
|
|
snprintf(key, sizeof key, "%s", rest);
|
|
for (char *p = key; *p; p++) *p = tolower((unsigned char)*p);
|
|
char *end = key + strlen(key);
|
|
while (end > key && end[-1] == ' ') end--;
|
|
*end = 0;
|
|
char *val = db_get(key);
|
|
if (val) {
|
|
snprintf(resp, sizeof resp, "%s: %s", key, val);
|
|
free(val);
|
|
} else {
|
|
snprintf(resp, sizeof resp, "%s: not found", key);
|
|
}
|
|
}
|
|
irc_msg(s, reply_target, resp);
|
|
log_stamp(); fprintf(stderr, CLR_MAGENTA "ZYNK %s from %s:" CLR_RESET " %s\n", reply_target, src_nick, resp);
|
|
return 1;
|
|
}
|
|
|
|
static int cmd_ping(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
|
|
if (strncmp(msg, "!ping", 5) != 0) return 0;
|
|
if (msg[5] != ' ' && msg[5] != '\0') return 0;
|
|
if (rate_limit_check(src_nick) < 0) return 1;
|
|
char pong_buf[96]; snprintf(pong_buf, sizeof pong_buf, "%s: pong!", src_nick);
|
|
irc_msg(s, reply_target, pong_buf);
|
|
log_stamp(); fprintf(stderr, CLR_YELLOW "PING from %s in %s" CLR_RESET "\n", src_nick, reply_target);
|
|
return 1;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
static int cmd_weather(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
|
|
if (strncmp(msg, "!weather", 8) != 0) return 0;
|
|
if (msg[8] != ' ' && msg[8] != '\0') return 0;
|
|
if (rate_limit_check(src_nick) < 0) return 1;
|
|
char city[256];
|
|
const char *rest = msg[8] == ' ' ? msg + 9 : "";
|
|
while (*rest == ' ') rest++;
|
|
if (*rest) {
|
|
snprintf(city, sizeof city, "%s", rest);
|
|
char *end = city + strlen(city);
|
|
while (end > city && end[-1] == ' ') end--;
|
|
*end = 0;
|
|
} else {
|
|
snprintf(city, sizeof city, "Berlin");
|
|
}
|
|
for (char *p = city; *p; p++) if (*p == ' ') *p = '+';
|
|
char url[512];
|
|
snprintf(url, sizeof url, "https://wttr.in/%s?format=%%l:+%%t+%%C&m", city);
|
|
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;
|
|
}
|
|
|
|
static int cmd_forecast(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
|
|
if (strncmp(msg, "!forecast", 9) != 0) return 0;
|
|
if (msg[9] != ' ' && msg[9] != '\0') return 0;
|
|
if (rate_limit_check(src_nick) < 0) return 1;
|
|
char city[256], city_url[256];
|
|
const char *rest = msg[9] == ' ' ? msg + 10 : "";
|
|
while (*rest == ' ') rest++;
|
|
if (*rest) {
|
|
snprintf(city, sizeof city, "%s", rest);
|
|
char *end = city + strlen(city);
|
|
while (end > city && end[-1] == ' ') end--;
|
|
*end = 0;
|
|
} else {
|
|
snprintf(city, sizeof city, "Berlin");
|
|
}
|
|
snprintf(city_url, sizeof city_url, "%s", city);
|
|
for (char *p = city_url; *p; p++) if (*p == ' ') *p = '+';
|
|
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;
|
|
}
|
|
|
|
static int cmd_ai(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
|
|
if (strncmp(msg, "!ai", 3) != 0) return 0;
|
|
if (msg[3] != ' ' && msg[3] != '\0') return 0;
|
|
const char *rest = msg[3] == ' ' ? msg + 4 : "";
|
|
while (*rest == ' ') rest++;
|
|
if (!*rest) {
|
|
irc_msg(s, reply_target, "Usage: !ai <question>");
|
|
return 1;
|
|
}
|
|
char question[2048];
|
|
snprintf(question, sizeof question, "%s", rest);
|
|
char *end = question + strlen(question);
|
|
while (end > question && end[-1] == ' ') end--;
|
|
*end = 0;
|
|
ai_ask(s, question, reply_target, src_nick, NULL);
|
|
return 1;
|
|
}
|
|
|
|
static int cmd_code(Session *s, const char *msg, const char *reply_target, const char *src_nick, const char *tgt) {
|
|
if (strncmp(msg, "!code", 5) != 0) return 0;
|
|
if (msg[5] != ' ' && msg[5] != '\0') return 0;
|
|
if (tgt[0] != '#') {
|
|
irc_msg(s, reply_target, "!code can only be used in a channel");
|
|
return 1;
|
|
}
|
|
if (!chan_is_op(tgt, src_nick)) {
|
|
irc_msg(s, reply_target, "You need to be a channel op to use !code");
|
|
return 1;
|
|
}
|
|
const char *rest = msg[5] == ' ' ? msg + 6 : "";
|
|
while (*rest == ' ') rest++;
|
|
if (!*rest) {
|
|
irc_msg(s, reply_target, "Usage: !code <instruction for code change>");
|
|
return 1;
|
|
}
|
|
char question[2048];
|
|
snprintf(question, sizeof question,
|
|
"[CODE CHANGE REQUEST from op %s in %s] %s", src_nick, tgt, rest);
|
|
char *end = question + strlen(question);
|
|
while (end > question && end[-1] == ' ') end--;
|
|
*end = 0;
|
|
ai_ask(s, question, reply_target, src_nick, "build");
|
|
log_stamp(); fprintf(stderr, CLR_RED "CODE %s from %s (op in %s):" CLR_RESET " %s\n", reply_target, src_nick, tgt, rest);
|
|
return 1;
|
|
}
|
|
|
|
static void cmd_greeting_or_chat(Session *s, const char *msg, const char *reply_target, const char *src_nick) {
|
|
int nicklen = strlen(s->nick);
|
|
const char *cmd = msg;
|
|
if (strncasecmp(msg, s->nick, nicklen) == 0 && msg[nicklen] == ':') {
|
|
cmd = msg + nicklen + 1;
|
|
while (*cmd == ' ') cmd++;
|
|
if (!*cmd) cmd = msg;
|
|
}
|
|
char resp[1024];
|
|
int matched = 0;
|
|
if (strcasecmp(cmd, "hi") == 0 || strcasecmp(cmd, "hey") == 0 || strcasecmp(cmd, "hello") == 0) {
|
|
snprintf(resp, sizeof resp, "Hi, %s!", src_nick); matched = 1;
|
|
} else if (strcasecmp(cmd, "bye") == 0 || strcasecmp(cmd, "goodbye") == 0) {
|
|
snprintf(resp, sizeof resp, "Bye, %s!", src_nick); matched = 1;
|
|
} else if (strcasecmp(cmd, "jojo") == 0) {
|
|
snprintf(resp, sizeof resp, "Jo, %s!", src_nick); matched = 1;
|
|
} else if (strcasecmp(cmd, "whatsup") == 0) {
|
|
snprintf(resp, sizeof resp, "Not much, %s!", src_nick); matched = 1;
|
|
} else if (strcasecmp(cmd, "waddup") == 0) {
|
|
snprintf(resp, sizeof resp, "Yo %s!", src_nick); matched = 1;
|
|
} else if (strcasecmp(cmd, "waddup yo") == 0) {
|
|
snprintf(resp, sizeof resp, "Yo!"); matched = 1;
|
|
} else if (strcasecmp(cmd, "deine muddi") == 0 || strcasecmp(cmd, "deine mutter") == 0) {
|
|
snprintf(resp, sizeof resp, "Ey, %s, lass das!", src_nick); matched = 1;
|
|
} else if (strcasecmp(cmd, "penis") == 0) {
|
|
snprintf(resp, sizeof resp, "..."); matched = 1;
|
|
}
|
|
if (matched) {
|
|
irc_msg(s, reply_target, resp);
|
|
log_stamp(); fprintf(stderr, CLR_CYAN "CHAT %s from %s:" CLR_RESET " %s\n", reply_target, src_nick, resp);
|
|
return;
|
|
}
|
|
if (cmd != msg) {
|
|
ai_ask(s, cmd, reply_target, src_nick, NULL);
|
|
}
|
|
}
|
|
|
|
/* ---- IRC protocol handlers ---- */
|
|
|
|
static void handle_privmsg(Session *s, const char *params, const char *src_nick) {
|
|
const char *p = params;
|
|
const char *target = p;
|
|
p = strchr(p, ' '); if (!p) return;
|
|
char tgt[256]; size_t tl = p - target;
|
|
if (tl >= sizeof tgt) tl = sizeof tgt - 1;
|
|
memcpy(tgt, target, tl); tgt[tl] = 0;
|
|
while (*p == ' ') p++;
|
|
if (*p == ':') p++;
|
|
const char *msg = p;
|
|
if (strcasecmp(src_nick, s->nick) == 0) return;
|
|
const char *reply_target = (tgt[0] == '#') ? tgt : src_nick;
|
|
if (cmd_zynk(s, msg, reply_target, src_nick, tgt)) return;
|
|
if (cmd_ping(s, msg, reply_target, src_nick)) return;
|
|
if (cmd_quit(s, msg, reply_target, src_nick, tgt)) return;
|
|
if (cmd_weather(s, msg, reply_target, src_nick)) return;
|
|
if (cmd_forecast(s, msg, reply_target, src_nick)) return;
|
|
if (cmd_ai(s, msg, reply_target, src_nick)) return;
|
|
if (cmd_code(s, msg, reply_target, src_nick, tgt)) return;
|
|
cmd_greeting_or_chat(s, msg, reply_target, src_nick);
|
|
}
|
|
|
|
static void handle_namreply(Session *s, const char *params) {
|
|
(void)s;
|
|
char our[32], _chan[64];
|
|
const char *p = params;
|
|
/* params: "<nick> <type> <chan> :<nicks>" */
|
|
if (sscanf(p, "%31s %*s %63s", our, _chan) < 2) return;
|
|
p = strchr(p, ':');
|
|
if (!p) return;
|
|
p++;
|
|
char buf[32];
|
|
while (*p) {
|
|
while (*p == ' ') p++;
|
|
if (!*p) break;
|
|
int is_op = 0;
|
|
while (*p && (*p == '@' || *p == '~' || *p == '&' || *p == '%')) {
|
|
if (*p == '@' || *p == '~' || *p == '&') is_op = 1;
|
|
p++;
|
|
}
|
|
int i = 0;
|
|
while (*p && *p != ' ' && i < 31) buf[i++] = *p++;
|
|
buf[i] = 0;
|
|
if (is_op && buf[0]) chan_add_op(_chan, buf);
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
static void handle_join(Session *s, const char *params) {
|
|
(void)s;
|
|
const char *p = params;
|
|
if (*p == ':') p++;
|
|
chan_get_or_add(p);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
static void handle_quit_net(const char *src_nick) {
|
|
for (int i = 0; i < nchans; i++)
|
|
chan_del_op(chans[i].name, src_nick);
|
|
}
|
|
|
|
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;
|
|
if (strcasecmp(src_nick, s->nick) == 0) {
|
|
const char *newnick = params;
|
|
if (*newnick == ':') newnick++;
|
|
strncpy(s->nick, newnick, sizeof s->nick - 1);
|
|
s->nick[sizeof s->nick - 1] = 0;
|
|
}
|
|
}
|
|
|
|
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 ---- */
|
|
|
|
static void irc_handle(Session *s, const char *raw) {
|
|
if (!raw || !*raw) return;
|
|
const char *prefix = NULL, *cmd = raw;
|
|
char pfx_buf[512], cmd_buf[64];
|
|
pfx_buf[0] = cmd_buf[0] = 0;
|
|
if (*raw == ':') {
|
|
raw++;
|
|
const char *sp = strchr(raw, ' ');
|
|
if (!sp) return;
|
|
size_t plen = sp - raw;
|
|
if (plen >= sizeof pfx_buf) plen = sizeof pfx_buf - 1;
|
|
memcpy(pfx_buf, raw, plen); pfx_buf[plen] = 0;
|
|
prefix = pfx_buf;
|
|
cmd = sp + 1;
|
|
while (*cmd == ' ') cmd++;
|
|
if (!*cmd) return;
|
|
}
|
|
const char *params = strchr(cmd, ' ');
|
|
if (params) {
|
|
size_t clen = params - cmd;
|
|
if (clen >= sizeof cmd_buf) clen = sizeof cmd_buf - 1;
|
|
memcpy(cmd_buf, cmd, clen); cmd_buf[clen] = 0;
|
|
while (*params == ' ') params++;
|
|
} else {
|
|
size_t cl2 = strlen(cmd);
|
|
if (cl2 >= sizeof cmd_buf) cl2 = sizeof cmd_buf - 1;
|
|
memcpy(cmd_buf, cmd, cl2); cmd_buf[cl2] = 0;
|
|
params = "";
|
|
}
|
|
if (strcmp(cmd_buf, "PING") == 0) { irc_pong(s, params); return; }
|
|
char src_nick[64] = "";
|
|
if (prefix) {
|
|
const char *ex = strchr(prefix, '!');
|
|
size_t nlen = ex ? (size_t)(ex - prefix) : strlen(prefix);
|
|
if (nlen >= sizeof src_nick) nlen = sizeof src_nick - 1;
|
|
memcpy(src_nick, prefix, nlen); src_nick[nlen] = 0;
|
|
}
|
|
if (strcmp(cmd_buf, "001") == 0) {
|
|
s->connected = 1;
|
|
log_stamp(); fprintf(stderr, CLR_GREEN "Connected to %s" CLR_RESET "\n", s->host);
|
|
return;
|
|
}
|
|
if (strcmp(cmd_buf, "376") == 0 || strcmp(cmd_buf, "422") == 0) {
|
|
log_stamp(); fprintf(stderr, CLR_GREEN "MOTD end, joining channels..." CLR_RESET "\n");
|
|
char *copy = strdup(s->auto_join);
|
|
if (copy) {
|
|
char *save;
|
|
for (char *tok = strtok_r(copy, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) {
|
|
while (*tok == ' ') tok++;
|
|
char *end = tok + strlen(tok);
|
|
while (end > tok && end[-1] == ' ') end--;
|
|
*end = 0;
|
|
if (*tok) { irc_join(s, tok); log_stamp(); fprintf(stderr, CLR_GREEN "Joining %s" CLR_RESET "\n", tok); }
|
|
}
|
|
free(copy);
|
|
}
|
|
return;
|
|
}
|
|
if (strcmp(cmd_buf, "PRIVMSG") == 0) { handle_privmsg(s, params, src_nick); return; }
|
|
if (strcmp(cmd_buf, "353") == 0) { handle_namreply(s, params); return; }
|
|
if (strcmp(cmd_buf, "MODE") == 0) { handle_mode(s, params); return; }
|
|
if (strcmp(cmd_buf, "JOIN") == 0 && prefix) { handle_join(s, params); return; }
|
|
if (strcmp(cmd_buf, "PART") == 0 && prefix) { handle_part(params, src_nick); return; }
|
|
if (strcmp(cmd_buf, "KICK") == 0 && prefix) { handle_kick(params); return; }
|
|
if (strcmp(cmd_buf, "QUIT") == 0 && prefix) { handle_quit_net(src_nick); return; }
|
|
if (strcmp(cmd_buf, "NICK") == 0 && prefix) { handle_nick_change(s, prefix, params); return; }
|
|
handle_error_codes(s, cmd_buf, params);
|
|
}
|
|
|
|
/* ---- IRC line parser ---- */
|
|
|
|
static void irc_feed(Session *s, const char *data, int len) {
|
|
for (int i = 0; i < len; i++) {
|
|
char c = data[i];
|
|
if (c == '\r') continue;
|
|
if (c == '\n') {
|
|
s->rbuf[s->rlen] = 0;
|
|
if (s->rlen > 0) irc_handle(s, s->rbuf);
|
|
s->rlen = 0;
|
|
} else {
|
|
if (s->rlen < RBUF_SZ - 1) s->rbuf[s->rlen++] = c;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* ---- usage ---- */
|
|
|
|
static void usage(const char *prog) {
|
|
fprintf(stderr,
|
|
"Usage: %s [-ssl] [-server host] [-port p] [-nick n] [-join c]\n"
|
|
" -h This help\n"
|
|
" -noverify Skip TLS certificate verification\n"
|
|
" -server host IRC server (default: %s)\n"
|
|
" -port p Port (default: %d)\n"
|
|
" -pass p Server password\n"
|
|
" -nick n Nickname (default: zynk<PID>)\n"
|
|
" -join c Auto-join channels (comma-sep, default: #zynk)\n"
|
|
"\n"
|
|
"Zynk commands:\n"
|
|
" zynk foo = bar Store 'bar' under key 'foo'\n"
|
|
" zynk foo Retrieve value for 'foo'\n",
|
|
prog, DEFAULT_SERVER, DEF_PORT);
|
|
}
|
|
|
|
/* ---- reconnect ---- */
|
|
|
|
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 ---- */
|
|
|
|
int main(int argc, char **argv) {
|
|
const char *sv = DEFAULT_SERVER;
|
|
int use_tls = 0;
|
|
int port = DEF_PORT;
|
|
char nickbuf[32];
|
|
const char *nick = NULL;
|
|
char passbuf[256] = "";
|
|
char joinbuf[256] = "#zynk";
|
|
int pos = 0;
|
|
log_stamp(); fprintf(stderr, CLR_CYAN "[zynk] starting up" CLR_RESET "\n");
|
|
for (int i = 1; i < argc; i++) {
|
|
if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
|
|
usage(argv[0]); return 0;
|
|
}
|
|
if (argv[i][0] == '-') {
|
|
if (strcmp(argv[i], "-ssl") == 0 || strcmp(argv[i], "-tls") == 0)
|
|
use_tls = 1;
|
|
else if (strcmp(argv[i], "-pass") == 0) {
|
|
if (++i >= argc) { usage(argv[0]); return 1; }
|
|
snprintf(passbuf, sizeof passbuf, "%s", argv[i]);
|
|
} else if (strcmp(argv[i], "-nick") == 0) {
|
|
if (++i >= argc) { usage(argv[0]); return 1; }
|
|
nick = argv[i];
|
|
} else if (strcmp(argv[i], "-port") == 0) {
|
|
if (++i >= argc) { usage(argv[0]); return 1; }
|
|
port = atoi(argv[i]);
|
|
} else if (strcmp(argv[i], "-server") == 0) {
|
|
if (++i >= argc) { usage(argv[0]); return 1; }
|
|
sv = argv[i];
|
|
} else if (strcmp(argv[i], "-join") == 0) {
|
|
if (++i >= argc) { usage(argv[0]); return 1; }
|
|
snprintf(joinbuf, sizeof joinbuf, "%s", argv[i]);
|
|
} else if (strcmp(argv[i], "-noverify") == 0) {
|
|
tls_verify = 0;
|
|
} else {
|
|
usage(argv[0]); return 1;
|
|
}
|
|
} else switch (pos++) {
|
|
case 0: sv = argv[i]; break;
|
|
case 1: {
|
|
const char *p = argv[i];
|
|
if (p[0] == '+') { use_tls = 1; p++; }
|
|
port = atoi(p);
|
|
break;
|
|
}
|
|
case 2: nick = argv[i]; break;
|
|
default:
|
|
fprintf(stderr, CLR_RED "Unexpected arg:" CLR_RESET " %s\n", argv[i]);
|
|
return 1;
|
|
}
|
|
}
|
|
if (port <= 0 || port > 65535) port = DEF_PORT;
|
|
if ((port == 6697 || port == 7000) && !use_tls) use_tls = 1;
|
|
if (!nick) { snprintf(nickbuf, sizeof nickbuf, "zynk"); nick = nickbuf; }
|
|
if (db_init() < 0) { fprintf(stderr, CLR_RED "DB init failed" CLR_RESET "\n"); return 1; }
|
|
Session s;
|
|
memset(&s, 0, sizeof s);
|
|
snprintf(s.host, sizeof s.host, "%s", sv);
|
|
s.port = port;
|
|
snprintf(s.nick, sizeof s.nick, "%s", nick);
|
|
snprintf(s.user, sizeof s.user, "%s", nick);
|
|
snprintf(s.real, sizeof s.real, "zynk");
|
|
snprintf(s.auto_join, sizeof s.auto_join, "%s", joinbuf);
|
|
s.fd = -1;
|
|
s.use_tls = use_tls;
|
|
if (passbuf[0]) snprintf(s.pass, sizeof s.pass, "%s", passbuf);
|
|
if (use_tls && tls_init() < 0) { fprintf(stderr, CLR_RED "TLS init failed" CLR_RESET "\n"); return 1; }
|
|
signal(SIGINT, handle_sigterm);
|
|
signal(SIGTERM, handle_sigterm);
|
|
signal(SIGPIPE, SIG_IGN);
|
|
s.fd = net_connect(s.host, s.port);
|
|
if (s.fd < 0) { fprintf(stderr, CLR_RED "Could not connect to %s:%d" CLR_RESET "\n", s.host, s.port); return 1; }
|
|
if (s.use_tls && tls_handshake(&s) < 0) {
|
|
fprintf(stderr, CLR_RED "TLS handshake failed" CLR_RESET "\n"); close(s.fd); return 1;
|
|
}
|
|
int fl = fcntl(s.fd, F_GETFL, 0);
|
|
fcntl(s.fd, F_SETFL, fl | O_NONBLOCK);
|
|
log_stamp(); fprintf(stderr, CLR_GREEN "Connecting to %s:%d as %s..." CLR_RESET "\n", s.host, s.port, s.nick);
|
|
if (s.pass[0]) net_send(&s, "PASS %s\r\n", s.pass);
|
|
irc_nick(&s, s.nick);
|
|
net_send(&s, "USER %s 0 * :%s\r\n", s.user, s.real);
|
|
running = 1;
|
|
pending_ai_pid = 0;
|
|
while (running) {
|
|
struct pollfd pfd = { .fd = s.fd, .events = POLLIN };
|
|
int ret = poll(&pfd, 1, POLL_MS);
|
|
if (ret < 0) { if (errno == EINTR) continue; break; }
|
|
if (pfd.revents & (POLLIN | POLLHUP)) {
|
|
char buf[4096];
|
|
int n = net_read(&s, buf, sizeof buf);
|
|
if (n > 0) { irc_feed(&s, buf, n); }
|
|
else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EINTR)) {
|
|
log_stamp(); fprintf(stderr, CLR_YELLOW "Disconnected" CLR_RESET "\n");
|
|
s.connected = 0;
|
|
if (net_reconnect(&s) < 0) break;
|
|
continue;
|
|
}
|
|
}
|
|
ai_check_completion(&s);
|
|
}
|
|
if (s.connected && s.fd >= 0) {
|
|
int old_fl = fcntl(s.fd, F_GETFL, 0);
|
|
fcntl(s.fd, F_SETFL, old_fl & ~O_NONBLOCK);
|
|
net_send(&s, "QUIT :zynk\r\n");
|
|
struct timespec ts = { .tv_sec = 0, .tv_nsec = 500000000 };
|
|
nanosleep(&ts, NULL);
|
|
}
|
|
tls_cleanup(&s);
|
|
if (s.fd >= 0) close(s.fd);
|
|
db_close_cleanup();
|
|
return 0;
|
|
}
|