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