Line data Source code
1 280 : // SPDX-License-Identifier: LGPL-2.1-or-later
2 : import { EventEmitter } from '../event';
3 :
4 : import type { JsonObject } from './common';
5 : import { calculate_application, calculate_url } from './location-utils';
6 : import { ParentWebSocket } from './parentwebsocket';
7 :
8 : type ControlCallback = (message: JsonObject) => void;
9 : type MessageCallback = (data: string | Uint8Array) => void;
10 : type FilterCallback = (message: string | ArrayBuffer, channel: string | null, control: JsonObject | null) => boolean;
11 :
12 127 : class TransportGlobals {
13 127 : default_transport: Transport | null = null;
14 127 : reload_after_disconnect = false;
15 127 : expect_disconnect = false;
16 127 : init_callback: ControlCallback | null = null;
17 127 : default_host: string | null = null;
18 127 : process_hints: ControlCallback | null = null;
19 127 : incoming_filters: FilterCallback[] = [];
20 280 : }
21 :
22 : // the transport globals must be a *real* global, across bundles -- i.e. a <script>ed cockpit.js and bundled
23 : // channel.ts must share the same instance, to avoid initializing transports (and thus initing) twice
24 :
25 : declare global {
26 : interface Document {
27 : cockpit_transport_globals?: TransportGlobals;
28 : }
29 : }
30 :
31 280 : if (!document.cockpit_transport_globals)
32 151 : document.cockpit_transport_globals = new TransportGlobals();
33 :
34 280 : export const transport_globals = document.cockpit_transport_globals;
35 :
36 1 : window.addEventListener('beforeunload', () => {
37 1 : transport_globals.expect_disconnect = true;
38 1 : }, false);
39 :
40 138 : function transport_debug(...args: unknown[]) {
41 33 : if (window.debugging == "all" || window.debugging?.includes("channel"))
42 30 : console.debug(...args);
43 138 : }
44 :
45 : /* Private Transport class */
46 127 : class Transport extends EventEmitter<{ ready(): void }> {
47 : application: string;
48 : ready: boolean;
49 :
50 127 : #last_channel = 0;
51 127 : #channel_seed = "";
52 127 : #ws: WebSocket | ParentWebSocket | null;
53 127 : #ignore_health_check = false;
54 127 : #got_message = false;
55 127 : #check_health_timer;
56 127 : #control_cbs: Record<string, ControlCallback> = {};
57 127 : #message_cbs: Record<string, MessageCallback> = {};
58 127 : #waiting_for_init = true;
59 :
60 127 : constructor() {
61 127 : super();
62 :
63 127 : this.application = calculate_application();
64 :
65 127 : if (window.mock)
66 19 : window.mock.last_transport = this;
67 :
68 : /* See if we should communicate via parent */
69 120 : if (window.parent !== window && window.name.indexOf("cockpit1:") === 0) {
70 120 : this.#ws = new ParentWebSocket(window.parent);
71 120 : } else {
72 127 : const ws_loc = calculate_url();
73 127 : transport_debug("connecting to " + ws_loc);
74 127 : this.#ws = new WebSocket(ws_loc, "cockpit1");
75 :
76 13 : this.#check_health_timer = window.setInterval(() => {
77 13 : if (this.ready && this.#ws)
78 13 : this.#ws.send("\n{ \"command\": \"ping\" }");
79 0 : if (!this.#got_message) {
80 0 : if (this.#ignore_health_check) {
81 0 : console.log("health check failure ignored");
82 0 : } else {
83 0 : console.log("health check failed");
84 0 : this.close({ problem: "timeout" });
85 0 : }
86 0 : }
87 13 : this.#got_message = false;
88 13 : }, 30000);
89 127 : }
90 :
91 127 : this.ready = false;
92 :
93 124 : this.#ws.onopen = () => {
94 124 : if (this.#ws) {
95 124 : if (typeof this.#ws.binaryType !== "undefined")
96 124 : this.#ws.binaryType = "arraybuffer";
97 124 : this.#ws.send("\n{ \"command\": \"init\", \"version\": 1 }");
98 124 : }
99 124 : };
100 :
101 25 : this.#ws.onclose = () => {
102 25 : transport_debug("WebSocket onclose");
103 25 : this.#ws = null;
104 16 : if (transport_globals.reload_after_disconnect) {
105 16 : transport_globals.expect_disconnect = true;
106 : // @ts-expect-error force-reload parameter is Firefox-only
107 16 : window.location.reload(true);
108 16 : }
109 25 : this.close();
110 25 : };
111 :
112 124 : this.#ws.onmessage = event => this.dispatch_data(event);
113 127 : }
114 :
115 : /* Called when ready for channels to interact */
116 127 : #ready_for_channels() {
117 127 : if (!this.ready) {
118 127 : this.ready = true;
119 127 : this.emit("ready");
120 127 : }
121 127 : }
122 :
123 124 : #process_init(options: JsonObject) {
124 19 : if (options.problem) {
125 19 : this.close({ problem: options.problem });
126 19 : return;
127 19 : }
128 :
129 19 : if (options.version !== 1) {
130 19 : console.error("received unsupported version in init message: " + options.version);
131 19 : this.close({ problem: "not-supported" });
132 19 : return;
133 19 : }
134 :
135 124 : if (options["channel-seed"])
136 124 : this.#channel_seed = String(options["channel-seed"]);
137 124 : if (typeof options.host === 'string')
138 124 : transport_globals.default_host = options.host;
139 :
140 124 : if (transport_globals.init_callback)
141 124 : transport_globals.init_callback(options);
142 :
143 124 : if (this.#waiting_for_init) {
144 124 : this.#waiting_for_init = false;
145 124 : this.#ready_for_channels();
146 124 : }
147 124 : }
148 :
149 124 : #process_control(data: JsonObject) {
150 124 : const channel = data.channel;
151 :
152 : /* Init message received */
153 124 : if (data.command == "init") {
154 124 : this.#process_init(data);
155 19 : } else if (this.#waiting_for_init) {
156 19 : this.#waiting_for_init = false;
157 19 : if (data.command != "close" || channel) {
158 19 : console.error("received message before init: ", data.command);
159 19 : data = { problem: "protocol-error" };
160 19 : }
161 19 : this.close(data);
162 :
163 : /* Any pings get sent back as pongs */
164 19 : } else if (data.command == "ping") {
165 108 : data.command = "pong";
166 108 : this.send_control(data);
167 32 : } else if (data.command == "pong") {
168 : /* Any pong commands are ignored */
169 32 : } else if (data.command == "hint") {
170 120 : if (transport_globals.process_hints)
171 120 : transport_globals.process_hints(data);
172 120 : } else if (typeof channel === 'string') {
173 124 : const func = this.#control_cbs[channel];
174 124 : if (func)
175 124 : func(data);
176 124 : }
177 124 : }
178 :
179 124 : #process_message(channel: string, payload: string | Uint8Array) {
180 124 : const func = this.#message_cbs[channel];
181 124 : if (func)
182 124 : func(payload);
183 124 : }
184 :
185 124 : dispatch_data(arg: MessageEvent<string | ArrayBuffer>): boolean {
186 124 : this.#got_message = true;
187 :
188 124 : const message = arg.data;
189 124 : let channel;
190 124 : let control: JsonObject | null = null;
191 124 : let payload: string | Uint8Array | null = null;
192 :
193 23 : if (message instanceof ArrayBuffer) {
194 : /* Binary message */
195 23 : const frame = new window.Uint8Array(message);
196 23 : const nl = frame.indexOf(10);
197 :
198 23 : channel = new TextDecoder().decode(frame.subarray(0, nl));
199 19 : if (!channel) {
200 19 : console.warn('Received invalid binary message without a channel');
201 19 : return false;
202 19 : }
203 :
204 23 : payload = frame.subarray(nl + 1);
205 23 : transport_debug("recv binary message:", control, payload);
206 23 : } else {
207 124 : const nl = message.indexOf('\n');
208 124 : channel = message.substring(0, nl);
209 124 : if (nl == 0) {
210 124 : control = JSON.parse(message);
211 124 : transport_debug("recv control:", control);
212 124 : } else {
213 124 : payload = message.substring(nl + 1);
214 124 : transport_debug("recv text message:", channel, payload);
215 124 : }
216 124 : }
217 :
218 124 : for (const filter of transport_globals.incoming_filters)
219 120 : if (filter(message, channel, control) === false)
220 120 : return false;
221 :
222 124 : if (control)
223 124 : this.#process_control(control);
224 124 : else if (channel && payload)
225 124 : this.#process_message(channel, payload);
226 :
227 124 : return true;
228 124 : }
229 :
230 25 : close(options?: JsonObject): void {
231 25 : if (!options)
232 25 : options = { problem: "disconnected" };
233 25 : options.command = "close";
234 25 : window.clearInterval(this.#check_health_timer);
235 25 : const ows = this.#ws;
236 25 : this.#ws = null;
237 25 : if (ows)
238 20 : ows.close();
239 25 : if (transport_globals.expect_disconnect)
240 25 : return;
241 21 : this.#ready_for_channels(); /* ready to fail */
242 :
243 : /* Broadcast to everyone */
244 21 : for (const chan in this.#control_cbs)
245 21 : this.#control_cbs[chan].apply(null, [options]);
246 25 : }
247 :
248 127 : next_channel(): string {
249 127 : this.#last_channel++;
250 127 : return this.#channel_seed + String(this.#last_channel);
251 127 : }
252 :
253 136 : send_data(data: string | ArrayBuffer): boolean {
254 32 : if (!this.#ws) {
255 32 : return false;
256 32 : }
257 133 : this.#ws.send(data);
258 133 : return true;
259 136 : }
260 :
261 136 : send_message(payload: string | ArrayBuffer | Uint8Array, channel: string): boolean {
262 136 : if (channel)
263 136 : transport_debug("send " + channel, payload);
264 :
265 : else
266 136 : transport_debug("send control:", payload);
267 :
268 28 : if (typeof payload !== 'string') {
269 : /* A binary message */
270 28 : const body = payload instanceof ArrayBuffer ? new Uint8Array(payload) : payload;
271 :
272 : // We want to create channel + '\n' + body in binary
273 28 : const header = new TextEncoder().encode(`${channel}\n`);
274 28 : const output = new Uint8Array(header.length + body.length);
275 28 : output.set(header);
276 28 : output.set(body, header.length);
277 28 : return this.send_data(output.buffer);
278 28 : } else {
279 : /* A string message */
280 136 : return this.send_data(channel.toString() + "\n" + payload);
281 136 : }
282 136 : }
283 :
284 138 : send_control(data: JsonObject): boolean {
285 33 : if (!this.#ws && (data.command == "close" || data.command == "kill"))
286 30 : return false; /* don't complain if closed and closing */
287 138 : if (this.#check_health_timer &&
288 30 : data.command == "hint" && data.hint == "ignore_transport_health_check") {
289 : /* This is for us, process it directly. */
290 30 : this.#ignore_health_check = !!data.data;
291 30 : return false;
292 30 : }
293 138 : return this.send_message(JSON.stringify(data), "");
294 138 : }
295 :
296 127 : register(channel: string, control_cb: ControlCallback, message_cb: MessageCallback): void {
297 127 : this.#control_cbs[channel] = control_cb;
298 127 : this.#message_cbs[channel] = message_cb;
299 127 : }
300 :
301 135 : unregister(channel: string): void {
302 135 : delete this.#control_cbs[channel];
303 135 : delete this.#message_cbs[channel];
304 135 : }
305 280 : }
306 : export type { Transport };
307 :
308 282 : export function ensure_transport(callback: (transport: Transport) => void) {
309 282 : if (!transport_globals.default_transport)
310 160 : transport_globals.default_transport = new Transport();
311 282 : const transport = transport_globals.default_transport;
312 273 : if (transport.ready) {
313 273 : callback(transport);
314 157 : } else {
315 138 : transport.on("ready", () => {
316 138 : callback(transport);
317 138 : });
318 166 : }
319 282 : }
320 :
321 : /* Always close the transport explicitly: allows parent windows to track us */
322 41 : window.addEventListener("unload", () => {
323 41 : if (transport_globals.default_transport)
324 41 : transport_globals.default_transport.close();
325 41 : });
|