commit 491f3322688dbef4709a1f774d11780e169a0658
parent cd82406424782feb8dcc615b7b767822b5070e0e
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Wed, 2 Sep 2026 01:05:42 +0530
parent cd82406424782feb8dcc615b7b767822b5070e0e
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Wed, 2 Sep 2026 01:05:42 +0530
Make liveside POSIX-first with extractable ports
18 files changed, 1548 insertions(+), 533 deletions(-)
A
|
141
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
284
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
100
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/.astylerc b/.astylerc @@ -0,0 +1,18 @@ +# liveside C formatting: suckless-inspired via Artistic Style. +# See STYLE.md and https://suckless.org/coding_style/. +# +# AStyle cannot enforce every project rule (for example declarations at the +# top of blocks), but this keeps braces, indentation, pointer alignment, and +# spacing close enough for routine non-agent edits. + +--style=linux +--indent=tab +--align-pointer=name +--break-return-type +--break-return-type-decl +--pad-oper +--pad-header +--unpad-paren +--delete-empty-lines +--lineend=linux +--suffix=none
diff --git a/.gitignore b/.gitignore @@ -1 +1,5 @@ liveside +liveside.exe +client/liveside.js.inc +thirdparty/ +mor.log
diff --git a/AGENTS.md b/AGENTS.md @@ -0,0 +1,7 @@ +# Agent Instructions + +- Follow `STYLE.md` for C code. The project adopts the suckless coding style. +- Keep liveside POSIX-first. +- Use mor-managed external dependencies where possible. +- Only add code under `ports/` for reusable, extractable capabilities that are core to liveside and not adequately covered by small C libraries. +- Keep `CONTEXT.md` and `docs/adr/` aligned with architectural decisions.
diff --git a/CONTEXT.md b/CONTEXT.md @@ -0,0 +1,53 @@ +# Context Glossary + +## POSIX-first + +The source model where liveside prefers POSIX interfaces and semantics as the default vocabulary for portability. Non-POSIX platforms are supported by depending on external compatibility libraries rather than by carrying broad compatibility code in liveside itself. + +## First-class Windows support + +Windows is a supported target with expected build and runtime behavior, not a best-effort afterthought. Support may use external compatibility dependencies. For filesystem watching, Windows should have native event-driven behavior rather than only polling. + +## Compatibility dependency + +An external library or header package that supplies standard or POSIX-like interfaces missing from a target platform, reducing liveside's own maintenance burden. + +## Port + +Project-owned compatibility or reusable platform code that may later be extracted into an external library if it matures. Ports are acceptable for capabilities that are core to liveside and not adequately covered by existing small libraries. + +## Watcher port + +A port that adapts a native filesystem notification facility to liveside's watcher model. A watcher port is acceptable when no suitable external compatibility library provides the needed core behavior. + +## Downloaded dependency + +A dependency fetched into the project by mor from the URLs recorded in `requirements.ini`. Downloaded dependencies are not vendored into source control. + +## Floating dependency + +A downloaded dependency intentionally tracked by branch name rather than pinned to an exact commit. Breakage risk is accepted when the dependency's public contract is stable enough for liveside's needs. + +## Ignore file + +A project-local file, such as `.livesideignore` or `.gitignore`, that defines paths liveside should not watch or treat as reload-triggering content. liveside loads both files by default at each directory level, applying parent rules before child rules and `.gitignore` before `.livesideignore` within the same directory. + +## Ignore rule + +A gitignore-style pattern that determines whether a path should be excluded from watching and reload triggering. Ignore handling should support commonly useful features, including comments, blank lines, exact paths, `*`, directory suffix `/`, anchored `/`, recursive `**`, basename matching, negation `!`, escaped `#`, escaped spaces, and nested ignore files with directory-scoped rules. + +## Ignored path + +A path matched by the active ignore rules. An ignored path may be observed by a raw platform watcher, but it must not cause a browser reload. + +## Ignore port + +The reusable path-ignore parser and matcher under `ports/ignore`. It is project-owned because no suitable small C dependency was found, but it should be designed so it can be extracted into a standalone library later. + +## frankensocket + +The project-owned socket smoothing layer under `ports/frankensocket`. It keeps BSD socket vocabulary visible across POSIX and Win32 by defining missing names such as `SOCKET` and `INVALID_SOCKET` on POSIX, while exposing frankensocket-specific functions for unavoidable differences such as startup, cleanup, close, send, recv, and error reporting. + +## Unsupported platform + +A platform with enough POSIX support to compile liveside but without a native watcher backend. Unsupported platforms use polling as the fallback watcher behavior.
diff --git a/LICENSE b/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2025, Bharatvaj Hemanth +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/Makefile b/Makefile @@ -1,24 +1,72 @@ CC ?= gcc +MOR ?= mor +ASTYLE ?= astyle +UNAME_S := $(shell uname -s 2>/dev/null) CFLAGS += -Wall -Wextra -O2 -std=c99 -pedantic -# For a native MSVC build, don't use this Makefile at all -- see README.md -# for the plain `cl` command line instead. This is for gcc/clang, whether -# that's macOS/Linux/BSD directly, or a MinGW-w64/MSYS2 gcc on Windows -# ($(OS) is set to Windows_NT by cmd.exe and by MinGW/MSYS shells). ifeq ($(OS),Windows_NT) BIN = liveside.exe + DEPS_TARGET = deps-windows + DEPS_DIR = thirdparty/deps-windows + CPPFLAGS += -I$(DEPS_DIR)/win32ports-dirent_h \ + -I$(DEPS_DIR)/win32ports-getopt_h \ + -I$(DEPS_DIR)/win32ports-sys_time_h \ + -I$(DEPS_DIR)/win32ports-unistd_h LDLIBS += -lws2_32 else BIN = liveside + DEPS_TARGET = deps + DEPS_DIR = thirdparty/deps + CPPFLAGS += -D_POSIX_C_SOURCE=200809L + ifeq ($(UNAME_S),Darwin) + CPPFLAGS += -D_DARWIN_C_SOURCE + endif LDLIBS += -lpthread endif -all: $(BIN) +TINYCTHREAD_DIR = $(DEPS_DIR)/tinycthread +TINYCTHREAD_SRC = $(TINYCTHREAD_DIR)/source/tinycthread.c +CPPFLAGS += -I$(TINYCTHREAD_DIR)/source +PORT_SRCS = ports/ignore/ignore.c -$(BIN): liveside.c - $(CC) $(CFLAGS) -o $@ liveside.c $(LDLIBS) +all: deps $(BIN) + +deps: requirements.ini + $(MOR) $(DEPS_TARGET) + +client/liveside.js.inc: client/liveside.js + awk '{ gsub(/\\/, "\\\\"); gsub(/"/, "\\\""); printf "\t\"%s\\n\"\n", $$0 }' client/liveside.js > $@ + +$(BIN): liveside.c client/liveside.js.inc $(TINYCTHREAD_SRC) $(PORT_SRCS) + $(CC) $(CPPFLAGS) $(CFLAGS) -o $@ liveside.c $(TINYCTHREAD_SRC) $(PORT_SRCS) $(LDLIBS) + +format: + @command -v $(ASTYLE) >/dev/null 2>&1 || \ + { echo "missing astyle; install Artistic Style to format C code"; exit 1; } + $(ASTYLE) --options=.astylerc liveside.c ports/frankensocket/*.h ports/ignore/*.c ports/ignore/*.h ports/win32/*.h + +check-format: + @command -v $(ASTYLE) >/dev/null 2>&1 || \ + { echo "missing astyle; install Artistic Style to check C code"; exit 1; } + @tmp=$$(mktemp -d); \ + for f in liveside.c ports/frankensocket/*.h ports/ignore/*.c ports/ignore/*.h ports/win32/*.h; do \ + mkdir -p "$$tmp/$$(dirname $$f)"; cp "$$f" "$$tmp/$$f"; \ + done; \ + $(ASTYLE) --options=.astylerc "$$tmp"/liveside.c "$$tmp"/ports/frankensocket/*.h "$$tmp"/ports/ignore/*.c "$$tmp"/ports/ignore/*.h "$$tmp"/ports/win32/*.h >/dev/null; \ + diff -ru liveside.c "$$tmp"/liveside.c >/dev/null && \ + diff -ru ports/frankensocket "$$tmp"/ports/frankensocket >/dev/null && \ + diff -ru ports/ignore "$$tmp"/ports/ignore >/dev/null && \ + diff -ru ports/win32 "$$tmp"/ports/win32 >/dev/null || \ + { echo "C sources are not astyle-formatted; run make format"; rm -rf "$$tmp"; exit 1; }; \ + rm -rf "$$tmp" + +check-man: liveside.1 + mandoc -T lint -W warning liveside.1 clean: - -@rm -f liveside liveside.exe + -@rm -f liveside liveside.exe client/liveside.js.inc + +distclean: clean + -@rm -rf thirdparty -.PHONY: all clean +.PHONY: all deps format check-format check-man clean distclean
diff --git a/README.md b/README.md @@ -1,16 +1,17 @@ # liveside -A tiny live-reload server written in portable C99 — no external -dependencies, and no assumption of POSIX. It watches a directory tree +A tiny live-reload server written in POSIX-first portable C99. It watches a directory tree for changes and pushes the browser a Server-Sent Events (SSE) `reload` message, which reloads the page. -Runs on macOS, Linux, the BSDs, and Windows (MSVC, or gcc via MinGW-w64/ -MSYS2). All the platform-specific bits — sockets, threads, sleeping, -monotonic time, directory listing, `getopt` — sit behind one small -abstraction near the top of [liveside.c](liveside.c) with a POSIX -implementation and a Windows one; the rest of the file never touches -`pthread`/BSD sockets/POSIX calls directly. +Runs on macOS, Linux, the BSDs, and Windows. The main server code stays +POSIX-first (`poll`, `dirent`, `unistd`, BSD sockets, `stat`) and uses +[TinyCThread](https://github.com/tinycthread/tinycthread) +for portable threads/mutexes. On Win32 toolchains that do not provide POSIX +headers directly, use packages from [win32ports](https://github.com/win32ports). +Project-owned code under `ports/` is reserved for reusable pieces that are core +to liveside and may be extracted later, such as socket smoothing, +ignore-file matching, and the native Windows watcher. It is deliberately **not** a static file server — it only ever answers two requests, `/livereload` (the SSE stream) and `/liveside.js` (the @@ -25,35 +26,32 @@ without AppleScript/xdotool or driving a specific app. ## Build -**macOS / Linux / BSD**, or **Windows via MinGW-w64/MSYS2 gcc**: +Fetch dependencies with mor, then build: ```bash +make deps make ``` -The Makefile detects Windows (`$(OS)=Windows_NT`, set by cmd.exe and by -MinGW/MSYS shells) and links `-lws2_32` instead of `-lpthread`, producing -`liveside.exe`. +`make` also runs `make deps` automatically. Dependencies are recorded in +[requirements.ini](requirements.ini) and downloaded into `thirdparty/`, which +is ignored by git. TinyCThread is fetched this way and compiled alongside +`liveside.c`. -**Windows via MSVC** doesn't use this Makefile (its `nmake` syntax is a -different enough beast that trying to share one Makefile isn't worth -it) — compile directly: +On Windows, `make deps` fetches TinyCThread plus win32ports headers for POSIX +interfaces such as `dirent.h`, `getopt.h`, `sys/time.h`, and `unistd.h`. The +Makefile detects `$(OS)=Windows_NT`, links Winsock, includes the native +`ReadDirectoryChangesW` watcher port, and produces `liveside.exe`. -``` -cl /std:c11 /O2 liveside.c ws2_32.lib -``` +## Style -`/std:c11` is needed for the designated initializers used in a couple of -struct literals (`struct sockaddr_in addr = { 0 };` etc.) — available -since VS2019 16.8. Also assumes a Universal CRT (VS2015+) for `snprintf`. -Older MSVC versions may need those two spots adjusted by hand. +liveside adopts the [suckless coding style](https://suckless.org/coding_style/) +for C code. Use `make format` / `make check-format` with `.astylerc`; see +[STYLE.md](STYLE.md). -Caveat: **the Windows path is implemented against documented Win32/ -Winsock2 APIs but not build-verified from this session** (no Windows -machine or working cross-compiler toolchain was available to test -against) — only the POSIX path has actually been compiled and run. If -something doesn't compile under your specific MSVC version, it's most -likely one of the two spots above. +The served `/liveside.js` body is generated from `client/liveside.js` into +`client/liveside.js.inc` at build time and included by the C preprocessor, so +edit the JavaScript file directly rather than maintaining a C string copy. ## Run @@ -72,6 +70,10 @@ Options: Ctrl-C stops it. +## License + +BSD 3-Clause. See [LICENSE](LICENSE). + ## Client liveside serves its own client script, so pairing it with an existing @@ -91,8 +93,9 @@ 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 +- **macOS / FreeBSD / NetBSD / OpenBSD / DragonFly 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 @@ -102,12 +105,17 @@ knows where to find the SSE stream. - **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, including Windows**: falls back to polling — - recursively hashing each file's name, size, and mtime every `poll-ms` - and comparing to the previous hash. Windows has its own native - equivalent (`ReadDirectoryChangesW`) but this doesn't use it yet; - polling works fine, just with up to `poll-ms` of latency instead of - being instant. - -Directories named `.git`, `node_modules`, `dist`, `.cache`, or starting -with `.` are never watched. +- **Windows**: uses a native `ReadDirectoryChangesW` watcher over the + recursive watch root, then filters events through the ignore rules before + broadcasting reloads. +- **Everywhere else**: falls back to polling — recursively hashing each file's + name, size, and mtime every `poll-ms` and comparing to the previous hash. + Polling works fine, just with up to `poll-ms` of latency instead of being + instant. + +Ignore rules are loaded from `.gitignore` and `.livesideignore` files at the +watch root and in nested directories. Parent rules apply before child rules; +within one directory, `.gitignore` is read before `.livesideignore` so +liveside-specific rules can override with `!`. Ignored paths are excluded from +polling snapshots and watcher scans, and native watcher events for ignored +paths are filtered before reloads are broadcast.
diff --git a/STYLE.md b/STYLE.md @@ -0,0 +1,34 @@ +# Coding Style + +liveside follows the suckless coding style guidelines: + +https://suckless.org/coding_style/ + +Use Artistic Style for routine formatting: + +```sh +make format +make check-format +``` + +The formatter config is `.astylerc`. AStyle does not enforce every rule below +(for example, declarations at the top of blocks), so use it as the mechanical +baseline rather than a substitute for the style guide. + +Project conventions: + +- C99, POSIX-first. +- Define `_POSIX_C_SOURCE=200809L` for POSIX builds where practical. +- System headers first, alphabetically where include-order constraints allow. +- Local headers after a blank line. +- Tabs for indentation, spaces for alignment. +- Function return type on its own line; function name and arguments on the next line. +- Declarations at the top of blocks; do not mix declarations and statements. +- No `//` comments. +- Keep lines to a reasonable length, targeting 79 columns. +- Prefer `int` predicates over C99 `bool` for new C code. +- Do not introduce new `_t` typedef names; use CamelCase for typedef'd user types. +- Static functions and globals unless they must be exported. + +Existing code may not yet be fully converted. New code should follow this style, +and touched code should move toward it without unrelated churn.
diff --git a/client/liveside.js b/client/liveside.js @@ -1,4 +1,7 @@ -/* +/** + * @file liveside.js + * @brief Browser client for liveside's Server-Sent Events reload stream. + * * liveside client snippet. * * liveside serves this file itself, so the easiest way to use it is @@ -14,6 +17,14 @@ * connect. */ (function () { + /** + * Resolve the liveside server origin used for the EventSource connection. + * + * The script prefers an explicit window.__RELOAD_PORT__, then derives the + * origin from this script tag's src, and finally falls back to localhost:8081. + * + * @returns {string} Origin such as "http://localhost:8081". + */ function resolveOrigin() { if (window.__RELOAD_PORT__) { return "http://" + location.hostname + ":" + window.__RELOAD_PORT__; @@ -26,6 +37,13 @@ return "http://" + location.hostname + ":8081"; } + /** + * Open the SSE connection and schedule automatic reconnects on failure. + * + * A "reload" message from the server reloads the current page. + * + * @returns {void} + */ function connect() { var es = new EventSource(resolveOrigin() + "/livereload");
diff --git a/docs/adr/0001-posix-first-external-deps-and-extractable-ports.md b/docs/adr/0001-posix-first-external-deps-and-extractable-ports.md @@ -0,0 +1,10 @@ +# POSIX-first with external dependencies and extractable ports + +liveside is POSIX-first: shared source should prefer POSIX interfaces and use mor-fetched external dependencies, such as TinyCThread and win32ports, rather than carrying broad compatibility shims. Project-owned code under `ports/` is allowed only for reusable capabilities that are core to liveside and not adequately covered by small existing C libraries, currently frankensocket, the Windows native watcher port, and the gitignore-style ignore matcher; these ports should be written so they can be extracted into standalone projects later. + +## Consequences + +- Windows should get a native `ReadDirectoryChangesW` watcher port instead of relying only on polling. +- Polling remains the fallback for platforms with enough POSIX support to compile liveside but no native watcher backend. +- mor dependencies intentionally track upstream branches rather than exact commits; breakage risk is accepted in exchange for lower maintenance. +- Ignore semantics are part of liveside's core behavior: `.gitignore` and `.livesideignore` are loaded by default, nested ignore files are supported, and ignored paths must not trigger reloads.
diff --git a/docs/adr/0002-adopt-suckless-coding-style.md b/docs/adr/0002-adopt-suckless-coding-style.md @@ -0,0 +1,3 @@ +# Adopt suckless coding style + +liveside adopts the suckless coding style as its C style baseline because the project is a small BSD-3-Clause C program that values simple POSIX-first code, low abstraction overhead, and long-term readability. Artistic Style with the project `.astylerc` is the mechanical formatter for non-agent contributors; existing code may be converted gradually, but new and touched C code should follow `STYLE.md` so the codebase moves toward one consistent style without unrelated formatting churn.
diff --git a/liveside.1 b/liveside.1 @@ -0,0 +1,106 @@ +.Dd September 1, 2026 +.Dt LIVESIDE 1 +.Os +.Sh NAME +.Nm liveside +.Nd tiny live-reload server using Server-Sent Events +.Sh SYNOPSIS +.Nm +.Op Fl h +.Op Fl p Ar port +.Op Fl d Ar watch-dir +.Op Fl c Ar build-cmd +.Op Fl i Ar poll-ms +.Sh DESCRIPTION +.Nm +watches a directory tree for changes and notifies connected browsers over +Server-Sent Events \&(SSE). The browser client reloads the page when it +receives a reload event. +.Pp +.Nm +is not a static file server. +It only serves the SSE endpoint and its small browser client script; use it +alongside another server such as +.Nm python3 +with +.Fl m Li http.server , +.Nm darkhttpd , +or any other site server. +.Pp +To use it, include the client script in the page being developed: +.Bd -literal -offset indent +<script src="http://localhost:8081/liveside.js"></script> +.Ed +.Pp +The client reconnects automatically and reloads the page whenever +.Nm +detects a relevant file change. +.Sh IMPLEMENTATION NOTES +On macOS, FreeBSD, NetBSD, OpenBSD, and DragonFly BSD, +.Nm +uses kqueue. +On Linux it uses inotify. +On Windows it uses ReadDirectoryChangesW. +On other platforms it falls back to polling file names, modification times, +and sizes. +.Pp +Ignore rules are loaded from nested +.Pa .gitignore +and +.Pa .livesideignore +files. +.Sh OPTIONS +.Bl -tag -width Ds +.It Fl p Ar port +Serve the HTTP/SSE endpoints on +.Ar port . +The default is 8081. +.It Fl d Ar watch-dir +Watch +.Ar watch-dir +recursively. +The default is the current directory. +.It Fl c Ar build-cmd +Run +.Ar build-cmd +before notifying browsers. +If the command exits non-zero, clients are not reloaded. +.It Fl i Ar poll-ms +Set the polling interval in milliseconds for platforms without a native watcher +backend. +The default is 300. +This option is only used by the polling fallback. +.It Fl h +Print usage information and exit. +.El +.Sh ENDPOINTS +.Bl -tag -width /livereload +.It Pa /livereload +SSE stream used by browser clients. +.It Pa /liveside.js +Browser client script served by +.Nm . +.It Pa / +Plain-text status page. +.El +.Sh EXIT STATUS +.Ex -std +.Sh EXAMPLES +Run liveside beside another local site server: +.Bd -literal -offset indent +$ ./liveside -d ./site -p 8081 +.Ed +.Pp +Run a build command before each reload: +.Bd -literal -offset indent +$ ./liveside -d ./site -c 'make all' +.Ed +.Pp +Serve the actual site separately, for example: +.Bd -literal -offset indent +$ python3 -m http.server 8000 +.Ed +.Sh SEE ALSO +.Xr sh 1 +.Sh AUTHORS +.An saikrupa
diff --git a/liveside.c b/liveside.c @@ -1,4 +1,7 @@ -/* +/** + * @file liveside.c + * @brief Tiny portable live-reload server using Server-Sent Events. + * * liveside: watch a directory for changes and notify connected * browsers over Server-Sent Events (SSE) so they can reload themselves. * @@ -15,12 +18,9 @@ * on a poll interval; anywhere else (including Windows) it falls back to * polling. * - * Portability layer: everything platform-specific (sockets, threads, - * mutexes, sleep, monotonic time, directory listing, getopt) is behind a - * small abstraction defined right below, with a POSIX implementation and - * a Windows one. The rest of the file only ever calls the abstraction - * (sock_t, thread_t/thread_spawn/thread_detach, mutex_t/mutex_lock, etc.), - * never raw pthread/BSD-socket/POSIX calls directly. + * The server body is POSIX-first: it uses poll, dirent, unistd, stat, and BSD + * socket concepts. TinyCThread supplies the portable thread/mutex API, and + * frankensocket smooths the small unavoidable POSIX/Win32 socket differences. */ #include <errno.h> @@ -33,274 +33,221 @@ #include <time.h> #ifdef _WIN32 +#include "ports/frankensocket/frankensocket.h" -#define WIN32_LEAN_AND_MEAN -#include <winsock2.h> -#include <ws2tcpip.h> -#include <windows.h> +#include <dirent.h> +#include <fcntl.h> +#include <getopt.h> +#include <poll.h> #include <sys/stat.h> -#pragma comment(lib, "ws2_32.lib") +#include <sys/time.h> +#include <tinycthread.h> +#include <unistd.h> -typedef SOCKET sock_t; -#define SOCK_INVALID INVALID_SOCKET -#define CLOSESOCK closesocket -/* Winsock2's WSAPOLLFD is source-compatible with POSIX struct pollfd - * (Microsoft tagged it `pollfd` on purpose), so this just works. */ -#define poll(fds, n, to) WSAPoll((fds), (n), (to)) +#include "ports/ignore/ignore.h" +#define lstat stat #ifndef S_ISDIR #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR) #endif #ifndef S_ISREG #define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG) #endif -#define lstat stat - -/* MSVC's CRT has no dirent.h. This shim, backed by FindFirstFile/ - * FindNextFile, only needs to support what the WATCH_POLL backend below - * actually does with it (the only watcher backend that compiles on - * Windows, since kqueue/inotify are macOS/Linux-only) -- open a - * directory, list entries by name, close it. */ -struct dirent { - char d_name[MAX_PATH]; -}; - -typedef struct { - HANDLE h; - WIN32_FIND_DATAA fd; - int first; - struct dirent ent; -} DIR; - -static DIR *opendir(const char *path) -{ - char pattern[MAX_PATH]; - snprintf(pattern, sizeof(pattern), "%s\\*", path); - - DIR *d = (DIR *)calloc(1, sizeof(*d)); - if (!d) - return NULL; +#else +#include <dirent.h> +#include <fcntl.h> +#include <poll.h> +#include <sys/stat.h> +#include <sys/time.h> +#include <tinycthread.h> +#include <unistd.h> - d->h = FindFirstFileA(pattern, &d->fd); - if (d->h == INVALID_HANDLE_VALUE) { - free(d); - return NULL; - } - d->first = 1; - return d; -} +#include "ports/frankensocket/frankensocket.h" +#include "ports/ignore/ignore.h" +#endif -static struct dirent *readdir(DIR *d) +static void +usleep_ms(long ms) { - if (!d->first && !FindNextFileA(d->h, &d->fd)) - return NULL; - d->first = 0; - snprintf(d->ent.d_name, sizeof(d->ent.d_name), "%s", d->fd.cFileName); - return &d->ent; + struct timespec ts; + ts.tv_sec = ms / 1000; + ts.tv_nsec = (ms % 1000) * 1000000L; + thrd_sleep(&ts, NULL); } -static void closedir(DIR *d) +static long long +now_ms(void) { - if (!d) - return; - FindClose(d->h); - free(d); + struct timeval tv; + gettimeofday(&tv, NULL); + return (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000; } -/* getopt() isn't in MSVC's CRT either. This is intentionally minimal -- - * one option per argv element, no combined short options ("-abc"), no - * "--" terminator -- because that's the only way liveside's own -p/-d/ - * -c/-i/-h options are ever documented or invoked. */ -static char *optarg; -static int optind = 1; - -static int getopt(int argc, char *const argv[], const char *optstring) -{ - if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0') - return -1; - - char opt = argv[optind][1]; - const char *p = strchr(optstring, opt); - if (!p) { - optind++; - return '?'; - } - - optind++; - if (p[1] == ':') { - if (optind >= argc) - return '?'; - optarg = argv[optind++]; - } - return opt; -} - -typedef HANDLE thread_t; -typedef CRITICAL_SECTION mutex_t; - -static void mutex_init(mutex_t *m) { InitializeCriticalSection(m); } -static void mutex_lock(mutex_t *m) { EnterCriticalSection(m); } -static void mutex_unlock(mutex_t *m) { LeaveCriticalSection(m); } - -struct thread_start_ctx { - void *(*fn)(void *); - void *arg; -}; +#if defined(_WIN32) +#define WATCH_WIN32 1 +#include "ports/win32/watch.h" +#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || \ + defined(__OpenBSD__) || defined(__DragonFly__) +#define WATCH_KQUEUE 1 +#include <sys/event.h> +#include <sys/resource.h> +#include <sys/time.h> +#elif defined(__linux__) +#define WATCH_INOTIFY 1 +#include <sys/inotify.h> +#else +#define WATCH_POLL 1 +#endif -static DWORD WINAPI thread_trampoline(LPVOID p) -{ - struct thread_start_ctx *ctx = (struct thread_start_ctx *)p; - void *(*fn)(void *) = ctx->fn; - void *arg = ctx->arg; - free(ctx); - fn(arg); - return 0; -} +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 */ +static ignore_context_t g_ignore; -static int thread_spawn(thread_t *t, void *(*fn)(void *), void *arg) +/** + * @brief Decide whether a path should be skipped by watchers. + * @param path Path to test. + * @param is_dir Whether @p path is a directory. + * @return true when @p path is ignored, false otherwise. + */ +static bool +path_ignored(const char *path, bool is_dir) { - struct thread_start_ctx *ctx = - (struct thread_start_ctx *)malloc(sizeof(*ctx)); - if (!ctx) - return -1; - ctx->fn = fn; - ctx->arg = arg; - *t = CreateThread(NULL, 0, thread_trampoline, ctx, 0, NULL); - return *t ? 0 : -1; + return ignore_path_ignored(&g_ignore, path, is_dir); } -static void thread_detach(thread_t t) { CloseHandle(t); } - -static void msleep(long ms) { Sleep((DWORD)ms); } - -static long long now_ms(void) { return (long long)GetTickCount64(); } - -static long io_send(sock_t fd, const void *buf, size_t len) +static void +tree_scan_signature(const char *path, unsigned long *sig) { - return send(fd, (const char *)buf, (int)len, 0); + DIR *dir = opendir(path); + if (!dir) + return; + struct dirent *entry; + while ((entry = readdir(dir)) != NULL) { + char child[4096]; + snprintf(child, sizeof(child), "%s/%s", path, entry->d_name); + struct stat st; + if (lstat(child, &st) != 0) + continue; + bool is_dir = S_ISDIR(st.st_mode); + if (path_ignored(child, is_dir) || ignore_is_ignore_file(child)) + continue; + for (const char *p = entry->d_name; *p; p++) + *sig = *sig * 131 + (unsigned char) * p; + if (is_dir) + tree_scan_signature(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 long io_recv(sock_t fd, void *buf, size_t len) +static unsigned long +tree_signature(const char *root) { - return recv(fd, (char *)buf, (int)len, 0); + unsigned long sig = 0; + tree_scan_signature(root, &sig); + return sig; } -#define socket_perror(msg) \ - fprintf(stderr, "%s: WSA error %d\n", (msg), WSAGetLastError()) - -#else /* POSIX */ - -#include <dirent.h> -#include <fcntl.h> -#include <poll.h> -#include <pthread.h> -#include <sys/socket.h> -#include <sys/stat.h> -#include <netinet/in.h> -#include <netinet/tcp.h> -#include <unistd.h> +/** @name Watcher backend + * + * Opaque watcher abstraction implemented by kqueue, inotify, or a polling + * fallback. Each backend provides watch_open(), watch_wait(), watch_settle(), + * and watch_close(). + * @{ + */ -typedef int sock_t; -#define SOCK_INVALID (-1) -#define CLOSESOCK close +typedef struct watcher watcher_t; -typedef pthread_t thread_t; -typedef pthread_mutex_t mutex_t; +#if defined(WATCH_WIN32) -static void mutex_init(mutex_t *m) { pthread_mutex_init(m, NULL); } -static void mutex_lock(mutex_t *m) { pthread_mutex_lock(m); } -static void mutex_unlock(mutex_t *m) { pthread_mutex_unlock(m); } +struct watcher { + win32_watch_t *native; +}; -static int thread_spawn(thread_t *t, void *(*fn)(void *), void *arg) +static watcher_t * +watch_open(const char *root) { - return pthread_create(t, NULL, fn, arg); + watcher_t *w = calloc(1, sizeof(*w)); + if (!w) + return NULL; + w->native = win32_watch_open(root, &g_ignore); + if (!w->native) { + free(w); + return NULL; + } + printf("[liveside] watching '%s' via ReadDirectoryChangesW\n", root); + return w; } -static void thread_detach(thread_t t) { pthread_detach(t); } - -static void msleep(long ms) { usleep((useconds_t)ms * 1000); } - -static long long now_ms(void) +static bool +watch_wait(watcher_t *w) { - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; + return win32_watch_wait(w->native); } -static long io_send(sock_t fd, const void *buf, size_t len) +static void +watch_settle(watcher_t *w) { - return (long)send(fd, buf, len, 0); + (void)w; + usleep_ms(150); } -static long io_recv(sock_t fd, void *buf, size_t len) +static void +watch_close(watcher_t *w) { - return (long)recv(fd, buf, len, 0); + if (!w) + return; + win32_watch_close(w->native); + free(w); } -#define socket_perror perror - -#endif /* _WIN32 */ - -#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 <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 */ +#elif defined(WATCH_KQUEUE) -/* Directory names never worth descending into while watching. */ -static const char *g_ignored[] = { - ".", "..", ".git", "node_modules", "dist", ".cache", NULL +struct kq_path { + int fd; + bool ignore_file; }; -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; + struct kq_path *paths; size_t count, cap; char root[4096]; + unsigned long last_sig; }; -static void kq_add_path(watcher_t *w, const char *path) +/** + * @brief Add one file or directory vnode to a kqueue watcher. + * @param w Watcher receiving the new file descriptor and kevent. + * @param path File-system path to monitor. + */ +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)); + w->paths = realloc(w->paths, w->cap * sizeof(*w->paths)); } + int flags; + int fd; +#ifdef O_EVTONLY /* O_EVTONLY: get notifications without holding the file open in a - * way that blocks unmounts/deletes underneath us. */ - int fd = open(path, O_EVTONLY); + * way that blocks unmounts/deletes underneath us. This is available + * on macOS; BSDs use a normal read-only descriptor for EVFILT_VNODE. */ + flags = O_EVTONLY; +#else + flags = O_RDONLY; +#endif + fd = open(path, flags); if (fd < 0) return; - /* Deliberately no NOTE_ATTRIB: it fires on *any* attribute change, * not just content-relevant ones, including a plain atime bump from * something merely reading the file (e.g. Spotlight/mdworker @@ -311,38 +258,41 @@ static void kq_add_path(watcher_t *w, const char *path) * this tool's purpose. */ struct kevent kev; EV_SET(&kev, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, - NOTE_WRITE | NOTE_DELETE | NOTE_RENAME | NOTE_EXTEND | - NOTE_LINK, - 0, NULL); + NOTE_WRITE | NOTE_DELETE | NOTE_RENAME | NOTE_EXTEND | + NOTE_LINK, + 0, NULL); if (kevent(w->kq, &kev, 1, NULL, 0, NULL) < 0) { close(fd); return; } - - w->fds[w->count++] = fd; + w->paths[w->count].fd = fd; + w->paths[w->count].ignore_file = ignore_is_ignore_file(path); + w->count++; } -static void kq_scan(watcher_t *w, const char *path) +/** + * @brief Recursively add a tree of regular files and directories to kqueue. + * @param w Watcher to populate. + * @param path Root of the subtree being scanned. + */ +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)) + bool is_dir = S_ISDIR(st.st_mode); + if (path_ignored(child, is_dir)) + continue; + if (is_dir) kq_scan(w, child); else if (S_ISREG(st.st_mode)) kq_add_path(w, child); @@ -350,15 +300,26 @@ static void kq_scan(watcher_t *w, const char *path) closedir(dir); } -static void kq_rebuild(watcher_t *w) +/** + * @brief Rebuild all kqueue watches after tree structure changes. + * @param w Watcher to refresh. + */ +static void +kq_rebuild(watcher_t *w) { for (size_t i = 0; i < w->count; i++) - close(w->fds[i]); + close(w->paths[i].fd); w->count = 0; kq_scan(w, w->root); } -static watcher_t *watch_open(const char *root) +/** + * @brief Initialize the active platform watcher backend. + * @param root Root directory to watch recursively. + * @return Allocated watcher, or NULL on failure. + */ +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 @@ -368,28 +329,42 @@ static watcher_t *watch_open(const char *root) 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; + return 0; } snprintf(w->root, sizeof(w->root), "%s", root); + w->last_sig = tree_signature(root); kq_rebuild(w); printf("[liveside] watching %zu paths via kqueue\n", w->count); return w; } -static bool watch_wait(watcher_t *w) +/** + * @brief Block until a relevant file-system change is detected. + * @param w Active watcher. + * @return true after a normal wakeup/interrupted wait, false on fatal error. + */ +static bool +watch_wait(watcher_t *w) { struct kevent ev; - int n = kevent(w->kq, NULL, 0, &ev, 1, NULL); /* blocks */ + int n; +again: + n = kevent(w->kq, NULL, 0, &ev, 1, NULL); /* blocks */ if (n < 0) return errno == EINTR; if (n == 0) return true; - + bool ignore_file_event = false; + for (size_t i = 0; i < w->count; i++) { + if ((uintptr_t)w->paths[i].fd == ev.ident) { + ignore_file_event = w->paths[i].ignore_file; + break; + } + } /* 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 @@ -399,35 +374,48 @@ static bool watch_wait(watcher_t *w) * 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. */ - msleep(80); + usleep_ms(80); struct kevent drain[64]; struct timespec zero = {0, 0}; while (kevent(w->kq, NULL, 0, drain, 64, &zero) > 0) ; - + unsigned long cur_sig = tree_signature(w->root); + if (ignore_file_event || cur_sig == w->last_sig) { + kq_rebuild(w); + w->last_sig = cur_sig; + goto again; + } + w->last_sig = cur_sig; return true; } -/* Absorbs any filesystem events generated by our own -c build command, +/** 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) +static void +watch_settle(watcher_t *w) { - msleep(150); + usleep_ms(150); struct kevent drain[64]; struct timespec zero = {0, 0}; while (kevent(w->kq, NULL, 0, drain, 64, &zero) > 0) ; kq_rebuild(w); + w->last_sig = tree_signature(w->root); } -static void watch_close(watcher_t *w) +/** + * @brief Release all resources owned by a watcher. + * @param w Watcher to destroy; may be NULL where supported. + */ +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->paths[i].fd); + free(w->paths); close(w->kq); free(w); } @@ -436,6 +424,7 @@ static void watch_close(watcher_t *w) struct watch_entry { int wd; + char path[4096]; }; struct watcher { @@ -445,7 +434,13 @@ struct watcher { char root[4096]; }; -static void in_add_dir(watcher_t *w, const char *path) +/** + * @brief Recursively add a directory and its subdirectories to inotify. + * @param w Watcher to populate. + * @param path Directory path to monitor. + */ +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, @@ -460,37 +455,39 @@ static void in_add_dir(watcher_t *w, const char *path) * actually reload. IN_MODIFY/IN_CLOSE_WRITE already cover real * content changes. */ int wd = inotify_add_watch(w->fd, path, - IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVED_FROM | - IN_MOVED_TO | IN_CLOSE_WRITE); + IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVED_FROM | + IN_MOVED_TO | 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; - + w->entries[w->count].wd = wd; + snprintf(w->entries[w->count].path, sizeof(w->entries[w->count].path), + "%s", path); + w->count++; 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)) + if (lstat(child, &st) == 0 && S_ISDIR(st.st_mode) && + !path_ignored(child, true)) in_add_dir(w, child); } closedir(dir); } -static void in_rebuild(watcher_t *w) +/** + * @brief Rebuild all inotify directory watches after tree changes. + * @param w Watcher to refresh. + */ +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); @@ -498,47 +495,79 @@ static void in_rebuild(watcher_t *w) in_add_dir(w, w->root); } -static watcher_t *watch_open(const char *root) +/** + * @brief Initialize the active platform watcher backend. + * @param root Root directory to watch recursively. + * @return Allocated watcher, or NULL on failure. + */ +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; + return 0; } snprintf(w->root, sizeof(w->root), "%s", root); in_rebuild(w); printf("[liveside] watching %zu directories via inotify\n", - w->count); + w->count); return w; } -static bool watch_wait(watcher_t *w) +/** + * @brief Block until a relevant file-system change is detected. + * @param w Active watcher. + * @return true after a normal wakeup/interrupted wait, false on fatal error. + */ +static bool +watch_wait(watcher_t *w) { char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event)))); +again: ssize_t n = read(w->fd, buf, sizeof(buf)); /* blocks */ if (n < 0) return errno == EINTR; if (n == 0) return true; - - msleep(80); + bool relevant = false; + for (char *p = buf; p < buf + n;) { + struct inotify_event *ev = (struct inotify_event *)p; + const char *dir = NULL; + for (size_t i = 0; i < w->count; i++) + if (w->entries[i].wd == ev->wd) + dir = w->entries[i].path; + if (dir && ev->len > 0) { + char full[4096]; + snprintf(full, sizeof(full), "%s/%s", dir, ev->name); + bool is_dir = (ev->mask & IN_ISDIR) != 0; + if (!ignore_is_ignore_file(full) && !path_ignored(full, is_dir)) + relevant = true; + } + p += sizeof(*ev) + ev->len; + } + usleep_ms(80); 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. */ + if (!relevant) { + in_rebuild(w); + goto again; + } return true; } -/* Absorbs any filesystem events generated by our own -c build command, +/** 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) +static void +watch_settle(watcher_t *w) { - msleep(150); + usleep_ms(150); 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)) @@ -546,7 +575,12 @@ static void watch_settle(watcher_t *w) in_rebuild(w); } -static void watch_close(watcher_t *w) +/** + * @brief Release all resources owned by a watcher. + * @param w Watcher to destroy; may be NULL where supported. + */ +static void +watch_close(watcher_t *w) { if (!w) return; @@ -557,36 +591,42 @@ static void watch_close(watcher_t *w) free(w); } -#else /* WATCH_POLL -- also what Windows builds use */ +#else /* WATCH_POLL */ struct watcher { char root[4096]; unsigned long last; + unsigned long last_ignore; }; -static void poll_scan(const char *path, unsigned long *sig) +/** + * @brief Fold a directory tree snapshot into a lightweight polling signature. + * @param path Directory to scan recursively. + * @param sig In/out hash accumulator updated with names, sizes, and mtimes. + */ +static void +poll_scan(const char *path, unsigned long *sig, bool ignore_files_only) { 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; - + bool is_dir = S_ISDIR(st.st_mode); + bool is_ignore_file = ignore_is_ignore_file(child); + if (path_ignored(child, is_dir)) + continue; + if (ignore_files_only != is_ignore_file && !is_dir) + 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); + *sig = *sig * 131 + (unsigned char) * p; + if (is_dir) { + poll_scan(child, sig, ignore_files_only); } else if (S_ISREG(st.st_mode)) { *sig ^= (unsigned long)st.st_mtime * 2654435761UL; *sig ^= (unsigned long)st.st_size; @@ -595,250 +635,312 @@ static void poll_scan(const char *path, unsigned long *sig) closedir(dir); } -static unsigned long poll_snapshot(const char *root) +/** + * @brief Compute a polling signature for a whole watched tree. + * @param root Root directory to scan. + * @return Hash-like signature of current file names, sizes, and mtimes. + */ +static unsigned long +poll_snapshot(const char *root, bool ignore_files_only) { unsigned long sig = 0; - poll_scan(root, &sig); + poll_scan(root, &sig, ignore_files_only); return sig; } -static watcher_t *watch_open(const char *root) +/** + * @brief Initialize the active platform watcher backend. + * @param root Root directory to watch recursively. + * @return Allocated watcher, or NULL on failure. + */ +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); + w->last = poll_snapshot(root, false); + w->last_ignore = poll_snapshot(root, true); printf("[liveside] watching '%s' via polling (%dms interval)\n", - root, g_poll_ms); + root, g_poll_ms); return w; } -static bool watch_wait(watcher_t *w) +/** + * @brief Block until a relevant file-system change is detected. + * @param w Active watcher. + * @return true after a normal wakeup/interrupted wait, false on fatal error. + */ +static bool +watch_wait(watcher_t *w) { while (g_running) { - msleep(g_poll_ms); - unsigned long cur = poll_snapshot(w->root); + usleep_ms(g_poll_ms); + unsigned long cur_ignore = poll_snapshot(w->root, true); + unsigned long cur = poll_snapshot(w->root, false); + if (cur_ignore != w->last_ignore && cur == w->last) { + w->last_ignore = cur_ignore; + continue; + } if (cur != w->last) { w->last = cur; + w->last_ignore = cur_ignore; return true; } } return true; } -/* Absorbs any filesystem changes made by our own -c build command, so +/** 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) +static void +watch_settle(watcher_t *w) { - w->last = poll_snapshot(w->root); + w->last = poll_snapshot(w->root, false); + w->last_ignore = poll_snapshot(w->root, true); } -static void watch_close(watcher_t *w) +/** + * @brief Release all resources owned by a watcher. + * @param w Watcher to destroy; may be NULL where supported. + */ +static void +watch_close(watcher_t *w) { free(w); } #endif -/* --------------------------------------------------------------------- - * SSE client registry - * ------------------------------------------------------------------- */ +/** @} + * @name SSE client registry + * + * Tracks connected browser EventSource sockets and broadcasts reload frames. + * @{ + */ #define MAX_CLIENTS 64 -static sock_t g_client_fds[MAX_CLIENTS]; +static SOCKET g_client_fds[MAX_CLIENTS]; static int g_nclients = 0; -static mutex_t g_clients_mu; +static mtx_t g_clients_mu; -static void add_client(sock_t fd) +/** + * @brief Register a newly connected SSE client socket. + * @param fd Connected socket whose ownership moves to the registry on success. + */ +static void +add_client(SOCKET fd) { - mutex_lock(&g_clients_mu); + mtx_lock(&g_clients_mu); if (g_nclients < MAX_CLIENTS) { g_client_fds[g_nclients++] = fd; } else { fprintf(stderr, "[liveside] client limit reached, dropping\n"); - CLOSESOCK(fd); + frankensocket_close(fd); } - mutex_unlock(&g_clients_mu); + mtx_unlock(&g_clients_mu); } -static void remove_client(sock_t fd) +/** + * @brief Remove and close an SSE client socket. + * @param fd Socket descriptor to drop from the registry. + */ +static void +remove_client(SOCKET fd) { - mutex_lock(&g_clients_mu); + mtx_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; } } - CLOSESOCK(fd); - mutex_unlock(&g_clients_mu); + frankensocket_close(fd); + mtx_unlock(&g_clients_mu); } -/* Sends `msg` to every connected SSE client, dropping any that fail. */ -static void broadcast(const char *msg, size_t len) +/** + * @brief Send a raw SSE frame or comment to every connected client. + * + * Clients whose socket write fails are removed from the registry after the + * broadcast pass so the registry is not modified while it is being iterated. + * + * @param msg Buffer containing the bytes to send. + * @param len Number of bytes in @p msg. + */ +static void +broadcast(const char *msg, size_t len) { - sock_t dead[MAX_CLIENTS]; + SOCKET dead[MAX_CLIENTS]; int ndead = 0; - - mutex_lock(&g_clients_mu); + mtx_lock(&g_clients_mu); int n = g_nclients; for (int i = 0; i < n; i++) { - if (io_send(g_client_fds[i], msg, len) < 0) + if (frankensocket_send(g_client_fds[i], msg, len) < 0) dead[ndead++] = g_client_fds[i]; } - mutex_unlock(&g_clients_mu); - + mtx_unlock(&g_clients_mu); for (int i = 0; i < ndead; i++) remove_client(dead[i]); } -static void broadcast_reload(void) +/** @brief Broadcast the SSE reload event to all connected browsers. */ +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) +/** + * @brief Periodically send SSE comments to keep idle connections alive. + * @param arg Unused. + * @return 0 when g_running becomes false. + */ +static int +ping_thread(void *arg) { (void)arg; static const char ping[] = ": keep-alive\n\n"; while (g_running) { - msleep(30000); + usleep_ms(30000); if (g_nclients > 0) broadcast(ping, sizeof(ping) - 1); } - return NULL; + return 0; } -/* --------------------------------------------------------------------- - * Minimal HTTP server: just enough to speak SSE and hand out reload.js - * ------------------------------------------------------------------- */ +/** @} + * @name Minimal HTTP server + * + * Handles only the endpoints required by liveside: /livereload, /liveside.js, + * /, and 404 responses for everything else. + * @{ + */ -/* Keep this in sync with client/liveside.js. */ +/** JavaScript client served from /liveside.js. + * + * Generated from client/liveside.js by the Makefile. The generated include is + * deliberately not committed. + */ 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(sock_t fd) +#include "client/liveside.js.inc" + ; + +/** + * @brief Handle /livereload by upgrading the response to an SSE stream. + * @param fd Connected client socket. + */ +static void +handle_livereload(SOCKET 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 (io_send(fd, headers, sizeof(headers) - 1) < 0) { - CLOSESOCK(fd); + "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 (frankensocket_send(fd, headers, sizeof(headers) - 1) < 0) { + frankensocket_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) { - long n = io_recv(fd, buf, sizeof(buf)); + long n = frankensocket_recv(fd, buf, sizeof(buf)); if (n <= 0) break; } remove_client(fd); } -static void handle_reload_js(sock_t fd) +/** + * @brief Serve the embedded JavaScript client. + * @param fd Connected client socket. + */ +static void +handle_reload_js(SOCKET 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); - - io_send(fd, header, (size_t)hlen); - io_send(fd, CLIENT_JS, sizeof(CLIENT_JS) - 1); - CLOSESOCK(fd); + "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); + frankensocket_send(fd, header, (size_t)hlen); + frankensocket_send(fd, CLIENT_JS, sizeof(CLIENT_JS) - 1); + frankensocket_close(fd); } -static void handle_root(sock_t fd) +/** + * @brief Serve a small plaintext status response. + * @param fd Connected client socket. + */ +static void +handle_root(SOCKET 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); - + "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); - - io_send(fd, header, (size_t)hlen); - io_send(fd, body, (size_t)blen); - CLOSESOCK(fd); + "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); + frankensocket_send(fd, header, (size_t)hlen); + frankensocket_send(fd, body, (size_t)blen); + frankensocket_close(fd); } -static void handle_not_found(sock_t fd) +/** + * @brief Send a 404 response for unsupported paths. + * @param fd Connected client socket. + */ +static void +handle_not_found(SOCKET fd) { static const char resp[] = - "HTTP/1.1 404 Not Found\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n" - "\r\n"; - io_send(fd, resp, sizeof(resp) - 1); - CLOSESOCK(fd); + "HTTP/1.1 404 Not Found\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n"; + frankensocket_send(fd, resp, sizeof(resp) - 1); + frankensocket_close(fd); } -static void *connection_thread(void *arg) +/** + * @brief Parse one HTTP request and dispatch it to the matching handler. + * @param arg Connected socket cast through intptr_t. + * @return 0 after the connection is handled. + */ +static int +connection_thread(void *arg) { - sock_t fd = (sock_t)(intptr_t)arg; - + SOCKET fd = (SOCKET)(uintptr_t)arg; char buf[4096]; - long n = io_recv(fd, buf, sizeof(buf) - 1); + long n = frankensocket_recv(fd, buf, sizeof(buf) - 1); if (n <= 0) { - CLOSESOCK(fd); - return NULL; + frankensocket_close(fd); + return 0; } 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) @@ -847,48 +949,51 @@ static void *connection_thread(void *arg) handle_root(fd); else handle_not_found(fd); - - return NULL; + return 0; } -static sock_t g_listen_fd = SOCK_INVALID; +static SOCKET g_listen_fd = INVALID_SOCKET; -static sock_t start_http_server(void) +/** + * @brief Create, bind, and listen on the liveside HTTP socket. + * @return Listening socket, or INVALID_SOCKET on failure. + */ +static SOCKET +start_http_server(void) { - sock_t srv = socket(AF_INET, SOCK_STREAM, 0); - if (srv == SOCK_INVALID) { - socket_perror("socket"); - return SOCK_INVALID; + SOCKET srv = socket(AF_INET, SOCK_STREAM, 0); + if (srv == INVALID_SOCKET) { + frankensocket_perror("socket"); + return INVALID_SOCKET; } - int yes = 1; setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, (const char *)&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) { - socket_perror("bind"); - CLOSESOCK(srv); - return SOCK_INVALID; + frankensocket_perror("bind"); + frankensocket_close(srv); + return INVALID_SOCKET; } - if (listen(srv, 32) < 0) { - socket_perror("listen"); - CLOSESOCK(srv); - return SOCK_INVALID; + frankensocket_perror("listen"); + frankensocket_close(srv); + return INVALID_SOCKET; } - return srv; } -/* --------------------------------------------------------------------- - * File change -> rebuild + notify, driven by the watcher thread - * ------------------------------------------------------------------- */ +/** @} + * @name Change handling and program entry point + * + * Runs the watcher loop, optional build command, reload cooldown, signal + * handling, CLI parsing, and process startup/shutdown. + * @{ + */ -/* Minimum time between two reload broadcasts. Root-caused the double-fire +/** Minimum time between two reload broadcasts. Root-caused the double-fire * this was originally added to paper over: it was NOTE_ATTRIB (see * kq_add_path) picking up an atime bump from something merely reading a * just-written file (e.g. Spotlight/mdworker indexing it), not a race in @@ -904,48 +1009,55 @@ static sock_t start_http_server(void) static long long g_last_broadcast_ms = 0; static bool g_have_last_broadcast = false; -static void on_change(void) +/** + * @brief React to one coalesced file-system change. + * + * Runs the optional build command, enforces the reload cooldown, and notifies + * connected browsers only when the build succeeds. + */ +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); + "[liveside] build command failed (status %d), " + "not reloading\n", status); return; } } - if (g_have_last_broadcast && (now_ms() - g_last_broadcast_ms) < RELOAD_COOLDOWN_MS) { printf("[liveside] reload sent recently, skipping duplicate\n"); return; } - broadcast_reload(); g_last_broadcast_ms = now_ms(); g_have_last_broadcast = true; } -static void *watcher_loop(void *arg) +/** + * @brief Worker thread that waits for file changes and triggers reloads. + * @param arg Unused. + * @return 0 when the watcher stops. + */ +static int +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; + return 0; } - 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 @@ -954,40 +1066,54 @@ static void *watcher_loop(void *arg) * second, spurious rebuild-and-reload for every real one. */ watch_settle(w); } - watch_close(w); - return NULL; + return 0; } -static void handle_sigint(int sig) +/** + * @brief Signal handler that requests graceful shutdown. + * @param sig Signal number, ignored. + */ +static void +handle_sigint(int sig) { (void)sig; g_running = 0; } -static void usage(const char *prog) +/** + * @brief Print command-line usage. + * @param prog Program name to show in the usage line. + */ +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); + "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) +/** + * @brief Program entry point. + * @param argc Command-line argument count. + * @param argv Command-line argument vector. + * @return Process exit status. + */ +int +main(int argc, char **argv) { -#ifdef _WIN32 - WSADATA wsa; - if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { - fprintf(stderr, "[liveside] WSAStartup failed\n"); + if (frankensocket_startup() != 0) + return 1; + if (mtx_init(&g_clients_mu, mtx_plain) != thrd_success) { + fprintf(stderr, "[liveside] mutex initialization failed\n"); + frankensocket_cleanup(); return 1; } -#endif - mutex_init(&g_clients_mu); - int opt; while ((opt = getopt(argc, argv, "p:d:c:i:h")) != -1) { switch (opt) { @@ -1009,33 +1135,25 @@ int main(int argc, char **argv) return opt == 'h' ? 0 : 1; } } - + ignore_init(&g_ignore, g_watch_dir); signal(SIGINT, handle_sigint); signal(SIGTERM, handle_sigint); -#ifndef _WIN32 - /* No SIGPIPE on Windows -- a broken socket write there just returns - * an error, no signal to ignore. */ - signal(SIGPIPE, SIG_IGN); -#endif - + frankensocket_ignore_sigpipe(); printf("[liveside] watching '%s'\n", g_watch_dir); printf("[liveside] SSE endpoint: http://localhost:%d/livereload\n", - g_port); + g_port); printf("[liveside] client script: http://localhost:%d/liveside.js\n", - g_port); + 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 == SOCK_INVALID) + if (g_listen_fd == INVALID_SOCKET) return 1; - - thread_t watcher, pinger; - thread_spawn(&watcher, watcher_loop, NULL); - thread_detach(watcher); - thread_spawn(&pinger, ping_thread, NULL); - thread_detach(pinger); - + thrd_t watcher, pinger; + if (thrd_create(&watcher, watcher_loop, NULL) == thrd_success) + thrd_detach(watcher); + if (thrd_create(&pinger, ping_thread, NULL) == thrd_success) + thrd_detach(pinger); while (g_running) { /* accept() blocking indefinitely can't be woken up reliably from * a signal handler (shutdown()/close() on a *listening* socket @@ -1046,22 +1164,21 @@ int main(int argc, char **argv) int pr = poll(&pfd, 1, 500); if (pr <= 0) continue; - - sock_t fd = accept(g_listen_fd, NULL, NULL); - if (fd == SOCK_INVALID) + SOCKET fd = accept(g_listen_fd, NULL, NULL); + if (fd == INVALID_SOCKET) continue; int yes = 1; setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&yes, sizeof(yes)); - - thread_t conn; - thread_spawn(&conn, connection_thread, (void *)(intptr_t)fd); - thread_detach(conn); + thrd_t conn; + if (thrd_create(&conn, connection_thread, (void *)(uintptr_t)fd) == thrd_success) + thrd_detach(conn); + else + frankensocket_close(fd); } - - CLOSESOCK(g_listen_fd); + frankensocket_close(g_listen_fd); printf("\n[liveside] shutting down\n"); -#ifdef _WIN32 - WSACleanup(); -#endif + frankensocket_cleanup(); return 0; } + +/** @} */
diff --git a/ports/frankensocket/frankensocket.h b/ports/frankensocket/frankensocket.h @@ -0,0 +1,141 @@ +/* + * frankensocket - tiny socket compatibility layer for liveside. + * + * This header keeps the common BSD socket vocabulary visible on POSIX and + * Win32 while naming the unavoidable differences explicitly. + */ +#ifndef FRANKENSOCKET_H +#define FRANKENSOCKET_H + +#include <stddef.h> +#include <stdio.h> +#include <string.h> + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include <winsock2.h> +#include <ws2tcpip.h> +#include <windows.h> +#pragma comment(lib, "ws2_32.lib") + +typedef int FrankenSockError; + +static int +frankensocket_startup(void) +{ + WSADATA wsa; + + if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { + fprintf(stderr, "[liveside] WSAStartup failed\n"); + return -1; + } + return 0; +} + +static void +frankensocket_cleanup(void) +{ + WSACleanup(); +} + +static void +frankensocket_ignore_sigpipe(void) +{ +} + +static FrankenSockError +frankensocket_error(void) +{ + return WSAGetLastError(); +} + +static void +frankensocket_perror(const char *msg) +{ + fprintf(stderr, "%s: WSA error %d\n", msg, frankensocket_error()); +} + +static int +frankensocket_close(SOCKET s) +{ + return closesocket(s); +} + +static long +frankensocket_send(SOCKET s, const void *buf, size_t len) +{ + return send(s, (const char *)buf, (int)len, 0); +} + +static long +frankensocket_recv(SOCKET s, void *buf, size_t len) +{ + return recv(s, (char *)buf, (int)len, 0); +} + +#else +#include <errno.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <signal.h> +#include <sys/socket.h> +#include <unistd.h> + +typedef int SOCKET; +typedef int FrankenSockError; + +#ifndef INVALID_SOCKET +#define INVALID_SOCKET (-1) +#endif + +static int +frankensocket_startup(void) +{ + return 0; +} + +static void +frankensocket_cleanup(void) +{ +} + +static void +frankensocket_ignore_sigpipe(void) +{ + signal(SIGPIPE, SIG_IGN); +} + +static FrankenSockError +frankensocket_error(void) +{ + return errno; +} + +static void +frankensocket_perror(const char *msg) +{ + fprintf(stderr, "%s: %s\n", msg, strerror(frankensocket_error())); +} + +static int +frankensocket_close(SOCKET s) +{ + return close(s); +} + +static long +frankensocket_send(SOCKET s, const void *buf, size_t len) +{ + return (long)send(s, buf, len, 0); +} + +static long +frankensocket_recv(SOCKET s, void *buf, size_t len) +{ + return (long)recv(s, buf, len, 0); +} +#endif + +#endif /* FRANKENSOCKET_H */
diff --git a/ports/ignore/ignore.c b/ports/ignore/ignore.c @@ -0,0 +1,284 @@ +#include "ignore.h" + +#include <ctype.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#ifndef _WIN32 +#include <unistd.h> +#endif + +struct ignore_rule { + char base[IGNORE_PATH_MAX]; + char pattern[1024]; + bool negated; + bool dir_only; + bool anchored; + bool has_slash; +}; + +static void +path_copy(char *dst, size_t dstsz, const char *src) +{ + snprintf(dst, dstsz, "%s", src ? src : ""); + for (char *p = dst; *p; p++) + if (*p == '\\') + *p = '/'; +} + +static void +trim_trailing_slashes(char *s) +{ + size_t n = strlen(s); + while (n > 1 && s[n - 1] == '/') + s[--n] = '\0'; +} + +void +ignore_init(ignore_context_t *ctx, const char *root) +{ + path_copy(ctx->root, sizeof(ctx->root), root && *root ? root : "."); + trim_trailing_slashes(ctx->root); +} + +bool +ignore_is_ignore_file(const char *path) +{ + char norm[IGNORE_PATH_MAX]; + path_copy(norm, sizeof(norm), path); + const char *base = strrchr(norm, '/'); + base = base ? base + 1 : norm; + return strcmp(base, ".gitignore") == 0 || strcmp(base, ".livesideignore") == 0; +} + +static bool +is_builtin_ignored(const char *rel) +{ + if (strcmp(rel, ".") == 0 || strcmp(rel, "..") == 0) + return true; + const char *p = rel; + while (*p) { + const char *slash = strchr(p, '/'); + size_t n = slash ? (size_t)(slash - p) : strlen(p); + if ((n == 1 && p[0] == '.') || (n == 2 && p[0] == '.' && p[1] == '.') || + (n == 4 && strncmp(p, ".git", 4) == 0)) + return true; + if (!slash) + break; + p = slash + 1; + } + return false; +} + +static void +relative_to_root(const ignore_context_t *ctx, const char *path, + char *rel, size_t relsz) +{ + char norm[IGNORE_PATH_MAX]; + path_copy(norm, sizeof(norm), path); + trim_trailing_slashes(norm); + size_t root_len = strlen(ctx->root); + if (strncmp(norm, ctx->root, root_len) == 0 && + (norm[root_len] == '/' || norm[root_len] == '\0')) { + const char *r = norm + root_len; + if (*r == '/') + r++; + snprintf(rel, relsz, "%s", *r ? r : "."); + } else { + snprintf(rel, relsz, "%s", norm); + } +} + +static bool +unescape_line(char *s) +{ + char *r = s, *w = s; + while (*r) { + if (*r == '\\' && r[1]) + r++; + *w++ = *r++; + } + *w = '\0'; + return *s != '\0'; +} + +static bool +parse_rule(const char *base, char *line, struct ignore_rule *rule) +{ + char *p = line; + while (*p == ' ' || *p == '\t') + p++; + if (*p == '\0') + return false; + if (*p == '#' || (*p == '\\' && p[1] == '#')) { + if (*p == '#') + return false; + p++; + } + char *end = p + strlen(p); + while (end > p && (end[-1] == '\n' || end[-1] == '\r')) + *--end = '\0'; + while (end > p && (end[-1] == ' ' || end[-1] == '\t') && + !(end - 2 >= p && end[-2] == '\\')) + *--end = '\0'; + if (*p == '\0') + return false; + memset(rule, 0, sizeof(*rule)); + snprintf(rule->base, sizeof(rule->base), "%s", base); + if (*p == '!') { + rule->negated = true; + p++; + } + if (*p == '/') { + rule->anchored = true; + p++; + } + size_t len = strlen(p); + if (len > 0 && p[len - 1] == '/') { + rule->dir_only = true; + p[len - 1] = '\0'; + } + if (!unescape_line(p)) + return false; + rule->has_slash = strchr(p, '/') != NULL; + snprintf(rule->pattern, sizeof(rule->pattern), "%s", p); + return rule->pattern[0] != '\0'; +} + +static bool +char_match(char pc, char c) +{ + return pc == '?' ? c != '/' && c != '\0' : pc == c; +} + +static bool +wildmatch(const char *pat, const char *text) +{ + if (*pat == '\0') + return *text == '\0'; + if (pat[0] == '*' && pat[1] == '*') { + pat += 2; + while (*pat == '*') + pat++; + if (*pat == '/') { + pat++; + if (wildmatch(pat, text)) + return true; + for (const char *t = text; *t; t++) + if (*t == '/' && wildmatch(pat, t + 1)) + return true; + return false; + } + for (const char *t = text;; t++) { + if (wildmatch(pat, t)) + return true; + if (*t == '\0') + return false; + } + } + if (*pat == '*') { + pat++; + for (const char *t = text;; t++) { + if (wildmatch(pat, t)) + return true; + if (*t == '\0' || *t == '/') + return false; + } + } + return char_match(*pat, *text) && wildmatch(pat + 1, text + 1); +} + +static bool +match_basename(const char *pattern, const char *rel) +{ + const char *p = rel; + while (*p) { + const char *slash = strchr(p, '/'); + size_t n = slash ? (size_t)(slash - p) : strlen(p); + char comp[1024]; + if (n >= sizeof(comp)) + n = sizeof(comp) - 1; + memcpy(comp, p, n); + comp[n] = '\0'; + if (wildmatch(pattern, comp)) + return true; + if (!slash) + break; + p = slash + 1; + } + return false; +} + +static bool +rule_matches(const struct ignore_rule *rule, const char *rel, bool is_dir) +{ + char scoped[IGNORE_PATH_MAX]; + if (rule->base[0]) { + size_t n = strlen(rule->base); + if (strncmp(rel, rule->base, n) != 0 || (rel[n] != '/' && rel[n] != '\0')) + return false; + const char *r = rel + n; + if (*r == '/') + r++; + snprintf(scoped, sizeof(scoped), "%s", *r ? r : "."); + } else { + snprintf(scoped, sizeof(scoped), "%s", rel); + } + if (rule->dir_only) { + if (is_dir && (wildmatch(rule->pattern, scoped) || match_basename(rule->pattern, scoped))) + return true; + char prefix[1024]; + snprintf(prefix, sizeof(prefix), "%s/", rule->pattern); + return strncmp(scoped, prefix, strlen(prefix)) == 0 || + (!rule->anchored && strstr(scoped, prefix) != NULL); + } + if (rule->anchored || rule->has_slash) + return wildmatch(rule->pattern, scoped); + return match_basename(rule->pattern, scoped); +} + +static void +load_file_rules(const char *root, const char *base, const char *name, + const char *rel, bool is_dir, bool *ignored) +{ + char file[IGNORE_PATH_MAX]; + if (base[0]) + snprintf(file, sizeof(file), "%s/%s/%s", root, base, name); + else + snprintf(file, sizeof(file), "%s/%s", root, name); + FILE *fp = fopen(file, "r"); + if (!fp) + return; + char line[2048]; + while (fgets(line, sizeof(line), fp)) { + struct ignore_rule rule; + if (parse_rule(base, line, &rule) && rule_matches(&rule, rel, is_dir)) + *ignored = !rule.negated; + } + fclose(fp); +} + +bool +ignore_path_ignored(const ignore_context_t *ctx, const char *path, bool is_dir) +{ + char rel[IGNORE_PATH_MAX]; + relative_to_root(ctx, path, rel, sizeof(rel)); + if (is_builtin_ignored(rel)) + return true; + bool ignored = false; + char base[IGNORE_PATH_MAX] = ""; + load_file_rules(ctx->root, base, ".gitignore", rel, is_dir, &ignored); + load_file_rules(ctx->root, base, ".livesideignore", rel, is_dir, &ignored); + char walk[IGNORE_PATH_MAX]; + snprintf(walk, sizeof(walk), "%s", rel); + char *slash = walk; + while ((slash = strchr(slash, '/')) != NULL) { + *slash = '\0'; + snprintf(base, sizeof(base), "%s", walk); + load_file_rules(ctx->root, base, ".gitignore", rel, is_dir, &ignored); + load_file_rules(ctx->root, base, ".livesideignore", rel, is_dir, &ignored); + *slash++ = '/'; + } + return ignored; +}
diff --git a/ports/ignore/ignore.h b/ports/ignore/ignore.h @@ -0,0 +1,19 @@ +#ifndef LIVESIDE_IGNORE_H +#define LIVESIDE_IGNORE_H + +#include <stdbool.h> + +#define IGNORE_PATH_MAX 4096 + +typedef struct ignore_context { + char root[IGNORE_PATH_MAX]; +} ignore_context_t; + +void +ignore_init(ignore_context_t *ctx, const char *root); +bool +ignore_path_ignored(const ignore_context_t *ctx, const char *path, bool is_dir); +bool +ignore_is_ignore_file(const char *path); + +#endif /* LIVESIDE_IGNORE_H */
diff --git a/ports/win32/watch.h b/ports/win32/watch.h @@ -0,0 +1,100 @@ +#ifndef LIVESIDE_WIN32_WATCH_H +#define LIVESIDE_WIN32_WATCH_H + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include <windows.h> + +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "../ignore/ignore.h" + +#define WIN32_WATCH_BUFSZ 65536 + +typedef struct win32_watch { + HANDLE dir; + char root[IGNORE_PATH_MAX]; + ignore_context_t *ignore; +} win32_watch_t; + +static win32_watch_t * +win32_watch_open(const char *root, ignore_context_t *ignore) +{ + win32_watch_t *w = (win32_watch_t *)calloc(1, sizeof(*w)); + if (!w) + return NULL; + snprintf(w->root, sizeof(w->root), "%s", root); + w->ignore = ignore; + w->dir = CreateFileA(root, FILE_LIST_DIRECTORY, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); + if (w->dir == INVALID_HANDLE_VALUE) { + free(w); + return NULL; + } + return w; +} + +static bool +win32_watch_event_ignored(win32_watch_t *w, + const FILE_NOTIFY_INFORMATION *fni) +{ + char name[IGNORE_PATH_MAX]; + int n = WideCharToMultiByte(CP_UTF8, 0, fni->FileName, + (int)(fni->FileNameLength / sizeof(WCHAR)), name, + (int)sizeof(name) - 1, NULL, NULL); + if (n <= 0) + return false; + name[n] = '\0'; + for (char *p = name; *p; p++) + if (*p == '\\') + *p = '/'; + char full[IGNORE_PATH_MAX]; + snprintf(full, sizeof(full), "%s/%s", w->root, name); + if (ignore_is_ignore_file(full)) + return true; + DWORD attrs = GetFileAttributesA(full); + bool is_dir = attrs != INVALID_FILE_ATTRIBUTES && + (attrs & FILE_ATTRIBUTE_DIRECTORY) != 0; + return ignore_path_ignored(w->ignore, full, is_dir); +} + +static bool +win32_watch_wait(win32_watch_t *w) +{ + char buf[WIN32_WATCH_BUFSZ]; + DWORD bytes = 0; + DWORD filter = FILE_NOTIFY_CHANGE_FILE_NAME | + FILE_NOTIFY_CHANGE_DIR_NAME | + FILE_NOTIFY_CHANGE_SIZE | + FILE_NOTIFY_CHANGE_LAST_WRITE; + if (!ReadDirectoryChangesW(w->dir, buf, sizeof(buf), TRUE, filter, + &bytes, NULL, NULL)) + return false; + if (bytes == 0) + return true; + FILE_NOTIFY_INFORMATION *fni = (FILE_NOTIFY_INFORMATION *)buf; + for (;;) { + if (!win32_watch_event_ignored(w, fni)) + return true; + if (fni->NextEntryOffset == 0) + break; + fni = (FILE_NOTIFY_INFORMATION *)((char *)fni + fni->NextEntryOffset); + } + return true; +} + +static void +win32_watch_close(win32_watch_t *w) +{ + if (!w) + return; + CloseHandle(w->dir); + free(w); +} + +#endif /* LIVESIDE_WIN32_WATCH_H */
diff --git a/requirements.ini b/requirements.ini @@ -0,0 +1,16 @@ +; Dependencies intentionally track upstream branches instead of exact commits. +; liveside accepts the small breakage risk for these stable compatibility APIs +; to keep dependency maintenance low. + +[$] +/=thirdparty + +[deps] +tinycthread=https://github.com/tinycthread/tinycthread.git@master + +[deps-windows] +tinycthread=https://github.com/tinycthread/tinycthread.git@master +win32ports-dirent_h=https://github.com/win32ports/dirent_h.git@master +win32ports-getopt_h=https://github.com/win32ports/getopt_h.git@master +win32ports-sys_time_h=https://github.com/win32ports/sys_time_h.git@master +win32ports-unistd_h=https://github.com/win32ports/unistd_h.git@master
: nply/liveside