: nply/liveside

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
192 
193 
194 
195 
196 
197 
198 
199 
200 
201 
202 
203 
204 
205 
206 
207 
208 
209 
210 
211 
212 
213 
214 
215 
216 
217 
218 
219 
220 
221 
222 
223 
224 
225 
226 
227 
228 
229 
230 
231 
232 
233 
234 
235 
236 
237 
238 
239 
240 
241 
242 
243 
244 
245 
246 
247 
248 
249 
250 
251 
252 
253 
254 
255 
256 
257 
258 
259 
260 
261 
262 
263 
264 
265 
266 
267 
268 
269 
270 
271 
272 
273 
274 
275 
276 
277 
278 
279 
280 
281 
282 
283 
284 
285 
286 
287 
288 
289 
290 
291 
292 
293 
294 
295 
296 
297 
298 
299 
300 
301 
302 
303 
304 
305 
306 
307 
308 
309 
310 
311 
312 
313 
314 
315 
316 
317 
318 
319 
320 
321 
322 
323 
324 
325 
326 
327 
328 
329 
330 
331 
332 
333 
334 
335 
336 
337 
338 
339 
340 
341 
342 
343 
344 
345 
346 
347 
348 
349 
350 
351 
352 
353 
354 
355 
356 
357 
358 
359 
360 
361 
362 
363 
364 
365 
366 
367 
368 
369 
370 
371 
372 
373 
374 
375 
376 
377 
378 
379 
380 
381 
382 
383 
384 
385 
386 
387 
388 
389 
390 
391 
392 
393 
394 
395 
396 
397 
398 
399 
400 
401 
402 
403 
404 
405 
406 
407 
408 
409 
410 
411 
412 
413 
414 
415 
416 
417 
418 
419 
420 
421 
422 
423 
424 
425 
426 
427 
428 
429 
430 
431 
432 
433 
434 
435 
436 
437 
438 
439 
440 
441 
442 
443 
444 
445 
446 
447 
448 
449 
450 
451 
452 
453 
454 
455 
456 
457 
458 
459 
460 
461 
462 
463 
464 
465 
466 
467 
468 
469 
470 
471 
472 
473 
474 
475 
476 
477 
478 
479 
480 
481 
482 
483 
484 
485 
486 
487 
488 
489 
490 
491 
492 
493 
494 
495 
496 
497 
498 
499 
500 
501 
502 
503 
504 
505 
506 
507 
508 
509 
510 
511 
512 
513 
514 
515 
516 
517 
518 
519 
520 
521 
522 
523 
524 
525 
526 
527 
528 
529 
530 
531 
532 
533 
534 
535 
536 
537 
538 
539 
540 
541 
542 
543 
544 
545 
546 
547 
548 
549 
550 
551 
552 
553 
554 
555 
556 
557 
558 
559 
560 
561 
562 
563 
564 
565 
566 
567 
568 
569 
570 
571 
572 
573 
574 
575 
576 
577 
578 
579 
580 
581 
582 
583 
584 
585 
586 
587 
588 
589 
590 
591 
592 
593 
594 
595 
596 
597 
598 
599 
600 
601 
602 
603 
604 
605 
606 
607 
608 
609 
610 
611 
612 
613 
614 
615 
616 
617 
618 
619 
620 
621 
622 
623 
624 
625 
626 
627 
628 
629 
630 
631 
632 
633 
634 
635 
636 
637 
638 
639 
640 
641 
642 
643 
644 
645 
646 
647 
648 
649 
650 
651 
652 
653 
654 
655 
656 
657 
658 
659 
660 
661 
662 
663 
664 
665 
666 
667 
668 
669 
670 
671 
672 
673 
674 
675 
676 
677 
678 
679 
680 
681 
682 
683 
684 
685 
686 
687 
688 
689 
690 
691 
692 
693 
694 
695 
696 
697 
698 
699 
700 
701 
702 
703 
704 
705 
706 
707 
708 
709 
710 
711 
712 
713 
714 
715 
716 
717 
718 
719 
720 
721 
722 
723 
724 
725 
726 
727 
728 
729 
730 
731 
732 
733 
734 
735 
736 
737 
738 
739 
740 
741 
742 
743 
744 
745 
746 
747 
748 
749 
750 
751 
752 
753 
754 
755 
756 
757 
758 
759 
760 
761 
762 
763 
764 
765 
766 
767 
768 
769 
770 
771 
772 
773 
774 
775 
776 
777 
778 
779 
780 
781 
782 
783 
784 
785 
786 
787 
788 
789 
790 
791 
792 
793 
794 
795 
796 
797 
798 
799 
800 
801 
802 
803 
804 
805 
806 
807 
808 
809 
810 
811 
812 
813 
814 
815 
816 
817 
818 
819 
820 
821 
822 
823 
824 
825 
826 
827 
828 
829 
830 
831 
832 
833 
834 
835 
836 
837 
838 
839 
840 
841 
842 
843 
844 
845 
846 
847 
848 
849 
850 
851 
852 
853 
854 
855 
856 
857 
858 
859 
860 
861 
862 
863 
864 
865 
866 
867 
868 
869 
870 
871 
872 
873 
874 
875 
876 
877 
878 
879 
880 
881 
882 
883 
884 
885 
886 
887 
888 
889 
890 
891 
892 
893 
894 
895 
896 
897 
898 
899 
900 
901 
902 
903 
904 
905 
906 
907 
908 
909 
910 
911 
912 
913 
914 
915 
916 
917 
918 
919 
920 
921 
922 
923 
924 
925 
926 
927 
928 
929 
930 
931 
932 
933 
934 
935 
936 
937 
938 
939 
940 
941 
942 
943 
944 
945 
946 
947 
948 
949 
950 
951 
952 
953 
954 
955 
956 
957 
958 
959 
960 
961 
962 
963 
964 
965 
966 
967 
968 
969 
970 
971 
972 
973 
974 
975 
976 
977 
978 
979 
980 
981 
982 
983 
984 
985 
986 
987 
988 
989 
990 
991 
992 
993 
994 
995 
996 
997 
998 
999 
1000 
1001 
1002 
1003 
1004 
1005 
1006 
1007 
1008 
1009 
1010 
1011 
1012 
1013 
1014 
1015 
1016 
1017 
1018 
1019 
1020 
1021 
1022 
1023 
1024 
1025 
1026 
1027 
1028 
1029 
1030 
1031 
1032 
1033 
1034 
1035 
1036 
1037 
1038 
1039 
1040 
1041 
1042 
1043 
1044 
1045 
1046 
1047 
1048 
1049 
1050 
1051 
1052 
1053 
1054 
1055 
1056 
1057 
1058 
1059 
1060 
1061 
1062 
1063 
1064 
1065 
1066 
1067 
1068 
1069 
1070 
1071 
1072 
1073 
1074 
1075 
1076 
1077 
1078 
1079 
1080 
1081 
1082 
1083 
1084 
1085 
1086 
1087 
1088 
1089 
1090 
1091 
1092 
1093 
1094 
1095 
1096 
1097 
1098 
1099 
1100 
1101 
1102 
1103 
1104 
1105 
1106 
1107 
1108 
1109 
1110 
1111 
1112 
1113 
1114 
1115 
1116 
1117 
1118 
1119 
1120 
1121 
1122 
1123 
1124 
1125 
1126 
1127 
1128 
1129 
1130 
1131 
1132 
1133 
1134 
1135 
1136 
1137 
1138 
1139 
1140 
1141 
1142 
1143 
1144 
1145 
1146 
1147 
1148 
1149 
1150 
1151 
1152 
1153 
1154 
1155 
1156 
1157 
1158 
1159 
1160 
1161 
1162 
1163 
1164 
1165 
1166 
1167 
1168 
1169 
1170 
1171 
1172 
1173 
1174 
1175 
1176 
1177 
1178 
1179 
1180 
1181 
1182 
1183 
1184 
/**
 * @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.
 *
 * 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 (including Windows) it falls back to
 * polling.
 *
 * 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>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#ifdef _WIN32
#include "ports/frankensocket/frankensocket.h"

#include <dirent.h>
#include <fcntl.h>
#include <getopt.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <tinycthread.h>
#include <unistd.h>

#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
#else
#include <dirent.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <tinycthread.h>
#include <unistd.h>

#include "ports/frankensocket/frankensocket.h"
#include "ports/ignore/ignore.h"
#endif

static void
usleep_ms(long ms)
{
	struct timespec ts;
	ts.tv_sec = ms / 1000;
	ts.tv_nsec = (ms % 1000) * 1000000L;
	thrd_sleep(&ts, NULL);
}

static long long
now_ms(void)
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

#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 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;

/**
 * @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)
{
	return ignore_path_ignored(&g_ignore, path, is_dir);
}

static void
tree_scan_signature(const char *path, unsigned long *sig)
{
	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 unsigned long
tree_signature(const char *root)
{
	unsigned long sig = 0;
	tree_scan_signature(root, &sig);
	return sig;
}

/** @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 struct watcher watcher_t;

#if defined(WATCH_WIN32)

struct watcher {
	win32_watch_t *native;
};

static watcher_t *
watch_open(const char *root)
{
	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 bool
watch_wait(watcher_t *w)
{
	return win32_watch_wait(w->native);
}

static void
watch_settle(watcher_t *w)
{
	(void)w;
	usleep_ms(150);
}

static void
watch_close(watcher_t *w)
{
	if (!w)
		return;
	win32_watch_close(w->native);
	free(w);
}

#elif defined(WATCH_KQUEUE)

struct kq_path {
	int fd;
	bool ignore_file;
};

struct watcher {
	int kq;
	struct kq_path *paths;
	size_t count, cap;
	char root[4096];
	unsigned long last_sig;
};

/**
 * @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->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. 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
	 * indexing it shortly after a save) -- indistinguishable from a real
	 * edit but with nothing to actually reload. NOTE_WRITE/NOTE_EXTEND
	 * already cover real content changes; a bare `touch` with no
	 * write() won't trigger a reload here, which is the right call for
	 * 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);
	if (kevent(w->kq, &kev, 1, NULL, 0, NULL) < 0) {
		close(fd);
		return;
	}
	w->paths[w->count].fd = fd;
	w->paths[w->count].ignore_file = ignore_is_ignore_file(path);
	w->count++;
}

/**
 * @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) {
		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))
			continue;
		if (is_dir)
			kq_scan(w, child);
		else if (S_ISREG(st.st_mode))
			kq_add_path(w, child);
	}
	closedir(dir);
}

/**
 * @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->paths[i].fd);
	w->count = 0;
	kq_scan(w, w->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
	 * 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 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;
}

/**
 * @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;
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
	 * 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_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,
 * 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_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);
}

/**
 * @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->paths[i].fd);
	free(w->paths);
	close(w->kq);
	free(w);
}

#elif defined(WATCH_INOTIFY)

struct watch_entry {
	int wd;
	char path[4096];
};

struct watcher {
	int fd;
	struct watch_entry *entries;
	size_t count, cap;
	char root[4096];
};

/**
 * @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,
	 * not per file.
	 *
	 * Deliberately no IN_ATTRIB, matching kq_add_path's reasoning on the
	 * kqueue side: it fires on any metadata change including a plain
	 * atime bump from something merely reading the file (e.g. a search
	 * indexer), which was confirmed (on macOS/kqueue; untested here on
	 * Linux, but the same class of issue applies) to cause a spurious
	 * second "change" shortly after a real edit, with nothing new to
	 * 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);
	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;
	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) {
		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) &&
		    !path_ignored(child, true))
			in_add_dir(w, child);
	}
	closedir(dir);
}

/**
 * @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);
	w->count = 0;
	in_add_dir(w, w->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 0;
	}
	snprintf(w->root, sizeof(w->root), "%s", root);
	in_rebuild(w);
	printf("[liveside] watching %zu directories via inotify\n",
	       w->count);
	return 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;
	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,
 * 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_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))
		read(w->fd, buf, sizeof(buf));
	in_rebuild(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++)
		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;
	unsigned long last_ignore;
};

/**
 * @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) {
		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 (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;
		}
	}
	closedir(dir);
}

/**
 * @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, ignore_files_only);
	return sig;
}

/**
 * @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, false);
	w->last_ignore = poll_snapshot(root, true);
	printf("[liveside] watching '%s' via polling (%dms interval)\n",
	       root, g_poll_ms);
	return 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) {
		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
 * 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, false);
	w->last_ignore = poll_snapshot(w->root, true);
}

/**
 * @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

/** @}
 * @name SSE client registry
 *
 * Tracks connected browser EventSource sockets and broadcasts reload frames.
 * @{
 */

