-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoverride-websocket-signaling.js
More file actions
392 lines (368 loc) · 16.3 KB
/
override-websocket-signaling.js
File metadata and controls
392 lines (368 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
//@ts-check
const thisAppStartedAt = Date.now();
/** @type {undefined | number} */
let serverAddress = undefined;
const whoIsTheServerRequest = new Uint8Array([42, 42, 42, 42]);
/** @type {Promise<number>} */
const serverAddressP = new Promise((resolve) => {
// If someone responds within WHO_IS_THE_SERVER_TIMEOUT ms,
// there is a server already.
// If not, we are the server.
/**
* The longer the wait the more reliable it is,
* because P2P connection establishment (including signaling)
* may also take a while: it's not just about the ping between peers.
*
* Note that during this period we'll just idle
* and the most heavy tasks will start being worked on
* only after this timeout (i.e. after `preRun` has finished).
* This is why we set it to 0.
* Historically we did have to wait, but then we added late server discovery
* (see `SERVER_ADDRESS_QUERY_KEY`), so waiting is no longer necessary.
*
* At this point we should probably refactor this.
*
* Note that not waiting at all means that we'll always start our own server
* before trying to connect to another one.
* This seems to result a bigger delay due to us being busy
* creating the server instead of immediately handling
* the "someone else is the server" message.
* But it's probably better than always making the first player
* wait extra `WHO_IS_THE_SERVER_TIMEOUT` ms.
*/
const WHO_IS_THE_SERVER_TIMEOUT = 0;
if (globalThis.webxdc) {
/**
* @param {number} resolveVal
*/
const resolveAndCleanUp = (resolveVal) => {
resolve(resolveVal);
clearTimeout(timeoutId);
clearInterval(requestIntervalId);
};
globalThis.globalWebxdcRealtimeListener = (
/** @type {Uint8Array} */ uint8Array
) => {
// Yes, this is pretty stupid.
// We probably want a proper "enum" value instead of these magic numbers.
const isWhoIsTheServerRequest =
uint8Array.length === 4 &&
uint8Array[0] === 42 &&
uint8Array[1] === 42 &&
uint8Array[2] === 42 &&
uint8Array[3] === 42;
if (isWhoIsTheServerRequest) {
if (serverAddress === myAddress) {
globalThis.webxdcRealtimeChannel.send(
makeWhoIsTheServerResponse(serverAddress, thisAppStartedAt)
);
}
return;
}
const isWhoIsTheServerResponse =
uint8Array.length === WHO_IS_THE_SERVER_RESPONSE_SIZE &&
uint8Array[0] === 43 &&
uint8Array[1] === 43 &&
uint8Array[2] === 43 &&
uint8Array[3] === 43;
if (isWhoIsTheServerResponse) {
const responseServerAddress = new Uint32Array(uint8Array.buffer)[1];
const responseServerStartedAt = new Float64Array(
uint8Array.buffer,
8,
1
)[0];
if (responseServerStartedAt < thisAppStartedAt) {
// That peer should be the server, because they opened the game first.
resolveAndCleanUp(responseServerAddress);
if (
serverAddress != undefined &&
serverAddress != responseServerAddress
) {
// We are connected to the wrong server.
// Most likely we are the server, but we could also be already
// connected to someone else.
//
// Reload the page, set server address.
// It would be nice to simply execute a Quake command,
// but I couldn't get it to work with stdin.
//
// This is only useful if we were unable to find the server
// within `WHO_IS_THE_SERVER_TIMEOUT`, i.e. if the connection
// is quite slow.
//
// TODO don't reload if we're in the menu
// or picking game files or something,
// i.e. if we still have a chance to connect without reloading.
const newUrl = new URL(location.href);
newUrl.searchParams.append(
SERVER_ADDRESS_QUERY_KEY,
responseServerAddress.toString(10)
);
location.replace(newUrl);
}
}
return;
}
};
globalThis.webxdcRealtimeChannel.send(whoIsTheServerRequest);
// For some reason Android won't discover other servers,
// probably because the first "ping" message doesn't get sent.
// Let's retry!
const requestIntervalId = setInterval(() => {
globalThis.webxdcRealtimeChannel.send(whoIsTheServerRequest);
}, 300);
const timeoutId = setTimeout(() => {
globalThis.webxdcRealtimeChannel.send(
makeWhoIsTheServerResponse(myAddress, thisAppStartedAt)
);
resolveAndCleanUp(myAddress);
}, WHO_IS_THE_SERVER_TIMEOUT);
// It would probably make sense for this code to be at the top,
// but due to the fact that this is all horribly written,
// we wouldn't set `globalWebxdcRealtimeListener` then,
// and `resolveAndCleanUp` would be undefined.
const SERVER_ADDRESS_QUERY_KEY = "serverAddress";
const query = new URLSearchParams(window.location.search);
const presetServerAddress = query.get(SERVER_ADDRESS_QUERY_KEY);
if (presetServerAddress != null) {
const cleanedUrl = new URL(location.href);
cleanedUrl.searchParams.delete(SERVER_ADDRESS_QUERY_KEY);
history.replaceState(null, "", cleanedUrl);
resolveAndCleanUp(parseInt(presetServerAddress, 10));
}
} else {
/**
* @param {number} resolveVal
*/
const resolveAndCleanUp = (resolveVal) => {
resolve(resolveVal);
clearTimeout(timeoutId);
};
const whoIsTheServerChannel = new BroadcastChannel("whoIsTheServerChannel");
whoIsTheServerChannel.addEventListener("message", (event) => {
if (event.data === "whoIsTheServer") {
if (myAddress === serverAddress) {
whoIsTheServerChannel.postMessage({
serverAddress: serverAddress,
});
}
}
});
/**
* @param {MessageEvent} event
*/
const listener = (event) => {
if (event.data.serverAddress) {
resolveAndCleanUp(event.data.serverAddress);
whoIsTheServerChannel.removeEventListener("message", listener);
}
};
whoIsTheServerChannel.addEventListener("message", listener);
whoIsTheServerChannel.postMessage("whoIsTheServer");
const timeoutId = setTimeout(() => {
resolveAndCleanUp(myAddress);
whoIsTheServerChannel.postMessage({
serverAddress: myAddress,
});
whoIsTheServerChannel.removeEventListener("message", listener);
}, WHO_IS_THE_SERVER_TIMEOUT);
}
});
serverAddressP.then((newVal) => (serverAddress = newVal));
globalThis.serverAddressP = serverAddressP;
globalThis.amITheServerP = serverAddressP.then((serverAddress) => {
return serverAddress === myAddress;
});
amITheServerP.then((res) => {
console.log("amITheServer:", res);
if (res && globalThis.webxdc) {
// In case there is some network unreliability, keep checking
// if there is someone else trying to be a server,
// to be extra sure that all players end up on the same server.
setInterval(() => {
globalThis.webxdcRealtimeChannel.send(whoIsTheServerRequest);
}, 3000);
}
});
const WHO_IS_THE_SERVER_RESPONSE_SIZE = 4 + 4 + 8;
/**
* @param {number} serverAddress
* @param {number} serverStartedAt
*/
function makeWhoIsTheServerResponse(serverAddress, serverStartedAt) {
const buffer = new ArrayBuffer(WHO_IS_THE_SERVER_RESPONSE_SIZE);
const buffer1 = new Uint32Array(buffer);
buffer1[1] = serverAddress;
const response2 = new Float64Array(buffer, 8, 1);
response2[0] = serverStartedAt;
const response3 = new Uint8Array(buffer);
response3[0] = 43;
response3[1] = 43;
response3[2] = 43;
response3[3] = 43;
return response3;
}
globalThis.WebSocket = new Proxy(WebSocket, {
construct(target, argArray, newTarget, ...rest) {
console.log(
"WebSocket construction intercepted",
argArray,
"returning FakeWebSocket"
);
return new FakeWebSocket(...argArray);
},
});
/**
* @implements {WebSocket}
*/
class FakeWebSocket {
constructor(url, protocol) {
/**
* @type {InstanceType<typeof WebSocket>['onopen']}
*/
this.onopen = null;
/**
* @type {InstanceType<typeof WebSocket>['onmessage']}
*/
this.onmessage = null;
this.protocol = protocol;
this.url = url;
this.binaryType = "arraybuffer";
this._state = 1;
setTimeout(() => {
this.readyState = WebSocket.OPEN;
this.onopen?.({ type: "open" });
}, 0);
}
async send(data) {
console.log("FakeWebSocket.send()", data);
const state = this._state;
this._state++;
// Now it's OK to early-return
const amITheServer = await amITheServerP;
if (state === 1) {
// apparently the signaling server sends a TURN server.
this._mockSendServerToClientMessageBase64(
// ........................................╜}.&.............
// ...................<...............abcdefg12345678911....
// ..ABCDEFGHI1234567........dummy-relay.examle.com:3478.
"DAAAAAgADgAHAAgACAAAAAAAAAIQAAAAAAAKAAwABAAAAAgACgAAAL19AiYEAAAAAQAAABAAAAAMABQABwAIAAwAEAAMAAAAAAAAAjwAAAAIAAAAHAAAABIAAABhYmNkZWZnMTIzNDU2Nzg5MTEAABAAAABBQkNERUZHSEkxMjM0NTY3AAAAABsAAABkdW1teS1yZWxheS5leGFtbGUuY29tOjM0NzgA"
);
} else if (state === 2) {
if (amITheServer) {
// TODO feat: support more players?
// We could simply mock this WebSocket server "response"
// when a client actually connects.
const maxPlayers = 50;
for (let i = 0; i < maxPlayers; i++) {
// The actual peer ID doesn't matter, as long as it's different
// from the previous ones.
const peerIdLastByte = i;
// SDP offer.
// prettier-ignore
const data = new Uint8Array([
// ............................................AAAA....╩..
// .v=0..o=- 1111111111111111111 2 IN IP4 127.0.0.1..s=-..
// t=0 0..a=group:BUNDLE 0..a=extmap-allow-mixed..a=msid-s
// emantic: WMS..m=application 9 UDP/DTLS/SCTP webrtc-data
// channel..c=IN IP4 0.0.0.0..a=ice-ufrag:abcd..a=ice-pwd:
// abcdefghijklmnopqrstuvwx..a=ice-options:trickle..a=fing
// erprint:sha-256 00:11:22:33:44:55:66:77:88:99:11:22:33:
// 44:55:66:77:88:99:11:22:33:44:55:66:77:88:99:11:22:33:4
// 4..a=setup:actpass..a=mid:0..a=sctp-port:5000..a=max-me
// ssage-size:123456....
0x0C, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0E, 0x00, 0x07, 0x00, 0x08, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x10, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0A, 0x00, 0x10, 0x00, 0x08, 0x00, 0x07, 0x00, 0x0C, 0x00,
0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x41, 0x41, 0x41, peerIdLastByte,
0x04, 0x00, 0x00, 0x00, 0xCA, 0x01, 0x00, 0x00, 0x76, 0x3D, 0x30, 0x0D,
0x0A, 0x6F, 0x3D, 0x2D, 0x20, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
0x20, 0x32, 0x20, 0x49, 0x4E, 0x20, 0x49, 0x50, 0x34, 0x20, 0x31, 0x32,
0x37, 0x2E, 0x30, 0x2E, 0x30, 0x2E, 0x31, 0x0D, 0x0A, 0x73, 0x3D, 0x2D,
0x0D, 0x0A, 0x74, 0x3D, 0x30, 0x20, 0x30, 0x0D, 0x0A, 0x61, 0x3D, 0x67,
0x72, 0x6F, 0x75, 0x70, 0x3A, 0x42, 0x55, 0x4E, 0x44, 0x4C, 0x45, 0x20,
0x30, 0x0D, 0x0A, 0x61, 0x3D, 0x65, 0x78, 0x74, 0x6D, 0x61, 0x70, 0x2D,
0x61, 0x6C, 0x6C, 0x6F, 0x77, 0x2D, 0x6D, 0x69, 0x78, 0x65, 0x64, 0x0D,
0x0A, 0x61, 0x3D, 0x6D, 0x73, 0x69, 0x64, 0x2D, 0x73, 0x65, 0x6D, 0x61,
0x6E, 0x74, 0x69, 0x63, 0x3A, 0x20, 0x57, 0x4D, 0x53, 0x0D, 0x0A, 0x6D,
0x3D, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E,
0x20, 0x39, 0x20, 0x55, 0x44, 0x50, 0x2F, 0x44, 0x54, 0x4C, 0x53, 0x2F,
0x53, 0x43, 0x54, 0x50, 0x20, 0x77, 0x65, 0x62, 0x72, 0x74, 0x63, 0x2D,
0x64, 0x61, 0x74, 0x61, 0x63, 0x68, 0x61, 0x6E, 0x6E, 0x65, 0x6C, 0x0D,
0x0A, 0x63, 0x3D, 0x49, 0x4E, 0x20, 0x49, 0x50, 0x34, 0x20, 0x30, 0x2E,
0x30, 0x2E, 0x30, 0x2E, 0x30, 0x0D, 0x0A, 0x61, 0x3D, 0x69, 0x63, 0x65,
0x2D, 0x75, 0x66, 0x72, 0x61, 0x67, 0x3A, 0x61, 0x62, 0x63, 0x64, 0x0D,
0x0A, 0x61, 0x3D, 0x69, 0x63, 0x65, 0x2D, 0x70, 0x77, 0x64, 0x3A, 0x61,
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D,
0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x0D,
0x0A, 0x61, 0x3D, 0x69, 0x63, 0x65, 0x2D, 0x6F, 0x70, 0x74, 0x69, 0x6F,
0x6E, 0x73, 0x3A, 0x74, 0x72, 0x69, 0x63, 0x6B, 0x6C, 0x65, 0x0D, 0x0A,
0x61, 0x3D, 0x66, 0x69, 0x6E, 0x67, 0x65, 0x72, 0x70, 0x72, 0x69, 0x6E,
0x74, 0x3A, 0x73, 0x68, 0x61, 0x2D, 0x32, 0x35, 0x36, 0x20, 0x30, 0x30,
0x3A, 0x31, 0x31, 0x3A, 0x32, 0x32, 0x3A, 0x33, 0x33, 0x3A, 0x34, 0x34,
0x3A, 0x35, 0x35, 0x3A, 0x36, 0x36, 0x3A, 0x37, 0x37, 0x3A, 0x38, 0x38,
0x3A, 0x39, 0x39, 0x3A, 0x31, 0x31, 0x3A, 0x32, 0x32, 0x3A, 0x33, 0x33,
0x3A, 0x34, 0x34, 0x3A, 0x35, 0x35, 0x3A, 0x36, 0x36, 0x3A, 0x37, 0x37,
0x3A, 0x38, 0x38, 0x3A, 0x39, 0x39, 0x3A, 0x31, 0x31, 0x3A, 0x32, 0x32,
0x3A, 0x33, 0x33, 0x3A, 0x34, 0x34, 0x3A, 0x35, 0x35, 0x3A, 0x36, 0x36,
0x3A, 0x37, 0x37, 0x3A, 0x38, 0x38, 0x3A, 0x39, 0x39, 0x3A, 0x31, 0x31,
0x3A, 0x32, 0x32, 0x3A, 0x33, 0x33, 0x3A, 0x34, 0x34, 0x0D, 0x0A, 0x61,
0x3D, 0x73, 0x65, 0x74, 0x75, 0x70, 0x3A, 0x61, 0x63, 0x74, 0x70, 0x61,
0x73, 0x73, 0x0D, 0x0A, 0x61, 0x3D, 0x6D, 0x69, 0x64, 0x3A, 0x30, 0x0D,
0x0A, 0x61, 0x3D, 0x73, 0x63, 0x74, 0x70, 0x2D, 0x70, 0x6F, 0x72, 0x74,
0x3A, 0x35, 0x30, 0x30, 0x30, 0x0D, 0x0A, 0x61, 0x3D, 0x6D, 0x61, 0x78,
0x2D, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2D, 0x73, 0x69, 0x7A,
0x65, 0x3A, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x0D, 0x0A, 0x00, 0x00
]);
this._onMessageArrayBuffer(data.buffer);
}
} else {
this._mockSendServerToClientMessageBase64(
// ........................................°8.X....Myname..
"DAAAAAgADAAHAAgACAAAAAAAABcMAAAACAAMAAQACAAIAAAACAAAAPg4CFgGAAAATXluYW1lAAA="
);
}
} else if (state === 3) {
if (!amITheServer) {
// ....................................°8.X....╔...v=0..o=-
// 1111111111111111111 2 IN IP4 127.0.0.1..s=-..t=0 0..a=gro
// up:BUNDLE 0..a=extmap-allow-mixed..a=msid-semantic: WMS..
// m=application 9 UDP/DTLS/SCTP webrtc-datachannel..c=IN IP
// 4 0.0.0.0..a=ice-ufrag:abcd..a=ice-pwd:abcdefghijklmnopqr
// stuvwx..a=ice-options:trickle..a=fingerprint:sha-256 11:2
// 2:33:44:55:66:77:88:99:11:22:33:44:55:66:77:88:99:11:22:3
// 3:44:55:66:77:88:99:11:22:33:44:55..a=setup:active..a=mid
// :0..a=sctp-port:5000..a=max-message-size:123456.....
this._mockSendServerToClientMessageBase64(
"DAAAAAgADAAHAAgACAAAAAAAAA0MAAAACAAMAAQACAAIAAAA+DgIWAQAAADJAQAAdj0wDQpvPS0gMTExMTExMTExMTExMTExMTExMSAyIElOIElQNCAxMjcuMC4wLjENCnM9LQ0KdD0wIDANCmE9Z3JvdXA6QlVORExFIDANCmE9ZXh0bWFwLWFsbG93LW1peGVkDQphPW1zaWQtc2VtYW50aWM6IFdNUw0KbT1hcHBsaWNhdGlvbiA5IFVEUC9EVExTL1NDVFAgd2VicnRjLWRhdGFjaGFubmVsDQpjPUlOIElQNCAwLjAuMC4wDQphPWljZS11ZnJhZzphYmNkDQphPWljZS1wd2Q6YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4DQphPWljZS1vcHRpb25zOnRyaWNrbGUNCmE9ZmluZ2VycHJpbnQ6c2hhLTI1NiAxMToyMjozMzo0NDo1NTo2Njo3Nzo4ODo5OToxMToyMjozMzo0NDo1NTo2Njo3Nzo4ODo5OToxMToyMjozMzo0NDo1NTo2Njo3Nzo4ODo5OToxMToyMjozMzo0NDo1NQ0KYT1zZXR1cDphY3RpdmUNCmE9bWlkOjANCmE9c2N0cC1wb3J0OjUwMDANCmE9bWF4LW1lc3NhZ2Utc2l6ZToxMjM0NTYNCgAAAA=="
);
}
}
}
_mockSendServerToClientMessageBase64(base64Str) {
fetch(`data:application/octet-stream;base64,${base64Str}`).then(
async (res) => {
const data =
this.binaryType === "arraybuffer" ? res.arrayBuffer() : res.blob();
this.onmessage?.(
new MessageEvent("message", {
data: await data,
})
);
}
);
}
/**
* This does not respect `this.binaryType`, and always sends ArrayBuffer,
* which is fine for now.
*/
_onMessageArrayBuffer(arrayBuffer) {
this.onmessage?.(
new MessageEvent("message", {
data: arrayBuffer,
})
);
}
}