-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoverride-webrtc.js
More file actions
339 lines (301 loc) · 9.6 KB
/
override-webrtc.js
File metadata and controls
339 lines (301 loc) · 9.6 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
//@ts-check
// Mutate WebRTC objects such that RTCDataChannel.send sends data over a
// `BroadcastChannel` instead of the actual WebRTC implementation.
/**
* @type (message: unknown) => void
*/
let broadcastMessage;
if (globalThis.webxdc) {
// https://webxdc.org/docs/spec/joinRealtimeChannel.html
if (webxdc.joinRealtimeChannel == undefined) {
document.body.innerText =
"Error: webxdc.joinRealtimeChannel is not supported by this (messenger?) application.";
document.body.style.color = "red";
throw new Error();
}
let realtimeChannel;
try {
realtimeChannel = webxdc.joinRealtimeChannel();
} catch (error) {
// At least on Delta Chat Electron, `joinRealtimeChannel` can fail
// after a page reload / navigation
// (see https://webxdc.org/docs/spec/joinRealtimeChannel.html#realtimechannelleave).
// This is a stupid hack to keep the channel between page reloads.
try {
window.top.__webxdcRealtimeChannel.leave();
} catch (error2) {
console.error(
"Failed to leave realtime channel after failed attempt to create one",
error2
);
}
realtimeChannel = webxdc.joinRealtimeChannel();
}
globalThis.webxdcRealtimeChannel = realtimeChannel;
try {
window.top.__webxdcRealtimeChannel = realtimeChannel;
} catch (error) {
console.warn(
"Could not set window.top.__webxdcRealtimeChannel = realtimeChannel.",
"This might be fine."
);
}
broadcastMessage = (message) => realtimeChannel.send(message);
realtimeChannel.setListener((message) => {
handlePacket(message);
globalThis.globalWebxdcRealtimeListener?.(message);
});
} else {
const broadcastChannel = new BroadcastChannel("webrtc-data");
broadcastMessage = (message) => broadcastChannel.postMessage(message);
broadcastChannel.addEventListener("message", (event) =>
handlePacket(event.data)
);
}
/**
* @param {Uint8Array} body
* @param {number} sourceAddress
* @param {number} destinationAddress
* @returns {void}
*/
function sendPacket(body, sourceAddress, destinationAddress) {
broadcastMessage(packetize(body, sourceAddress, destinationAddress));
}
const PACKET_HEADER_SIZE_U32 = 2;
const PACKET_HEADER_SIZE_BYTES =
Uint32Array.BYTES_PER_ELEMENT * PACKET_HEADER_SIZE_U32;
/**
* @param {Uint8Array} data
* @param {number} sourceAddress
* @param {number} destinationAddress
* @returns {Uint8Array}
*/
function packetize(data, sourceAddress, destinationAddress) {
const packetArrayBuffer = new ArrayBuffer(
data.buffer.byteLength + PACKET_HEADER_SIZE_BYTES
);
const headerSlice = new Uint32Array(
packetArrayBuffer,
0,
PACKET_HEADER_SIZE_U32
);
headerSlice[0] = sourceAddress;
headerSlice[1] = destinationAddress;
const packet = new Uint8Array(headerSlice.buffer);
packet.set(data, PACKET_HEADER_SIZE_BYTES);
return packet;
}
/**
* Handles a raw packet and emits an `onmessage` event
* on the datachannel that is selected by looking at the destination address
* specified in the packet.
*
* webxdc realtime channels do not have concept of "channels" or "addresses",
* so we have to implement this manually.
*/
function handlePacket(/** @type {Uint8Array} */ packet) {
if (packet.buffer.byteLength < PACKET_HEADER_SIZE_BYTES) {
return;
}
// TODO perf: does this clone the buffer or nah?
const packetHeader = new Uint32Array(
packet.buffer,
0,
PACKET_HEADER_SIZE_U32
);
const packetSourceAddress = packetHeader[0];
// Ignore special packets (see `isWhoIsTheServerRequest`,
// `isWhoIsTheServerResponse`). Yes, this is stupid.
if (
packetSourceAddress === 0x2b2b2b2b ||
packetSourceAddress === 0x2a2a2a2a
) {
return;
}
const packetDestinationAddress = packetHeader[1];
// Remember though that there are also special packets,
// (see `isWhoIsTheServerRequest`, `isWhoIsTheServerResponse`).
globalThis.addressToLastPacketTimestamp.set(packetSourceAddress, Date.now());
if (packetDestinationAddress !== myAddress) {
return;
}
let dataChannel = addressToDataChannel.get(packetSourceAddress);
if (!dataChannel) {
dataChannel = unassignedDataChannels.pop();
if (!dataChannel) {
console.warn(
`received the first packet from ${packetSourceAddress}, ` +
"but there are no available data channels."
);
return;
}
console.log(
"We received a connection from a new address:",
packetSourceAddress
);
dataChannel._destinationAddress = packetSourceAddress;
addressToDataChannel.set(packetSourceAddress, dataChannel);
}
// Strip the "header"
const packetBody = new Uint8Array(packet.buffer, PACKET_HEADER_SIZE_BYTES);
const messageEvent = new MessageEvent("message", {
data: packetBody,
// Probably only `data` here is important.
// data: event.data,
// origin: event.origin,
// lastEventId: event.lastEventId,
// source: event.source,
// ports: event.ports,
});
dataChannel.dispatchEvent(messageEvent);
dataChannel.onmessage?.(messageEvent);
globalThis.statsNumPacketsHandled =
(globalThis.statsNumPacketsHandled ?? 0) + 1;
}
const myAddress = (() => {
// Using the array in order to be extra sure that the resulting number fits
// into 32 bits.
const arr = new Uint32Array(1);
arr[0] = Math.random() * (Math.pow(2, 32) - 1);
return arr[0];
})();
globalThis.myAddress = myAddress;
/** @type {Map<number, RTCDataChannel>} */
const addressToDataChannel = new Map();
/**
* Unused, available pre-created datachannels,
* that do not have a destination address associated with them yet.
* @type {RTCDataChannel[]}
*/
const unassignedDataChannels = [];
/** @type {Map<number, number>} */
globalThis.addressToLastPacketTimestamp = new Map();
/**
* @param {RTCDataChannel} dataChannel
*/
function emitOpenOnChannelAfterTimeout(dataChannel) {
setTimeout(() => {
const openEvent = new Event("open");
openEvent.channel = dataChannel;
dataChannel.dispatchEvent(openEvent);
dataChannel.onopen?.(openEvent);
});
}
/**
* @implements {RTCPeerConnection}
*/
class FakeRTCPeerConnection extends EventTarget {
constructor() {
super();
this.iceConnectionState = "connected";
this.iceGatheringState = "complete";
}
setLocalDescription(desc) {
this.localDescription = desc;
this.currentLocalDescription = desc;
return Promise.resolve();
}
setRemoteDescription(desc) {
this.remoteDescription = desc;
this.currentRemoteDescription = desc;
return Promise.resolve();
}
createAnswer() {
return Promise.resolve(
new RTCSessionDescription({
type: "answer",
sdp: "foo",
})
);
}
createOffer(...args) {
return Promise.resolve(
new RTCSessionDescription({
type: "offer",
sdp: "foo",
})
);
}
createDataChannel(label, dataChannelDict) {
return /** @type {RTCDataChannel} */ (
new FakeRTCDataChannel(label, dataChannelDict)
);
}
}
/**
* @implements {RTCDataChannel}
*/
class FakeRTCDataChannel extends EventTarget {
constructor(label, dataChannelDict) {
super();
this.label = label;
}
}
globalThis.RTCPeerConnection = FakeRTCPeerConnection;
globalThis.RTCDataChannel = FakeRTCDataChannel;
globalThis.RTCPeerConnection = new Proxy(RTCPeerConnection, {
construct(target, argArray, newTarget, ...rest) {
/** @type {RTCPeerConnection} */
const rtcpc = Reflect.construct(target, argArray, newTarget, ...rest);
rtcpc.addEventListener("datachannel", (event) => {
console.log("Intercepted datachannel event:", event);
event.channel._destinationAddress = undefined;
unassignedDataChannels.push(event.channel);
emitOpenOnChannelAfterTimeout(event.channel);
});
globalThis.amITheServerP.then((amITheServer) => {
if (amITheServer) {
setTimeout(() => {
const dc = originalCreateChannel.call(rtcpc, "test");
const event = new Event("datachannel");
event.channel = dc;
rtcpc.dispatchEvent(event);
rtcpc.ondatachannel?.(event);
}, 10);
}
});
setTimeout(() => {
console.log("Dispatching fake iceconnectionstatechange");
Object.defineProperty(rtcpc, "iceConnectionState", {
get() {
return "connected";
},
});
const iceConnectionStateChangeEvent = new Event(
"iceconnectionstatechange"
);
rtcpc.dispatchEvent(iceConnectionStateChangeEvent);
rtcpc.oniceconnectionstatechange?.(iceConnectionStateChangeEvent);
}, 10);
return rtcpc;
},
});
const originalCreateChannel = RTCPeerConnection.prototype.createDataChannel;
RTCPeerConnection.prototype.createDataChannel = function (...args) {
/** @type {RTCDataChannel} */
// TODO use `Reflect`?
const ret = originalCreateChannel.call(this, ...args);
console.log("Intercepted createDataChannel", ret);
// Only clients do `createDataChannel`, so it's OK to unconditionally
// set `_destinationAddress` to `SERVER_PEER_ID`,
// because clients only send packets to the server
// and never to other clients.
globalThis.serverAddressP.then((serverAddress) => {
if (myAddress === serverAddress) {
console.error("Did not expect server to call `createDataChannel`");
}
ret._destinationAddress = serverAddress;
addressToDataChannel.set(serverAddress, ret);
emitOpenOnChannelAfterTimeout(ret);
});
return ret;
};
let numSends = 0;
const _originalSend = RTCDataChannel.prototype.send;
RTCDataChannel.prototype.send = function (/** @type {Uint8Array} */ arg) {
sendPacket(arg, myAddress, this._destinationAddress);
numSends++;
};
setInterval(() => {
console.log("Number of `RTCDataChannel.send()`s:", numSends);
}, 5000);