summaryrefslogtreecommitdiff
path: root/web/discover.py
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-12 15:45:52 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:16 -0300
commitfd7775b4e9c24b6bb8f664beb7d4fd2ccecd8d85 (patch)
tree33a4ba949a2c883d3cbd13d7fd069770f013f166 /web/discover.py
parent7f418a6bb3c2d5319d781a61a14aeaf15aff4c89 (diff)
downloadcloud9-fd7775b4e9c24b6bb8f664beb7d4fd2ccecd8d85.tar.gz
cloud9-fd7775b4e9c24b6bb8f664beb7d4fd2ccecd8d85.zip
9web: serve local sites with 9P build controls and passive listener discovery
Add optional catalogue mode with an explicit site registry, per-site HTTP roots, MIME/index/pretty-URL handling, HEAD and byte ranges. Existing generated sites are available immediately, without preview processes. Expose build, watch, cancel, status, logs and state events through the shared 9P backend and HTTP dashboard. Supervise process groups, coalesce queued rebuilds and watch configured source paths. Discover Linux TCP listeners by socket inode ownership and executable/argument recognizers; never probe endpoints. Document configuration, the user-systemd unit, workstation ports, network access assumptions and limitations including in-place publication and static-only Worker sites. Keep the original upstream gateway mode. Validation: catalogue integration suite (including paginated directory reads, cancellation and parked events), existing HTTP filesystem and mux suites, real 9ns mount, dual-stack service restart and all five workstation sites. Real entomology build: 129 pages, zero failures.
Diffstat (limited to 'web/discover.py')
-rw-r--r--web/discover.py93
1 files changed, 93 insertions, 0 deletions
diff --git a/web/discover.py b/web/discover.py
new file mode 100644
index 0000000..8c750c1
--- /dev/null
+++ b/web/discover.py
@@ -0,0 +1,93 @@
+"""One-shot Linux listener inventory for 9web. Never connects to a listener.
+
+Only socket-inode ownership establishes a process/listener relationship. Parent
+commands can identify a launcher, but never turn an arbitrary Node socket into
+HTTP. Output deliberately omits full argv/environment (which may hold secrets).
+"""
+import ipaddress
+import json
+import os
+import socket
+import sys
+
+
+def recognize(argv):
+ if not argv:
+ return None
+ exe = os.path.basename(argv[0])
+ args = argv[1:]
+ if exe in ('miniserve', '9web'):
+ return exe, 'https' if '--tls-cert' in args else 'http', 'recognized executable'
+ if exe.startswith('python') and any(args[i:i+2] == ['-m', 'http.server'] for i in range(len(args))):
+ return 'python http.server', 'http', 'python -m http.server'
+ if exe == 'typst' and 'watch' in args:
+ return 'typst watch', 'http', 'typst watch'
+ # Require a CLI entrypoint, not a substring anywhere in arbitrary arguments.
+ if exe in ('node', 'nodejs', 'bun') and args:
+ entry = args[0].replace('\\', '/')
+ if entry.endswith(('/vite/bin/vite.js', '/vite/bin/vite.mjs')):
+ return 'vite', 'https' if '--https' in args else 'http', 'Vite CLI entrypoint'
+ if '/wrangler/' in entry and 'dev' in args:
+ return 'wrangler dev', 'http', 'Wrangler dev entrypoint'
+ return None
+
+
+def inventory(web_pid=None, web_ports=()):
+ owners = {}
+ for name in os.listdir('/proc'):
+ if not name.isdecimal():
+ continue
+ base = '/proc/' + name
+ try:
+ argv = open(base + '/cmdline', 'rb').read(65536).decode(errors='replace').rstrip('\0').split('\0')
+ exe = os.path.basename(os.readlink(base + '/exe'))
+ cwd = os.readlink(base + '/cwd')
+ fds = os.listdir(base + '/fd')
+ except (OSError, ValueError):
+ continue
+ recognized = recognize([exe] + argv[1:])
+ # 9web has both HTTP and 9P sockets. Its own configured listeners are
+ # supplied separately by the catalogue, never inferred from its name.
+ if exe == '9web':
+ recognized = None
+ for fd in fds:
+ try:
+ link = os.readlink(base + '/fd/' + fd)
+ except OSError:
+ continue
+ if link.startswith('socket:['):
+ owners.setdefault(link[8:-1], []).append(dict(
+ pid=int(name), process=exe, cwd=cwd, recognized=recognized))
+ rows = []
+ for table, family in [('tcp', socket.AF_INET), ('tcp6', socket.AF_INET6)]:
+ try:
+ lines = open('/proc/net/' + table).readlines()[1:]
+ except OSError:
+ continue
+ for line in lines:
+ fields = line.split()
+ if fields[3] != '0A':
+ continue
+ raw, port = fields[1].split(':')
+ packed = b''.join(int(raw[i:i+8], 16).to_bytes(4, sys.byteorder) for i in range(0, len(raw), 8))
+ address = socket.inet_ntop(family, packed)
+ inode = fields[9]
+ processes = {p['pid']: p for p in owners.get(inode, [])}
+ recognized = [p for p in processes.values() if p['recognized']]
+ p = recognized[0] if recognized else next(iter(processes.values()), None)
+ rec = p['recognized'] if p else None
+ if web_pid in processes and int(port, 16) in web_ports:
+ p = processes[web_pid]
+ rec = ('9web', 'http', '9web registered HTTP listener')
+ rows.append(dict(id=table + '-' + inode, address=address, port=int(port, 16),
+ protocol=rec[1] if rec else 'unknown', service=rec[0] if rec else None,
+ pid=p['pid'] if p else None, process=p['process'] if p else None,
+ cwd=p['cwd'] if p else None,
+ local=ipaddress.ip_address(address).is_loopback,
+ evidence=('socket inode ownership; ' + rec[2]) if rec else
+ ('socket inode ownership; unrecognized protocol' if p else 'process ownership unavailable')))
+ return sorted(rows, key=lambda r: (r['port'], r['address']))
+
+
+if __name__ == '__main__':
+ print(json.dumps(inventory(int(sys.argv[1]), [int(p) for p in sys.argv[2].split(',')]) if len(sys.argv) == 3 else inventory()))