#define MAX_CLIENTS 64

static SOCKET g_client_fds[MAX_CLIENTS];
static int g_nclients = 0;
static mtx_t g_clients_mu;

/**
 * @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)
{
	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");
		frankensocket_close(fd);
	}
	mtx_unlock(&g_clients_mu);
}

/**
 * @brief Remove and close an SSE client socket.
 * @param fd Socket descriptor to drop from the registry.
 */
static void
remove_client(SOCKET fd)
{
	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;
		}
	}
	frankensocket_close(fd);
	mtx_unlock(&g_clients_mu);
}

/**
 * @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)
{
	SOCKET dead[MAX_CLIENTS];
	int ndead = 0;
	mtx_lock(&g_clients_mu);
	int n = g_nclients;
	for (int i = 0; i < n; i++) {
		if (frankensocket_send(g_client_fds[i], msg, len) < 0)
			dead[ndead++] = g_client_fds[i];
	}
	mtx_unlock(&g_clients_mu);
	for (int i = 0; i < ndead; i++)
		remove_client(dead[i]);
}

/** @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);
}

/**
 * @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) {
		usleep_ms(30000);
		if (g_nclients > 0)
			broadcast(ping, sizeof(ping) - 1);
	}
	return 0;
}

/** @}
 * @name Minimal HTTP server
 *
 * Handles only the endpoints required by liveside: /livereload, /liveside.js,
 * /, and 404 responses for everything else.
 * @{
 */

