screen-relay 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +201 -0
  2. package/Makefile +165 -0
  3. package/README.md +112 -1
  4. package/THIRD-PARTY-NOTICES.md +75 -0
  5. package/dist/cli/client.d.ts +28 -0
  6. package/dist/cli/commands.d.ts +52 -0
  7. package/dist/cli/config.d.ts +32 -0
  8. package/dist/cli/format.d.ts +15 -0
  9. package/dist/cli/help.d.ts +5 -0
  10. package/dist/cli/host/common.d.ts +23 -0
  11. package/dist/cli/host/doctor.d.ts +2 -0
  12. package/dist/cli/host/packages.d.ts +13 -0
  13. package/dist/cli/host/session_commands.d.ts +8 -0
  14. package/dist/cli/host/setup.d.ts +22 -0
  15. package/dist/cli/host/state.d.ts +23 -0
  16. package/dist/cli/host/supervisor.d.ts +94 -0
  17. package/dist/cli/host/watcher.d.ts +4 -0
  18. package/dist/cli/host/windows.d.ts +82 -0
  19. package/dist/cli/main.d.ts +3 -0
  20. package/dist/cli/mode.d.ts +14 -0
  21. package/dist/cli/output.d.ts +24 -0
  22. package/dist/cli/parser.d.ts +6 -0
  23. package/dist/cli/relay.mjs +12631 -0
  24. package/dist/cli/skills.d.ts +21 -0
  25. package/dist/cli/theme.d.ts +14 -0
  26. package/dist/protocol/errors.d.ts +155 -0
  27. package/dist/protocol/index.d.ts +119 -0
  28. package/dist/protocol/index.js +418 -0
  29. package/dist/sdk/index.d.ts +78 -0
  30. package/dist/sdk/index.js +834 -0
  31. package/dist/sdk/transport.d.ts +20 -0
  32. package/dist/viewer/index.html +96 -0
  33. package/dist/viewer/viewer.js +1079 -0
  34. package/package.json +47 -7
  35. package/packages.tsv +38 -0
  36. package/skills/core/SKILL.md +171 -0
  37. package/skills/core/references/cli.md +119 -0
  38. package/skills/core/references/config.md +48 -0
  39. package/skills/core/references/macos.md +50 -0
  40. package/skills/core/references/sdk.md +69 -0
  41. package/skills/core/references/troubleshooting.md +33 -0
  42. package/skills/core/references/wayland.md +47 -0
  43. package/skills/screen-relay/SKILL.md +24 -0
  44. package/skills/vercel-sandbox/SKILL.md +68 -0
  45. package/src/engine/backends/linux/keycodes.hpp +35 -0
  46. package/src/engine/backends/linux/wayland/capture.cpp +298 -0
  47. package/src/engine/backends/linux/wayland/input.cpp +559 -0
  48. package/src/engine/backends/linux/wayland/keymap.cpp +118 -0
  49. package/src/engine/backends/linux/wayland/keymap.hpp +54 -0
  50. package/src/engine/backends/linux/wayland/protocols/virtual-keyboard-unstable-v1.xml +112 -0
  51. package/src/engine/backends/linux/wayland/protocols/wlr-screencopy-unstable-v1.xml +234 -0
  52. package/src/engine/backends/linux/wayland/protocols/wlr-virtual-pointer-unstable-v1.xml +152 -0
  53. package/src/engine/backends/linux/wayland/wayland.cpp +166 -0
  54. package/src/engine/backends/linux/wayland/wayland.hpp +60 -0
  55. package/src/engine/backends/linux/x11/capture.cpp +206 -0
  56. package/src/engine/backends/linux/x11/input.cpp +266 -0
  57. package/src/engine/backends/macos/capture.mm +367 -0
  58. package/src/engine/backends/macos/display.hpp +20 -0
  59. package/src/engine/backends/macos/display.mm +84 -0
  60. package/src/engine/backends/macos/input.mm +287 -0
  61. package/src/engine/backends/macos/keys.hpp +34 -0
  62. package/src/engine/backends/windows/capture.cpp +393 -0
  63. package/src/engine/backends/windows/input.cpp +274 -0
  64. package/src/engine/backends/windows/output.cpp +65 -0
  65. package/src/engine/backends/windows/output.hpp +26 -0
  66. package/src/engine/core/capture-bucket.hpp +40 -0
  67. package/src/engine/core/capture-source.hpp +59 -0
  68. package/src/engine/core/capture.cpp +565 -0
  69. package/src/engine/core/capture.hpp +58 -0
  70. package/src/engine/core/color.cpp +176 -0
  71. package/src/engine/core/color.hpp +16 -0
  72. package/src/engine/core/cpu-budget.hpp +196 -0
  73. package/src/engine/core/flow.hpp +317 -0
  74. package/src/engine/core/input.cpp +98 -0
  75. package/src/engine/core/input.hpp +115 -0
  76. package/src/engine/core/wait.cpp +125 -0
  77. package/src/engine/core/wait.hpp +41 -0
  78. package/src/engine/server/backend.cpp +65 -0
  79. package/src/engine/server/backend.hpp +18 -0
  80. package/src/engine/server/config.cpp +257 -0
  81. package/src/engine/server/config.hpp +24 -0
  82. package/src/engine/server/main.cpp +82 -0
  83. package/src/engine/server/metrics.cpp +47 -0
  84. package/src/engine/server/metrics.hpp +10 -0
  85. package/src/engine/server/screenshot.cpp +108 -0
  86. package/src/engine/server/screenshot.hpp +31 -0
  87. package/src/engine/server/server.cpp +535 -0
  88. package/src/engine/server/server.hpp +89 -0
  89. package/src/engine/server/wire.cpp +70 -0
  90. package/src/engine/server/wire.hpp +29 -0
  91. package/index.js +0 -2
