commit 24d421b859b5d178391bd23c5d2e241e82c206fa
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Mon, 24 Aug 2026 23:39:00 +0530
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Mon, 24 Aug 2026 23:39:00 +0530
Brave New World
5 files changed, 977 insertions(+), 0 deletions(-)
diff --git a/Makefile b/Makefile @@ -0,0 +1,15 @@ +CC ?= gcc +CFLAGS += -Wall -Wextra -O2 -std=c99 -pedantic +LDLIBS += -lpthread + +BIN = liveside + +all: $(BIN) + +$(BIN): liveside.c + $(CC) $(CFLAGS) -o $@ liveside.c $(LDLIBS) + +clean: + -@rm -f $(BIN) + +.PHONY: all clean
diff --git a/README.md b/README.md @@ -0,0 +1,79 @@ +# liveside + +A tiny live-reload server written in plain C (no external dependencies, +just POSIX + pthreads). It watches a directory tree for changes and +pushes the browser a Server-Sent Events (SSE) `reload` message, which +reloads the page. + +It is deliberately **not** a static file server — it only ever answers +two requests, `/livereload` (the SSE stream) and `/liveside.js` (the +client snippet). Your actual site keeps being served by whatever you +already use — `darkhttpd`, `lighttpd`, `python3 -m http.server`, anything +— on its own port. liveside just sits alongside it (hence the name). + +It fills the same role as the `autorefresh` target in the +saikrupagas.com `Makefile` (`ls | entr make refresh`, which rebuilds and +then simulates a keypress in Arc/Firefox), but works in any browser +without AppleScript/xdotool or driving a specific app. + +## Build + +No dependencies beyond a C99 compiler and pthreads: + +```bash +make +``` + +## Run + +```bash +./liveside -d /path/to/site -p 8081 +``` + +Options: + +- `-d watch-dir` — directory to watch recursively (default `.`) +- `-p port` — HTTP/SSE port (default `8081`) +- `-c build-cmd` — shell command to run (e.g. `make all`) before notifying + clients; if it exits non-zero, clients are not told to reload +- `-i poll-ms` — polling interval in milliseconds, **only used as a + fallback** on platforms without kqueue/inotify (default `300`) + +Ctrl-C stops it. + +## Client + +liveside serves its own client script, so pairing it with an existing +static server (e.g. `darkhttpd` on 8000 for the site, this on 8081 for +reload) needs nothing copied between them — just point an absolute +`<script>` tag at liveside's port: + +```html +<script src="http://localhost:8081/liveside.js"></script> +``` + +That's a cross-origin request, which script tags don't need CORS for. It +auto-detects the right origin to connect back to from its own `src`. If +you instead copy `client/liveside.js` into the site itself and load it +same-origin, set `window.__RELOAD_PORT__` before the script tag so it +knows where to find the SSE stream. + +## How change detection works + +- **macOS/BSD**: opens a `kqueue` watch (`EVFILT_VNODE`) on every file and + directory under the watched tree, so edits, adds, deletes, and renames + are reported by the kernel the moment they happen — no polling delay. + Because new files need their own watch, any event triggers a cheap + rebuild of the watch set (a full re-walk), which also lets it notice + freshly created files. A short debounce window coalesces the burst of + events a single save often produces (write + truncate + attrib change) + into one reload. +- **Linux**: same idea via `inotify`, but watches are per-directory + (inotify reports changes to files *inside* a watched directory, unlike + kqueue), so it needs far fewer watch descriptors for the same tree. +- **Everywhere else**: falls back to polling — recursively hashing each + file's name, size, and mtime every `poll-ms` and comparing to the + previous hash. + +Directories named `.git`, `node_modules`, `dist`, `.cache`, or starting +with `.` are never watched.
diff --git a/client/liveside.js b/client/liveside.js @@ -0,0 +1,43 @@ +/* + * liveside client snippet. + * + * liveside serves this file itself, so the easiest way to use it is + * an absolute script tag pointing at liveside's own port: + * + * <script src="http://localhost:8081/liveside.js"></script> + * + * That's a cross-origin request, which is fine for a <script> tag (no + * CORS preflight involved) and lets this snippet auto-detect where the + * SSE stream lives from its own src URL. If you instead copy this file + * into the site being served and load it same-origin, set + * window.__RELOAD_PORT__ before this script runs so it knows where to + * connect. + */ +(function () { + function resolveOrigin() { + if (window.__RELOAD_PORT__) { + return "http://" + location.hostname + ":" + window.__RELOAD_PORT__; + } + var script = document.currentScript; + if (script && script.src) { + var url = new URL(script.src); + return url.protocol + "//" + url.host; + } + return "http://" + location.hostname + ":8081"; + } + + function connect() { + var es = new EventSource(resolveOrigin() + "/livereload"); + + es.onmessage = function (evt) { + if (evt.data === "reload") location.reload(); + }; + + es.onerror = function () { + es.close(); + setTimeout(connect, 1000); + }; + } + + connect(); +})();
diff --git a/liveside.c b/liveside.c @@ -0,0 +1,839 @@ +/* + * liveside: watch a directory for changes and notify connected + * browsers over Server-Sent Events (SSE) so they can reload themselves. + * + * This is deliberately NOT a file server — pair it with whatever's + * already serving the site (darkhttpd, lighttpd, python3 -m http.server, + * ...), running on its own port. liveside only ever answers two + * requests: `/livereload` (the SSE stream) and `/liveside.js` (the client + * snippet). Point a page's <script src="http://localhost:PORT/liveside.js"> + * at it — cross-origin script tags don't need CORS — and it reconnects on + * its own and reloads the page whenever a watched file changes. + * + * File-change detection is platform-native where available (kqueue on + * macOS/BSD, inotify on Linux) so reloads are instant instead of waiting + * on a poll interval; anywhere else it falls back to polling. + */ + +#include <dirent.h> +#include <errno.h> +#include <fcntl.h> +#include <poll.h> +#include <pthread.h> +#include <signal.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/socket.h> +#include <sys/stat.h> +#include <time.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <unistd.h> + +#if defined(__APPLE__) + #define WATCH_KQUEUE 1 + #include <sys/event.h> + #include <sys/resource.h> + #include <sys/time.h> +#elif defined(__linux__) + #define WATCH_INOTIFY 1 + #include <poll.h> + #include <sys/inotify.h> +#else + #define WATCH_POLL 1 +#endif + +static volatile sig_atomic_t g_running = 1; +static uint16_t g_port = 8081; +static const char *g_watch_dir = "."; +static const char *g_build_cmd = NULL; +static int g_poll_ms = 300; /* only used by the WATCH_POLL fallback */ + +/* Directory names never worth descending into while watching. */ +static const char *g_ignored[] = { + ".", "..", ".git", "node_modules", "dist", ".cache", NULL +}; + +static bool is_ignored(const char *name) +{ + for (int i = 0; g_ignored[i]; i++) + if (strcmp(name, g_ignored[i]) == 0) + return true; + /* Skip dotfiles/dot-directories (editor swap files, .DS_Store...). */ + return name[0] == '.'; +} + +/* ------------------------------------------------------------------- */ +/* Watcher backend: opaque watcher_t + watch_open/watch_wait/watch_close */ +/* ------------------------------------------------------------------- */ + +typedef struct watcher watcher_t; + +#if defined(WATCH_KQUEUE) + +struct watcher { + int kq; + int *fds; + size_t count, cap; + char root[4096]; +}; + +static void kq_add_path(watcher_t *w, const char *path) +{ + if (w->count == w->cap) { + w->cap = w->cap ? w->cap * 2 : 64; + w->fds = realloc(w->fds, w->cap * sizeof(int)); + } + + /* O_EVTONLY: get notifications without holding the file open in a + * way that blocks unmounts/deletes underneath us. */ + int fd = open(path, O_EVTONLY); + if (fd < 0) + return; + + struct kevent kev; + EV_SET(&kev, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, + NOTE_WRITE | NOTE_DELETE | NOTE_RENAME | NOTE_EXTEND | + NOTE_ATTRIB | NOTE_LINK, + 0, NULL); + if (kevent(w->kq, &kev, 1, NULL, 0, NULL) < 0) { + close(fd); + return; + } + + w->fds[w->count++] = fd; +} + +static void kq_scan(watcher_t *w, const char *path) +{ + kq_add_path(w, path); + + DIR *dir = opendir(path); + if (!dir) + return; + + struct dirent *entry; + while ((entry = readdir(dir)) != NULL) { + if (is_ignored(entry->d_name)) + continue; + + char child[4096]; + snprintf(child, sizeof(child), "%s/%s", path, entry->d_name); + + struct stat st; + if (lstat(child, &st) != 0) + continue; + + if (S_ISDIR(st.st_mode)) + kq_scan(w, child); + else if (S_ISREG(st.st_mode)) + kq_add_path(w, child); + } + closedir(dir); +} + +static void kq_rebuild(watcher_t *w) +{ + for (size_t i = 0; i < w->count; i++) + close(w->fds[i]); + w->count = 0; + kq_scan(w, w->root); +} + +static watcher_t *watch_open(const char *root) +{ + /* Watching every file needs one fd each; raise the soft limit to + * whatever the hard limit allows so a normal-sized site doesn't + * quietly hit macOS's low default (often 256). */ + struct rlimit rl; + if (getrlimit(RLIMIT_NOFILE, &rl) == 0) { + rl.rlim_cur = rl.rlim_max; + setrlimit(RLIMIT_NOFILE, &rl); + } + + watcher_t *w = calloc(1, sizeof(*w)); + w->kq = kqueue(); + if (w->kq < 0) { + free(w); + return NULL; + } + snprintf(w->root, sizeof(w->root), "%s", root); + kq_rebuild(w); + printf("[liveside] watching %zu paths via kqueue\n", w->count); + return w; +} + +static bool watch_wait(watcher_t *w) +{ + struct kevent ev; + int n = kevent(w->kq, NULL, 0, &ev, 1, NULL); /* blocks */ + if (n < 0) + return errno == EINTR; + if (n == 0) + return true; + + /* Debounce: a save is often a write + truncate + attrib change in + * quick succession, and `make` can touch several files at once. + * Coalesce whatever else is pending into a single reload. Note we + * deliberately don't call kq_rebuild() here -- the existing watches + * are still valid for this notification, and watch_settle() (called + * by the caller after it's done reacting, e.g. after running a -c + * build) is what refreshes the watch set. Rebuilding here too would + * just double the (expensive, one-open()-per-file) cost of every + * detected change for no benefit. */ + usleep(80 * 1000); + struct kevent drain[64]; + struct timespec zero = {0, 0}; + while (kevent(w->kq, NULL, 0, drain, 64, &zero) > 0) + ; + + return true; +} + +/* Absorbs any filesystem events generated by our own -c build command, + * so they aren't mistaken for the next user-made change. See the comment + * on watch_settle's call site in watcher_loop for why this exists. */ +static void watch_settle(watcher_t *w) +{ + usleep(150 * 1000); + struct kevent drain[64]; + struct timespec zero = {0, 0}; + while (kevent(w->kq, NULL, 0, drain, 64, &zero) > 0) + ; + kq_rebuild(w); +} + +static void watch_close(watcher_t *w) +{ + if (!w) + return; + for (size_t i = 0; i < w->count; i++) + close(w->fds[i]); + free(w->fds); + close(w->kq); + free(w); +} + +#elif defined(WATCH_INOTIFY) + +struct watch_entry { + int wd; +}; + +struct watcher { + int fd; + struct watch_entry *entries; + size_t count, cap; + char root[4096]; +}; + +static void in_add_dir(watcher_t *w, const char *path) +{ + /* inotify watches report changes to files *inside* a watched + * directory, so unlike kqueue we only need one watch per directory, + * not per file. */ + int wd = inotify_add_watch(w->fd, path, + IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVED_FROM | + IN_MOVED_TO | IN_ATTRIB | IN_CLOSE_WRITE); + if (wd < 0) + return; + + if (w->count == w->cap) { + w->cap = w->cap ? w->cap * 2 : 64; + w->entries = realloc(w->entries, w->cap * sizeof(*w->entries)); + } + w->entries[w->count++].wd = wd; + + DIR *dir = opendir(path); + if (!dir) + return; + + struct dirent *entry; + while ((entry = readdir(dir)) != NULL) { + if (is_ignored(entry->d_name)) + continue; + + char child[4096]; + snprintf(child, sizeof(child), "%s/%s", path, entry->d_name); + + struct stat st; + if (lstat(child, &st) == 0 && S_ISDIR(st.st_mode)) + in_add_dir(w, child); + } + closedir(dir); +} + +static void in_rebuild(watcher_t *w) +{ + for (size_t i = 0; i < w->count; i++) + inotify_rm_watch(w->fd, w->entries[i].wd); + w->count = 0; + in_add_dir(w, w->root); +} + +static watcher_t *watch_open(const char *root) +{ + watcher_t *w = calloc(1, sizeof(*w)); + w->fd = inotify_init1(0); + if (w->fd < 0) { + free(w); + return NULL; + } + snprintf(w->root, sizeof(w->root), "%s", root); + in_rebuild(w); + printf("[liveside] watching %zu directories via inotify\n", + w->count); + return w; +} + +static bool watch_wait(watcher_t *w) +{ + char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event)))); + ssize_t n = read(w->fd, buf, sizeof(buf)); /* blocks */ + if (n < 0) + return errno == EINTR; + if (n == 0) + return true; + + usleep(80 * 1000); + struct pollfd pfd = {.fd = w->fd, .events = POLLIN}; + while (poll(&pfd, 1, 0) > 0 && (pfd.revents & POLLIN)) + read(w->fd, buf, sizeof(buf)); + + /* No in_rebuild() here -- see the matching comment in the kqueue + * watch_wait() above. watch_settle() does the one rebuild that's + * actually needed, after the caller's done reacting. */ + return true; +} + +/* Absorbs any filesystem events generated by our own -c build command, + * so they aren't mistaken for the next user-made change. See the comment + * on watch_settle's call site in watcher_loop for why this exists. */ +static void watch_settle(watcher_t *w) +{ + usleep(150 * 1000); + char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event)))); + struct pollfd pfd = {.fd = w->fd, .events = POLLIN}; + while (poll(&pfd, 1, 0) > 0 && (pfd.revents & POLLIN)) + read(w->fd, buf, sizeof(buf)); + in_rebuild(w); +} + +static void watch_close(watcher_t *w) +{ + if (!w) + return; + for (size_t i = 0; i < w->count; i++) + inotify_rm_watch(w->fd, w->entries[i].wd); + free(w->entries); + close(w->fd); + free(w); +} + +#else /* WATCH_POLL */ + +struct watcher { + char root[4096]; + unsigned long last; +}; + +static void poll_scan(const char *path, unsigned long *sig) +{ + DIR *dir = opendir(path); + if (!dir) + return; + + struct dirent *entry; + while ((entry = readdir(dir)) != NULL) { + if (is_ignored(entry->d_name)) + continue; + + char child[4096]; + snprintf(child, sizeof(child), "%s/%s", path, entry->d_name); + + struct stat st; + if (lstat(child, &st) != 0) + continue; + + for (const char *p = entry->d_name; *p; p++) + *sig = *sig * 131 + (unsigned char)*p; + + if (S_ISDIR(st.st_mode)) { + poll_scan(child, sig); + } else if (S_ISREG(st.st_mode)) { + *sig ^= (unsigned long)st.st_mtime * 2654435761UL; + *sig ^= (unsigned long)st.st_size; + } + } + closedir(dir); +} + +static unsigned long poll_snapshot(const char *root) +{ + unsigned long sig = 0; + poll_scan(root, &sig); + return sig; +} + +static watcher_t *watch_open(const char *root) +{ + watcher_t *w = calloc(1, sizeof(*w)); + snprintf(w->root, sizeof(w->root), "%s", root); + w->last = poll_snapshot(root); + printf("[liveside] watching '%s' via polling (%dms interval)\n", + root, g_poll_ms); + return w; +} + +static bool watch_wait(watcher_t *w) +{ + while (g_running) { + usleep((useconds_t)g_poll_ms * 1000); + unsigned long cur = poll_snapshot(w->root); + if (cur != w->last) { + w->last = cur; + return true; + } + } + return true; +} + +/* Absorbs any filesystem changes made by our own -c build command, so + * they aren't mistaken for the next user-made change. See the comment + * on watch_settle's call site in watcher_loop for why this exists. */ +static void watch_settle(watcher_t *w) +{ + w->last = poll_snapshot(w->root); +} + +static void watch_close(watcher_t *w) +{ + free(w); +} + +#endif + +/* --------------------------------------------------------------------- + * SSE client registry + * ------------------------------------------------------------------- */ + +#define MAX_CLIENTS 64 + +static int g_client_fds[MAX_CLIENTS]; +static int g_nclients = 0; +static pthread_mutex_t g_clients_mu = PTHREAD_MUTEX_INITIALIZER; + +static void add_client(int fd) +{ + pthread_mutex_lock(&g_clients_mu); + if (g_nclients < MAX_CLIENTS) { + g_client_fds[g_nclients++] = fd; + } else { + fprintf(stderr, "[liveside] client limit reached, dropping\n"); + close(fd); + } + pthread_mutex_unlock(&g_clients_mu); +} + +static void remove_client(int fd) +{ + pthread_mutex_lock(&g_clients_mu); + for (int i = 0; i < g_nclients; i++) { + if (g_client_fds[i] == fd) { + g_client_fds[i] = g_client_fds[--g_nclients]; + break; + } + } + close(fd); + pthread_mutex_unlock(&g_clients_mu); +} + +/* Sends `msg` to every connected SSE client, dropping any that fail. */ +static void broadcast(const char *msg, size_t len) +{ + int dead[MAX_CLIENTS]; + int ndead = 0; + + pthread_mutex_lock(&g_clients_mu); + int n = g_nclients; + for (int i = 0; i < n; i++) { + if (write(g_client_fds[i], msg, len) < 0) + dead[ndead++] = g_client_fds[i]; + } + pthread_mutex_unlock(&g_clients_mu); + + for (int i = 0; i < ndead; i++) + remove_client(dead[i]); +} + +static void broadcast_reload(void) +{ + static const char frame[] = "data: reload\n\n"; + printf("[liveside] notifying %d client(s)\n", g_nclients); + broadcast(frame, sizeof(frame) - 1); +} + +static void *ping_thread(void *arg) +{ + (void)arg; + static const char ping[] = ": keep-alive\n\n"; + while (g_running) { + sleep(30); + if (g_nclients > 0) + broadcast(ping, sizeof(ping) - 1); + } + return NULL; +} + +/* --------------------------------------------------------------------- + * Minimal HTTP server: just enough to speak SSE and hand out reload.js + * ------------------------------------------------------------------- */ + +/* Keep this in sync with client/liveside.js. */ +static const char CLIENT_JS[] = +"(function () {\n" +" function resolveOrigin() {\n" +" if (window.__RELOAD_PORT__)\n" +" return \"http://\" + location.hostname + \":\" + window.__RELOAD_PORT__;\n" +" var script = document.currentScript;\n" +" if (script && script.src) {\n" +" var url = new URL(script.src);\n" +" return url.protocol + \"//\" + url.host;\n" +" }\n" +" return \"http://\" + location.hostname + \":8081\";\n" +" }\n" +"\n" +" function connect() {\n" +" var es = new EventSource(resolveOrigin() + \"/livereload\");\n" +" es.onmessage = function (evt) {\n" +" if (evt.data === \"reload\") location.reload();\n" +" };\n" +" es.onerror = function () {\n" +" es.close();\n" +" setTimeout(connect, 1000);\n" +" };\n" +" }\n" +"\n" +" connect();\n" +"})();\n"; + +static void handle_livereload(int fd) +{ + static const char headers[] = + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/event-stream\r\n" + "Cache-Control: no-cache\r\n" + "Connection: keep-alive\r\n" + "Access-Control-Allow-Origin: *\r\n" + "\r\n" + ": connected\n\n"; + + if (write(fd, headers, sizeof(headers) - 1) < 0) { + close(fd); + return; + } + + add_client(fd); + printf("[liveside] client connected (%d total)\n", g_nclients); + + /* This thread's only remaining job is to notice when the browser + * goes away; broadcast()/ping_thread() do all the writing. */ + char buf[64]; + while (g_running) { + ssize_t n = read(fd, buf, sizeof(buf)); + if (n <= 0) + break; + } + remove_client(fd); +} + +static void handle_reload_js(int fd) +{ + char header[256]; + int hlen = snprintf(header, sizeof(header), + "HTTP/1.1 200 OK\r\n" + "Content-Type: application/javascript; charset=utf-8\r\n" + "Cache-Control: no-store\r\n" + "Access-Control-Allow-Origin: *\r\n" + "Content-Length: %zu\r\n" + "Connection: close\r\n" + "\r\n", + sizeof(CLIENT_JS) - 1); + + write(fd, header, (size_t)hlen); + write(fd, CLIENT_JS, sizeof(CLIENT_JS) - 1); + close(fd); +} + +static void handle_root(int fd) +{ + char body[256]; + int blen = snprintf(body, sizeof(body), + "liveside\nwatching: %s\nSSE endpoint: /livereload\n" + "client script: /liveside.js\n", g_watch_dir); + + char header[256]; + int hlen = snprintf(header, sizeof(header), + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: %d\r\n" + "Connection: close\r\n" + "\r\n", blen); + + write(fd, header, (size_t)hlen); + write(fd, body, (size_t)blen); + close(fd); +} + +static void handle_not_found(int fd) +{ + static const char resp[] = + "HTTP/1.1 404 Not Found\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n"; + write(fd, resp, sizeof(resp) - 1); + close(fd); +} + +static void *connection_thread(void *arg) +{ + int fd = (int)(intptr_t)arg; + + char buf[4096]; + ssize_t n = recv(fd, buf, sizeof(buf) - 1, 0); + if (n <= 0) { + close(fd); + return NULL; + } + buf[n] = '\0'; + + char method[16] = { 0 }; + char path[512] = { 0 }; + sscanf(buf, "%15s %511s", method, path); + + if (strcmp(path, "/livereload") == 0) + handle_livereload(fd); + else if (strcmp(path, "/liveside.js") == 0) + handle_reload_js(fd); + else if (strcmp(path, "/") == 0) + handle_root(fd); + else + handle_not_found(fd); + + return NULL; +} + +static int g_listen_fd = -1; + +static int start_http_server(void) +{ + int srv = socket(AF_INET, SOCK_STREAM, 0); + if (srv < 0) { + perror("socket"); + return -1; + } + + int yes = 1; + setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); + + struct sockaddr_in addr = { 0 }; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = INADDR_ANY; + addr.sin_port = htons(g_port); + + if (bind(srv, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + perror("bind"); + close(srv); + return -1; + } + + if (listen(srv, 32) < 0) { + perror("listen"); + close(srv); + return -1; + } + + return srv; +} + +/* --------------------------------------------------------------------- + * File change -> rebuild + notify, driven by the watcher thread + * ------------------------------------------------------------------- */ + +/* Minimum time between two reload broadcasts. watch_settle() absorbs most + * self-inflicted events from a -c build writing into the watched tree, + * but it can't catch everything -- measured on macOS with Spotlight + * (mdworker) actively indexing the watched folder, a single edit could + * still produce a second, indistinguishable-from-real change notification + * 1.3-1.9s after the first (almost certainly Spotlight touching metadata + * on the just-written files some time after the fact -- moving the + * settle window or halving the watch-rebuild cost didn't change this + * gap, which rules out our own rebuild as the source). Rather than chase + * every possible external trigger, rate-limit the visible effect instead: + * if a reload was just sent, skip sending another one for a cooldown + * comfortably above that observed gap. The build still runs every time + * (cheap, and keeps output current); only the duplicate reload is + * suppressed. Trade-off: two genuine edits saved within the cooldown of + * each other will only visibly reload once, showing the first save's + * content until a later change arrives -- acceptable for a dev tool. */ +#define RELOAD_COOLDOWN_MS 2500 + +static struct timespec g_last_broadcast; +static bool g_have_last_broadcast = false; + +static long ms_since(const struct timespec *from) +{ + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + return (now.tv_sec - from->tv_sec) * 1000 + + (now.tv_nsec - from->tv_nsec) / 1000000; +} + +static void on_change(void) +{ + printf("[liveside] change detected\n"); + + if (g_build_cmd) { + int status = system(g_build_cmd); + if (status != 0) { + fprintf(stderr, + "[liveside] build command failed (status %d), " + "not reloading\n", status); + return; + } + } + + if (g_have_last_broadcast && ms_since(&g_last_broadcast) < RELOAD_COOLDOWN_MS) { + printf("[liveside] reload sent recently, skipping duplicate\n"); + return; + } + + broadcast_reload(); + clock_gettime(CLOCK_MONOTONIC, &g_last_broadcast); + g_have_last_broadcast = true; +} + +static void *watcher_loop(void *arg) +{ + (void)arg; + + watcher_t *w = watch_open(g_watch_dir); + if (!w) { + fprintf(stderr, "[liveside] failed to initialize file watcher\n"); + return NULL; + } + + while (g_running) { + if (!watch_wait(w)) + break; /* fatal watcher error */ + if (!g_running) + break; + on_change(); + + /* If -c runs a build that writes into the watched tree itself + * (e.g. regenerating .html from .html.in in place, as + * saikrupagas.com's `make dev-all` does), those writes are + * filesystem events too. Without this, they'd be picked up as + * a second "change" on the next watch_wait() -- triggering a + * second, spurious rebuild-and-reload for every real one. */ + watch_settle(w); + } + + watch_close(w); + return NULL; +} + +static void handle_sigint(int sig) +{ + (void)sig; + g_running = 0; +} + +static void usage(const char *prog) +{ + fprintf(stderr, + "usage: %s [-p port] [-d watch-dir] [-c build-cmd] [-i poll-ms]\n" + " -p port HTTP/SSE port to serve on (default: 8081)\n" + " -d watch-dir Directory to watch recursively (default: .)\n" + " -c build-cmd Shell command to run before notifying clients\n" + " -i poll-ms Polling interval in ms (only used as a fallback\n" + " on platforms without kqueue/inotify; default: 300)\n", + prog); +} + +int main(int argc, char **argv) +{ + int opt; + while ((opt = getopt(argc, argv, "p:d:c:i:h")) != -1) { + switch (opt) { + case 'p': + g_port = (uint16_t)atoi(optarg); + break; + case 'd': + g_watch_dir = optarg; + break; + case 'c': + g_build_cmd = optarg; + break; + case 'i': + g_poll_ms = atoi(optarg); + break; + case 'h': + default: + usage(argv[0]); + return opt == 'h' ? 0 : 1; + } + } + + signal(SIGINT, handle_sigint); + signal(SIGTERM, handle_sigint); + signal(SIGPIPE, SIG_IGN); + + printf("[liveside] watching '%s'\n", g_watch_dir); + printf("[liveside] SSE endpoint: http://localhost:%d/livereload\n", + g_port); + printf("[liveside] client script: http://localhost:%d/liveside.js\n", + g_port); + if (g_build_cmd) + printf("[liveside] build command: %s\n", g_build_cmd); + + g_listen_fd = start_http_server(); + if (g_listen_fd < 0) + return 1; + + pthread_t watcher, pinger; + pthread_create(&watcher, NULL, watcher_loop, NULL); + pthread_detach(watcher); + pthread_create(&pinger, NULL, ping_thread, NULL); + pthread_detach(pinger); + + while (g_running) { + /* accept() blocking indefinitely can't be woken up reliably from + * a signal handler (shutdown()/close() on a *listening* socket + * doesn't unblock a pending accept() on macOS/BSD), so poll with + * a short timeout instead and just recheck g_running each time + * it expires. */ + struct pollfd pfd = { .fd = g_listen_fd, .events = POLLIN }; + int pr = poll(&pfd, 1, 500); + if (pr <= 0) + continue; + + int fd = accept(g_listen_fd, NULL, NULL); + if (fd < 0) + continue; + int yes = 1; + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)); + + pthread_t conn; + pthread_create(&conn, NULL, connection_thread, (void *)(intptr_t)fd); + pthread_detach(conn); + } + + close(g_listen_fd); + printf("\n[liveside] shutting down\n"); + return 0; +}
: nply/liveside