From 535ccb5a8d0119688fa2347d099292ee239b30cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kyle=20=F0=9F=90=86?= Date: Wed, 17 Dec 2025 14:23:52 -0500 Subject: [PATCH 1/9] Graceful shutdown handling and memory safety fixes --- src/handler.zig | 61 +++++++++++++++++++++-------- src/main.zig | 16 +++++--- src/server.zig | 61 +++++++++++++++++++++++------ src/spider.zig | 101 ++++++++++++++++++++++++++++++++++++------------ src/store.zig | 32 +++++++++++++-- 5 files changed, 211 insertions(+), 60 deletions(-) diff --git a/src/handler.zig b/src/handler.zig index 6d514a9..51c9315 100644 --- a/src/handler.zig +++ b/src/handler.zig @@ -148,6 +148,7 @@ pub const Handler = struct { broadcaster: *Broadcaster, send_fn: *const fn (conn_id: u64, data: []const u8) void, event_limiter: *rate_limiter.EventRateLimiter, + shutdown: *std.atomic.Value(bool), pub fn init( allocator: std.mem.Allocator, @@ -157,6 +158,7 @@ pub const Handler = struct { broadcaster: *Broadcaster, send_fn: *const fn (conn_id: u64, data: []const u8) void, event_limiter: *rate_limiter.EventRateLimiter, + shutdown: *std.atomic.Value(bool), ) Handler { return .{ .allocator = allocator, @@ -166,10 +168,12 @@ pub const Handler = struct { .broadcaster = broadcaster, .send_fn = send_fn, .event_limiter = event_limiter, + .shutdown = shutdown, }; } pub fn handle(self: *Handler, conn: *Connection, message: []const u8) void { + if (self.shutdown.load(.acquire)) return; conn.touch(); if (!validateMessageStructure(message)) { @@ -370,13 +374,17 @@ pub const Handler = struct { } fn handleReq(self: *Handler, conn: *Connection, msg: *nostr.ClientMsg) void { - const sub_id = msg.subscriptionId(); + const sub_id_raw = msg.subscriptionId(); - if (sub_id.len == 0 or sub_id.len > 64) { - self.sendClosed(conn, sub_id, "error: invalid subscription ID"); + if (sub_id_raw.len == 0 or sub_id_raw.len > 64) { + self.sendClosed(conn, sub_id_raw, "error: invalid subscription ID"); return; } + var sub_id_buf: [64]u8 = undefined; + @memcpy(sub_id_buf[0..sub_id_raw.len], sub_id_raw); + const sub_id = sub_id_buf[0..sub_id_raw.len]; + if (self.config.auth_required) { if (!conn.isAuthenticated()) { self.sendClosed(conn, sub_id, "auth-required: authentication required to subscribe"); @@ -425,7 +433,9 @@ pub const Handler = struct { }; defer iter.deinit(); - while (iter.next() catch null) |json| { + while (true) { + if (self.shutdown.load(.acquire)) return; + const json = iter.next() catch null orelse break; var buf: [65536]u8 = undefined; const event_msg = nostr.RelayMsg.eventRaw(sub_id, json, &buf) catch continue; _ = conn.send(event_msg); @@ -438,7 +448,9 @@ pub const Handler = struct { }; defer mk_iter.deinit(); - while (mk_iter.next() catch null) |json| { + while (true) { + if (self.shutdown.load(.acquire)) return; + const json = mk_iter.next() catch null orelse break; var buf: [65536]u8 = undefined; const event_msg = nostr.RelayMsg.eventRaw(sub_id, json, &buf) catch continue; _ = conn.send(event_msg); @@ -452,7 +464,9 @@ pub const Handler = struct { }; defer iter.deinit(); - while (iter.next() catch null) |json| { + while (true) { + if (self.shutdown.load(.acquire)) return; + const json = iter.next() catch null orelse break; var buf: [65536]u8 = undefined; const event_msg = nostr.RelayMsg.eventRaw(sub_id, json, &buf) catch continue; _ = conn.send(event_msg); @@ -508,13 +522,16 @@ pub const Handler = struct { var total_count: u64 = 0; for (filters) |filter| { + if (self.shutdown.load(.acquire)) return; var iter = self.store.query(&[_]nostr.Filter{filter}, self.config.query_limit_max) catch { self.sendClosed(conn, sub_id, "error: query failed"); return; }; defer iter.deinit(); - while (iter.next() catch null) |_| { + while (true) { + if (self.shutdown.load(.acquire)) return; + _ = iter.next() catch null orelse break; total_count += 1; } } @@ -616,7 +633,9 @@ pub const Handler = struct { defer iter.deinit(); var count: u32 = 0; - while (iter.next() catch null) |json| { + while (true) { + if (self.shutdown.load(.acquire)) return; + const json = iter.next() catch null orelse break; var event = nostr.Event.parse(json) catch continue; defer event.deinit(); session.storage.insert(@intCast(event.createdAt()), event.id()) catch continue; @@ -665,11 +684,13 @@ pub const Handler = struct { conn.removeNegSession(msg.subscriptionId()); } - fn reconcileAndSend(_: *Handler, conn: *Connection, sub_id: []const u8, session: *NegSession, query: []const u8) void { + fn reconcileAndSend(self: *Handler, conn: *Connection, sub_id: []const u8, session: *NegSession, query: []const u8) void { + if (self.shutdown.load(.acquire)) return; var out_buf: [65536]u8 = undefined; var neg = nostr.negentropy.Negentropy.init(session.storage.storage(), 0); var result = neg.reconcile(query, &out_buf, conn.allocator()) catch { + if (self.shutdown.load(.acquire)) return; var err_buf: [512]u8 = undefined; const err_msg = nostr.RelayMsg.negErr(sub_id, "error: reconciliation failed", &err_buf) catch return; conn.sendDirect(err_msg); @@ -677,48 +698,56 @@ pub const Handler = struct { }; defer result.deinit(); + if (self.shutdown.load(.acquire)) return; var msg_buf: [131072]u8 = undefined; const neg_msg = nostr.RelayMsg.negMsg(sub_id, result.output, &msg_buf) catch return; conn.sendDirect(neg_msg); } - fn sendNegErr(_: *Handler, conn: *Connection, sub_id: []const u8, reason: []const u8) void { + fn sendNegErr(self: *Handler, conn: *Connection, sub_id: []const u8, reason: []const u8) void { + if (self.shutdown.load(.acquire)) return; var buf: [512]u8 = undefined; const msg = nostr.RelayMsg.negErr(sub_id, reason, &buf) catch return; conn.sendDirect(msg); } - fn sendOk(_: *Handler, conn: *Connection, event_id: *const [32]u8, success: bool, message: []const u8) void { + fn sendOk(self: *Handler, conn: *Connection, event_id: *const [32]u8, success: bool, message: []const u8) void { + if (self.shutdown.load(.acquire)) return; var buf: [512]u8 = undefined; const msg = nostr.RelayMsg.ok(event_id, success, message, &buf) catch return; conn.sendDirect(msg); } - fn sendEose(_: *Handler, conn: *Connection, sub_id: []const u8) void { + fn sendEose(self: *Handler, conn: *Connection, sub_id: []const u8) void { + if (self.shutdown.load(.acquire)) return; var buf: [256]u8 = undefined; const msg = nostr.RelayMsg.eose(sub_id, &buf) catch return; conn.sendDirect(msg); } - fn sendClosed(_: *Handler, conn: *Connection, sub_id: []const u8, message: []const u8) void { + fn sendClosed(self: *Handler, conn: *Connection, sub_id: []const u8, message: []const u8) void { + if (self.shutdown.load(.acquire)) return; var buf: [512]u8 = undefined; const msg = nostr.RelayMsg.closed(sub_id, message, &buf) catch return; conn.sendDirect(msg); } - fn sendCount(_: *Handler, conn: *Connection, sub_id: []const u8, count_val: u64) void { + fn sendCount(self: *Handler, conn: *Connection, sub_id: []const u8, count_val: u64) void { + if (self.shutdown.load(.acquire)) return; var buf: [256]u8 = undefined; const msg = nostr.RelayMsg.count(sub_id, count_val, &buf) catch return; conn.sendDirect(msg); } - fn sendNotice(_: *Handler, conn: *Connection, message: []const u8) void { + fn sendNotice(self: *Handler, conn: *Connection, message: []const u8) void { + if (self.shutdown.load(.acquire)) return; var buf: [512]u8 = undefined; const msg = nostr.RelayMsg.notice(message, &buf) catch return; conn.sendDirect(msg); } - fn sendAuthChallenge(_: *Handler, conn: *Connection) void { + fn sendAuthChallenge(self: *Handler, conn: *Connection) void { + if (self.shutdown.load(.acquire)) return; if (conn.challenge_sent) return; var buf: [256]u8 = undefined; const auth_msg = nostr.RelayMsg.auth(&conn.auth_challenge, &buf) catch return; diff --git a/src/main.zig b/src/main.zig index 54d1b5f..4a4ab50 100644 --- a/src/main.zig +++ b/src/main.zig @@ -157,7 +157,7 @@ pub fn main() !void { var event_limiter = rate_limiter.EventRateLimiter.init(allocator, config.events_per_minute); defer event_limiter.deinit(); - var handler = Handler.init(allocator, &config, &store, &subs, &broadcaster, sendCallback, &event_limiter); + var handler = Handler.init(allocator, &config, &store, &subs, &broadcaster, sendCallback, &event_limiter, &g_shutdown); var server = try Server.init(allocator, &config, &handler, &subs); defer server.deinit(); @@ -165,10 +165,9 @@ pub fn main() !void { g_server = &server; defer g_server = null; - // Initialize Spider if enabled var spider: ?Spider = null; if (config.spider_enabled) { - spider = Spider.init(allocator, &config, &store, &broadcaster) catch |err| { + spider = Spider.init(allocator, &config, &store, &broadcaster, &g_shutdown) catch |err| { std.log.err("Failed to initialize Spider: {}", .{err}); return err; }; @@ -196,16 +195,22 @@ pub fn main() !void { defer if (cleanup_thread) |t| t.join(); try server.run(&g_shutdown); + server.deinit(); std.log.info("Shutdown complete", .{}); } fn storeCleanupThread(store: *Store, config: *const Config, shutdown: *std.atomic.Value(bool)) void { - const hour_ns: u64 = 3600 * std.time.ns_per_s; + const check_interval_ns: u64 = std.time.ns_per_s; + const hour_checks: u64 = 3600; + var checks: u64 = 0; while (!shutdown.load(.acquire)) { - std.Thread.sleep(hour_ns); + std.Thread.sleep(check_interval_ns); if (shutdown.load(.acquire)) break; + checks += 1; + if (checks < hour_checks) continue; + checks = 0; if (config.deleted_retention_days > 0) { const max_age_seconds: i64 = @as(i64, @intCast(config.deleted_retention_days)) * 86400; @@ -282,7 +287,6 @@ fn processImportLine(allocator: std.mem.Allocator, store: *Store, line: []const return; }; - // Handle NIP-09 deletions if (nostr.isDeletion(&event)) { const ids_to_delete = nostr.getDeletionIds(allocator, &event) catch { failed.* += 1; diff --git a/src/server.zig b/src/server.zig index 9daf11c..0034e18 100644 --- a/src/server.zig +++ b/src/server.zig @@ -25,6 +25,7 @@ pub const Server = struct { mutex: std.Thread.Mutex, http_server: ?HttpServer = null, + listener_failed: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), conn_limiter: rate_limiter.ConnectionLimiter, ip_filter: rate_limiter.IpFilter, @@ -55,11 +56,18 @@ pub const Server = struct { pub fn deinit(self: *Server) void { if (self.http_server) |*s| { s.deinit(); - } + self.http_server = null; + } else return; self.conn_limiter.deinit(); self.ip_filter.deinit(); } + pub fn stop(self: *Server) void { + if (self.http_server) |*s| { + s.stop(); + } + } + pub fn run(self: *Server, shutdown: *std.atomic.Value(bool)) !void { const h = Handler{ .server = self, @@ -71,26 +79,57 @@ pub const Server = struct { }, h); self.http_server = server; - defer server.deinit(); - defer server.stop(); - var router = try server.router(.{}); router.get("/", index, .{}); - const idle_thread = std.Thread.spawn(.{}, idleTimeoutThread, .{ self, shutdown }) catch null; + const idle_thread = std.Thread.spawn(.{}, idleTimeoutThread, .{ self, shutdown, &self.listener_failed }) catch null; defer if (idle_thread) |t| t.join(); std.log.info("Server running on {s}:{d}", .{ self.config.host, self.config.port }); - try server.listen(); + const listen_thread = std.Thread.spawn(.{}, listenWrapper, .{ &server, &self.listener_failed }) catch |err| { + std.log.err("Failed to start listener thread: {}", .{err}); + return err; + }; + + while (!shutdown.load(.acquire)) { + if (self.listener_failed.load(.acquire)) { + std.log.err("Server listener failed, shutting down", .{}); + shutdown.store(true, .release); + break; + } + std.Thread.sleep(100 * std.time.ns_per_ms); + } + + std.log.info("Shutting down server...", .{}); + if (!self.listener_failed.load(.acquire)) { + server.stop(); + } + listen_thread.join(); + std.Thread.sleep(50 * std.time.ns_per_ms); + + if (self.listener_failed.load(.acquire)) { + return error.ListenerFailed; + } } - fn idleTimeoutThread(self: *Server, shutdown: *std.atomic.Value(bool)) void { - const check_interval_ns: u64 = 30 * std.time.ns_per_s; + fn listenWrapper(server: *HttpServer, failed_flag: *std.atomic.Value(bool)) void { + server.listen() catch |err| { + std.log.err("Server listen failed: {}", .{err}); + failed_flag.store(true, .release); + }; + } - while (!shutdown.load(.acquire)) { - std.Thread.sleep(check_interval_ns); - if (shutdown.load(.acquire)) break; + fn idleTimeoutThread(self: *Server, shutdown: *std.atomic.Value(bool), listener_failed: *std.atomic.Value(bool)) void { + const check_interval_s: u64 = 30; + var seconds_waited: u64 = 0; + + while (!shutdown.load(.acquire) and !listener_failed.load(.acquire)) { + std.Thread.sleep(std.time.ns_per_s); + if (shutdown.load(.acquire) or listener_failed.load(.acquire)) break; + seconds_waited += 1; + if (seconds_waited < check_interval_s) continue; + seconds_waited = 0; if (self.config.idle_seconds == 0) continue; diff --git a/src/spider.zig b/src/spider.zig index 408c432..721a469 100644 --- a/src/spider.zig +++ b/src/spider.zig @@ -13,7 +13,7 @@ const BATCH_CREATION_DELAY_MS: u64 = 500; const RECONNECT_DELAY_MS: u64 = 10_000; const MAX_RECONNECT_DELAY_MS: u64 = 3600_000; const BLACKOUT_MS: u64 = 24 * 3600_000; -const QUICK_DISCONNECT_MS: i64 = 120_000; +const QUICK_DISCONNECT_MS: i64 = 30_000; const RATE_LIMIT_BACKOFF_MS: u64 = 60_000; const MAX_RATE_LIMIT_BACKOFF_MS: u64 = 1800_000; const CATCHUP_WINDOW_MS: i64 = 1800_000; @@ -24,6 +24,7 @@ pub const Spider = struct { store: *Store, broadcaster: *Broadcaster, running: std.atomic.Value(bool), + global_shutdown: *std.atomic.Value(bool), relays: std.StringArrayHashMap(RelayConn), follow_pubkeys: std.ArrayListUnmanaged([32]u8), follow_mutex: std.Thread.Mutex, @@ -35,6 +36,7 @@ pub const Spider = struct { config: *const Config, store: *Store, broadcaster: *Broadcaster, + global_shutdown: *std.atomic.Value(bool), ) !Spider { var spider = Spider{ .allocator = allocator, @@ -42,6 +44,7 @@ pub const Spider = struct { .store = store, .broadcaster = broadcaster, .running = std.atomic.Value(bool).init(false), + .global_shutdown = global_shutdown, .relays = std.StringArrayHashMap(RelayConn).init(allocator), .follow_pubkeys = .{}, .follow_mutex = .{}, @@ -100,10 +103,28 @@ pub const Spider = struct { try self.threads.append(self.allocator, refresh_thread); } + fn shouldRun(self: *Spider) bool { + return self.running.load(.acquire) and !self.global_shutdown.load(.acquire); + } + + fn interruptibleSleep(self: *Spider, ms: u64) void { + const interval_ms: u64 = 100; + var remaining = ms; + while (remaining > 0 and self.shouldRun()) { + const sleep_ms = @min(remaining, interval_ms); + std.Thread.sleep(sleep_ms * @as(u64, std.time.ns_per_ms)); + remaining -|= sleep_ms; + } + } + pub fn stop(self: *Spider) void { log.info("Spider stopping...", .{}); self.running.store(false, .release); + for (self.relays.values()) |*conn| { + conn.closeClient(); + } + for (self.threads.items) |thread| { thread.join(); } @@ -167,11 +188,16 @@ pub const Spider = struct { client.writeText(@constCast(req_msg)) catch continue; + client.readTimeout(5000) catch {}; + var events_received: u64 = 0; var got_kind3 = false; - var msg_count: usize = 0; - while (msg_count < 20) : (msg_count += 1) { - const message = client.read() catch break; + const bootstrap_start = std.time.milliTimestamp(); + while (std.time.milliTimestamp() - bootstrap_start < 10_000) { + const message = client.read() catch |err| { + if (err == error.WouldBlock) continue; + break; + }; if (message) |msg| { defer client.done(msg); if (msg.data.len > 0) { @@ -243,12 +269,11 @@ pub const Spider = struct { } fn refreshLoop(self: *Spider) void { - const interval_s: u64 = @max(1, @as(u64, self.config.spider_sync_interval)); - const interval_ms: u64 = interval_s * 1000; - while (self.running.load(.acquire)) { - std.Thread.sleep(interval_ms * std.time.ns_per_ms); + const interval_ms: u64 = @max(1000, @as(u64, self.config.spider_sync_interval) * 1000); + while (self.shouldRun()) { + self.interruptibleSleep(interval_ms); - if (!self.running.load(.acquire)) break; + if (!self.shouldRun()) break; const old_count = blk: { self.follow_mutex.lock(); @@ -275,13 +300,13 @@ pub const Spider = struct { var conn = self.relays.getPtr(relay_url) orelse return; - while (self.running.load(.acquire)) { + while (self.shouldRun()) { if (conn.blackout_until > 0) { const now = std.time.milliTimestamp(); if (now < conn.blackout_until) { const wait_ms: u64 = @intCast(conn.blackout_until - now); log.info("{s}: In blackout for {d}ms more", .{ relay_url, wait_ms }); - std.Thread.sleep(@as(u64, @min(wait_ms, 60_000)) * std.time.ns_per_ms); + self.interruptibleSleep(@min(wait_ms, 60_000)); continue; } conn.blackout_until = 0; @@ -293,22 +318,21 @@ pub const Spider = struct { const success = self.connectAndSubscribe(conn, relay_url); const connection_duration = std.time.milliTimestamp() - connect_start; + if (!self.shouldRun()) break; + if (success) { if (connection_duration < QUICK_DISCONNECT_MS) { - log.warn("{s}: Quick disconnect after {d}ms", .{ relay_url, connection_duration }); + log.warn("{s}: Quick disconnect after {d}ms, waiting {d}ms", .{ relay_url, connection_duration, conn.reconnect_delay_ms }); + self.interruptibleSleep(conn.reconnect_delay_ms); conn.reconnect_delay_ms = @min(conn.reconnect_delay_ms * 2, MAX_RECONNECT_DELAY_MS); } else { log.info("{s}: Disconnected after {d}ms uptime", .{ relay_url, connection_duration }); - if (conn.reconnect_delay_ms > RECONNECT_DELAY_MS * 8) { - conn.reconnect_delay_ms = conn.reconnect_delay_ms / 2; - } else { - conn.reconnect_delay_ms = RECONNECT_DELAY_MS; - } + conn.reconnect_delay_ms = RECONNECT_DELAY_MS; + self.interruptibleSleep(5000); } - std.Thread.sleep(5 * std.time.ns_per_s); } else { log.warn("{s}: Connection failed, waiting {d}ms", .{ relay_url, conn.reconnect_delay_ms }); - std.Thread.sleep(conn.reconnect_delay_ms * std.time.ns_per_ms); + self.interruptibleSleep(conn.reconnect_delay_ms); conn.reconnect_delay_ms = @min(conn.reconnect_delay_ms * 2, MAX_RECONNECT_DELAY_MS); } @@ -352,6 +376,9 @@ pub const Spider = struct { return false; }; + conn.active_client = &client; + defer conn.active_client = null; + client.handshake(parsed.path, .{ .headers = host_header, }) catch |err| { @@ -363,9 +390,12 @@ pub const Spider = struct { conn.state = .connected; const now = std.time.milliTimestamp(); - if (conn.last_connect == 0) { + if (!self.shouldRun()) return false; + + if (conn.last_connect == 0 and conn.negentropy_supported) { if (!self.performNegentropySync(&client, relay_url)) { - log.err("{s}: Connection lost during negentropy sync", .{relay_url}); + log.warn("{s}: Negentropy sync failed, disabling for this relay", .{relay_url}); + conn.negentropy_supported = false; return false; } } else if (conn.last_disconnect > 0) { @@ -471,6 +501,7 @@ pub const Spider = struct { var local_count: usize = 0; while (iter.next() catch null) |json| { + if (local_count % 1000 == 0 and !self.shouldRun()) return false; var event = nostr.Event.parse(json) catch continue; defer event.deinit(); local_storage.insert(@intCast(event.createdAt()), event.id()) catch continue; @@ -509,6 +540,8 @@ pub const Spider = struct { return false; }; + client.readTimeout(1000) catch {}; + var have_ids: std.ArrayListUnmanaged([32]u8) = .{}; defer have_ids.deinit(self.allocator); var need_ids: std.ArrayListUnmanaged([32]u8) = .{}; @@ -522,11 +555,14 @@ pub const Spider = struct { var connection_alive = true; while (std.time.milliTimestamp() - sync_start < sync_timeout_ms) { + if (!self.shouldRun()) return false; + if (!got_response and std.time.milliTimestamp() - sync_start > initial_timeout_ms) { log.warn("{s}: No negentropy response, relay may not support NIP-77", .{relay_url}); return true; } - const message = client.read() catch { + const message = client.read() catch |err| { + if (err == error.WouldBlock) continue; connection_alive = false; break; }; @@ -607,6 +643,8 @@ pub const Spider = struct { var i: usize = 0; while (i < ids.len) { + if (!self.shouldRun()) return; + const end = @min(i + batch_size, ids.len); const batch = ids[i..end]; @@ -635,7 +673,11 @@ pub const Spider = struct { const fetch_start = std.time.milliTimestamp(); while (std.time.milliTimestamp() - fetch_start < 30_000) { - const message = client.read() catch break; + if (!self.shouldRun()) return; + const message = client.read() catch |err| { + if (err == error.WouldBlock) continue; + break; + }; if (message) |msg| { defer client.done(msg); if (std.mem.startsWith(u8, msg.data, "[\"EOSE\"")) break; @@ -668,6 +710,8 @@ pub const Spider = struct { var i: usize = 0; while (i < self.follow_pubkeys.items.len) { + if (!self.shouldRun()) return error.Shutdown; + const end = @min(i + BATCH_SIZE, self.follow_pubkeys.items.len); const batch = self.follow_pubkeys.items[i..end]; @@ -698,8 +742,11 @@ pub const Spider = struct { fn readLoop(self: *Spider, client: *websocket.Client, relay_url: []const u8) void { var events_received: u64 = 0; - while (self.running.load(.acquire)) { + client.readTimeout(1000) catch {}; + + while (self.shouldRun()) { const message = client.read() catch |err| { + if (err == error.WouldBlock) continue; if (err == error.Closed or err == error.ConnectionResetByPeer) { log.info("{s}: Connection closed", .{relay_url}); } else { @@ -850,6 +897,8 @@ const RelayConn = struct { last_disconnect: i64 = 0, rate_limit_until: i64 = 0, rate_limit_backoff_ms: u64 = RATE_LIMIT_BACKOFF_MS, + negentropy_supported: bool = true, + active_client: ?*websocket.Client = null, const State = enum { disconnected, connecting, connected }; @@ -857,6 +906,10 @@ const RelayConn = struct { return .{ .url = url }; } + fn closeClient(self: *RelayConn) void { + _ = self; + } + fn applyRateLimit(self: *RelayConn) void { const now = std.time.milliTimestamp(); self.rate_limit_until = now + @as(i64, @intCast(self.rate_limit_backoff_ms)); diff --git a/src/store.zig b/src/store.zig index cb74a7a..c26457e 100644 --- a/src/store.zig +++ b/src/store.zig @@ -490,6 +490,7 @@ pub const MultiKindResult = struct { pub const QueryIterator = struct { store: *Store, filters: []const nostr.Filter, + owned_filters: ?[]nostr.Filter = null, limit: u32, returned: u32 = 0, txn: ?Txn = null, @@ -503,14 +504,35 @@ pub const QueryIterator = struct { const IndexType = enum { created, kind, pubkey, tag }; pub fn init(store: *Store, filters: []const nostr.Filter, limit: u32) QueryIterator { + const allocator = store.allocator; + const owned = allocator.alloc(nostr.Filter, filters.len) catch { + return QueryIterator{ + .store = store, + .filters = &.{}, + .limit = limit, + }; + }; + for (filters, 0..) |f, i| { + owned[i] = f.clone(allocator) catch { + for (0..i) |j| owned[j].deinit(); + allocator.free(owned); + return QueryIterator{ + .store = store, + .filters = &.{}, + .limit = limit, + }; + }; + } + var iter = QueryIterator{ .store = store, - .filters = filters, + .filters = owned, + .owned_filters = owned, .limit = limit, }; - if (filters.len > 0) { - const f = filters[0]; + if (owned.len > 0) { + const f = owned[0]; if (f.authors()) |authors| { if (authors.len == 1) { @@ -662,5 +684,9 @@ pub const QueryIterator = struct { pub fn deinit(self: *QueryIterator) void { if (self.cursor) |*cur| cur.close(); if (self.txn) |*t| t.abort(); + if (self.owned_filters) |owned| { + for (owned) |*f| f.deinit(); + self.store.allocator.free(owned); + } } }; From cb08542a711e6005afe1863a70486427275ee435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kyle=20=F0=9F=90=86?= Date: Wed, 17 Dec 2025 14:50:50 -0500 Subject: [PATCH 2/9] Fix race condition in WriteQueue with atomic ws_conn access --- src/write_queue.zig | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/write_queue.zig b/src/write_queue.zig index 21bfd82..ced1f29 100644 --- a/src/write_queue.zig +++ b/src/write_queue.zig @@ -3,36 +3,36 @@ const httpz = @import("httpz"); const websocket = httpz.websocket; pub const WriteQueue = struct { - ws_conn: ?*websocket.Conn, + ws_conn: std.atomic.Value(?*websocket.Conn), dropped_count: std.atomic.Value(u64), allocator: std.mem.Allocator, pub fn init(allocator: std.mem.Allocator) WriteQueue { return .{ - .ws_conn = null, + .ws_conn = std.atomic.Value(?*websocket.Conn).init(null), .dropped_count = std.atomic.Value(u64).init(0), .allocator = allocator, }; } pub fn start(self: *WriteQueue, ws_conn: *websocket.Conn) void { - self.ws_conn = ws_conn; + self.ws_conn.store(ws_conn, .release); } pub fn stop(self: *WriteQueue) void { - self.ws_conn = null; + self.ws_conn.store(null, .release); } pub fn enqueue(self: *WriteQueue, data: []const u8) bool { - if (self.ws_conn) |conn| { - conn.write(data) catch { - _ = self.dropped_count.fetchAdd(1, .monotonic); - return false; - }; - return true; - } - _ = self.dropped_count.fetchAdd(1, .monotonic); - return false; + const conn = self.ws_conn.load(.acquire) orelse { + _ = self.dropped_count.fetchAdd(1, .monotonic); + return false; + }; + conn.write(data) catch { + _ = self.dropped_count.fetchAdd(1, .monotonic); + return false; + }; + return true; } pub fn droppedCount(self: *WriteQueue) u64 { From d1f54702bff2110743780f0fe26604571093ce52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kyle=20=F0=9F=90=86?= Date: Wed, 17 Dec 2025 16:37:58 -0500 Subject: [PATCH 3/9] Fix segfaults in spider read errors, shutdown race conditions, and double-free --- src/handler.zig | 4 ++++ src/server.zig | 6 +++++- src/spider.zig | 23 ++++++++++++++++++----- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/handler.zig b/src/handler.zig index 51c9315..9b0dd28 100644 --- a/src/handler.zig +++ b/src/handler.zig @@ -427,6 +427,7 @@ pub const Handler = struct { if (filters.len == 1 and isKindOnlyQuery(&filters[0])) { const kinds = filters[0].kinds().?; if (kinds.len == 1) { + if (self.shutdown.load(.acquire)) return; var iter = self.store.query(filters, limit) catch { self.sendClosed(conn, sub_id, "error: query failed"); return; @@ -442,6 +443,7 @@ pub const Handler = struct { conn.events_sent += 1; } } else { + if (self.shutdown.load(.acquire)) return; var mk_iter = self.store.queryMultiKind(kinds, limit) catch { self.sendClosed(conn, sub_id, "error: query failed"); return; @@ -458,6 +460,7 @@ pub const Handler = struct { } } } else { + if (self.shutdown.load(.acquire)) return; var iter = self.store.query(filters, limit) catch { self.sendClosed(conn, sub_id, "error: query failed"); return; @@ -625,6 +628,7 @@ pub const Handler = struct { return; }; + if (self.shutdown.load(.acquire)) return; var iter = self.store.query(&[_]nostr.Filter{filter}, self.config.negentropy_max_sync_events) catch { conn.removeNegSession(sub_id); self.sendNegErr(conn, sub_id, "error: query failed"); diff --git a/src/server.zig b/src/server.zig index 0034e18..fada3cb 100644 --- a/src/server.zig +++ b/src/server.zig @@ -106,7 +106,7 @@ pub const Server = struct { server.stop(); } listen_thread.join(); - std.Thread.sleep(50 * std.time.ns_per_ms); + std.Thread.sleep(500 * std.time.ns_per_ms); if (self.listener_failed.load(.acquire)) { return error.ListenerFailed; @@ -172,6 +172,7 @@ const WsClient = struct { conn: *websocket.Conn, connection: *Connection, server: *Server, + closed: bool = false, pub const Context = struct { server: *Server, @@ -252,6 +253,9 @@ const WsClient = struct { } pub fn close(self: *WsClient) void { + if (self.closed) return; + self.closed = true; + const server = self.server; const allocator = server.allocator; diff --git a/src/spider.zig b/src/spider.zig index 721a469..8f662c7 100644 --- a/src/spider.zig +++ b/src/spider.zig @@ -350,7 +350,8 @@ pub const Spider = struct { if (conn.isRateLimited()) { const wait_ms: u64 = @intCast(@max(0, conn.rate_limit_until - std.time.milliTimestamp())); log.info("{s}: Rate limited, waiting {d}ms", .{ relay_url, wait_ms }); - std.Thread.sleep(wait_ms * std.time.ns_per_ms); + self.interruptibleSleep(wait_ms); + if (!self.shouldRun()) return false; } const parsed = parseRelayUrl(relay_url) orelse { @@ -390,6 +391,8 @@ pub const Spider = struct { conn.state = .connected; const now = std.time.milliTimestamp(); + client.readTimeout(1000) catch {}; + if (!self.shouldRun()) return false; if (conn.last_connect == 0 and conn.negentropy_supported) { @@ -444,9 +447,13 @@ pub const Spider = struct { var catchup_events: u64 = 0; const catchup_start = std.time.milliTimestamp(); const catchup_timeout_ms: i64 = 30_000; + var read_error = false; while (std.time.milliTimestamp() - catchup_start < catchup_timeout_ms) { - const message = client.read() catch break; + const message = client.read() catch { + read_error = true; + break; + }; if (message) |msg_data| { defer client.done(msg_data); if (msg_data.data.len > 0) { @@ -468,9 +475,11 @@ pub const Spider = struct { } } - var close_buf: [64]u8 = undefined; - const close_msg = std.fmt.bufPrint(&close_buf, "[\"CLOSE\",\"catchup\"]", .{}) catch return; - client.writeText(@constCast(close_msg)) catch {}; + if (!read_error) { + var close_buf: [64]u8 = undefined; + const close_msg = std.fmt.bufPrint(&close_buf, "[\"CLOSE\",\"catchup\"]", .{}) catch return; + client.writeText(@constCast(close_msg)) catch {}; + } log.info("{s}: Catch-up finished with {d} events", .{ relay_url, catchup_events }); } @@ -672,10 +681,12 @@ pub const Spider = struct { } const fetch_start = std.time.milliTimestamp(); + var read_error = false; while (std.time.milliTimestamp() - fetch_start < 30_000) { if (!self.shouldRun()) return; const message = client.read() catch |err| { if (err == error.WouldBlock) continue; + read_error = true; break; }; if (message) |msg| { @@ -687,6 +698,8 @@ pub const Spider = struct { } } + if (read_error) return; + var close_buf: [64]u8 = undefined; const close_msg = std.fmt.bufPrint(&close_buf, "[\"CLOSE\",\"fetch\"]", .{}) catch break; client.writeText(@constCast(close_msg)) catch {}; From e64e91bffa6afa607f3f7675c02cbfed9a71845b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kyle=20=F0=9F=90=86?= Date: Wed, 17 Dec 2025 22:20:17 -0500 Subject: [PATCH 4/9] memory fixes, WS upgrade, update LICENSE --- LICENSE | 1108 ++++++++++++++++++++++++----------------- README.md | 2 +- build.zig | 14 +- build.zig.zon | 12 +- src/config.zig | 8 + src/connection.zig | 40 +- src/main.zig | 32 +- src/nostr.zig | 1 + src/server.zig | 318 ------------ src/spider.zig | 92 ++-- src/subscriptions.zig | 29 ++ src/tcp_server.zig | 352 +++++++++++++ src/write_queue.zig | 34 +- 13 files changed, 1190 insertions(+), 852 deletions(-) delete mode 100644 src/server.zig create mode 100644 src/tcp_server.zig diff --git a/LICENSE b/LICENSE index 8e31f80..a2661bb 100644 --- a/LICENSE +++ b/LICENSE @@ -1,472 +1,664 @@ -Copyright (c) 2025 PrivKey LLC +Wisp - Nostr Relay +Copyright (C) 2025 PrivKey LLC -Contact information - Name: PrivKey LLC - Email: information@privkey.io - Website: https://www.privkey.io + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 -The software in this repository is licensed under the GNU LGPL version 2.1 (or any later version). - -SPDX-License-Identifier: LGPL-2.1-or-later - -License-Text: - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - Preamble - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. END OF TERMS AND CONDITIONS + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 2df5ce4..038a5e4 100644 --- a/README.md +++ b/README.md @@ -62,4 +62,4 @@ See `wisp.toml.example` for all options. ## License -LGPL-2.1-or-later +AGPL-3.0 diff --git a/build.zig b/build.zig index 4dbfe9c..a149f53 100644 --- a/build.zig +++ b/build.zig @@ -4,17 +4,12 @@ pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); - // Import dependencies - const httpz = b.dependency("httpz", .{ - .target = target, - .optimize = optimize, - }); - // Get websocket from httpz to avoid version conflicts - const httpz_dep = httpz.builder.dependency("websocket", .{ + const nostr = b.dependency("nostr", .{ .target = target, .optimize = optimize, }); - const nostr = b.dependency("nostr", .{ + // websocket client for spider outbound connections + const websocket = b.dependency("websocket", .{ .target = target, .optimize = optimize, }); @@ -26,9 +21,8 @@ pub fn build(b: *std.Build) void { .target = target, .optimize = optimize, .imports = &.{ - .{ .name = "httpz", .module = httpz.module("httpz") }, - .{ .name = "websocket", .module = httpz_dep.module("websocket") }, .{ .name = "nostr", .module = nostr.module("nostr") }, + .{ .name = "websocket", .module = websocket.module("websocket") }, }, }), }); diff --git a/build.zig.zon b/build.zig.zon index a717293..c04eaa5 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,19 +1,15 @@ .{ .name = .wisp, - .version = "0.1.2", + .version = "0.1.3", .fingerprint = 0xc4bdec9fe6401a8d, .dependencies = .{ - .httpz = .{ - .url = "https://github.com/karlseguin/http.zig/archive/refs/heads/master.tar.gz", - .hash = "httpz-0.0.0-PNVzrEktBwCzPoiua-S8LAYo2tILqczm3tSpneEzLQ9L", - }, + // websocket client for spider outbound connections .websocket = .{ .url = "https://github.com/karlseguin/websocket.zig/archive/refs/heads/master.tar.gz", - .hash = "websocket-0.1.0-ZPISdRNzAwAGszh62EpRtoQxu8wb1MSMVI6Ow0o2dmyJ", + .hash = "websocket-0.1.0-ZPISdZJxAwAt6Ys_JpoHQQV3NpWCof_N9Jg-Ul2g7OoV", }, .nostr = .{ - .url = "https://github.com/privkeyio/libnostr-z/archive/refs/tags/v0.1.6.tar.gz", - .hash = "nostr-0.1.6-JY6OcMPABABT9tx-BY8jcJpBa-boEF20VbZY-iX3DMMe", + .path = "../libnostr-z", }, }, .paths = .{ diff --git a/src/config.zig b/src/config.zig index f924c1d..b6a13d9 100644 --- a/src/config.zig +++ b/src/config.zig @@ -45,6 +45,8 @@ pub const Config = struct { min_pow_difficulty: u8, + log_level: []const u8, + _allocated: std.ArrayListUnmanaged([]const u8), _allocator: ?std.mem.Allocator, @@ -86,6 +88,7 @@ pub const Config = struct { .negentropy_enabled = true, .negentropy_max_sync_events = 1000000, .min_pow_difficulty = 0, + .log_level = "info", ._allocated = undefined, ._allocator = null, }; @@ -227,6 +230,10 @@ pub const Config = struct { } else if (std.mem.eql(u8, key, "max_sync_events")) { self.negentropy_max_sync_events = try std.fmt.parseInt(u32, value, 10); } + } else if (std.mem.eql(u8, section, "logging")) { + if (std.mem.eql(u8, key, "level")) { + self.log_level = try self.allocString(value); + } } } @@ -288,6 +295,7 @@ pub const Config = struct { if (std.posix.getenv("WISP_MIN_POW_DIFFICULTY")) |v| { self.min_pow_difficulty = std.fmt.parseInt(u8, v, 10) catch self.min_pow_difficulty; } + if (std.posix.getenv("WISP_LOG_LEVEL")) |v| self.log_level = v; } pub fn deinit(self: *Config) void { diff --git a/src/connection.zig b/src/connection.zig index a6e5b80..8f4e93d 100644 --- a/src/connection.zig +++ b/src/connection.zig @@ -1,8 +1,8 @@ const std = @import("std"); const nostr = @import("nostr.zig"); -const httpz = @import("httpz"); -const websocket = httpz.websocket; -const WriteQueue = @import("write_queue.zig").WriteQueue; +const write_queue = @import("write_queue.zig"); +const WriteQueue = write_queue.WriteQueue; +const WriteFn = write_queue.WriteFn; pub const NegSession = struct { storage: nostr.negentropy.VectorStorage, @@ -24,7 +24,9 @@ pub const Connection = struct { neg_sessions: std.StringHashMap(NegSession), created_at: i64, last_activity: i64, - ws_conn: ?*websocket.Conn = null, + direct_write_fn: ?WriteFn = null, + direct_write_ctx: ?*anyopaque = null, + write_mutex: std.Thread.Mutex = .{}, events_received: u64 = 0, events_sent: u64 = 0, @@ -55,7 +57,9 @@ pub const Connection = struct { self.events_sent = 0; self.client_ip = undefined; self.client_ip_len = 0; - self.ws_conn = null; + self.direct_write_fn = null; + self.direct_write_ctx = null; + self.write_mutex = .{}; std.crypto.random.bytes(&self.auth_challenge); self.authenticated_pubkeys = std.AutoHashMap([32]u8, void).init(self.arena.allocator()); self.challenge_sent = false; @@ -63,8 +67,8 @@ pub const Connection = struct { self.deinitialized = false; } - pub fn startWriteQueue(self: *Connection, ws_conn: *websocket.Conn) void { - self.write_queue.start(ws_conn); + pub fn startWriteQueue(self: *Connection, write_fn: WriteFn, write_ctx: *anyopaque) void { + self.write_queue.start(write_fn, write_ctx); } pub fn stopWriteQueue(self: *Connection) void { @@ -98,11 +102,29 @@ pub const Connection = struct { } pub fn sendDirect(self: *Connection, data: []const u8) void { - if (self.ws_conn) |conn| { - conn.write(data) catch {}; + self.write_mutex.lock(); + defer self.write_mutex.unlock(); + if (self.direct_write_fn) |write_fn| { + if (self.direct_write_ctx) |ctx| { + write_fn(ctx, data); + } } } + pub fn setDirectWriter(self: *Connection, write_fn: WriteFn, ctx: *anyopaque) void { + self.write_mutex.lock(); + defer self.write_mutex.unlock(); + self.direct_write_fn = write_fn; + self.direct_write_ctx = ctx; + } + + pub fn clearDirectWriter(self: *Connection) void { + self.write_mutex.lock(); + defer self.write_mutex.unlock(); + self.direct_write_fn = null; + self.direct_write_ctx = null; + } + pub fn deinit(self: *Connection) void { if (self.deinitialized) return; self.deinitialized = true; diff --git a/src/main.zig b/src/main.zig index 4a4ab50..47a7f21 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,16 +1,23 @@ const std = @import("std"); const Config = @import("config.zig").Config; + +pub const std_options = std.Options{ + .log_level = .info, + .log_scope_levels = &[_]std.log.ScopeLevel{ + .{ .scope = .websocket, .level = .err }, + }, +}; const Lmdb = @import("lmdb.zig").Lmdb; const Store = @import("store.zig").Store; const Subscriptions = @import("subscriptions.zig").Subscriptions; const Handler = @import("handler.zig").Handler; const Broadcaster = @import("broadcaster.zig").Broadcaster; -const Server = @import("server.zig").Server; +const TcpServer = @import("tcp_server.zig").TcpServer; const Spider = @import("spider.zig").Spider; const nostr = @import("nostr.zig"); const rate_limiter = @import("rate_limiter.zig"); -var g_server: ?*Server = null; +var g_server: ?*TcpServer = null; var g_shutdown: std.atomic.Value(bool) = std.atomic.Value(bool).init(false); fn signalHandler(_: c_int) callconv(std.builtin.CallingConvention.c) void { @@ -63,9 +70,8 @@ fn printHelp() void { } pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); + // Use c_allocator for production - better memory behavior than GPA + const allocator = std.heap.c_allocator; const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); @@ -95,7 +101,7 @@ pub fn main() !void { const hex = std.fmt.bytesToHex(decoded.pubkey, .lower); spider_admin_arg = try allocator.dupe(u8, &hex); } - } else if (!cmd_set) { + } else if (!cmd_set and !std.mem.endsWith(u8, arg, ".toml")) { cmd = parseCommand(arg); cmd_set = true; } else if (cmd == .relay and config_path == null and !std.mem.startsWith(u8, arg, "-")) { @@ -159,7 +165,7 @@ pub fn main() !void { var handler = Handler.init(allocator, &config, &store, &subs, &broadcaster, sendCallback, &event_limiter, &g_shutdown); - var server = try Server.init(allocator, &config, &handler, &subs); + var server = try TcpServer.init(allocator, &config, &handler, &subs, &g_shutdown); defer server.deinit(); g_server = &server; @@ -194,8 +200,16 @@ pub fn main() !void { const cleanup_thread = std.Thread.spawn(.{}, storeCleanupThread, .{ &store, &config, &g_shutdown }) catch null; defer if (cleanup_thread) |t| t.join(); - try server.run(&g_shutdown); - server.deinit(); + try server.run(); + + if (spider) |*s| { + s.stop(); + s.deinit(); + } + spider = null; + + // server.deinit() will be called by defer + std.Thread.sleep(200 * std.time.ns_per_ms); std.log.info("Shutdown complete", .{}); } diff --git a/src/nostr.zig b/src/nostr.zig index 3efe6fc..99c0af6 100644 --- a/src/nostr.zig +++ b/src/nostr.zig @@ -31,3 +31,4 @@ pub const Auth = nostr_lib.Auth; pub const Replaceable = nostr_lib.Replaceable; pub const IndexKeys = nostr_lib.IndexKeys; pub const negentropy = nostr_lib.negentropy; +pub const ws = nostr_lib.ws; diff --git a/src/server.zig b/src/server.zig deleted file mode 100644 index fada3cb..0000000 --- a/src/server.zig +++ /dev/null @@ -1,318 +0,0 @@ -const std = @import("std"); -const httpz = @import("httpz"); -const websocket = httpz.websocket; - -const Config = @import("config.zig").Config; -const MsgHandler = @import("handler.zig").Handler; -const Subscriptions = @import("subscriptions.zig").Subscriptions; -const Connection = @import("connection.zig").Connection; -const nip11 = @import("nip11.zig"); -const nostr = @import("nostr.zig"); -const rate_limiter = @import("rate_limiter.zig"); -const posix = std.posix; - -pub const std_options = std.Options{ .log_scope_levels = &[_]std.log.ScopeLevel{ - .{ .scope = .websocket, .level = .err }, -} }; - -pub const Server = struct { - allocator: std.mem.Allocator, - config: *const Config, - handler: *MsgHandler, - subs: *Subscriptions, - - next_id: u64 = 0, - mutex: std.Thread.Mutex, - - http_server: ?HttpServer = null, - listener_failed: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), - - conn_limiter: rate_limiter.ConnectionLimiter, - ip_filter: rate_limiter.IpFilter, - - const HttpServer = httpz.Server(Handler); - - pub fn init( - allocator: std.mem.Allocator, - config: *const Config, - handler: *MsgHandler, - subs: *Subscriptions, - ) !Server { - var ip_filter = rate_limiter.IpFilter.init(allocator); - try ip_filter.loadWhitelist(config.ip_whitelist); - try ip_filter.loadBlacklist(config.ip_blacklist); - - return .{ - .allocator = allocator, - .config = config, - .handler = handler, - .subs = subs, - .mutex = .{}, - .conn_limiter = rate_limiter.ConnectionLimiter.init(allocator, config.max_connections_per_ip), - .ip_filter = ip_filter, - }; - } - - pub fn deinit(self: *Server) void { - if (self.http_server) |*s| { - s.deinit(); - self.http_server = null; - } else return; - self.conn_limiter.deinit(); - self.ip_filter.deinit(); - } - - pub fn stop(self: *Server) void { - if (self.http_server) |*s| { - s.stop(); - } - } - - pub fn run(self: *Server, shutdown: *std.atomic.Value(bool)) !void { - const h = Handler{ - .server = self, - }; - - var server = try HttpServer.init(self.allocator, .{ - .port = self.config.port, - .address = self.config.host, - }, h); - self.http_server = server; - - var router = try server.router(.{}); - router.get("/", index, .{}); - - const idle_thread = std.Thread.spawn(.{}, idleTimeoutThread, .{ self, shutdown, &self.listener_failed }) catch null; - defer if (idle_thread) |t| t.join(); - - std.log.info("Server running on {s}:{d}", .{ self.config.host, self.config.port }); - - const listen_thread = std.Thread.spawn(.{}, listenWrapper, .{ &server, &self.listener_failed }) catch |err| { - std.log.err("Failed to start listener thread: {}", .{err}); - return err; - }; - - while (!shutdown.load(.acquire)) { - if (self.listener_failed.load(.acquire)) { - std.log.err("Server listener failed, shutting down", .{}); - shutdown.store(true, .release); - break; - } - std.Thread.sleep(100 * std.time.ns_per_ms); - } - - std.log.info("Shutting down server...", .{}); - if (!self.listener_failed.load(.acquire)) { - server.stop(); - } - listen_thread.join(); - std.Thread.sleep(500 * std.time.ns_per_ms); - - if (self.listener_failed.load(.acquire)) { - return error.ListenerFailed; - } - } - - fn listenWrapper(server: *HttpServer, failed_flag: *std.atomic.Value(bool)) void { - server.listen() catch |err| { - std.log.err("Server listen failed: {}", .{err}); - failed_flag.store(true, .release); - }; - } - - fn idleTimeoutThread(self: *Server, shutdown: *std.atomic.Value(bool), listener_failed: *std.atomic.Value(bool)) void { - const check_interval_s: u64 = 30; - var seconds_waited: u64 = 0; - - while (!shutdown.load(.acquire) and !listener_failed.load(.acquire)) { - std.Thread.sleep(std.time.ns_per_s); - if (shutdown.load(.acquire) or listener_failed.load(.acquire)) break; - seconds_waited += 1; - if (seconds_waited < check_interval_s) continue; - seconds_waited = 0; - - if (self.config.idle_seconds == 0) continue; - - const idle_conn_ids = self.subs.getIdleConnections(self.config.idle_seconds); - defer self.allocator.free(idle_conn_ids); - - for (idle_conn_ids) |conn_id| { - if (self.subs.getConnection(conn_id)) |conn| { - var buf: [128]u8 = undefined; - const notice = nostr.RelayMsg.notice("connection closed: idle timeout", &buf) catch continue; - conn.sendDirect(notice); - if (conn.ws_conn) |ws| { - ws.close(.{ .code = 1000, .reason = "idle timeout" }) catch {}; - } - std.log.debug("Closed idle connection {d}", .{conn_id}); - } - } - } - } - - pub fn send(self: *Server, conn_id: u64, data: []const u8) void { - if (self.subs.getConnection(conn_id)) |conn| { - _ = conn.send(data); - } - } - - pub fn connectionCount(self: *Server) usize { - return self.subs.connectionCount(); - } -}; - -const Handler = struct { - server: *Server, - - pub const WebsocketHandler = WsClient; -}; - -const WsClient = struct { - id: u64, - conn: *websocket.Conn, - connection: *Connection, - server: *Server, - closed: bool = false, - - pub const Context = struct { - server: *Server, - client_ip: []const u8, - }; - - pub fn init(ws_conn: *websocket.Conn, ctx: *const Context) !WsClient { - const server = ctx.server; - const allocator = server.allocator; - const client_ip = ctx.client_ip; - - const TCP_NODELAY = 1; - posix.setsockopt(ws_conn.stream.handle, posix.IPPROTO.TCP, TCP_NODELAY, &std.mem.toBytes(@as(i32, 1))) catch {}; - - if (!server.ip_filter.isAllowed(client_ip)) { - return error.IpBlocked; - } - - if (!server.conn_limiter.canConnect(client_ip)) { - return error.TooManyConnectionsFromIp; - } - - server.mutex.lock(); - if (server.subs.connectionCount() >= server.config.max_connections) { - server.mutex.unlock(); - return error.TooManyConnections; - } - const conn_id = server.next_id; - server.next_id += 1; - server.mutex.unlock(); - - const connection = try allocator.create(Connection); - connection.init(allocator, conn_id); - connection.setClientIp(client_ip); - - connection.ws_conn = ws_conn; - connection.startWriteQueue(ws_conn); - - server.subs.addConnection(connection) catch { - connection.stopWriteQueue(); - connection.deinit(); - allocator.destroy(connection); - return error.ConnectionFailed; - }; - - server.conn_limiter.addConnection(client_ip); - - return WsClient{ - .id = conn_id, - .conn = ws_conn, - .connection = connection, - .server = server, - }; - } - - fn sendAuthChallenge(self: *WsClient) void { - if (self.connection.challenge_sent) return; - - var buf: [256]u8 = undefined; - const auth_msg = nostr.RelayMsg.auth(&self.connection.auth_challenge, &buf) catch return; - self.connection.sendDirect(auth_msg); - self.connection.challenge_sent = true; - } - - pub fn clientMessage(self: *WsClient, data: []const u8) !void { - if (self.server.config.auth_required or self.server.config.auth_to_write) { - self.sendAuthChallenge(); - } - - if (data.len > self.server.config.max_message_size) { - var buf: [256]u8 = undefined; - const notice = nostr.RelayMsg.notice("error: message too large", &buf) catch return; - try self.conn.write(notice); - return; - } - - self.server.handler.handle(self.connection, data); - } - - pub fn close(self: *WsClient) void { - if (self.closed) return; - self.closed = true; - - const server = self.server; - const allocator = server.allocator; - - const client_ip = self.connection.getClientIp(); - if (client_ip.len > 0) { - server.conn_limiter.removeConnection(client_ip); - } - - server.subs.removeConnection(self.id); - self.connection.stopWriteQueue(); - self.connection.deinit(); - allocator.destroy(self.connection); - } -}; - -fn index(h: Handler, req: *httpz.Request, res: *httpz.Response) !void { - if (req.header("upgrade")) |upgrade| { - if (std.ascii.eqlIgnoreCase(upgrade, "websocket")) { - var addr_buf: [64]u8 = undefined; - const remote_addr = std.fmt.bufPrint(&addr_buf, "{any}", .{req.address}) catch "unknown"; - - const client_ip = rate_limiter.extractClientIp( - req.header("x-forwarded-for"), - req.header("x-real-ip"), - remote_addr, - h.server.config.trust_proxy, - ); - - const ctx = WsClient.Context{ .server = h.server, .client_ip = client_ip }; - if (try httpz.upgradeWebsocket(WsClient, req, res, &ctx) == false) { - res.status = 400; - res.body = "invalid websocket handshake"; - } - return; - } - } - - if (req.header("accept")) |accept| { - if (std.mem.indexOf(u8, accept, "application/nostr+json") != null) { - res.header("Content-Type", "application/nostr+json"); - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "*"); - res.header("Access-Control-Allow-Methods", "GET, OPTIONS"); - nip11.write(h.server.config, res.writer()) catch { - res.status = 500; - }; - return; - } - } - - res.content_type = .HTML; - res.body = - \\ - \\Wisp - \\ - \\

Wisp Nostr Relay

- \\

Connect via WebSocket at this URL.

- \\ - ; -} diff --git a/src/spider.zig b/src/spider.zig index 8f662c7..4374fec 100644 --- a/src/spider.zig +++ b/src/spider.zig @@ -396,15 +396,17 @@ pub const Spider = struct { if (!self.shouldRun()) return false; if (conn.last_connect == 0 and conn.negentropy_supported) { - if (!self.performNegentropySync(&client, relay_url)) { - log.warn("{s}: Negentropy sync failed, disabling for this relay", .{relay_url}); - conn.negentropy_supported = false; + if (!self.performNegentropySync(&client, relay_url, conn)) { return false; } } else if (conn.last_disconnect > 0) { - self.performCatchup(&client, conn, relay_url); + if (!self.performCatchup(&client, conn, relay_url)) { + return false; + } } + if (!self.shouldRun()) return false; + conn.last_connect = now; conn.clearRateLimit(); @@ -420,7 +422,7 @@ pub const Spider = struct { return true; } - fn performCatchup(self: *Spider, client: *websocket.Client, conn: *RelayConn, relay_url: []const u8) void { + fn performCatchup(self: *Spider, client: *websocket.Client, conn: *RelayConn, relay_url: []const u8) bool { const since_ts = conn.last_disconnect - CATCHUP_WINDOW_MS; const until_ts = std.time.milliTimestamp() + CATCHUP_WINDOW_MS; const since_unix = @divFloor(since_ts, 1000); @@ -431,17 +433,17 @@ pub const Spider = struct { self.follow_mutex.lock(); defer self.follow_mutex.unlock(); - if (self.follow_pubkeys.items.len == 0) return; + if (self.follow_pubkeys.items.len == 0) return true; var msg_buf: [65536]u8 = undefined; const msg = buildCatchupReqMessage(&msg_buf, self.follow_pubkeys.items, since_unix, until_unix) catch |err| { log.err("{s}: Failed to build catch-up REQ: {}", .{ relay_url, err }); - return; + return true; }; client.writeText(@constCast(msg)) catch |err| { log.err("{s}: Failed to send catch-up REQ: {}", .{ relay_url, err }); - return; + return false; }; var catchup_events: u64 = 0; @@ -475,16 +477,23 @@ pub const Spider = struct { } } - if (!read_error) { - var close_buf: [64]u8 = undefined; - const close_msg = std.fmt.bufPrint(&close_buf, "[\"CLOSE\",\"catchup\"]", .{}) catch return; - client.writeText(@constCast(close_msg)) catch {}; + if (read_error) { + log.info("{s}: Catch-up finished with {d} events (connection lost)", .{ relay_url, catchup_events }); + return false; } + var close_buf: [64]u8 = undefined; + const close_msg = std.fmt.bufPrint(&close_buf, "[\"CLOSE\",\"catchup\"]", .{}) catch { + log.info("{s}: Catch-up finished with {d} events", .{ relay_url, catchup_events }); + return true; + }; + client.writeText(@constCast(close_msg)) catch {}; + log.info("{s}: Catch-up finished with {d} events", .{ relay_url, catchup_events }); + return true; } - fn performNegentropySync(self: *Spider, client: *websocket.Client, relay_url: []const u8) bool { + fn performNegentropySync(self: *Spider, client: *websocket.Client, relay_url: []const u8, conn: *RelayConn) bool { self.follow_mutex.lock(); const pubkeys = self.allocator.dupe([32]u8, self.follow_pubkeys.items) catch { self.follow_mutex.unlock(); @@ -495,6 +504,12 @@ pub const Spider = struct { if (pubkeys.len == 0) return true; + if (pubkeys.len > 100) { + log.info("{s}: Too many pubkeys ({d}) for negentropy, skipping initial sync", .{ relay_url, pubkeys.len }); + conn.negentropy_supported = false; + return true; + } + var local_storage = negentropy.VectorStorage.init(self.allocator); defer local_storage.deinit(); @@ -520,7 +535,7 @@ pub const Spider = struct { log.info("{s}: Negentropy sync starting with {d} local events", .{ relay_url, local_count }); - var filter_buf: [32768]u8 = undefined; + var filter_buf: [65536]u8 = undefined; const filter_json = buildNegentropyFilter(&filter_buf, pubkeys) catch { log.err("{s}: Failed to build negentropy filter", .{relay_url}); return true; @@ -567,7 +582,8 @@ pub const Spider = struct { if (!self.shouldRun()) return false; if (!got_response and std.time.milliTimestamp() - sync_start > initial_timeout_ms) { - log.warn("{s}: No negentropy response, relay may not support NIP-77", .{relay_url}); + log.warn("{s}: No negentropy response, disabling for this relay", .{relay_url}); + conn.negentropy_supported = false; return true; } const message = client.read() catch |err| { @@ -580,7 +596,8 @@ pub const Spider = struct { if (msg.data.len == 0) continue; if (std.mem.startsWith(u8, msg.data, "[\"NEG-ERR\"")) { - log.warn("{s}: Negentropy not supported, skipping historical sync", .{relay_url}); + log.warn("{s}: Negentropy not supported, disabling for this relay", .{relay_url}); + conn.negentropy_supported = false; var close_buf: [64]u8 = undefined; const close_msg = std.fmt.bufPrint(&close_buf, "[\"NEG-CLOSE\",\"neg-sync\"]", .{}) catch break; client.writeText(@constCast(close_msg)) catch {}; @@ -631,28 +648,35 @@ pub const Spider = struct { } } - if (connection_alive) { - var close_buf: [64]u8 = undefined; - const close_msg = std.fmt.bufPrint(&close_buf, "[\"NEG-CLOSE\",\"neg-sync\"]", .{}) catch return true; - client.writeText(@constCast(close_msg)) catch {}; + if (!connection_alive) { + if (!got_response) { + log.warn("{s}: Connection lost before negentropy response, will retry", .{relay_url}); + } + return false; } + var close_buf: [64]u8 = undefined; + const close_msg = std.fmt.bufPrint(&close_buf, "[\"NEG-CLOSE\",\"neg-sync\"]", .{}) catch return true; + client.writeText(@constCast(close_msg)) catch {}; + log.info("{s}: Need {d} events, have {d} events to skip", .{ relay_url, need_ids.items.len, have_ids.items.len }); - if (connection_alive and need_ids.items.len > 0) { - self.fetchEventsByIds(client, relay_url, need_ids.items); + if (need_ids.items.len > 0) { + if (!self.fetchEventsByIds(client, relay_url, need_ids.items)) { + return false; + } } - return connection_alive; + return true; } - fn fetchEventsByIds(self: *Spider, client: *websocket.Client, relay_url: []const u8, ids: [][32]u8) void { + fn fetchEventsByIds(self: *Spider, client: *websocket.Client, relay_url: []const u8, ids: [][32]u8) bool { const batch_size: usize = 100; var fetched: u64 = 0; var i: usize = 0; while (i < ids.len) { - if (!self.shouldRun()) return; + if (!self.shouldRun()) return true; const end = @min(i + batch_size, ids.len); const batch = ids[i..end]; @@ -674,7 +698,10 @@ pub const Spider = struct { }; if (req_msg) |msg| { - client.writeText(@constCast(msg)) catch break; + client.writeText(@constCast(msg)) catch { + log.info("{s}: Fetched {d} events via negentropy sync (connection lost)", .{ relay_url, fetched }); + return false; + }; } else { i = end; continue; @@ -683,7 +710,7 @@ pub const Spider = struct { const fetch_start = std.time.milliTimestamp(); var read_error = false; while (std.time.milliTimestamp() - fetch_start < 30_000) { - if (!self.shouldRun()) return; + if (!self.shouldRun()) return true; const message = client.read() catch |err| { if (err == error.WouldBlock) continue; read_error = true; @@ -698,16 +725,23 @@ pub const Spider = struct { } } - if (read_error) return; + if (read_error) { + log.info("{s}: Fetched {d} events via negentropy sync (connection lost)", .{ relay_url, fetched }); + return false; + } var close_buf: [64]u8 = undefined; - const close_msg = std.fmt.bufPrint(&close_buf, "[\"CLOSE\",\"fetch\"]", .{}) catch break; + const close_msg = std.fmt.bufPrint(&close_buf, "[\"CLOSE\",\"fetch\"]", .{}) catch { + i = end; + continue; + }; client.writeText(@constCast(close_msg)) catch {}; i = end; } log.info("{s}: Fetched {d} events via negentropy sync", .{ relay_url, fetched }); + return true; } fn sendSubscriptions(self: *Spider, client: *websocket.Client, relay_url: []const u8) !void { diff --git a/src/subscriptions.zig b/src/subscriptions.zig index bd7a88f..ec148c8 100644 --- a/src/subscriptions.zig +++ b/src/subscriptions.zig @@ -56,6 +56,35 @@ pub const Subscriptions = struct { return self.connections.get(conn_id); } + pub fn withConnection(self: *Subscriptions, conn_id: u64, comptime func: fn (*Connection) void) void { + self.rwlock.lockShared(); + defer self.rwlock.unlockShared(); + if (self.connections.get(conn_id)) |conn| { + func(conn); + } + } + + pub fn sendToConnection(self: *Subscriptions, conn_id: u64, data: []const u8) bool { + self.rwlock.lockShared(); + defer self.rwlock.unlockShared(); + if (self.connections.get(conn_id)) |conn| { + return conn.send(data); + } + return false; + } + + pub fn closeIdleConnection(self: *Subscriptions, conn_id: u64, notice: []const u8) bool { + self.rwlock.lockShared(); + defer self.rwlock.unlockShared(); + if (self.connections.get(conn_id)) |conn| { + conn.sendDirect(notice); + conn.stopWriteQueue(); + conn.clearDirectWriter(); + return true; + } + return false; + } + pub fn connectionCount(self: *Subscriptions) usize { self.rwlock.lockShared(); defer self.rwlock.unlockShared(); diff --git a/src/tcp_server.zig b/src/tcp_server.zig new file mode 100644 index 0000000..ab1ff86 --- /dev/null +++ b/src/tcp_server.zig @@ -0,0 +1,352 @@ +const std = @import("std"); +const net = std.net; +const posix = std.posix; +const nostr = @import("nostr.zig"); +const ws = nostr.ws; + +const Config = @import("config.zig").Config; +const MsgHandler = @import("handler.zig").Handler; +const Subscriptions = @import("subscriptions.zig").Subscriptions; +const Connection = @import("connection.zig").Connection; +const nip11 = @import("nip11.zig"); +const rate_limiter = @import("rate_limiter.zig"); +const write_queue = @import("write_queue.zig"); + +const WsWriter = struct { + stream: net.Stream, + mutex: std.Thread.Mutex = .{}, + + fn write(ctx: *anyopaque, data: []const u8) void { + const self: *WsWriter = @ptrCast(@alignCast(ctx)); + self.mutex.lock(); + defer self.mutex.unlock(); + self.writeWsFrame(data) catch {}; + } + + fn writeWsFrame(self: *WsWriter, data: []const u8) !void { + var header: [14]u8 = undefined; + var header_len: usize = 2; + + header[0] = 0x81; // FIN + text opcode + + if (data.len < 126) { + header[1] = @intCast(data.len); + } else if (data.len < 65536) { + header[1] = 126; + header[2] = @intCast((data.len >> 8) & 0xFF); + header[3] = @intCast(data.len & 0xFF); + header_len = 4; + } else { + header[1] = 127; + const len64: u64 = data.len; + header[2] = @intCast((len64 >> 56) & 0xFF); + header[3] = @intCast((len64 >> 48) & 0xFF); + header[4] = @intCast((len64 >> 40) & 0xFF); + header[5] = @intCast((len64 >> 32) & 0xFF); + header[6] = @intCast((len64 >> 24) & 0xFF); + header[7] = @intCast((len64 >> 16) & 0xFF); + header[8] = @intCast((len64 >> 8) & 0xFF); + header[9] = @intCast(len64 & 0xFF); + header_len = 10; + } + + try self.stream.writeAll(header[0..header_len]); + try self.stream.writeAll(data); + } +}; + +pub const TcpServer = struct { + allocator: std.mem.Allocator, + config: *const Config, + handler: *MsgHandler, + subs: *Subscriptions, + + next_id: u64 = 0, + mutex: std.Thread.Mutex = .{}, + + listener: ?net.Server = null, + shutdown: *std.atomic.Value(bool), + + conn_limiter: rate_limiter.ConnectionLimiter, + ip_filter: rate_limiter.IpFilter, + + pub fn init( + allocator: std.mem.Allocator, + config: *const Config, + handler: *MsgHandler, + subs: *Subscriptions, + shutdown: *std.atomic.Value(bool), + ) !TcpServer { + var ip_filter = rate_limiter.IpFilter.init(allocator); + try ip_filter.loadWhitelist(config.ip_whitelist); + try ip_filter.loadBlacklist(config.ip_blacklist); + + return .{ + .allocator = allocator, + .config = config, + .handler = handler, + .subs = subs, + .shutdown = shutdown, + .conn_limiter = rate_limiter.ConnectionLimiter.init(allocator, config.max_connections_per_ip), + .ip_filter = ip_filter, + }; + } + + pub fn deinit(self: *TcpServer) void { + if (self.listener) |*l| { + l.deinit(); + self.listener = null; + } + // Only deinit limiters if they haven't been freed + // This makes deinit idempotent + if (self.conn_limiter.ip_buckets.capacity() > 0) { + self.conn_limiter.deinit(); + } + if (self.ip_filter.whitelist.capacity() > 0) { + self.ip_filter.deinit(); + } + } + + pub fn run(self: *TcpServer) !void { + const address = try net.Address.parseIp(self.config.host, self.config.port); + self.listener = try address.listen(.{ + .reuse_address = true, + }); + + std.log.info("Server running on {s}:{d}", .{ self.config.host, self.config.port }); + + const idle_thread = std.Thread.spawn(.{}, idleTimeoutThread, .{ self, self.shutdown }) catch null; + defer if (idle_thread) |t| t.join(); + + while (!self.shutdown.load(.acquire)) { + const conn = self.listener.?.accept() catch |err| { + if (err == error.SocketNotListening) break; + continue; + }; + + const thread = std.Thread.spawn(.{}, handleConnection, .{ self, conn }) catch |err| { + std.log.warn("Failed to spawn connection thread: {}", .{err}); + conn.stream.close(); + continue; + }; + thread.detach(); + } + + std.log.info("Shutting down server...", .{}); + if (self.listener) |*l| { + l.deinit(); + self.listener = null; + } + // Give connection threads time to finish + std.Thread.sleep(200 * std.time.ns_per_ms); + } + + fn idleTimeoutThread(self: *TcpServer, shutdown: *std.atomic.Value(bool)) void { + const check_interval_s: u64 = 30; + var seconds_waited: u64 = 0; + + while (!shutdown.load(.acquire)) { + std.Thread.sleep(std.time.ns_per_s); + if (shutdown.load(.acquire)) break; + seconds_waited += 1; + if (seconds_waited < check_interval_s) continue; + seconds_waited = 0; + + if (self.config.idle_seconds == 0) continue; + + const idle_conn_ids = self.subs.getIdleConnections(self.config.idle_seconds); + defer self.allocator.free(idle_conn_ids); + + for (idle_conn_ids) |conn_id| { + var buf: [128]u8 = undefined; + const notice = nostr.RelayMsg.notice("connection closed: idle timeout", &buf) catch continue; + if (self.subs.closeIdleConnection(conn_id, notice)) { + std.log.debug("Closed idle connection {d}", .{conn_id}); + } + } + } + } + + pub fn stop(self: *TcpServer) void { + if (self.listener) |*l| { + l.deinit(); + self.listener = null; + } + } + + fn handleConnection(self: *TcpServer, conn: net.Server.Connection) void { + defer conn.stream.close(); + + // Check shutdown early to avoid accessing freed resources + if (self.shutdown.load(.acquire)) return; + + var addr_buf: [64]u8 = undefined; + const client_ip = extractIp(conn.address, &addr_buf); + + if (self.shutdown.load(.acquire)) return; + + if (!self.ip_filter.isAllowed(client_ip)) { + return; + } + + if (!self.conn_limiter.canConnect(client_ip)) { + return; + } + + var buf: [8192]u8 = undefined; + const n = conn.stream.read(&buf) catch return; + if (n == 0) return; + + const req_data = buf[0..n]; + + if (isWebsocketUpgrade(req_data)) { + self.handleWebsocket(conn, client_ip, req_data) catch |err| { + std.log.debug("Websocket error: {}", .{err}); + }; + } else { + self.handleHttp(conn, req_data) catch {}; + } + } + + fn handleWebsocket(self: *TcpServer, conn: net.Server.Connection, client_ip: []const u8, initial_data: []const u8) !void { + const req, const consumed = try ws.handshake.Req.parse(initial_data); + _ = consumed; + + const accept = ws.handshake.secAccept(req.key); + var response_buf: [256]u8 = undefined; + const response = try std.fmt.bufPrint(&response_buf, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {s}\r\n\r\n", .{&accept}); + try conn.stream.writeAll(response); + + self.mutex.lock(); + if (self.subs.connectionCount() >= self.config.max_connections) { + self.mutex.unlock(); + return error.TooManyConnections; + } + const conn_id = self.next_id; + self.next_id += 1; + self.mutex.unlock(); + + var ws_writer = WsWriter{ .stream = conn.stream }; + + const connection = try self.allocator.create(Connection); + connection.init(self.allocator, conn_id); + connection.setClientIp(client_ip); + connection.setDirectWriter(WsWriter.write, @ptrCast(&ws_writer)); + connection.startWriteQueue(WsWriter.write, @ptrCast(&ws_writer)); + + try self.subs.addConnection(connection); + self.conn_limiter.addConnection(client_ip); + + defer { + connection.stopWriteQueue(); + connection.clearDirectWriter(); + self.subs.removeConnection(conn_id); + self.conn_limiter.removeConnection(client_ip); + connection.deinit(); + self.allocator.destroy(connection); + } + + if (self.config.auth_required or self.config.auth_to_write) { + var auth_buf: [256]u8 = undefined; + const auth_msg = nostr.RelayMsg.auth(&connection.auth_challenge, &auth_buf) catch return; + connection.sendDirect(auth_msg); + connection.challenge_sent = true; + } + + var frame_buf: [65536]u8 = undefined; + var read_pos: usize = 0; + + while (!self.shutdown.load(.acquire)) { + const bytes_read = conn.stream.read(frame_buf[read_pos..]) catch |err| { + if (err == error.ConnectionResetByPeer or err == error.BrokenPipe) break; + return err; + }; + if (bytes_read == 0) break; + + read_pos += bytes_read; + connection.touch(); + + while (read_pos > 0) { + const frame, const frame_len = ws.Frame.parse(frame_buf[0..read_pos]) catch |err| { + if (err == error.SplitBuffer) break; + return err; + }; + + try frame.assertValid(false); + + if (frame.opcode == .close) { + var close_response: [16]u8 = undefined; + const close_frame = ws.Frame{ .fin = 1, .opcode = .close, .payload = &.{}, .mask = 0 }; + const close_len = close_frame.encode(&close_response, 1000); + conn.stream.writeAll(close_response[0..close_len]) catch {}; + return; + } else if (frame.opcode == .ping) { + var pong_buf: [256]u8 = undefined; + const pong_frame = ws.Frame{ .fin = 1, .opcode = .pong, .payload = frame.payload, .mask = 0 }; + const pong_len = pong_frame.encode(&pong_buf, 0); + conn.stream.writeAll(pong_buf[0..pong_len]) catch {}; + } else if (frame.opcode == .text or frame.opcode == .binary) { + if (frame.payload.len <= self.config.max_message_size) { + self.handler.handle(connection, frame.payload); + } else { + var notice_buf: [256]u8 = undefined; + const notice = nostr.RelayMsg.notice("error: message too large", ¬ice_buf) catch continue; + connection.sendDirect(notice); + } + } + + if (frame_len < read_pos) { + std.mem.copyForwards(u8, &frame_buf, frame_buf[frame_len..read_pos]); + } + read_pos -= frame_len; + } + } + } + + fn handleHttp(self: *TcpServer, conn: net.Server.Connection, req_data: []const u8) !void { + const accepts_json = std.mem.indexOf(u8, req_data, "application/nostr+json") != null; + + if (accepts_json) { + var response_buf: [4096]u8 = undefined; + var content_buf: [2048]u8 = undefined; + + var content_stream = std.io.fixedBufferStream(&content_buf); + try nip11.write(self.config, content_stream.writer()); + const content = content_stream.getWritten(); + + const response = try std.fmt.bufPrint(&response_buf, "HTTP/1.1 200 OK\r\nContent-Type: application/nostr+json\r\nAccess-Control-Allow-Origin: *\r\nContent-Length: {d}\r\n\r\n{s}", .{ content.len, content }); + try conn.stream.writeAll(response); + } else { + const html = + \\ + \\Wisp + \\ + \\

Wisp Nostr Relay

+ \\

Connect via WebSocket at this URL.

+ \\ + ; + const response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: " ++ std.fmt.comptimePrint("{d}", .{html.len}) ++ "\r\n\r\n" ++ html; + try conn.stream.writeAll(response); + } + } + + fn isWebsocketUpgrade(data: []const u8) bool { + return std.ascii.indexOfIgnoreCase(data, "upgrade: websocket") != null; + } + + fn extractIp(address: net.Address, buf: []u8) []const u8 { + const formatted = std.fmt.bufPrint(buf, "{any}", .{address}) catch return "unknown"; + if (std.mem.lastIndexOf(u8, formatted, ":")) |colon| { + return formatted[0..colon]; + } + return formatted; + } + + pub fn send(self: *TcpServer, conn_id: u64, data: []const u8) void { + _ = self.subs.sendToConnection(conn_id, data); + } + + pub fn connectionCount(self: *TcpServer) usize { + return self.subs.connectionCount(); + } +}; diff --git a/src/write_queue.zig b/src/write_queue.zig index ced1f29..97dfae3 100644 --- a/src/write_queue.zig +++ b/src/write_queue.zig @@ -1,37 +1,51 @@ const std = @import("std"); -const httpz = @import("httpz"); -const websocket = httpz.websocket; +const net = std.net; + +pub const WriteFn = *const fn (ctx: *anyopaque, data: []const u8) void; pub const WriteQueue = struct { - ws_conn: std.atomic.Value(?*websocket.Conn), + write_fn: ?WriteFn, + write_ctx: ?*anyopaque, dropped_count: std.atomic.Value(u64), allocator: std.mem.Allocator, + mutex: std.Thread.Mutex, pub fn init(allocator: std.mem.Allocator) WriteQueue { return .{ - .ws_conn = std.atomic.Value(?*websocket.Conn).init(null), + .write_fn = null, + .write_ctx = null, .dropped_count = std.atomic.Value(u64).init(0), .allocator = allocator, + .mutex = .{}, }; } - pub fn start(self: *WriteQueue, ws_conn: *websocket.Conn) void { - self.ws_conn.store(ws_conn, .release); + pub fn start(self: *WriteQueue, write_fn: WriteFn, write_ctx: *anyopaque) void { + self.mutex.lock(); + defer self.mutex.unlock(); + self.write_fn = write_fn; + self.write_ctx = write_ctx; } pub fn stop(self: *WriteQueue) void { - self.ws_conn.store(null, .release); + self.mutex.lock(); + defer self.mutex.unlock(); + self.write_fn = null; + self.write_ctx = null; } pub fn enqueue(self: *WriteQueue, data: []const u8) bool { - const conn = self.ws_conn.load(.acquire) orelse { + self.mutex.lock(); + defer self.mutex.unlock(); + const write_fn = self.write_fn orelse { _ = self.dropped_count.fetchAdd(1, .monotonic); return false; }; - conn.write(data) catch { + const ctx = self.write_ctx orelse { _ = self.dropped_count.fetchAdd(1, .monotonic); return false; }; + write_fn(ctx, data); return true; } @@ -40,6 +54,6 @@ pub const WriteQueue = struct { } pub fn queueDepth(_: *WriteQueue) usize { - return 0; // No queue + return 0; } }; From b6122d69d6bed94d8612089aca2056abf12a18e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kyle=20=F0=9F=90=86?= Date: Wed, 24 Dec 2025 16:23:15 -0500 Subject: [PATCH 5/9] Add NIP-02 to supported NIPs --- README.md | 2 +- src/nip11.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 038a5e4..ad56367 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Spider reads your follow list and pulls your feed. Point your client at `ws://lo ## Features -* NIPs: 1, 9, 11, 13, 16, 33, 40, 42, 45, 50, 65, 70, 77 +* NIPs: 1, 2, 9, 11, 13, 16, 33, 40, 42, 45, 50, 65, 70, 77 * LMDB storage (no external database) * Spider mode for syncing events from external relays * Import/export to JSONL diff --git a/src/nip11.zig b/src/nip11.zig index 97cf024..69215dc 100644 --- a/src/nip11.zig +++ b/src/nip11.zig @@ -35,7 +35,7 @@ pub fn write(config: *const Config, w: anytype) !void { try writeJsonString(w, contact); } - try w.writeAll(",\"supported_nips\":[1,9,11,13,16,33,40,42,45,50,65,70,77]"); + try w.writeAll(",\"supported_nips\":[1,2,9,11,13,16,33,40,42,45,50,65,70,77]"); try w.writeAll(",\"software\":\"https://github.com/privkeyio/wisp\""); try w.writeAll(",\"version\":\"0.1.0\""); From b18a5fb0716e60e0adca99ea13952f87299e76a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kyle=20=F0=9F=90=86?= Date: Wed, 24 Dec 2025 16:26:36 -0500 Subject: [PATCH 6/9] Update websocket dependency hash --- build.zig.zon | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.zig.zon b/build.zig.zon index c04eaa5..058c881 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -6,7 +6,7 @@ // websocket client for spider outbound connections .websocket = .{ .url = "https://github.com/karlseguin/websocket.zig/archive/refs/heads/master.tar.gz", - .hash = "websocket-0.1.0-ZPISdZJxAwAt6Ys_JpoHQQV3NpWCof_N9Jg-Ul2g7OoV", + .hash = "websocket-0.1.0-ZPISdRNzAwAGszh62EpRtoQxu8wb1MSMVI6Ow0o2dmyJ", }, .nostr = .{ .path = "../libnostr-z", From 0a78a8db5c515c8d2b545d472bea58c208edaa88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kyle=20=F0=9F=90=86?= Date: Wed, 24 Dec 2025 16:30:50 -0500 Subject: [PATCH 7/9] Use GitHub URL for libnostr-z dependency --- build.zig.zon | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build.zig.zon b/build.zig.zon index 058c881..4d1af94 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,7 +9,8 @@ .hash = "websocket-0.1.0-ZPISdRNzAwAGszh62EpRtoQxu8wb1MSMVI6Ow0o2dmyJ", }, .nostr = .{ - .path = "../libnostr-z", + .url = "https://github.com/privkeyio/libnostr-z/archive/refs/tags/v0.1.8.tar.gz", + .hash = "nostr-0.1.8-JY6OcM8yBgBerCkIS-c3a_YdGedXYw_PHRPT1ey73eSw", }, }, .paths = .{ From 41abeb54a7358d8569734f2fa8300c108984ad91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kyle=20=F0=9F=90=86?= Date: Wed, 24 Dec 2025 16:58:37 -0500 Subject: [PATCH 8/9] bug fixes --- src/connection.zig | 8 -------- src/handler.zig | 21 +++++---------------- src/tcp_server.zig | 9 ++++++--- src/write_queue.zig | 8 -------- 4 files changed, 11 insertions(+), 35 deletions(-) diff --git a/src/connection.zig b/src/connection.zig index 8f4e93d..27dde9a 100644 --- a/src/connection.zig +++ b/src/connection.zig @@ -26,7 +26,6 @@ pub const Connection = struct { last_activity: i64, direct_write_fn: ?WriteFn = null, direct_write_ctx: ?*anyopaque = null, - write_mutex: std.Thread.Mutex = .{}, events_received: u64 = 0, events_sent: u64 = 0, @@ -59,7 +58,6 @@ pub const Connection = struct { self.client_ip_len = 0; self.direct_write_fn = null; self.direct_write_ctx = null; - self.write_mutex = .{}; std.crypto.random.bytes(&self.auth_challenge); self.authenticated_pubkeys = std.AutoHashMap([32]u8, void).init(self.arena.allocator()); self.challenge_sent = false; @@ -102,8 +100,6 @@ pub const Connection = struct { } pub fn sendDirect(self: *Connection, data: []const u8) void { - self.write_mutex.lock(); - defer self.write_mutex.unlock(); if (self.direct_write_fn) |write_fn| { if (self.direct_write_ctx) |ctx| { write_fn(ctx, data); @@ -112,15 +108,11 @@ pub const Connection = struct { } pub fn setDirectWriter(self: *Connection, write_fn: WriteFn, ctx: *anyopaque) void { - self.write_mutex.lock(); - defer self.write_mutex.unlock(); self.direct_write_fn = write_fn; self.direct_write_ctx = ctx; } pub fn clearDirectWriter(self: *Connection) void { - self.write_mutex.lock(); - defer self.write_mutex.unlock(); self.direct_write_fn = null; self.direct_write_ctx = null; } diff --git a/src/handler.zig b/src/handler.zig index 9b0dd28..ae77914 100644 --- a/src/handler.zig +++ b/src/handler.zig @@ -434,9 +434,7 @@ pub const Handler = struct { }; defer iter.deinit(); - while (true) { - if (self.shutdown.load(.acquire)) return; - const json = iter.next() catch null orelse break; + while (iter.next() catch null) |json| { var buf: [65536]u8 = undefined; const event_msg = nostr.RelayMsg.eventRaw(sub_id, json, &buf) catch continue; _ = conn.send(event_msg); @@ -450,9 +448,7 @@ pub const Handler = struct { }; defer mk_iter.deinit(); - while (true) { - if (self.shutdown.load(.acquire)) return; - const json = mk_iter.next() catch null orelse break; + while (mk_iter.next() catch null) |json| { var buf: [65536]u8 = undefined; const event_msg = nostr.RelayMsg.eventRaw(sub_id, json, &buf) catch continue; _ = conn.send(event_msg); @@ -467,9 +463,7 @@ pub const Handler = struct { }; defer iter.deinit(); - while (true) { - if (self.shutdown.load(.acquire)) return; - const json = iter.next() catch null orelse break; + while (iter.next() catch null) |json| { var buf: [65536]u8 = undefined; const event_msg = nostr.RelayMsg.eventRaw(sub_id, json, &buf) catch continue; _ = conn.send(event_msg); @@ -525,16 +519,13 @@ pub const Handler = struct { var total_count: u64 = 0; for (filters) |filter| { - if (self.shutdown.load(.acquire)) return; var iter = self.store.query(&[_]nostr.Filter{filter}, self.config.query_limit_max) catch { self.sendClosed(conn, sub_id, "error: query failed"); return; }; defer iter.deinit(); - while (true) { - if (self.shutdown.load(.acquire)) return; - _ = iter.next() catch null orelse break; + while (iter.next() catch null) |_| { total_count += 1; } } @@ -637,9 +628,7 @@ pub const Handler = struct { defer iter.deinit(); var count: u32 = 0; - while (true) { - if (self.shutdown.load(.acquire)) return; - const json = iter.next() catch null orelse break; + while (iter.next() catch null) |json| { var event = nostr.Event.parse(json) catch continue; defer event.deinit(); session.storage.insert(@intCast(event.createdAt()), event.id()) catch continue; diff --git a/src/tcp_server.zig b/src/tcp_server.zig index ab1ff86..eb49728 100644 --- a/src/tcp_server.zig +++ b/src/tcp_server.zig @@ -27,7 +27,7 @@ const WsWriter = struct { var header: [14]u8 = undefined; var header_len: usize = 2; - header[0] = 0x81; // FIN + text opcode + header[0] = 0x81; if (data.len < 126) { header[1] = @intCast(data.len); @@ -50,8 +50,11 @@ const WsWriter = struct { header_len = 10; } - try self.stream.writeAll(header[0..header_len]); - try self.stream.writeAll(data); + var iovecs = [_]std.posix.iovec_const{ + .{ .base = &header, .len = header_len }, + .{ .base = data.ptr, .len = data.len }, + }; + _ = try self.stream.writev(&iovecs); } }; diff --git a/src/write_queue.zig b/src/write_queue.zig index 97dfae3..89c43dd 100644 --- a/src/write_queue.zig +++ b/src/write_queue.zig @@ -8,7 +8,6 @@ pub const WriteQueue = struct { write_ctx: ?*anyopaque, dropped_count: std.atomic.Value(u64), allocator: std.mem.Allocator, - mutex: std.Thread.Mutex, pub fn init(allocator: std.mem.Allocator) WriteQueue { return .{ @@ -16,27 +15,20 @@ pub const WriteQueue = struct { .write_ctx = null, .dropped_count = std.atomic.Value(u64).init(0), .allocator = allocator, - .mutex = .{}, }; } pub fn start(self: *WriteQueue, write_fn: WriteFn, write_ctx: *anyopaque) void { - self.mutex.lock(); - defer self.mutex.unlock(); self.write_fn = write_fn; self.write_ctx = write_ctx; } pub fn stop(self: *WriteQueue) void { - self.mutex.lock(); - defer self.mutex.unlock(); self.write_fn = null; self.write_ctx = null; } pub fn enqueue(self: *WriteQueue, data: []const u8) bool { - self.mutex.lock(); - defer self.mutex.unlock(); const write_fn = self.write_fn orelse { _ = self.dropped_count.fetchAdd(1, .monotonic); return false; From 14afb1c208453f4cd06669ff45ae3eeef6ecaa85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kyle=20=F0=9F=90=86?= Date: Wed, 24 Dec 2025 20:20:18 -0500 Subject: [PATCH 9/9] Fix TCP_NODELAY, double cleanup, filter cloning, and write error handling --- src/config.zig | 8 ----- src/connection.zig | 14 ++++++++ src/main.zig | 9 ----- src/store.zig | 32 ++--------------- src/subscriptions.zig | 8 +++++ src/tcp_server.zig | 84 ++++++++++++++++++++++++++++++------------- 6 files changed, 85 insertions(+), 70 deletions(-) diff --git a/src/config.zig b/src/config.zig index b6a13d9..f924c1d 100644 --- a/src/config.zig +++ b/src/config.zig @@ -45,8 +45,6 @@ pub const Config = struct { min_pow_difficulty: u8, - log_level: []const u8, - _allocated: std.ArrayListUnmanaged([]const u8), _allocator: ?std.mem.Allocator, @@ -88,7 +86,6 @@ pub const Config = struct { .negentropy_enabled = true, .negentropy_max_sync_events = 1000000, .min_pow_difficulty = 0, - .log_level = "info", ._allocated = undefined, ._allocator = null, }; @@ -230,10 +227,6 @@ pub const Config = struct { } else if (std.mem.eql(u8, key, "max_sync_events")) { self.negentropy_max_sync_events = try std.fmt.parseInt(u32, value, 10); } - } else if (std.mem.eql(u8, section, "logging")) { - if (std.mem.eql(u8, key, "level")) { - self.log_level = try self.allocString(value); - } } } @@ -295,7 +288,6 @@ pub const Config = struct { if (std.posix.getenv("WISP_MIN_POW_DIFFICULTY")) |v| { self.min_pow_difficulty = std.fmt.parseInt(u8, v, 10) catch self.min_pow_difficulty; } - if (std.posix.getenv("WISP_LOG_LEVEL")) |v| self.log_level = v; } pub fn deinit(self: *Config) void { diff --git a/src/connection.zig b/src/connection.zig index 27dde9a..5423390 100644 --- a/src/connection.zig +++ b/src/connection.zig @@ -1,4 +1,5 @@ const std = @import("std"); +const posix = std.posix; const nostr = @import("nostr.zig"); const write_queue = @import("write_queue.zig"); const WriteQueue = write_queue.WriteQueue; @@ -26,6 +27,7 @@ pub const Connection = struct { last_activity: i64, direct_write_fn: ?WriteFn = null, direct_write_ctx: ?*anyopaque = null, + socket_handle: ?posix.socket_t = null, events_received: u64 = 0, events_sent: u64 = 0, @@ -58,6 +60,7 @@ pub const Connection = struct { self.client_ip_len = 0; self.direct_write_fn = null; self.direct_write_ctx = null; + self.socket_handle = null; std.crypto.random.bytes(&self.auth_challenge); self.authenticated_pubkeys = std.AutoHashMap([32]u8, void).init(self.arena.allocator()); self.challenge_sent = false; @@ -117,6 +120,17 @@ pub const Connection = struct { self.direct_write_ctx = null; } + pub fn setSocketHandle(self: *Connection, handle: posix.socket_t) void { + self.socket_handle = handle; + } + + pub fn shutdown(self: *Connection) void { + if (self.socket_handle) |handle| { + posix.shutdown(handle, .both) catch {}; + self.socket_handle = null; + } + } + pub fn deinit(self: *Connection) void { if (self.deinitialized) return; self.deinitialized = true; diff --git a/src/main.zig b/src/main.zig index 47a7f21..436492f 100644 --- a/src/main.zig +++ b/src/main.zig @@ -202,15 +202,6 @@ pub fn main() !void { try server.run(); - if (spider) |*s| { - s.stop(); - s.deinit(); - } - spider = null; - - // server.deinit() will be called by defer - std.Thread.sleep(200 * std.time.ns_per_ms); - std.log.info("Shutdown complete", .{}); } diff --git a/src/store.zig b/src/store.zig index c26457e..cb74a7a 100644 --- a/src/store.zig +++ b/src/store.zig @@ -490,7 +490,6 @@ pub const MultiKindResult = struct { pub const QueryIterator = struct { store: *Store, filters: []const nostr.Filter, - owned_filters: ?[]nostr.Filter = null, limit: u32, returned: u32 = 0, txn: ?Txn = null, @@ -504,35 +503,14 @@ pub const QueryIterator = struct { const IndexType = enum { created, kind, pubkey, tag }; pub fn init(store: *Store, filters: []const nostr.Filter, limit: u32) QueryIterator { - const allocator = store.allocator; - const owned = allocator.alloc(nostr.Filter, filters.len) catch { - return QueryIterator{ - .store = store, - .filters = &.{}, - .limit = limit, - }; - }; - for (filters, 0..) |f, i| { - owned[i] = f.clone(allocator) catch { - for (0..i) |j| owned[j].deinit(); - allocator.free(owned); - return QueryIterator{ - .store = store, - .filters = &.{}, - .limit = limit, - }; - }; - } - var iter = QueryIterator{ .store = store, - .filters = owned, - .owned_filters = owned, + .filters = filters, .limit = limit, }; - if (owned.len > 0) { - const f = owned[0]; + if (filters.len > 0) { + const f = filters[0]; if (f.authors()) |authors| { if (authors.len == 1) { @@ -684,9 +662,5 @@ pub const QueryIterator = struct { pub fn deinit(self: *QueryIterator) void { if (self.cursor) |*cur| cur.close(); if (self.txn) |*t| t.abort(); - if (self.owned_filters) |owned| { - for (owned) |*f| f.deinit(); - self.store.allocator.free(owned); - } } }; diff --git a/src/subscriptions.zig b/src/subscriptions.zig index ec148c8..1c96c96 100644 --- a/src/subscriptions.zig +++ b/src/subscriptions.zig @@ -33,6 +33,13 @@ pub const Subscriptions = struct { try self.connections.put(conn.id, conn); } + pub fn tryAddConnection(self: *Subscriptions, conn: *Connection, max_connections: usize) !void { + self.rwlock.lock(); + defer self.rwlock.unlock(); + if (self.connections.count() >= max_connections) return error.TooManyConnections; + try self.connections.put(conn.id, conn); + } + pub fn removeConnection(self: *Subscriptions, conn_id: u64) void { self.rwlock.lock(); defer self.rwlock.unlock(); @@ -80,6 +87,7 @@ pub const Subscriptions = struct { conn.sendDirect(notice); conn.stopWriteQueue(); conn.clearDirectWriter(); + conn.shutdown(); return true; } return false; diff --git a/src/tcp_server.zig b/src/tcp_server.zig index eb49728..31902d6 100644 --- a/src/tcp_server.zig +++ b/src/tcp_server.zig @@ -15,12 +15,16 @@ const write_queue = @import("write_queue.zig"); const WsWriter = struct { stream: net.Stream, mutex: std.Thread.Mutex = .{}, + failed: bool = false, fn write(ctx: *anyopaque, data: []const u8) void { const self: *WsWriter = @ptrCast(@alignCast(ctx)); self.mutex.lock(); defer self.mutex.unlock(); - self.writeWsFrame(data) catch {}; + if (self.failed) return; + self.writeWsFrame(data) catch { + self.failed = true; + }; } fn writeWsFrame(self: *WsWriter, data: []const u8) !void { @@ -100,14 +104,8 @@ pub const TcpServer = struct { l.deinit(); self.listener = null; } - // Only deinit limiters if they haven't been freed - // This makes deinit idempotent - if (self.conn_limiter.ip_buckets.capacity() > 0) { - self.conn_limiter.deinit(); - } - if (self.ip_filter.whitelist.capacity() > 0) { - self.ip_filter.deinit(); - } + self.conn_limiter.deinit(); + self.ip_filter.deinit(); } pub fn run(self: *TcpServer) !void { @@ -140,7 +138,6 @@ pub const TcpServer = struct { l.deinit(); self.listener = null; } - // Give connection threads time to finish std.Thread.sleep(200 * std.time.ns_per_ms); } @@ -212,6 +209,9 @@ pub const TcpServer = struct { } fn handleWebsocket(self: *TcpServer, conn: net.Server.Connection, client_ip: []const u8, initial_data: []const u8) !void { + const TCP_NODELAY = 1; + posix.setsockopt(conn.stream.handle, posix.IPPROTO.TCP, TCP_NODELAY, &std.mem.toBytes(@as(i32, 1))) catch {}; + const req, const consumed = try ws.handshake.Req.parse(initial_data); _ = consumed; @@ -220,24 +220,27 @@ pub const TcpServer = struct { const response = try std.fmt.bufPrint(&response_buf, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {s}\r\n\r\n", .{&accept}); try conn.stream.writeAll(response); + var ws_writer = WsWriter{ .stream = conn.stream }; + self.mutex.lock(); - if (self.subs.connectionCount() >= self.config.max_connections) { - self.mutex.unlock(); - return error.TooManyConnections; - } const conn_id = self.next_id; self.next_id += 1; self.mutex.unlock(); - var ws_writer = WsWriter{ .stream = conn.stream }; - const connection = try self.allocator.create(Connection); connection.init(self.allocator, conn_id); connection.setClientIp(client_ip); + connection.setSocketHandle(conn.stream.handle); connection.setDirectWriter(WsWriter.write, @ptrCast(&ws_writer)); connection.startWriteQueue(WsWriter.write, @ptrCast(&ws_writer)); - try self.subs.addConnection(connection); + self.subs.tryAddConnection(connection, self.config.max_connections) catch |err| { + connection.stopWriteQueue(); + connection.clearDirectWriter(); + connection.deinit(); + self.allocator.destroy(connection); + return err; + }; self.conn_limiter.addConnection(client_ip); defer { @@ -260,6 +263,14 @@ pub const TcpServer = struct { var read_pos: usize = 0; while (!self.shutdown.load(.acquire)) { + if (read_pos >= frame_buf.len) { + var close_response: [16]u8 = undefined; + const close_frame = ws.Frame{ .fin = 1, .opcode = .close, .payload = &.{}, .mask = 0 }; + const close_len = close_frame.encode(&close_response, 1002); + conn.stream.writeAll(close_response[0..close_len]) catch {}; + return; + } + const bytes_read = conn.stream.read(frame_buf[read_pos..]) catch |err| { if (err == error.ConnectionResetByPeer or err == error.BrokenPipe) break; return err; @@ -270,6 +281,8 @@ pub const TcpServer = struct { connection.touch(); while (read_pos > 0) { + if (try self.checkOversizedFrame(connection, conn, frame_buf[0..read_pos])) return; + const frame, const frame_len = ws.Frame.parse(frame_buf[0..read_pos]) catch |err| { if (err == error.SplitBuffer) break; return err; @@ -289,13 +302,7 @@ pub const TcpServer = struct { const pong_len = pong_frame.encode(&pong_buf, 0); conn.stream.writeAll(pong_buf[0..pong_len]) catch {}; } else if (frame.opcode == .text or frame.opcode == .binary) { - if (frame.payload.len <= self.config.max_message_size) { - self.handler.handle(connection, frame.payload); - } else { - var notice_buf: [256]u8 = undefined; - const notice = nostr.RelayMsg.notice("error: message too large", ¬ice_buf) catch continue; - connection.sendDirect(notice); - } + self.handler.handle(connection, frame.payload); } if (frame_len < read_pos) { @@ -306,6 +313,35 @@ pub const TcpServer = struct { } } + fn checkOversizedFrame(self: *TcpServer, connection: *Connection, conn: net.Server.Connection, data: []const u8) !bool { + if (data.len < 2) return false; + const payload_len_byte: u8 = data[1] & 0b0111_1111; + const payload_len: u64 = switch (payload_len_byte) { + 126 => blk: { + if (data.len < 4) return false; + break :blk std.mem.readInt(u16, data[2..4], .big); + }, + 127 => blk: { + if (data.len < 10) return false; + break :blk std.mem.readInt(u64, data[2..10], .big); + }, + else => payload_len_byte, + }; + if (payload_len > self.config.max_message_size) { + var notice_buf: [256]u8 = undefined; + const notice = nostr.RelayMsg.notice("error: message too large", ¬ice_buf) catch { + return true; + }; + connection.sendDirect(notice); + var close_response: [16]u8 = undefined; + const close_frame = ws.Frame{ .fin = 1, .opcode = .close, .payload = &.{}, .mask = 0 }; + const close_len = close_frame.encode(&close_response, 1009); + conn.stream.writeAll(close_response[0..close_len]) catch {}; + return true; + } + return false; + } + fn handleHttp(self: *TcpServer, conn: net.Server.Connection, req_data: []const u8) !void { const accepts_json = std.mem.indexOf(u8, req_data, "application/nostr+json") != null;