@@ -0,0 +1,41 @@
1
+ #pragma once
2
+ #include <cstdint>
3
+
4
+ namespace relay {
5
+ #ifdef _WIN32
6
+ /// A manual-reset event HANDLE that a capture source sets when it may have new damage and resets in drainDamage().
7
+ using WaitHandle = void*;
8
+ #else
9
+ /// A file descriptor that polls readable when a capture source may have new damage.
10
+ using WaitHandle = int;
11
+ #endif
12
+ /// Reports whether a capture source returned a usable handle.
13
+ inline bool validWaitHandle(WaitHandle handle) {
14
+ #ifdef _WIN32
15
+ return handle != nullptr && handle != reinterpret_cast<void*>(-1);
16
+ #else
17
+ return handle >= 0;
18
+ #endif
19
+ }
20
+ /// A flag that another thread sets to interrupt a blocked wait(); it also satisfies the WaitHandle contract.
21
+ class Wake {
22
+ public:
23
+ Wake();
24
+ ~Wake();
25
+ Wake(const Wake&) = delete;
26
+ Wake& operator=(const Wake&) = delete;
27
+ bool valid() const;
28
+ void signal();
29
+ /// Clears the flag and reports whether it was set.
30
+ bool consume();
31
+ WaitHandle handle() const { return handle_; }
32
+ private:
33
+ WaitHandle handle_;
34
+ #if !defined(_WIN32) && !defined(__linux__)
35
+ int write_handle_ = -1;
36
+ #endif
37
+ };
38
+ struct WaitReady { bool source = false, wake = false; };
39
+ /// Blocks until the source or wake is ready or timeout_ns passes; a negative timeout waits indefinitely.
40
+ WaitReady wait(WaitHandle source, Wake& wake, int64_t timeout_ns);
41
+ }
@@ -0,0 +1,65 @@
1
+ #include "backend.hpp"
2
+ #include <stdexcept>
3
+
4
+ namespace relay {
5
+ #ifdef RELAY_BACKEND_x11
6
+ namespace x11 {
7
+ bool initializeNativeBackend(const std::string& output);
8
+ std::unique_ptr<CaptureSource> makeCaptureSource();
9
+ std::unique_ptr<InputBackend> makeInputBackend();
10
+ }
11
+ #endif
12
+ #ifdef RELAY_BACKEND_wayland
13
+ namespace wayland {
14
+ bool initializeNativeBackend(const std::string& output);
15
+ std::unique_ptr<CaptureSource> makeCaptureSource();
16
+ std::unique_ptr<InputBackend> makeInputBackend();
17
+ }
18
+ #endif
19
+ #ifdef RELAY_BACKEND_windows
20
+ namespace windows {
21
+ bool initializeNativeBackend(const std::string& output);
22
+ std::unique_ptr<CaptureSource> makeCaptureSource();
23
+ std::unique_ptr<InputBackend> makeInputBackend();
24
+ }
25
+ #endif
26
+ #ifdef RELAY_BACKEND_macos
27
+ namespace macos {
28
+ bool initializeNativeBackend(const std::string& output);
29
+ std::unique_ptr<CaptureSource> makeCaptureSource();
30
+ std::unique_ptr<InputBackend> makeInputBackend();
31
+ }
32
+ #endif
33
+
34
+ namespace {
35
+ const Backend backends[] = {
36
+ #ifdef RELAY_BACKEND_x11
37
+ {"x11", x11::initializeNativeBackend, x11::makeCaptureSource, x11::makeInputBackend},
38
+ #endif
39
+ #ifdef RELAY_BACKEND_wayland
40
+ {"wayland", wayland::initializeNativeBackend, wayland::makeCaptureSource, wayland::makeInputBackend},
41
+ #endif
42
+ #ifdef RELAY_BACKEND_windows
43
+ {"windows", windows::initializeNativeBackend, windows::makeCaptureSource, windows::makeInputBackend},
44
+ #endif
45
+ #ifdef RELAY_BACKEND_macos
46
+ {"macos", macos::initializeNativeBackend, macos::makeCaptureSource, macos::makeInputBackend},
47
+ #endif
48
+ };
49
+ }
50
+
51
+ const Backend& defaultBackend() { return backends[0]; }
52
+ std::string backendNames() {
53
+ std::string names;
54
+ for (const auto& backend : backends) {
55
+ if (!names.empty()) names += ", ";
56
+ names += backend.name;
57
+ }
58
+ return names;
59
+ }
60
+ const Backend& backendFor(const std::string& name) {
61
+ for (const auto& backend : backends)
62
+ if (name == backend.name) return backend;
63
+ throw std::runtime_error("Unknown backend '" + name + "'; compiled backends: " + backendNames());
64
+ }
65
+ }
@@ -0,0 +1,18 @@
1
+ #pragma once
2
+
3
+ #include "core/capture-source.hpp"
4
+ #include "core/input.hpp"
5
+ #include <memory>
6
+ #include <string>
7
+
8
+ namespace relay {
9
+ struct Backend {
10
+ const char* name;
11
+ bool (*initialize)(const std::string& output);
12
+ std::unique_ptr<CaptureSource> (*capture)();
13
+ std::unique_ptr<InputBackend> (*input)();
14
+ };
15
+ const Backend& defaultBackend();
16
+ const Backend& backendFor(const std::string& name);
17
+ std::string backendNames();
18
+ }
@@ -0,0 +1,257 @@
1
+ #include "config.hpp"
2
+ #include "backend.hpp"
3
+ #include <charconv>
4
+ #include <filesystem>
5
+ #include <fstream>
6
+ #include <iostream>
7
+ #include <sstream>
8
+ #include <stdexcept>
9
+ #ifdef _WIN32
10
+ #include <windows.h>
11
+ #include <aclapi.h>
12
+ #else
13
+ #include <sys/stat.h>
14
+ #include <unistd.h>
15
+ #endif
16
+ #ifdef __APPLE__
17
+ #include <cerrno>
18
+ #include <mach-o/dyld.h>
19
+ #include <membership.h>
20
+ #include <sys/acl.h>
21
+ #include <uuid/uuid.h>
22
+ #endif
23
+
24
+ namespace relay {
25
+ namespace {
26
+ #ifdef _WIN32
27
+ /// Reports whether an ACE only denies, audits, or labels access, so it cannot grant anyone access to the file.
28
+ bool deniesOrAudits(BYTE type) {
29
+ switch (type) {
30
+ case ACCESS_DENIED_ACE_TYPE: case ACCESS_DENIED_OBJECT_ACE_TYPE: case ACCESS_DENIED_CALLBACK_ACE_TYPE:
31
+ case ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE: case SYSTEM_AUDIT_ACE_TYPE: case SYSTEM_AUDIT_OBJECT_ACE_TYPE:
32
+ case SYSTEM_AUDIT_CALLBACK_ACE_TYPE: case SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE: case SYSTEM_ALARM_ACE_TYPE:
33
+ case SYSTEM_MANDATORY_LABEL_ACE_TYPE:
34
+ return true;
35
+ default:
36
+ return false;
37
+ }
38
+ }
39
+ /// Reports whether only the current user, SYSTEM, and Administrators own or may open the file.
40
+ bool privateTokenFile(const std::string& path) {
41
+ std::error_code error;
42
+ if (!std::filesystem::is_regular_file(path, error) || std::filesystem::file_size(path, error) > 66 || error) return false;
43
+ HANDLE token = nullptr;
44
+ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return false;
45
+ alignas(TOKEN_USER) unsigned char buffer[256];
46
+ DWORD length = 0;
47
+ const bool queried = GetTokenInformation(token, TokenUser, buffer, sizeof(buffer), &length);
48
+ CloseHandle(token);
49
+ if (!queried) return false;
50
+ const PSID user = reinterpret_cast<TOKEN_USER*>(buffer)->User.Sid;
51
+ PSID owner = nullptr;
52
+ PACL dacl = nullptr;
53
+ PSECURITY_DESCRIPTOR descriptor = nullptr;
54
+ if (GetNamedSecurityInfoA(path.c_str(), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
55
+ &owner, nullptr, &dacl, nullptr, &descriptor) != ERROR_SUCCESS) return false;
56
+ const auto privileged = [&](PSID sid) {
57
+ return EqualSid(sid, user) || IsWellKnownSid(sid, WinLocalSystemSid) || IsWellKnownSid(sid, WinBuiltinAdministratorsSid);
58
+ };
59
+ bool owned = dacl && owner && privileged(owner);
60
+ for (DWORD index = 0; owned && index < dacl->AceCount; ++index) {
61
+ ACE_HEADER* header = nullptr;
62
+ if (!GetAce(dacl, index, reinterpret_cast<void**>(&header))) { owned = false; break; }
63
+ if (deniesOrAudits(header->AceType)) continue;
64
+ owned = header->AceType == ACCESS_ALLOWED_ACE_TYPE &&
65
+ privileged(&reinterpret_cast<ACCESS_ALLOWED_ACE*>(header)->SidStart);
66
+ }
67
+ LocalFree(descriptor);
68
+ return owned;
69
+ }
70
+ /// Path of the running engine binary, used to find the bundled viewer.
71
+ std::filesystem::path executablePath() {
72
+ wchar_t path[MAX_PATH];
73
+ const DWORD length = GetModuleFileNameW(nullptr, path, MAX_PATH);
74
+ if (!length || length == MAX_PATH) throw std::runtime_error("Could not find the engine executable");
75
+ return std::filesystem::path(path);
76
+ }
77
+ #elif defined(__APPLE__)
78
+ /// Path of the running engine binary, used to find the bundled viewer.
79
+ std::filesystem::path executablePath() {
80
+ uint32_t size = 0;
81
+ if (_NSGetExecutablePath(nullptr, &size) != -1 || !size) throw std::runtime_error("Could not find the engine executable");
82
+ std::string path(size, '\0');
83
+ if (_NSGetExecutablePath(path.data(), &size) != 0) throw std::runtime_error("Could not find the engine executable");
84
+ return std::filesystem::canonical(path.c_str());
85
+ }
86
+ #else
87
+ /// Path of the running engine binary, used to find the bundled viewer.
88
+ std::filesystem::path executablePath() { return std::filesystem::canonical("/proc/self/exe"); }
89
+ #endif
90
+ #ifdef __APPLE__
91
+ /// Reports whether an extended ACL entry names only the user running the engine.
92
+ bool ownerAclEntry(acl_entry_t entry) {
93
+ uuid_t owner;
94
+ if (mbr_uid_to_uuid(geteuid(), owner)) return false;
95
+ void* qualifier = acl_get_qualifier(entry);
96
+ if (!qualifier) return false;
97
+ const bool same = uuid_compare(*static_cast<uuid_t*>(qualifier), owner) == 0;
98
+ acl_free(qualifier);
99
+ return same;
100
+ }
101
+ /// Reports whether the file has no extended ACL entry that could grant another user access; deny entries and
102
+ /// allow entries for the owner are still accepted.
103
+ bool privateTokenAcl(const std::string& path) {
104
+ acl_t acl = acl_get_file(path.c_str(), ACL_TYPE_EXTENDED);
105
+ if (!acl) return errno == ENOENT;
106
+ acl_entry_t entry;
107
+ int result = acl_get_entry(acl, ACL_FIRST_ENTRY, &entry);
108
+ while (result == 0) {
109
+ acl_tag_t tag;
110
+ if (acl_get_tag_type(entry, &tag)) break;
111
+ if (tag != ACL_EXTENDED_DENY && (tag != ACL_EXTENDED_ALLOW || !ownerAclEntry(entry))) break;
112
+ result = acl_get_entry(acl, ACL_NEXT_ENTRY, &entry);
113
+ }
114
+ const bool safe = result == -1 && errno == EINVAL;
115
+ acl_free(acl);
116
+ return safe;
117
+ }
118
+ #elif !defined(_WIN32)
119
+ /// Mode bits already reflect POSIX ACL grants, so there is nothing extra to check.
120
+ bool privateTokenAcl(const std::string&) { return true; }
121
+ #endif
122
+ #ifndef _WIN32
123
+ /// Reports whether the current user owns the file and no other user can read or write it.
124
+ bool privateTokenFile(const std::string& path) {
125
+ struct stat st{};
126
+ return !stat(path.c_str(), &st) && S_ISREG(st.st_mode) && st.st_uid == geteuid() && !(st.st_mode & 0077) &&
127
+ st.st_size <= 66 && privateTokenAcl(path);
128
+ }
129
+ #endif
130
+ }
131
+ bool secretEqual(const std::string& a, const std::string& b) {
132
+ if (a.size() != b.size()) return false;
133
+ unsigned difference = 0;
134
+ for (size_t i = 0; i < a.size(); ++i) difference |= unsigned(a[i] ^ b[i]);
135
+ return difference == 0;
136
+ }
137
+ std::string header(lws* wsi, lws_token_indexes token) {
138
+ char value[1024];
139
+ const int count = lws_hdr_copy(wsi, value, sizeof(value), token);
140
+ return count > 0 ? std::string(value, size_t(count)) : "";
141
+ }
142
+ bool authenticated(const Config& config, lws* wsi, bool websocket) {
143
+ if (config.token.empty()) return true;
144
+ if (!websocket) return secretEqual(header(wsi, WSI_TOKEN_HTTP_AUTHORIZATION), "Bearer " + config.token);
145
+ std::istringstream protocols(header(wsi, WSI_TOKEN_PROTOCOL));
146
+ std::string protocol;
147
+ while (std::getline(protocols, protocol, ',')) {
148
+ const auto first = protocol.find_first_not_of(" \t");
149
+ const auto last = protocol.find_last_not_of(" \t");
150
+ if (first != std::string::npos && secretEqual(protocol.substr(first, last-first+1), "bearer." + config.token)) return true;
151
+ }
152
+ return false;
153
+ }
154
+ bool loopbackOrigin(const std::string& origin) {
155
+ const auto scheme = origin.find("://");
156
+ if (scheme == std::string::npos || (origin.substr(0, scheme) != "http" && origin.substr(0, scheme) != "https")) return false;
157
+ const auto host = origin.substr(scheme + 3);
158
+ auto colon = host.find(':');
159
+ const auto name = host.substr(0, colon);
160
+ if (name != "localhost" && name != "127.0.0.1") return false;
161
+ if (colon == std::string::npos) return true;
162
+ const auto port = host.substr(colon + 1);
163
+ if (port.empty() || port.size() > 5) return false;
164
+ unsigned value = 0;
165
+ for (char c : port) { if (c < '0' || c > '9') return false; value = value * 10 + unsigned(c - '0'); }
166
+ return value > 0 && value <= 65535;
167
+ }
168
+ bool loopbackHost(const std::string& host) { return loopbackOrigin("http://" + host); }
169
+ bool localRequest(const Config& config, lws* wsi) {
170
+ const auto host = header(wsi, WSI_TOKEN_HOST);
171
+ if (!loopbackHost(host) && (config.origin.empty() || host != config.authority)) return false;
172
+ if (!config.token.empty() || lws_hdr_total_length(wsi, WSI_TOKEN_ORIGIN) <= 0) return true;
173
+ return loopbackHost(host) && loopbackOrigin(header(wsi, WSI_TOKEN_ORIGIN));
174
+ }
175
+ bool unsignedNumber(const std::string& text, uint64_t& value) {
176
+ if (text.empty()) return false;
177
+ const auto parsed = std::from_chars(text.data(), text.data()+text.size(), value);
178
+ return parsed.ec == std::errc{} && parsed.ptr == text.data()+text.size();
179
+ }
180
+ bool parseConfig(int argc, char** argv, Config& config) {
181
+ config.viewer = (executablePath().parent_path() / "viewer").string();
182
+ if (config.backend.empty()) config.backend = defaultBackend().name;
183
+ const auto bitrate = [](const std::string& text) {
184
+ uint64_t value;
185
+ if (!unsignedNumber(text, value) || value < 250000 || value > 100000000)
186
+ throw std::runtime_error("Bitrate must be an integer from 250000 to 100000000 bits per second");
187
+ return value;
188
+ };
189
+ for (int i = 1; i < argc; ++i) {
190
+ const std::string option = argv[i];
191
+ if (option == "--help") {
192
+ std::cout << "Usage: relay-engine [--bind ADDRESS] [--port PORT] [--viewer-dir DIR]\n"
193
+ " [--backend NAME] [--output NAME] [--check]\n"
194
+ " [--fps N] [--bitrate-min BPS] [--bitrate-start BPS] [--bitrate-max BPS]\n"
195
+ " [--token-file FILE [--public-origin https://HOST[:PORT]]]\n"
196
+ " [--tls-cert FILE --tls-key FILE | --behind-tls-proxy]\n"
197
+ " [--insecure-local: unauthenticated, isolated development network only]\n"
198
+ "FPS is 10 to 120; bitrates are 250000 to 100000000 bits per second with\n"
199
+ "min <= start <= max. Non-loopback --bind needs --token-file;\n"
200
+ "--public-origin also needs TLS or --behind-tls-proxy.\n"
201
+ "--check initializes the backend and exits without starting capture or the server.\n"
202
+ "Attach to DISPLAY using the caller's XAUTHORITY. Defaults: 127.0.0.1:8080, 60 fps,\n"
203
+ "1000000/8000000/40000000 bps.\n"
204
+ << "Compiled backends: " << backendNames() << '\n';
205
+ return false;
206
+ }
207
+ if (option == "--behind-tls-proxy") { config.proxy = true; continue; }
208
+ if (option == "--insecure-local") { config.insecure_local = true; continue; }
209
+ if (option == "--check") { config.check = true; continue; }
210
+ if (++i == argc) throw std::runtime_error("Missing value for " + option);
211
+ const std::string value = argv[i];
212
+ if (option == "--bind") config.bind = value;
213
+ else if (option == "--backend") config.backend = value;
214
+ else if (option == "--output") config.output = value;
215
+ else if (option == "--port") {
216
+ uint64_t port;
217
+ if (!unsignedNumber(value, port) || !port || port > 65535) throw std::runtime_error("Invalid port");
218
+ config.port = unsigned(port);
219
+ } else if (option == "--fps") {
220
+ uint64_t fps;
221
+ if (!unsignedNumber(value, fps) || fps < 10 || fps > 120)
222
+ throw std::runtime_error("FPS must be an integer from 10 to 120");
223
+ config.fps = unsigned(fps);
224
+ } else if (option == "--bitrate-min") config.bitrate_min = bitrate(value);
225
+ else if (option == "--bitrate-start") config.bitrate_start = bitrate(value);
226
+ else if (option == "--bitrate-max") config.bitrate_max = bitrate(value);
227
+ else if (option == "--viewer-dir") config.viewer = value;
228
+ else if (option == "--public-origin") {
229
+ if (value.rfind("https://", 0) != 0 || value.size() <= 8 || value.find_first_of("/?#@\\ \t\r\n", 8) != std::string::npos)
230
+ throw std::runtime_error("Public origin must be an HTTPS origin without path or credentials");
231
+ config.origin = value; config.authority = value.substr(8);
232
+ } else if (option == "--token-file") {
233
+ if (!privateTokenFile(value))
234
+ throw std::runtime_error("Token file must be private, owned by this user and contain 64 hexadecimal characters");
235
+ std::ifstream file(value); std::getline(file, config.token);
236
+ if (!file || config.token.size() != 64 || config.token.find_first_not_of("0123456789abcdef") != std::string::npos)
237
+ throw std::runtime_error("Token must contain 64 lowercase hexadecimal characters");
238
+ } else if (option == "--tls-cert") config.cert = value;
239
+ else if (option == "--tls-key") config.key = value;
240
+ else throw std::runtime_error("Unknown option: " + option);
241
+ }
242
+ backendFor(config.backend);
243
+ if (config.cert.empty() != config.key.empty() || (config.proxy && !config.cert.empty()))
244
+ throw std::runtime_error("Choose a TLS certificate/key pair or a TLS proxy");
245
+ if (config.bitrate_min > config.bitrate_start || config.bitrate_start > config.bitrate_max)
246
+ throw std::runtime_error("Bitrates must satisfy min <= start <= max");
247
+ if (!config.origin.empty() && config.token.empty()) throw std::runtime_error("Public origin requires a token");
248
+ if (config.insecure_local && (!config.token.empty() || !config.origin.empty() || !config.cert.empty() || config.proxy))
249
+ throw std::runtime_error("--insecure-local cannot be combined with remote access options");
250
+ if (config.bind != "127.0.0.1" && !config.insecure_local && (config.token.empty() || (!config.origin.empty() && config.cert.empty() && !config.proxy)))
251
+ throw std::runtime_error("Non-loopback binding requires a token; a public origin also requires TLS or --behind-tls-proxy");
252
+ if (config.insecure_local) std::cerr << "WARNING: unauthenticated development listener; isolate it and publish to host loopback only\n";
253
+ if (!config.check) for (const char* name : {"index.html", "viewer.js"})
254
+ if (!std::filesystem::is_regular_file(std::filesystem::path(config.viewer)/name)) throw std::runtime_error("Viewer assets missing; use --viewer-dir");
255
+ return true;
256
+ }
257
+ } // namespace relay
@@ -0,0 +1,24 @@
1
+ #pragma once
2
+
3
+ #include <libwebsockets.h>
4
+ #include <cstdint>
5
+ #include <string>
6
+
7
+ namespace relay {
8
+ struct Config {
9
+ std::string bind = "127.0.0.1", viewer, token, origin, authority, cert, key, backend, output;
10
+ unsigned port = 8080;
11
+ unsigned fps = 60;
12
+ uint64_t bitrate_min = 1000000, bitrate_start = 8000000, bitrate_max = 40000000;
13
+ bool proxy = false, insecure_local = false, check = false;
14
+ };
15
+ bool unsignedNumber(const std::string& text, uint64_t& value);
16
+ /** Fills config from argv and throws std::runtime_error on invalid options; returns false after printing --help. */
17
+ bool parseConfig(int argc, char** argv, Config& config);
18
+ bool secretEqual(const std::string& a, const std::string& b);
19
+ std::string header(lws* wsi, lws_token_indexes token);
20
+ bool authenticated(const Config& config, lws* wsi, bool websocket = false);
21
+ bool loopbackOrigin(const std::string& origin);
22
+ bool loopbackHost(const std::string& host);
23
+ bool localRequest(const Config& config, lws* wsi);
24
+ } // namespace relay
@@ -0,0 +1,82 @@
1
+ #include "server.hpp"
2
+ #include "backend.hpp"
3
+ #include <csignal>
4
+ #include <iostream>
5
+ #include <unistd.h>
6
+ #if defined(__GLIBC__)
7
+ #include <malloc.h>
8
+ #endif
9
+
10
+ namespace {
11
+ volatile std::sig_atomic_t stopping = 0;
12
+ void signalStop(int) { stopping = 1; }
13
+ lws_sorted_usec_list_t heartbeat{};
14
+ lws_context* heartbeatContext = nullptr;
15
+ void heartbeatTick(lws_sorted_usec_list_t*) {
16
+ lws_sul_schedule(heartbeatContext, 0, &heartbeat, heartbeatTick, 100000);
17
+ }
18
+ } // namespace
19
+ int main(int argc, char** argv) {
20
+ #if defined(__GLIBC__)
21
+ mallopt(M_ARENA_MAX, 2);
22
+ #endif
23
+ relay::Config config;
24
+ try {
25
+ if (!relay::parseConfig(argc, argv, config)) return 0;
26
+ } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 2; }
27
+ const auto& backend = relay::backendFor(config.backend);
28
+ if (!backend.initialize(config.output)) { std::cerr << "Native backend initialization failed\n"; return 1; }
29
+ if (config.check) return 0;
30
+ std::signal(SIGINT, signalStop); std::signal(SIGTERM, signalStop);
31
+ relay::Server s(config);
32
+ std::string captureError;
33
+ if (!s.capture.start(captureError)) {
34
+ std::cerr << "Capture startup failed: " << captureError << '\n';
35
+ s.capture.stop(); return 1;
36
+ }
37
+ try {
38
+ s.input = std::make_unique<relay::InputController>(backend.input());
39
+ const auto dimensions = s.input->dimensions();
40
+ relay::requireSurfaceSize(dimensions.first, dimensions.second);
41
+ s.width = dimensions.first; s.height = dimensions.second;
42
+ } catch (const std::exception& error) { std::cerr << error.what() << '\n'; s.capture.stop(); return 1; }
43
+ lws_protocols protocols[] = {{"http", relay::callback, sizeof(relay::HttpResponse), 4096, 0, nullptr, 0}, {"nsl1", relay::callback, sizeof(relay::HttpResponse), 4096, 0, nullptr, 0}, {nullptr, nullptr, 0, 0, 0, nullptr, 0}};
44
+ lws_context_creation_info info{};
45
+ info.port=int(config.port); info.iface=config.bind.c_str(); info.protocols=protocols; info.user=&s;
46
+ info.fd_limit_per_thread = 1024;
47
+ // shortcut: native TLS supports HTTP/1.1 only, enable HTTP/2 after multiplexed-response lifecycle tests.
48
+ info.alpn = "http/1.1";
49
+ if (!config.cert.empty()) {
50
+ info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
51
+ info.ssl_cert_filepath = config.cert.c_str(); info.ssl_private_key_filepath = config.key.c_str();
52
+ }
53
+ info.uid=-1; info.gid=-1;
54
+ s.context=lws_create_context(&info);
55
+ if (!s.context) { std::cerr << "Cannot listen on " << config.bind << ':' << config.port << '\n'; s.capture.stop(); return 1; }
56
+ s.wake->set(s.context);
57
+ s.screenshot.start(s.context);
58
+ heartbeatContext=s.context;
59
+ lws_sul_schedule(s.context, 0, &heartbeat, heartbeatTick, 100000);
60
+ int result = 0;
61
+ std::cerr << "Relay listening on " << config.bind << ':' << config.port << '\n';
62
+ std::cout << "{\"ready\":true,\"pid\":" << getpid() << ",\"port\":" << config.port << "}" << std::endl;
63
+ while (!stopping) {
64
+ captureError = s.capture.error();
65
+ if (!captureError.empty()) {
66
+ std::cerr << "Capture worker failed: " << captureError << '\n';
67
+ result = 1; break;
68
+ }
69
+ if (lws_service(s.context, 100) < 0) {
70
+ std::cerr << "WebSocket service failed\n";
71
+ result = 1; break;
72
+ }
73
+ }
74
+ s.end(); s.capture.stop(); s.screenshot.stop(); s.input.reset();
75
+ const auto stats=s.capture.stats();
76
+ std::cerr << "capture_stats captures=" << stats.captures << " encoded=" << stats.encoded
77
+ << " capture_ns=" << stats.capture_ns << " convert_ns=" << stats.convert_ns << " encode_ns=" << stats.encode_ns << '\n';
78
+ lws_sul_cancel(&heartbeat);
79
+ s.wake->set(nullptr);
80
+ lws_context_destroy(s.context); s.context=nullptr; heartbeatContext=nullptr;
81
+ return result;
82
+ }
@@ -0,0 +1,47 @@
1
+ #include "metrics.hpp"
2
+ #include "config.hpp"
3
+ #include <array>
4
+ #include <fstream>
5
+ #include <sstream>
6
+
7
+ namespace relay {
8
+ namespace {
9
+ bool readSmallFile(const char* path, std::string& text) {
10
+ std::ifstream file(path, std::ios::binary);
11
+ if (!file) return false;
12
+ std::array<char, 16384> buffer{};
13
+ file.read(buffer.data(), buffer.size());
14
+ const auto count = file.gcount();
15
+ if (file.bad() || (!file.eof() && file.peek() != std::char_traits<char>::eof())) return false;
16
+ text.assign(buffer.data(), size_t(count));
17
+ return !text.empty();
18
+ }
19
+ } // namespace
20
+ bool statValue(const std::string& text, const std::string& wanted, uint64_t& value) {
21
+ std::istringstream lines(text);
22
+ std::string line;
23
+ bool found = false;
24
+ while (std::getline(lines, line)) {
25
+ std::istringstream fields(line);
26
+ std::string key, number, extra;
27
+ if (!(fields >> key) || key != wanted) continue;
28
+ if (found || !(fields >> number) || (fields >> extra) || !unsignedNumber(number, value)) return false;
29
+ found = true;
30
+ }
31
+ return found;
32
+ }
33
+ bool cgroupMetrics(std::string& json) {
34
+ std::string cpu, memory, memoryStats;
35
+ uint64_t usage = 0, current = 0, inactive = 0;
36
+ if (!readSmallFile("/sys/fs/cgroup/cpu.stat", cpu) ||
37
+ !readSmallFile("/sys/fs/cgroup/memory.current", memory) ||
38
+ !readSmallFile("/sys/fs/cgroup/memory.stat", memoryStats)) return false;
39
+ const auto first = memory.find_first_not_of(" \t\r\n");
40
+ const auto last = memory.find_last_not_of(" \t\r\n");
41
+ if (first == std::string::npos || !unsignedNumber(memory.substr(first, last-first+1), current) ||
42
+ !statValue(cpu, "usage_usec", usage) || !statValue(memoryStats, "inactive_file", inactive)) return false;
43
+ json = "{\"usage_usec\":"+std::to_string(usage)+",\"memory_current\":"+std::to_string(current)+
44
+ ",\"inactive_file\":"+std::to_string(inactive)+"}";
45
+ return true;
46
+ }
47
+ } // namespace relay
@@ -0,0 +1,10 @@
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+ #include <string>
5
+
6
+ namespace relay {
7
+ bool statValue(const std::string& text, const std::string& wanted, uint64_t& value);
8
+ /** Reads cgroup v2 usage into a JSON object; returns false when any file is missing or malformed. */
9
+ bool cgroupMetrics(std::string& json);
10
+ } // namespace relay
@@ -0,0 +1,108 @@
1
+ #include "screenshot.hpp"
2
+ #include "backend.hpp"
3
+ #include "server.hpp"
4
+ #include "core/capture-source.hpp"
5
+ #include <libwebsockets.h>
6
+ #include <zlib.h>
7
+ #include <memory>
8
+ #include <stdexcept>
9
+
10
+ namespace relay {
11
+ namespace {
12
+ void require(bool ok, const char* error) {
13
+ if (!ok) throw std::runtime_error(error);
14
+ }
15
+ void append32(std::vector<uint8_t>& bytes, uint32_t value) {
16
+ bytes.push_back(value >> 24); bytes.push_back(value >> 16);
17
+ bytes.push_back(value >> 8); bytes.push_back(value);
18
+ }
19
+ void chunk(std::vector<uint8_t>& bytes, const char* type, const uint8_t* data, size_t size) {
20
+ append32(bytes, static_cast<uint32_t>(size));
21
+ const size_t start = bytes.size();
22
+ bytes.insert(bytes.end(), type, type + 4);
23
+ if (size) bytes.insert(bytes.end(), data, data + size);
24
+ append32(bytes, static_cast<uint32_t>(crc32(0, bytes.data() + start, size + 4)));
25
+ }
26
+ struct Resources {
27
+ std::unique_ptr<CaptureSource> source;
28
+ int width = 0, height = 0;
29
+ void init(const Backend& backend) {
30
+ source = backend.capture();
31
+ require(bool(source), "screenshot source unavailable");
32
+ const auto dimensions = source->dimensions();
33
+ width = dimensions.first; height = dimensions.second;
34
+ }
35
+ std::vector<uint8_t> capture() {
36
+ const size_t row = size_t(width) * 3 + 1;
37
+ source->drainDamage();
38
+ const auto image = source->capture();
39
+ require(image.data && image.width == width && image.height == height && image.stride >= width * 4 &&
40
+ image.stride <= width * 8 && (image.format == PixelFormat::BGRA || image.format == PixelFormat::ARGB),
41
+ "unsupported screenshot frame");
42
+ std::vector<uint8_t> pixels(size_t(height) * row);
43
+ for (int y = 0; y < height; ++y) {
44
+ const auto* source = image.data + y * image.stride;
45
+ auto* target = pixels.data() + y * row + 1;
46
+ for (int x = 0; x < width; ++x) {
47
+ target[x * 3] = source[x * 4 + (image.format == PixelFormat::BGRA ? 2 : 1)];
48
+ target[x * 3 + 1] = source[x * 4 + (image.format == PixelFormat::BGRA ? 1 : 2)];
49
+ target[x * 3 + 2] = source[x * 4 + (image.format == PixelFormat::BGRA ? 0 : 3)];
50
+ }
51
+ }
52
+ uLongf compressed_size = compressBound(pixels.size());
53
+ std::vector<uint8_t> compressed(compressed_size);
54
+ require(compress2(compressed.data(), &compressed_size, pixels.data(), pixels.size(), Z_DEFAULT_COMPRESSION) == Z_OK,
55
+ "PNG encode failed");
56
+ std::vector<uint8_t> header;
57
+ append32(header, uint32_t(width)); append32(header, uint32_t(height));
58
+ header.insert(header.end(), {8, 2, 0, 0, 0});
59
+ std::vector<uint8_t> result{137, 80, 78, 71, 13, 10, 26, 10};
60
+ chunk(result, "IHDR", header.data(), header.size());
61
+ chunk(result, "IDAT", compressed.data(), compressed_size);
62
+ chunk(result, "IEND", nullptr, 0);
63
+ require(result.size() <= 8 * 1024 * 1024, "PNG output exceeds 8 MiB");
64
+ return result;
65
+ }
66
+ };
67
+ } // namespace
68
+ void Screenshot::start(lws_context* context) {
69
+ worker_ = std::thread([this, context] { run(context); });
70
+ }
71
+ bool Screenshot::request() {
72
+ std::lock_guard<std::mutex> lock(mutex_);
73
+ if (busy_ || stopping_) return false;
74
+ busy_ = requested_ = true; ready_.notify_one(); return true;
75
+ }
76
+ bool Screenshot::take(std::vector<uint8_t>& bytes, std::string& error) {
77
+ std::lock_guard<std::mutex> lock(mutex_);
78
+ if (!complete_) return false;
79
+ bytes = std::move(bytes_); error = std::move(error_);
80
+ complete_ = false; return true;
81
+ }
82
+ void Screenshot::finish() { std::lock_guard<std::mutex> lock(mutex_); busy_ = false; }
83
+ void Screenshot::stop() {
84
+ { std::lock_guard<std::mutex> lock(mutex_); stopping_ = true; ready_.notify_one(); }
85
+ if (worker_.joinable()) worker_.join();
86
+ }
87
+ void Screenshot::run(lws_context* context) {
88
+ const auto& backend = backendFor(static_cast<Server*>(lws_context_user(context))->config.backend);
89
+ std::unique_ptr<Resources> resources;
90
+ for (;;) {
91
+ { std::unique_lock<std::mutex> lock(mutex_);
92
+ ready_.wait(lock, [this] { return stopping_ || requested_; });
93
+ if (stopping_) return;
94
+ requested_ = false;
95
+ }
96
+ std::vector<uint8_t> result;
97
+ std::string error;
98
+ try {
99
+ if (!resources) { resources = std::make_unique<Resources>(); resources->init(backend); }
100
+ result = resources->capture();
101
+ } catch (const std::exception& failure) { error = failure.what(); resources.reset(); }
102
+ { std::lock_guard<std::mutex> lock(mutex_);
103
+ bytes_ = std::move(result); error_ = std::move(error); complete_ = true;
104
+ }
105
+ lws_cancel_service(context);
106
+ }
107
+ }
108
+ } // namespace relay