/** 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[] =
#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 (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 = frankensocket_recv(fd, buf, sizeof(buf));
		if (n <= 0)
			break;
	}
	remove_client(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);
	frankensocket_send(fd, header, (size_t)hlen);
	frankensocket_send(fd, CLIENT_JS, sizeof(CLIENT_JS) - 1);
	frankensocket_close(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);
	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);
	frankensocket_send(fd, header, (size_t)hlen);
	frankensocket_send(fd, body, (size_t)blen);
	frankensocket_close(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";
	frankensocket_send(fd, resp, sizeof(resp) - 1);
	frankensocket_close(fd);
}

/**
 * @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)
{
	SOCKET fd = (SOCKET)(uintptr_t)arg;
	char buf[4096];
	long n = frankensocket_recv(fd, buf, sizeof(buf) - 1);
	if (n <= 0) {
		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)
		handle_reload_js(fd);
	else if (strcmp(path, "/") == 0)
		handle_root(fd);
	else
		handle_not_found(fd);
	return 0;
}

static SOCKET g_listen_fd = INVALID_SOCKET;

/**
 * @brief Create, bind, and listen on the liveside HTTP socket.
 * @return Listening socket, or INVALID_SOCKET on failure.
 */
static SOCKET
start_http_server(void)
{
	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) {
		frankensocket_perror("bind");
		frankensocket_close(srv);
		return INVALID_SOCKET;
	}
	if (listen(srv, 32) < 0) {
		frankensocket_perror("listen");
		frankensocket_close(srv);
		return INVALID_SOCKET;
	}
	return srv;
}

