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