@hiroosy/baileys-lite 0.3.8 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +97 -6
- package/package.json +2 -2
- package/src/voip/WaVoipCoordinator.js +57 -1
- package/src/voip/call/WaCallManager.js +265 -6
- package/src/voip/call/WaCallMediaSession.js +929 -61
- package/src/voip/call/call-state.js +45 -0
- package/src/voip/crypto/rtcp.js +6 -0
- package/src/voip/crypto/srtp.js +5 -0
- package/src/voip/crypto/ssrc.js +10 -0
- package/src/voip/index.js +212 -16
- package/src/voip/media/WaAudioEngine.js +35 -24
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/mlow-codec.js +12 -8
- package/src/voip/relay/WaManualRelay.js +504 -85
- package/src/voip/relay/relay-ack.js +66 -25
- package/src/voip/relay/sctp/association.js +14 -1
- package/src/voip/relay/stun.js +183 -16
- package/src/voip/signaling/bridge.js +15 -1
- package/src/voip/signaling/signaling.js +432 -1
- package/src/voip/types.js +1 -0
- package/src/voip/voip-deps.js +7 -0
- package/src/voip/voipClient.js +152 -17
|
@@ -5,7 +5,8 @@ import { PreNegotiatedDataChannel } from './datachannel/pre-negotiated.js';
|
|
|
5
5
|
import { createNoopLogger } from '../shim/core.js';
|
|
6
6
|
import { toError } from '../shim/util.js';
|
|
7
7
|
import { TEXT_ENCODER, toArrayBuffer } from '../bytes.js';
|
|
8
|
-
import { buildAllocateForRelay, buildBindingRequest, buildBindingRequestWithSubs, buildRelayBindingSuccess, buildSenderSubscriptions, buildSSRCSubscriptionList, buildWhatsAppPing, parseStunResponse } from './stun.js';
|
|
8
|
+
import { buildAllocateForRelay, buildBindingRequest, buildBindingRequestWithSubs, buildRelayBindingSuccess, buildSenderSubscriptions, buildSSRCSubscriptionList, buildWhatsAppPing, createWasmStreamDescriptors, parseRelayedAddressMismatch, parseStunResponse } from './stun.js';
|
|
9
|
+
import { randomBytes } from '../crypto/primitives.js';
|
|
9
10
|
import { PayloadType } from '../types.js';
|
|
10
11
|
|
|
11
12
|
const CONFIG = {
|
|
@@ -40,12 +41,18 @@ function randomUfrag() {
|
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
export class WaManualRelay extends EventEmitter {
|
|
44
|
+
rejectedModes = new Set();
|
|
45
|
+
answeredRelayNames = new Set();
|
|
46
|
+
maxActiveRelays = 3;
|
|
43
47
|
logger;
|
|
44
48
|
connections = new Map();
|
|
45
49
|
relayMap = new Map();
|
|
50
|
+
standbyRelays = [];
|
|
51
|
+
failedRelays = new Set();
|
|
46
52
|
audioSsrc = 0;
|
|
47
53
|
videoSsrc = 0;
|
|
48
54
|
subscriptionSsrc = 0;
|
|
55
|
+
streamSsrcs = null;
|
|
49
56
|
selfPid = 0;
|
|
50
57
|
peerPid = 0;
|
|
51
58
|
rxStun = { bindReq: 0, bindAnswered: 0, allocOk: 0, allocErr: 0, pong: 0, other: 0 };
|
|
@@ -54,10 +61,16 @@ export class WaManualRelay extends EventEmitter {
|
|
|
54
61
|
globalBufferedBytes = 0;
|
|
55
62
|
stats = { sent: 0, received: 0, connected: 0 };
|
|
56
63
|
retrySchedule = [1000, 2000, 4000];
|
|
64
|
+
transports = ['dtls', 'raw'];
|
|
65
|
+
allocateBuilder = null;
|
|
66
|
+
destroyed = false;
|
|
57
67
|
|
|
58
68
|
constructor(options = {}) {
|
|
59
69
|
super();
|
|
60
70
|
this.logger = options.logger ?? createNoopLogger();
|
|
71
|
+
this.transports = options.transports ?? this.transports;
|
|
72
|
+
this.maxActiveRelays = options.maxActiveRelays ?? this.maxActiveRelays;
|
|
73
|
+
this.allocateBuilder = options.allocateBuilder ?? null;
|
|
61
74
|
}
|
|
62
75
|
|
|
63
76
|
setSsrc(ssrc) {
|
|
@@ -77,42 +90,86 @@ export class WaManualRelay extends EventEmitter {
|
|
|
77
90
|
this.videoSsrc = ssrc;
|
|
78
91
|
}
|
|
79
92
|
|
|
93
|
+
setStreamSsrcs(ssrcs) {
|
|
94
|
+
this.streamSsrcs = ssrcs;
|
|
95
|
+
}
|
|
96
|
+
|
|
80
97
|
setSubscriptionSsrc(ssrc) {
|
|
81
98
|
this.subscriptionSsrc = ssrc;
|
|
82
99
|
}
|
|
83
100
|
|
|
101
|
+
setAllocateBuilder(builder) {
|
|
102
|
+
this.allocateBuilder = builder;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
refreshRelays(relays) {
|
|
106
|
+
const infos = relays.map((relay) => this.toRelayInfo(relay));
|
|
107
|
+
for (const conn of this.connections.values()) {
|
|
108
|
+
const current = conn.relayInfo;
|
|
109
|
+
const next = infos.find((info) => info.ip === current.ip && info.port === current.port && info.name === current.name)
|
|
110
|
+
?? infos.find((info) => info.ip === current.ip && info.port === current.port);
|
|
111
|
+
if (!next) continue;
|
|
112
|
+
conn.relayInfo = { ...next, id: current.id };
|
|
113
|
+
this.relayMap.set(current.id, conn.relayInfo);
|
|
114
|
+
conn.stunTransactionId = randomBytes(12);
|
|
115
|
+
}
|
|
116
|
+
this.resendSubscriptions();
|
|
117
|
+
}
|
|
118
|
+
|
|
84
119
|
makeConnectionId(ip, port, authTokenId) {
|
|
85
120
|
const base = ip.includes(':') ? `[${ip}]:${port}` : `${ip}:${port}`;
|
|
86
121
|
return authTokenId ? `${base}#${authTokenId}` : base;
|
|
87
122
|
}
|
|
88
123
|
|
|
124
|
+
toRelayInfo(relay) {
|
|
125
|
+
const port = relay.port || CONFIG.TRUE_WEB_CLIENT_RELAY_PORT;
|
|
126
|
+
return {
|
|
127
|
+
id: this.makeConnectionId(relay.ip, port, relay.authTokenId),
|
|
128
|
+
ip: relay.ip,
|
|
129
|
+
port,
|
|
130
|
+
token: relay.token,
|
|
131
|
+
authToken: relay.authToken,
|
|
132
|
+
rawAuthToken: relay.rawAuthToken,
|
|
133
|
+
rawToken: relay.rawToken,
|
|
134
|
+
key: relay.key,
|
|
135
|
+
relayId: relay.relayId,
|
|
136
|
+
name: relay.name || 'unknown',
|
|
137
|
+
authTokenId: relay.authTokenId,
|
|
138
|
+
isFna: relay.isFna,
|
|
139
|
+
fallbackPort: port === CONFIG.TRUE_WEB_CLIENT_RELAY_PORT ? 3478 : CONFIG.TRUE_WEB_CLIENT_RELAY_PORT
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
89
143
|
async configureRelays(relays) {
|
|
144
|
+
this.destroyed = false;
|
|
90
145
|
this.configuring = true;
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
authToken: relay.authToken,
|
|
100
|
-
rawAuthToken: relay.rawAuthToken,
|
|
101
|
-
rawToken: relay.rawToken,
|
|
102
|
-
key: relay.key,
|
|
103
|
-
relayId: relay.relayId,
|
|
104
|
-
name: relay.name || 'unknown',
|
|
105
|
-
authTokenId: relay.authTokenId,
|
|
106
|
-
isFna: relay.isFna
|
|
107
|
-
});
|
|
146
|
+
const infos = relays.map((relay) => this.toRelayInfo(relay)).filter((info) => !this.failedRelays.has(info.id));
|
|
147
|
+
for (const info of infos) {
|
|
148
|
+
if (this.relayMap.has(info.id)) {
|
|
149
|
+
this.relayMap.set(info.id, info);
|
|
150
|
+
}
|
|
151
|
+
else if (this.relayMap.size < this.maxActiveRelays) {
|
|
152
|
+
this.relayMap.set(info.id, info);
|
|
153
|
+
}
|
|
108
154
|
}
|
|
155
|
+
this.standbyRelays = infos.filter((info) => !this.relayMap.has(info.id));
|
|
109
156
|
const connectionPromises = [];
|
|
110
157
|
for (const [, relayInfo] of this.relayMap) {
|
|
111
158
|
if (!this.connections.has(relayInfo.id)) {
|
|
112
159
|
connectionPromises.push(this.ensureConnection(relayInfo));
|
|
113
160
|
}
|
|
114
161
|
}
|
|
115
|
-
|
|
162
|
+
if (connectionPromises.length > 0) {
|
|
163
|
+
const settled = connectionPromises.map((promise) => promise.catch(() => {}));
|
|
164
|
+
const firstOpen = new Promise((resolve) => {
|
|
165
|
+
for (const promise of settled) {
|
|
166
|
+
promise.then(() => {
|
|
167
|
+
if (this.hasConnection()) resolve();
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
await Promise.race([Promise.all(settled), firstOpen]);
|
|
172
|
+
}
|
|
116
173
|
this.configuring = false;
|
|
117
174
|
if (this.globalBuffer.length > 0) {
|
|
118
175
|
for (const item of this.globalBuffer) this.sendToRelay(item.ip, item.port, item.data);
|
|
@@ -121,9 +178,64 @@ export class WaManualRelay extends EventEmitter {
|
|
|
121
178
|
}
|
|
122
179
|
}
|
|
123
180
|
|
|
181
|
+
buildRoutes(relayInfo) {
|
|
182
|
+
const ports = [relayInfo.port];
|
|
183
|
+
if (relayInfo.fallbackPort !== undefined && relayInfo.fallbackPort !== relayInfo.port) {
|
|
184
|
+
ports.push(relayInfo.fallbackPort);
|
|
185
|
+
}
|
|
186
|
+
const routes = [];
|
|
187
|
+
const preferRaw = !relayInfo.authToken && this.transports.includes('raw');
|
|
188
|
+
const rank = (mode) => (this.rejectedModes.has(`${relayInfo.ip}|${mode}`) ? 2 : 0) + (preferRaw && mode !== 'raw' ? 1 : 0);
|
|
189
|
+
const modes = [...this.transports].sort((a, b) => rank(a) - rank(b));
|
|
190
|
+
for (const mode of modes) {
|
|
191
|
+
for (const port of ports) {
|
|
192
|
+
routes.push({ mode, port });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (routes.length === 0) {
|
|
196
|
+
routes.push({ mode: 'dtls', port: relayInfo.port });
|
|
197
|
+
}
|
|
198
|
+
return routes;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
applyRoute(conn, index) {
|
|
202
|
+
const route = conn.routes[index];
|
|
203
|
+
conn.routeIndex = index;
|
|
204
|
+
conn.mode = route.mode;
|
|
205
|
+
conn.dialPort = route.port;
|
|
206
|
+
conn.returnPathSeen = false;
|
|
207
|
+
this.restartAllocateLadder(conn);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
restartAllocateLadder(conn) {
|
|
211
|
+
conn.allocateStage = 0;
|
|
212
|
+
conn.allocateLocked = false;
|
|
213
|
+
conn.allocateExhausted = false;
|
|
214
|
+
conn.allocateCandidates = null;
|
|
215
|
+
conn.allocateAttempts.clear();
|
|
216
|
+
conn.allocatePacket = null;
|
|
217
|
+
conn.proven = false;
|
|
218
|
+
conn.refused = false;
|
|
219
|
+
conn.allocateResponses = 0;
|
|
220
|
+
conn.stunTransactionId = randomBytes(12);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
advanceRoute(conn, reason, targetIndex = conn.routeIndex + 1) {
|
|
224
|
+
if (targetIndex >= conn.routes.length) {
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
const from = conn.routes[conn.routeIndex];
|
|
228
|
+
this.applyRoute(conn, targetIndex);
|
|
229
|
+
this.logger.warn('[RELAY] switching relay route', { connectionId: conn.relayInfo.id, reason, from, to: conn.routes[conn.routeIndex] });
|
|
230
|
+
this.closePeerObjects(conn);
|
|
231
|
+
conn.state = ConnectionState.Closed;
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
|
|
124
235
|
getOrCreateConnection(relayInfo) {
|
|
125
236
|
let conn = this.connections.get(relayInfo.id);
|
|
126
237
|
if (!conn) {
|
|
238
|
+
const routes = this.buildRoutes(relayInfo);
|
|
127
239
|
conn = {
|
|
128
240
|
state: ConnectionState.None,
|
|
129
241
|
relayInfo,
|
|
@@ -141,6 +253,25 @@ export class WaManualRelay extends EventEmitter {
|
|
|
141
253
|
recovering: false,
|
|
142
254
|
lastInboundAt: 0,
|
|
143
255
|
localUfrag: randomUfrag(),
|
|
256
|
+
stunTransactionId: randomBytes(12),
|
|
257
|
+
routes,
|
|
258
|
+
routeIndex: 0,
|
|
259
|
+
mode: routes[0].mode,
|
|
260
|
+
dialPort: routes[0].port,
|
|
261
|
+
fallbackTimer: null,
|
|
262
|
+
answered: false,
|
|
263
|
+
keepaliveTicks: 0,
|
|
264
|
+
allocateStage: 0,
|
|
265
|
+
allocateLocked: false,
|
|
266
|
+
allocateExhausted: false,
|
|
267
|
+
allocateCandidates: null,
|
|
268
|
+
allocateRounds: 0,
|
|
269
|
+
returnPathSeen: false,
|
|
270
|
+
proven: false,
|
|
271
|
+
refused: false,
|
|
272
|
+
allocateResponses: 0,
|
|
273
|
+
openedAt: 0,
|
|
274
|
+
allocateAttempts: new Map(),
|
|
144
275
|
stats: { sentPackets: 0, receivedPackets: 0, sentBytes: 0, receivedBytes: 0 }
|
|
145
276
|
};
|
|
146
277
|
this.connections.set(relayInfo.id, conn);
|
|
@@ -149,17 +280,26 @@ export class WaManualRelay extends EventEmitter {
|
|
|
149
280
|
}
|
|
150
281
|
|
|
151
282
|
ensureConnection = async (relayInfo) => {
|
|
283
|
+
if (this.destroyed) {
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
152
286
|
const conn = this.getOrCreateConnection(relayInfo);
|
|
153
287
|
if (conn.state === ConnectionState.Open || conn.state === ConnectionState.Connecting) {
|
|
154
288
|
return (conn.connectPromise ?? Promise.resolve()).catch(() => {});
|
|
155
289
|
}
|
|
156
290
|
const promise = this.connect(conn);
|
|
157
291
|
conn.connectPromise = promise;
|
|
292
|
+
let failed = false;
|
|
158
293
|
try {
|
|
159
294
|
await promise;
|
|
160
|
-
} catch {
|
|
295
|
+
} catch {
|
|
296
|
+
failed = true;
|
|
297
|
+
} finally {
|
|
161
298
|
conn.connectPromise = null;
|
|
162
299
|
}
|
|
300
|
+
if (failed && !this.destroyed && this.advanceRoute(conn, 'connect_failed')) {
|
|
301
|
+
await this.ensureConnection(relayInfo);
|
|
302
|
+
}
|
|
163
303
|
};
|
|
164
304
|
|
|
165
305
|
performIceBinding(socket, relayInfo, conn) {
|
|
@@ -195,9 +335,9 @@ export class WaManualRelay extends EventEmitter {
|
|
|
195
335
|
resolve(false);
|
|
196
336
|
return;
|
|
197
337
|
}
|
|
198
|
-
const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling' });
|
|
338
|
+
const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling', transactionId: conn.stunTransactionId });
|
|
199
339
|
try {
|
|
200
|
-
socket.send(packet,
|
|
340
|
+
socket.send(packet, conn.dialPort, relayInfo.ip);
|
|
201
341
|
} catch { }
|
|
202
342
|
const wait = CONFIG.ICE_BINDING_TIMEOUTS_MS[attempt];
|
|
203
343
|
attempt += 1;
|
|
@@ -222,7 +362,7 @@ export class WaManualRelay extends EventEmitter {
|
|
|
222
362
|
}
|
|
223
363
|
try {
|
|
224
364
|
const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling' });
|
|
225
|
-
socket.send(packet,
|
|
365
|
+
socket.send(packet, conn.dialPort, relayInfo.ip);
|
|
226
366
|
} catch { }
|
|
227
367
|
}, CONFIG.ICE_CONSENT_REFRESH_MS);
|
|
228
368
|
}
|
|
@@ -230,12 +370,15 @@ export class WaManualRelay extends EventEmitter {
|
|
|
230
370
|
connect = async (conn) => {
|
|
231
371
|
this.closePeerObjects(conn);
|
|
232
372
|
conn.state = ConnectionState.Connecting;
|
|
373
|
+
conn.answered = false;
|
|
233
374
|
const relayInfo = conn.relayInfo;
|
|
375
|
+
const targetIp = relayInfo.ip;
|
|
376
|
+
const targetPort = conn.dialPort;
|
|
377
|
+
const dtlsRoute = conn.mode === 'dtls';
|
|
378
|
+
const timeoutMs = dtlsRoute ? 6000 : CONFIG.CONNECTION_TIMEOUT_MS;
|
|
234
379
|
return new Promise((resolve, reject) => {
|
|
235
380
|
const socket = dgram.createSocket('udp4');
|
|
236
381
|
conn.socket = socket;
|
|
237
|
-
const targetIp = relayInfo.ip;
|
|
238
|
-
const targetPort = relayInfo.port;
|
|
239
382
|
|
|
240
383
|
let settledConn = false;
|
|
241
384
|
const settle = (err) => {
|
|
@@ -254,6 +397,54 @@ export class WaManualRelay extends EventEmitter {
|
|
|
254
397
|
}
|
|
255
398
|
};
|
|
256
399
|
|
|
400
|
+
const receive = (payload) => {
|
|
401
|
+
if (conn.socket !== socket) return;
|
|
402
|
+
conn.lastInboundAt = Date.now();
|
|
403
|
+
conn.answered = true;
|
|
404
|
+
const view = payload instanceof Uint8Array ? payload : new Uint8Array(payload);
|
|
405
|
+
if (!conn.returnPathSeen && view.length > 0 && (view[0] & 0xc0) !== 0) {
|
|
406
|
+
conn.returnPathSeen = true;
|
|
407
|
+
this.logger.info('[RELAY] return media confirmed', { connectionId: relayInfo.id, mode: conn.mode, port: conn.dialPort, bytes: view.length });
|
|
408
|
+
this.markRelayProven(conn, 'media');
|
|
409
|
+
}
|
|
410
|
+
this.handleRelayStun(conn, relayInfo, payload);
|
|
411
|
+
conn.stats.receivedPackets++;
|
|
412
|
+
conn.stats.receivedBytes += byteLengthOf(payload);
|
|
413
|
+
this.stats.received++;
|
|
414
|
+
this.emit('relay_receive', { ip: relayInfo.ip, port: relayInfo.port, data: payload });
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
socket.on('error', (err) => {
|
|
418
|
+
if (conn.state === ConnectionState.Open) this.handleRelayLoss(conn);
|
|
419
|
+
settle(err instanceof Error ? err : new Error(String(err)));
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
conn.connectionTimeout = setTimeout(() => {
|
|
423
|
+
settle(new Error(`relay connect timed out after ${timeoutMs}ms (${conn.mode} ${targetIp}:${targetPort})`));
|
|
424
|
+
}, timeoutMs);
|
|
425
|
+
|
|
426
|
+
if (!dtlsRoute) {
|
|
427
|
+
socket.on('message', (datagram) => {
|
|
428
|
+
receive(new Uint8Array(datagram.buffer, datagram.byteOffset, datagram.byteLength));
|
|
429
|
+
});
|
|
430
|
+
socket.connect(targetPort, targetIp, (err) => {
|
|
431
|
+
if (settledConn) return;
|
|
432
|
+
if (err) {
|
|
433
|
+
settle(err);
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
conn.dataChannel = {
|
|
437
|
+
send: (data) => {
|
|
438
|
+
socket.send(Buffer.from(data));
|
|
439
|
+
},
|
|
440
|
+
getSendBacklog: () => 0,
|
|
441
|
+
close: () => {}
|
|
442
|
+
};
|
|
443
|
+
this.handleChannelOpen(conn, relayInfo, socket, settle);
|
|
444
|
+
});
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
|
|
257
448
|
const connLogger = this.logger.child?.({ connectionId: relayInfo.id }) ?? this.logger;
|
|
258
449
|
|
|
259
450
|
const dtls = new DtlsClient({
|
|
@@ -279,7 +470,6 @@ export class WaManualRelay extends EventEmitter {
|
|
|
279
470
|
if (!iceBindingDone) {
|
|
280
471
|
return;
|
|
281
472
|
}
|
|
282
|
-
|
|
283
473
|
const isDtlsRecord = datagram.length >= 1 && datagram[0] >= 20 && datagram[0] <= 63;
|
|
284
474
|
if (!isDtlsRecord) {
|
|
285
475
|
return;
|
|
@@ -293,51 +483,21 @@ export class WaManualRelay extends EventEmitter {
|
|
|
293
483
|
} catch { }
|
|
294
484
|
}
|
|
295
485
|
});
|
|
296
|
-
socket.on('error', (err) => {
|
|
297
|
-
if (conn.state === ConnectionState.Open) this.handleRelayLoss(conn);
|
|
298
|
-
settle(err instanceof Error ? err : new Error(String(err)));
|
|
299
|
-
});
|
|
300
486
|
|
|
301
487
|
dtls.on('connected', () => {
|
|
488
|
+
this.logger.info('[RELAY] dtls connected', { connectionId: relayInfo.id, port: targetPort });
|
|
302
489
|
dc.start();
|
|
303
490
|
});
|
|
304
491
|
dtls.on('error', (err) => {
|
|
305
492
|
settle(err);
|
|
306
493
|
});
|
|
307
494
|
dc.on('open', () => {
|
|
308
|
-
conn
|
|
309
|
-
this.flushBufferedPackets(conn);
|
|
310
|
-
conn.lastInboundAt = Date.now();
|
|
311
|
-
this.startKeepalive(conn);
|
|
312
|
-
if (CONFIG.ICE_CONSENT_REFRESH_ENABLED) this.startIceConsentRefresh(socket, relayInfo, conn);
|
|
313
|
-
this.sendStunAllocateOnOpen(conn, relayInfo);
|
|
314
|
-
for (const delayMs of [50, 150, 500, 3000]) setTimeout(() => this.sendStunAllocateOnOpen(conn, conn.relayInfo), delayMs);
|
|
315
|
-
this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing()));
|
|
316
|
-
this.stats.connected++;
|
|
317
|
-
const wasRecovering = conn.recovering;
|
|
318
|
-
if (wasRecovering) {
|
|
319
|
-
conn.recovering = false;
|
|
320
|
-
conn.retryCount = 0;
|
|
321
|
-
}
|
|
322
|
-
this.emit('relay_connected', { ip: relayInfo.ip, port: relayInfo.port });
|
|
323
|
-
if (wasRecovering) this.emit('relay_recovered', { connectionId: relayInfo.id });
|
|
324
|
-
settle(null);
|
|
495
|
+
this.handleChannelOpen(conn, relayInfo, socket, settle);
|
|
325
496
|
});
|
|
326
497
|
dc.on('error', (err) => {
|
|
327
498
|
settle(err);
|
|
328
499
|
});
|
|
329
|
-
dc.on('message',
|
|
330
|
-
conn.lastInboundAt = Date.now();
|
|
331
|
-
this.handleRelayStun(conn, relayInfo, payload);
|
|
332
|
-
conn.stats.receivedPackets++;
|
|
333
|
-
conn.stats.receivedBytes += byteLengthOf(payload);
|
|
334
|
-
this.stats.received++;
|
|
335
|
-
this.emit('relay_receive', { ip: relayInfo.ip, port: relayInfo.port, data: payload });
|
|
336
|
-
});
|
|
337
|
-
|
|
338
|
-
conn.connectionTimeout = setTimeout(() => {
|
|
339
|
-
settle(new Error(`relay connect timed out after ${CONFIG.CONNECTION_TIMEOUT_MS}ms`));
|
|
340
|
-
}, CONFIG.CONNECTION_TIMEOUT_MS);
|
|
500
|
+
dc.on('message', receive);
|
|
341
501
|
|
|
342
502
|
socket.bind(0, async () => {
|
|
343
503
|
if (CONFIG.ICE_BINDING_ENABLED) {
|
|
@@ -348,16 +508,65 @@ export class WaManualRelay extends EventEmitter {
|
|
|
348
508
|
return;
|
|
349
509
|
}
|
|
350
510
|
}
|
|
351
|
-
|
|
352
511
|
iceBindingDone = true;
|
|
353
512
|
dtls.start();
|
|
354
513
|
});
|
|
355
514
|
});
|
|
356
515
|
};
|
|
357
516
|
|
|
517
|
+
handleChannelOpen(conn, relayInfo, socket, settle) {
|
|
518
|
+
if (conn.socket !== socket) return;
|
|
519
|
+
if (conn.allocateLocked || conn.allocateExhausted || conn.proven || conn.refused) {
|
|
520
|
+
this.restartAllocateLadder(conn);
|
|
521
|
+
}
|
|
522
|
+
conn.state = ConnectionState.Open;
|
|
523
|
+
conn.answered = false;
|
|
524
|
+
conn.openedAt = Date.now();
|
|
525
|
+
this.flushBufferedPackets(conn);
|
|
526
|
+
conn.lastInboundAt = Date.now();
|
|
527
|
+
this.logger.info('[RELAY] channel open', { connectionId: relayInfo.id, mode: conn.mode, port: conn.dialPort, hasAuthToken: Boolean(relayInfo.authToken) });
|
|
528
|
+
this.startKeepalive(conn);
|
|
529
|
+
this.armRouteFallback(conn);
|
|
530
|
+
if (conn.mode === 'dtls' && CONFIG.ICE_CONSENT_REFRESH_ENABLED) this.startIceConsentRefresh(socket, relayInfo, conn);
|
|
531
|
+
this.sendStunAllocateOnOpen(conn, relayInfo);
|
|
532
|
+
for (const delayMs of [50, 150, 500, 3000]) setTimeout(() => this.sendStunAllocateOnOpen(conn, conn.relayInfo), delayMs);
|
|
533
|
+
this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing(conn.stunTransactionId)));
|
|
534
|
+
this.stats.connected++;
|
|
535
|
+
const wasRecovering = conn.recovering;
|
|
536
|
+
if (wasRecovering) {
|
|
537
|
+
conn.recovering = false;
|
|
538
|
+
conn.retryCount = 0;
|
|
539
|
+
}
|
|
540
|
+
this.emit('relay_connected', { ip: relayInfo.ip, port: relayInfo.port });
|
|
541
|
+
if (wasRecovering) this.emit('relay_recovered', { connectionId: relayInfo.id });
|
|
542
|
+
settle(null);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
armRouteFallback(conn) {
|
|
546
|
+
if (conn.fallbackTimer) {
|
|
547
|
+
clearTimeout(conn.fallbackTimer);
|
|
548
|
+
conn.fallbackTimer = null;
|
|
549
|
+
}
|
|
550
|
+
if (conn.routeIndex + 1 >= conn.routes.length) {
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
const socket = conn.socket;
|
|
554
|
+
conn.fallbackTimer = setTimeout(() => {
|
|
555
|
+
conn.fallbackTimer = null;
|
|
556
|
+
if (conn.socket !== socket || conn.state !== ConnectionState.Open || conn.answered) {
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
if (this.advanceRoute(conn, 'relay_unanswered')) {
|
|
560
|
+
void this.ensureConnection(conn.relayInfo);
|
|
561
|
+
}
|
|
562
|
+
}, 4000);
|
|
563
|
+
conn.fallbackTimer.unref?.();
|
|
564
|
+
}
|
|
565
|
+
|
|
358
566
|
resendSubscriptions() {
|
|
359
567
|
for (const [, conn] of this.connections) {
|
|
360
568
|
if (conn.state === ConnectionState.Open && conn.dataChannel) {
|
|
569
|
+
if (conn.allocateExhausted) this.restartAllocateLadder(conn);
|
|
361
570
|
this.sendStunAllocateOnOpen(conn, conn.relayInfo);
|
|
362
571
|
}
|
|
363
572
|
}
|
|
@@ -383,9 +592,19 @@ export class WaManualRelay extends EventEmitter {
|
|
|
383
592
|
}
|
|
384
593
|
else if (type === 0x0103) {
|
|
385
594
|
this.rxStun.allocOk++;
|
|
595
|
+
conn.allocateResponses++;
|
|
596
|
+
this.lockAllocateForm(conn, data);
|
|
386
597
|
}
|
|
387
598
|
else if (type === 0x0113 || type === 0x0111) {
|
|
388
|
-
|
|
599
|
+
const errorInfo = parseStunResponse(data);
|
|
600
|
+
conn.allocateResponses++;
|
|
601
|
+
if (this.rxStun.allocErr++ === 0) {
|
|
602
|
+
this.logger.warn('[RELAY] allocate/binding ERROR from relay', { connectionId: relayInfo.id, type: '0x' + type.toString(16), bytes: data.length, errorCode: errorInfo?.errorCode, errorReason: errorInfo?.errorReason, hex: Buffer.from(data).toString('hex') });
|
|
603
|
+
}
|
|
604
|
+
if (type === 0x0113 && errorInfo?.errorCode === 452) {
|
|
605
|
+
if (!conn.allocateLocked) conn.refused = true;
|
|
606
|
+
this.advanceAllocateForm(conn, relayInfo, data, errorInfo);
|
|
607
|
+
}
|
|
389
608
|
}
|
|
390
609
|
else if (type === 0x0802) {
|
|
391
610
|
this.rxStun.pong++;
|
|
@@ -396,33 +615,194 @@ export class WaManualRelay extends EventEmitter {
|
|
|
396
615
|
}
|
|
397
616
|
|
|
398
617
|
sendStunAllocateOnOpen(conn, relayInfo) {
|
|
399
|
-
if (
|
|
618
|
+
if (this.destroyed || !relayInfo.key) {
|
|
400
619
|
return;
|
|
401
620
|
}
|
|
402
|
-
|
|
621
|
+
const ssrc = this.subscriptionSsrc || this.audioSsrc;
|
|
622
|
+
if (!ssrc) {
|
|
403
623
|
return;
|
|
404
624
|
}
|
|
405
|
-
if (!this.
|
|
406
|
-
|
|
625
|
+
if (conn.mode === 'dtls' && !this.allocateBuilder) {
|
|
626
|
+
this.sendBindingRegistrations(conn, relayInfo, ssrc);
|
|
407
627
|
}
|
|
628
|
+
this.sendAllocate(conn, relayInfo);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
sendBindingRegistrations(conn, relayInfo, ssrc) {
|
|
408
632
|
const hmacKey = TEXT_ENCODER.encode(relayInfo.key);
|
|
409
|
-
const subs = buildSenderSubscriptions(
|
|
633
|
+
const subs = buildSenderSubscriptions(ssrc);
|
|
410
634
|
const remoteUfrag = relayInfo.authToken || relayInfo.token;
|
|
411
635
|
if (remoteUfrag) {
|
|
412
636
|
const username = TEXT_ENCODER.encode(`${remoteUfrag}:${conn.localUfrag}`);
|
|
413
|
-
this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true)));
|
|
637
|
+
this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true, conn.stunTransactionId)));
|
|
414
638
|
}
|
|
415
639
|
if (relayInfo.token && relayInfo.token !== remoteUfrag) {
|
|
416
640
|
const username = TEXT_ENCODER.encode(`${relayInfo.token}:${conn.localUfrag}`);
|
|
417
|
-
this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true)));
|
|
641
|
+
this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true, conn.stunTransactionId)));
|
|
642
|
+
}
|
|
643
|
+
this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(undefined, undefined, subs, false, false, conn.stunTransactionId)));
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
resolveRelayTarget(conn, relayInfo) {
|
|
647
|
+
const dialed = { ip: relayInfo.ip, port: conn.dialPort ?? relayInfo.port };
|
|
648
|
+
if (conn.mode === 'dtls') {
|
|
649
|
+
return dialed;
|
|
650
|
+
}
|
|
651
|
+
try {
|
|
652
|
+
const remote = conn.socket?.remoteAddress();
|
|
653
|
+
if (remote?.address && remote.port) {
|
|
654
|
+
return { ip: remote.address, port: remote.port };
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
catch (err) {
|
|
658
|
+
this.logger.debug('[RELAY] remote address unavailable', { message: toError(err).message });
|
|
659
|
+
}
|
|
660
|
+
return dialed;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
getAllocateCandidates(conn, relayInfo) {
|
|
664
|
+
if (conn.allocateCandidates) {
|
|
665
|
+
return conn.allocateCandidates;
|
|
666
|
+
}
|
|
667
|
+
const target = this.resolveRelayTarget(conn, relayInfo);
|
|
668
|
+
const ports = [target.port, relayInfo.port, conn.dialPort, relayInfo.fallbackPort].filter((port, index, all) => Number.isInteger(port) && port > 0 && all.indexOf(port) === index);
|
|
669
|
+
const candidates = ports.map((port) => ({ form: 'exact', ip: target.ip, port }));
|
|
670
|
+
candidates.push({ form: 'mapped', ip: target.ip, port: ports[0] });
|
|
671
|
+
candidates.push({ form: 'none', ip: target.ip, port: ports[0] });
|
|
672
|
+
conn.allocateCandidates = candidates;
|
|
673
|
+
return candidates;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
lockAllocateForm(conn, data) {
|
|
677
|
+
if (conn.allocateLocked) {
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
const attempt = conn.allocateAttempts.get(Buffer.from(data.subarray(8, 20)).toString('hex'));
|
|
681
|
+
if (attempt) {
|
|
682
|
+
conn.allocateStage = attempt.stage;
|
|
683
|
+
conn.stunTransactionId = attempt.transactionId;
|
|
684
|
+
}
|
|
685
|
+
conn.allocateLocked = true;
|
|
686
|
+
conn.allocateExhausted = false;
|
|
687
|
+
conn.refused = false;
|
|
688
|
+
this.rejectedModes.delete(`${conn.relayInfo.ip}|${conn.mode}`);
|
|
689
|
+
this.logger.info('[RELAY] allocate accepted', { connectionId: conn.relayInfo.id, route: { mode: conn.mode, port: conn.dialPort }, relayedAddress: attempt?.candidate ?? null });
|
|
690
|
+
this.markRelayProven(conn, 'allocate');
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
markRelayProven(conn, via) {
|
|
694
|
+
if (conn.proven) {
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
conn.proven = true;
|
|
698
|
+
const relayInfo = conn.relayInfo;
|
|
699
|
+
this.logger.info('[RELAY] relay proven', { connectionId: relayInfo.id, via });
|
|
700
|
+
if (this.answeredRelayNames.has(relayInfo.name)) {
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
this.answeredRelayNames.add(relayInfo.name);
|
|
704
|
+
this.emit('relay_answered', { name: relayInfo.name, ip: relayInfo.ip, port: relayInfo.port, rttMs: conn.openedAt ? Date.now() - conn.openedAt : undefined });
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
advanceAllocateForm(conn, relayInfo, data, errorInfo) {
|
|
708
|
+
if (conn.allocateLocked || conn.allocateExhausted) {
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
const attempt = conn.allocateAttempts.get(Buffer.from(data.subarray(8, 20)).toString('hex'));
|
|
712
|
+
if (!attempt || attempt.stage !== conn.allocateStage) {
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
const candidates = this.getAllocateCandidates(conn, relayInfo);
|
|
716
|
+
const mismatch = parseRelayedAddressMismatch(errorInfo?.errorReason);
|
|
717
|
+
const learned = mismatch?.relay;
|
|
718
|
+
if (learned && !candidates.some((entry) => entry.form === 'exact' && entry.ip === learned.ip && entry.port === learned.port)) {
|
|
719
|
+
candidates.splice(conn.allocateStage + 1, 0, { form: 'exact', ip: learned.ip, port: learned.port });
|
|
720
|
+
}
|
|
721
|
+
const echoedSame = Boolean(mismatch?.destination && mismatch?.relay && mismatch.destination.ip === mismatch.relay.ip && mismatch.destination.port === mismatch.relay.port);
|
|
722
|
+
if (echoedSame || conn.allocateStage >= candidates.length - 1) {
|
|
723
|
+
this.handleAllocateExhausted(conn, relayInfo, errorInfo);
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
this.logger.warn('[RELAY] relayed address rejected, trying next candidate', { connectionId: relayInfo.id, rejected: attempt.candidate, next: candidates[conn.allocateStage + 1], serverRead: mismatch?.destination ?? null, serverRelay: mismatch?.relay ?? null });
|
|
727
|
+
conn.allocateStage++;
|
|
728
|
+
conn.stunTransactionId = randomBytes(12);
|
|
729
|
+
this.sendAllocate(conn, relayInfo);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
handleAllocateExhausted(conn, relayInfo, errorInfo) {
|
|
733
|
+
conn.allocateExhausted = true;
|
|
734
|
+
conn.refused = true;
|
|
735
|
+
conn.allocatePacket = null;
|
|
736
|
+
this.logger.warn('[RELAY] every relayed address candidate was rejected', { connectionId: relayInfo.id, route: { mode: conn.mode, port: conn.dialPort }, errorReason: errorInfo?.errorReason });
|
|
737
|
+
this.rejectedModes.add(`${relayInfo.ip}|${conn.mode}`);
|
|
738
|
+
if (this.advanceRoute(conn, 'allocate_rejected')) {
|
|
739
|
+
void this.ensureConnection(relayInfo);
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
if (this.activateStandbyRelay(conn)) {
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
if (conn.allocateRounds < 2) {
|
|
746
|
+
conn.allocateRounds += 1;
|
|
747
|
+
this.applyRoute(conn, 0);
|
|
748
|
+
this.closePeerObjects(conn);
|
|
749
|
+
conn.state = ConnectionState.Closed;
|
|
750
|
+
conn.retryTimer = setTimeout(() => {
|
|
751
|
+
conn.retryTimer = null;
|
|
752
|
+
if (this.connections.get(relayInfo.id) !== conn) return;
|
|
753
|
+
void this.ensureConnection(relayInfo);
|
|
754
|
+
}, 3000 * conn.allocateRounds);
|
|
755
|
+
conn.retryTimer.unref?.();
|
|
756
|
+
return;
|
|
418
757
|
}
|
|
419
|
-
this.
|
|
758
|
+
this.logger.error('[RELAY] allocate failed on every route and relay', { connectionId: relayInfo.id, rounds: conn.allocateRounds });
|
|
759
|
+
}
|
|
420
760
|
|
|
421
|
-
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
761
|
+
activateStandbyRelay(conn) {
|
|
762
|
+
const next = this.standbyRelays.shift();
|
|
763
|
+
if (!next) {
|
|
764
|
+
return false;
|
|
765
|
+
}
|
|
766
|
+
const failedId = conn.relayInfo.id;
|
|
767
|
+
this.failedRelays.add(failedId);
|
|
768
|
+
this.relayMap.delete(failedId);
|
|
769
|
+
this.connections.delete(failedId);
|
|
770
|
+
if (conn.retryTimer) {
|
|
771
|
+
clearTimeout(conn.retryTimer);
|
|
772
|
+
conn.retryTimer = null;
|
|
773
|
+
}
|
|
774
|
+
this.closePeerObjects(conn);
|
|
775
|
+
conn.state = ConnectionState.Failed;
|
|
776
|
+
this.relayMap.set(next.id, next);
|
|
777
|
+
this.logger.warn('[RELAY] switching to standby relay', { from: failedId, to: next.id });
|
|
778
|
+
void this.ensureConnection(next);
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
sendAllocate(conn, relayInfo) {
|
|
783
|
+
if (conn.allocateExhausted) {
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
if (!relayInfo.rawToken || relayInfo.rawToken.length === 0 || !relayInfo.key || !this.audioSsrc) {
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
const candidates = this.getAllocateCandidates(conn, relayInfo);
|
|
790
|
+
const candidate = candidates[Math.min(conn.allocateStage, candidates.length - 1)];
|
|
791
|
+
let packet;
|
|
792
|
+
if (this.allocateBuilder) {
|
|
793
|
+
packet = this.allocateBuilder(relayInfo, candidate, conn.stunTransactionId);
|
|
794
|
+
}
|
|
795
|
+
else {
|
|
796
|
+
packet = buildAllocateForRelay(relayInfo.rawToken, this.streamSsrcs ? createWasmStreamDescriptors(this.streamSsrcs) : buildSSRCSubscriptionList([this.audioSsrc], [this.subscriptionSsrc], this.selfPid, this.peerPid), TEXT_ENCODER.encode(relayInfo.key), candidate.ip, candidate.port, conn.stunTransactionId, { relayedAddress: candidate.form });
|
|
797
|
+
}
|
|
798
|
+
if (!packet) {
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
425
801
|
conn.allocatePacket = toArrayBuffer(packet);
|
|
802
|
+
const attemptKey = Buffer.from(conn.stunTransactionId).toString('hex');
|
|
803
|
+
if (!conn.allocateAttempts.has(attemptKey)) {
|
|
804
|
+
conn.allocateAttempts.set(attemptKey, { stage: conn.allocateStage, transactionId: conn.stunTransactionId, candidate });
|
|
805
|
+
}
|
|
426
806
|
this.sendToChannel(conn, conn.allocatePacket);
|
|
427
807
|
}
|
|
428
808
|
|
|
@@ -437,6 +817,10 @@ export class WaManualRelay extends EventEmitter {
|
|
|
437
817
|
}
|
|
438
818
|
|
|
439
819
|
closePeerObjects(conn) {
|
|
820
|
+
if (conn.fallbackTimer) {
|
|
821
|
+
clearTimeout(conn.fallbackTimer);
|
|
822
|
+
conn.fallbackTimer = null;
|
|
823
|
+
}
|
|
440
824
|
if (conn.keepaliveTimer) {
|
|
441
825
|
clearInterval(conn.keepaliveTimer);
|
|
442
826
|
conn.keepaliveTimer = null;
|
|
@@ -462,8 +846,15 @@ export class WaManualRelay extends EventEmitter {
|
|
|
462
846
|
return;
|
|
463
847
|
}
|
|
464
848
|
|
|
849
|
+
if (!conn.proven && conn.answered && !conn.refused && conn.allocateResponses === 0 && Date.now() - conn.openedAt >= 3000) {
|
|
850
|
+
this.markRelayProven(conn, 'answered');
|
|
851
|
+
}
|
|
852
|
+
conn.keepaliveTicks++;
|
|
853
|
+
if (conn.keepaliveTicks % 5 === 0) {
|
|
854
|
+
this.logger.info('[RELAY] status', { connectionId: conn.relayInfo.id, mode: conn.mode, port: conn.dialPort, answered: conn.answered, locked: conn.allocateLocked, sentPackets: conn.stats.sentPackets, receivedPackets: conn.stats.receivedPackets, rx: this.rxStun });
|
|
855
|
+
}
|
|
465
856
|
if (conn.allocatePacket) this.sendToChannel(conn, conn.allocatePacket);
|
|
466
|
-
this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing()));
|
|
857
|
+
this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing(conn.stunTransactionId)));
|
|
467
858
|
}, CONFIG.KEEPALIVE_INTERVAL_MS);
|
|
468
859
|
}
|
|
469
860
|
|
|
@@ -515,26 +906,45 @@ export class WaManualRelay extends EventEmitter {
|
|
|
515
906
|
}
|
|
516
907
|
}
|
|
517
908
|
|
|
909
|
+
pickMediaConnections() {
|
|
910
|
+
const open = [];
|
|
911
|
+
for (const [, conn] of this.connections) {
|
|
912
|
+
if (conn.state === ConnectionState.Open && conn.dataChannel) open.push(conn);
|
|
913
|
+
}
|
|
914
|
+
const proven = open.filter((conn) => conn.proven);
|
|
915
|
+
if (proven.length > 0) return proven;
|
|
916
|
+
const viable = open.filter((conn) => !conn.refused);
|
|
917
|
+
return viable.length > 0 ? viable : open;
|
|
918
|
+
}
|
|
919
|
+
|
|
518
920
|
broadcast(data) {
|
|
519
921
|
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
520
922
|
const isAudio = bytes.length < 2 || (bytes[1] & 0x7f) !== PayloadType.H264;
|
|
521
923
|
let sentAny = false;
|
|
522
|
-
for (const
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
} catch { }
|
|
531
|
-
}
|
|
924
|
+
for (const conn of this.pickMediaConnections()) {
|
|
925
|
+
try {
|
|
926
|
+
conn.dataChannel.send(data, isAudio);
|
|
927
|
+
conn.stats.sentPackets++;
|
|
928
|
+
conn.stats.sentBytes += byteLengthOf(data);
|
|
929
|
+
this.stats.sent++;
|
|
930
|
+
sentAny = true;
|
|
931
|
+
} catch { }
|
|
532
932
|
}
|
|
533
933
|
return sentAny;
|
|
534
934
|
}
|
|
535
935
|
|
|
536
936
|
handleRelayLoss(conn) {
|
|
537
|
-
if (conn.state !== ConnectionState.Open) return;
|
|
937
|
+
if (this.destroyed || conn.state !== ConnectionState.Open) return;
|
|
938
|
+
if (!conn.answered) {
|
|
939
|
+
if (this.advanceRoute(conn, 'relay_lost_unanswered')) {
|
|
940
|
+
void this.ensureConnection(conn.relayInfo);
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
if (conn.routes.length > 1) {
|
|
944
|
+
this.applyRoute(conn, 0);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
this.logger.warn('[RELAY] relay lost', { connectionId: conn.relayInfo.id, port: conn.dialPort, silentMs: Date.now() - conn.lastInboundAt, answered: conn.answered, rx: this.rxStun });
|
|
538
948
|
this.closePeerObjects(conn);
|
|
539
949
|
conn.state = ConnectionState.Closed;
|
|
540
950
|
if (!conn.recovering) conn.retryCount = 0;
|
|
@@ -593,13 +1003,22 @@ export class WaManualRelay extends EventEmitter {
|
|
|
593
1003
|
}
|
|
594
1004
|
|
|
595
1005
|
cleanup() {
|
|
1006
|
+
this.destroyed = true;
|
|
596
1007
|
for (const [, conn] of this.connections) {
|
|
597
1008
|
if (conn.retryTimer) clearTimeout(conn.retryTimer);
|
|
598
1009
|
conn.retryTimer = null;
|
|
599
1010
|
this.closePeerObjects(conn);
|
|
1011
|
+
conn.state = ConnectionState.Closed;
|
|
1012
|
+
conn.connectPromise = null;
|
|
1013
|
+
conn.packetBuffer = [];
|
|
1014
|
+
conn.allocateAttempts.clear();
|
|
600
1015
|
}
|
|
601
1016
|
this.connections.clear();
|
|
602
1017
|
this.relayMap.clear();
|
|
1018
|
+
this.standbyRelays = [];
|
|
1019
|
+
this.failedRelays.clear();
|
|
1020
|
+
this.answeredRelayNames.clear();
|
|
1021
|
+
this.rejectedModes.clear();
|
|
603
1022
|
this.globalBuffer = [];
|
|
604
1023
|
this.globalBufferedBytes = 0;
|
|
605
1024
|
}
|