/** @}
 * @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
 * 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
 * write detection or our own -c build's writes -- dropping NOTE_ATTRIB and
 * watch_settle() together were enough on their own (confirmed: zero
 * duplicate reloads with this cooldown effectively disabled). This stays
 * on as a cheap safety net for whatever's left uncaught (inotify's
 * IN_ATTRIB has the same class of issue; the poll fallback has none of
 * this, but costs nothing to also guard), kept short enough that it
 * shouldn't ever visibly swallow a genuine rapid second edit. */
#define RELOAD_COOLDOWN_MS 150

static long long g_last_broadcast_ms = 0;
static bool g_have_last_broadcast = false;

/**
 * @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);
			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;
}

/**
 * @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 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
		 * 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 0;
}

/**
 * @brief Signal handler that requests graceful shutdown.
 * @param sig Signal number, ignored.
 */
static void
handle_sigint(int sig)
{
	(void)sig;
	g_running = 0;
}

/**
 * @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);
}

/**
 * @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)
{
	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;
	}
	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;
		}
	}
	ignore_init(&g_ignore, g_watch_dir);
	signal(SIGINT, handle_sigint);
	signal(SIGTERM, handle_sigint);
	frankensocket_ignore_sigpipe();
	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 == INVALID_SOCKET)
		return 1;
	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
		 * 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;
		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));
		thrd_t conn;
		if (thrd_create(&conn, connection_thread, (void *)(uintptr_t)fd) == thrd_success)
			thrd_detach(conn);
		else
			frankensocket_close(fd);
	}
	frankensocket_close(g_listen_fd);
	printf("\n[liveside] shutting down\n");
	frankensocket_cleanup();
	return 0;
}

/** @} */