werift 0.15.0-alpha.1 → 0.15.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/lib/ice/src/ice.js +13 -3
- package/lib/ice/src/ice.js.map +1 -1
- package/lib/webrtc/src/dataChannel.js +3 -2
- package/lib/webrtc/src/dataChannel.js.map +1 -1
- package/lib/webrtc/src/media/rtpTransceiver.d.ts +1 -1
- package/lib/webrtc/src/media/rtpTransceiver.js +3 -1
- package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
- package/lib/webrtc/src/peerConnection.d.ts +1 -1
- package/lib/webrtc/src/peerConnection.js +33 -25
- package/lib/webrtc/src/peerConnection.js.map +1 -1
- package/package.json +1 -1
- package/src/dataChannel.ts +4 -2
- package/src/media/rtpTransceiver.ts +5 -1
- package/src/peerConnection.ts +99 -85
package/lib/ice/src/ice.js
CHANGED
|
@@ -317,7 +317,13 @@ class Connection {
|
|
|
317
317
|
await promises_1.default.setTimeout(20);
|
|
318
318
|
}
|
|
319
319
|
// # wait for completion
|
|
320
|
-
|
|
320
|
+
let res;
|
|
321
|
+
if (this.checkList.length > 0) {
|
|
322
|
+
res = await this.checkListState.get();
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
res = ICE_FAILED;
|
|
326
|
+
}
|
|
321
327
|
// # cancel remaining checks
|
|
322
328
|
this.checkList.forEach((check) => check.handle?.cancel());
|
|
323
329
|
if (res !== ICE_COMPLETED) {
|
|
@@ -394,7 +400,9 @@ class Connection {
|
|
|
394
400
|
}
|
|
395
401
|
// # stop check list
|
|
396
402
|
if (this.checkList && !this.checkListDone) {
|
|
397
|
-
this.checkListState.put(new Promise((r) =>
|
|
403
|
+
this.checkListState.put(new Promise((r) => {
|
|
404
|
+
r(ICE_FAILED);
|
|
405
|
+
}));
|
|
398
406
|
}
|
|
399
407
|
this.nominated = {};
|
|
400
408
|
for (const protocol of this.protocols) {
|
|
@@ -614,7 +622,9 @@ class Connection {
|
|
|
614
622
|
}
|
|
615
623
|
if (!this.checkListDone) {
|
|
616
624
|
log("ICE failed");
|
|
617
|
-
this.checkListState.put(new Promise((r) =>
|
|
625
|
+
this.checkListState.put(new Promise((r) => {
|
|
626
|
+
r(ICE_FAILED);
|
|
627
|
+
}));
|
|
618
628
|
this.checkListDone = true;
|
|
619
629
|
}
|
|
620
630
|
}
|
package/lib/ice/src/ice.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ice.js","sourceRoot":"","sources":["../../../../ice/src/ice.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mCAAqC;AACrC,kDAA0B;AAC1B,8CAAsB;AACtB,+CAAwC;AACxC,2CAA6B;AAC7B,6DAAqC;AACrC,yDAAiC;AACjC,6BAA6B;AAC7B,gEAAuC;AACvC,qCAAgC;AAChC,+DAAqC;AACrC,gDAAwB;AAExB,2CAAgF;AAEhF,qCAA4E;AAC5E,wCAAgD;AAChD,4CAAuD;AACvD,8CAA+C;AAC/C,8CAAqD;AAGrD,MAAM,GAAG,GAAG,IAAA,eAAK,EAAC,4CAA4C,CAAC,CAAC;AAEhE,MAAa,UAAU;IAwCrB,YAAmB,cAAuB,EAAE,OAA6B;QAAtD,mBAAc,GAAd,cAAc,CAAS;QAvC1C,kBAAa,GAAG,IAAA,qBAAY,EAAC,CAAC,CAAC,CAAC;QAChC,kBAAa,GAAG,IAAA,qBAAY,EAAC,EAAE,CAAC,CAAC;QACjC,mBAAc,GAAW,EAAE,CAAC;QAC5B,mBAAc,GAAW,EAAE,CAAC;QAC5B,iBAAY,GAAG,KAAK,CAAC;QACrB,cAAS,GAAoB,EAAE,CAAC;QAChC,oBAAe,GAAgB,EAAE,CAAC;QAMlC,wBAAmB,GAAG,KAAK,CAAC;QAE5B,wBAAmB,GAAG,KAAK,CAAC;QAC5B,gBAAW,GAAW,MAAM,CAAC,IAAI,uBAAQ,CAAC,IAAA,oBAAW,EAAC,EAAE,CA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AED,SAAgB,eAAe,CAAC,IAAc;IAC5C,IAAI,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE;QAC1B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;KACvB;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AALD,0CAKC","sourcesContent":["import { randomBytes } from \"crypto\";\nimport debug from \"debug\";\nimport dns from \"dns\";\nimport { Uint64BE } from \"int64-buffer\";\nimport * as nodeIp from \"ip\";\nimport isEqual from \"lodash/isEqual\";\nimport range from \"lodash/range\";\nimport { isIPv4 } from \"net\";\nimport PCancelable from \"p-cancelable\";\nimport { Event } from \"rx.mini\";\nimport timers from \"timers/promises\";\nimport util from \"util\";\n\nimport { Candidate, candidateFoundation, candidatePriority } from \"./candidate\";\nimport { TransactionError } from \"./exceptions\";\nimport { difference, Future, future, PQueue, randomString } from \"./helper\";\nimport { classes, methods } from \"./stun/const\";\nimport { Message, parseMessage } from \"./stun/message\";\nimport { StunProtocol } from \"./stun/protocol\";\nimport { createTurnEndpoint } from \"./turn/protocol\";\nimport { Address, Protocol } from \"./types/model\";\n\nconst log = debug(\"werift-ice : packages/ice/src/ice.ts : log\");\n\nexport class Connection {\n localUserName = randomString(4);\n localPassword = randomString(22);\n remotePassword: string = \"\";\n remoteUsername: string = \"\";\n remoteIsLite = false;\n checkList: CandidatePair[] = [];\n localCandidates: Candidate[] = [];\n stunServer?: Address;\n turnServer?: Address;\n useIpv4: boolean;\n useIpv6: boolean;\n options: IceOptions;\n remoteCandidatesEnd = false;\n _components: Set<number>;\n _localCandidatesEnd = false;\n _tieBreaker: BigInt = BigInt(new Uint64BE(randomBytes(64)).toString());\n state: IceState = \"new\";\n\n readonly onData = new Event<[Buffer, number]>();\n readonly stateChanged = new Event<[IceState]>();\n\n private _remoteCandidates: Candidate[] = [];\n // P2P接続完了したソケット\n private nominated: { [key: number]: CandidatePair } = {};\n get nominatedKeys() {\n return Object.keys(this.nominated).map((v) => v.toString());\n }\n private nominating = new Set<number>();\n get remoteAddr() {\n return Object.values(this.nominated)[0].remoteAddr;\n }\n private checkListDone = false;\n private checkListState = new PQueue<number>();\n private earlyChecks: [Message, Address, Protocol][] = [];\n private localCandidatesStart = false;\n private protocols: Protocol[] = [];\n private queryConsentHandle?: Future;\n private promiseGatherCandidates?: Event<[]>;\n\n constructor(public iceControlling: boolean, options?: Partial<IceOptions>) {\n this.options = {\n ...defaultOptions,\n ...options,\n };\n const { components, stunServer, turnServer, useIpv4, useIpv6 } =\n this.options;\n this.stunServer = validateAddress(stunServer);\n this.turnServer = validateAddress(turnServer);\n this.useIpv4 = useIpv4;\n this.useIpv6 = useIpv6;\n this._components = new Set(range(1, components + 1));\n }\n\n // 4.1.1 Gathering Candidates\n async gatherCandidates(cb?: (candidate: Candidate) => void) {\n if (!this.localCandidatesStart) {\n this.localCandidatesStart = true;\n this.promiseGatherCandidates = new Event();\n\n const address = getHostAddress(this.useIpv4, this.useIpv6);\n for (const component of this._components) {\n const candidates = await this.getComponentCandidates(\n component,\n address,\n 5,\n cb\n );\n this.localCandidates = [...this.localCandidates, ...candidates];\n }\n\n this._localCandidatesEnd = true;\n this.promiseGatherCandidates.execute();\n }\n this.setState(\"completed\");\n }\n\n private async getComponentCandidates(\n component: number,\n addresses: string[],\n timeout = 5,\n cb?: (candidate: Candidate) => void\n ) {\n let candidates: Candidate[] = [];\n\n for (const address of addresses) {\n // # create transport\n const protocol = new StunProtocol(this);\n await protocol.connectionMade(isIPv4(address), this.options.portRange);\n protocol.localAddress = address;\n this.protocols.push(protocol);\n\n // # add host candidate\n const candidateAddress: Address = [address, protocol.getExtraInfo()[1]];\n\n protocol.localCandidate = new Candidate(\n candidateFoundation(\"host\", \"udp\", candidateAddress[0]),\n component,\n \"udp\",\n candidatePriority(component, \"host\"),\n candidateAddress[0],\n candidateAddress[1],\n \"host\"\n );\n\n candidates.push(protocol.localCandidate);\n if (cb) cb(protocol.localCandidate);\n }\n\n // # query STUN server for server-reflexive candidates (IPv4 only)\n const stunServer = this.stunServer;\n if (stunServer) {\n try {\n const srflxCandidates = (\n await Promise.all<Candidate | void>(\n this.protocols.map(\n (protocol) =>\n new Promise(async (r, f) => {\n const timer = setTimeout(f, timeout * 1000);\n if (\n protocol.localCandidate?.host &&\n isIPv4(protocol.localCandidate?.host)\n ) {\n const candidate = await serverReflexiveCandidate(\n protocol,\n stunServer\n ).catch((error) => log(\"error\", error));\n if (candidate && cb) cb(candidate);\n\n clearTimeout(timer);\n r(candidate);\n } else {\n clearTimeout(timer);\n r();\n }\n })\n )\n )\n ).filter((v): v is Candidate => typeof v !== \"undefined\");\n candidates = [...candidates, ...srflxCandidates];\n } catch (error) {\n log(\"query STUN server\", error);\n }\n }\n\n if (\n this.turnServer &&\n this.options.turnUsername &&\n this.options.turnPassword\n ) {\n const protocol = await createTurnEndpoint(\n this.turnServer,\n this.options.turnUsername,\n this.options.turnPassword,\n { portRange: this.options.portRange }\n );\n this.protocols.push(protocol);\n\n const candidateAddress = protocol.turn.relayedAddress;\n const relatedAddress = protocol.turn.mappedAddress;\n\n log(\"turn candidateAddress\", candidateAddress);\n\n protocol.localCandidate = new Candidate(\n candidateFoundation(\"relay\", \"udp\", candidateAddress[0]),\n component,\n \"udp\",\n candidatePriority(component, \"relay\"),\n candidateAddress[0],\n candidateAddress[1],\n \"relay\",\n relatedAddress[0],\n relatedAddress[1]\n );\n protocol.receiver = this;\n\n if (this.options.forceTurn) {\n candidates = [];\n }\n\n candidates.push(protocol.localCandidate);\n }\n\n return candidates;\n }\n\n async connect() {\n // \"\"\"\n // Perform ICE handshake.\n //\n // This coroutine returns if a candidate pair was successfully nominated\n // and raises an exception otherwise.\n // \"\"\"\n log(\"start connect ice\");\n if (!this._localCandidatesEnd) {\n if (!this.localCandidatesStart)\n throw new Error(\"Local candidates gathering was not performed\");\n if (this.promiseGatherCandidates)\n // wait for GatherCandidates finish\n await this.promiseGatherCandidates.asPromise();\n }\n if (!this.remoteUsername || !this.remotePassword)\n throw new Error(\"Remote username or password is missing\");\n\n // # 5.7.1. Forming Candidate Pairs\n this.remoteCandidates.forEach(this.pairRemoteCandidate);\n this.sortCheckList();\n\n this.unfreezeInitial();\n\n // # handle early checks\n this.earlyChecks.forEach((earlyCheck) => this.checkIncoming(...earlyCheck));\n this.earlyChecks = [];\n\n // # perform checks\n // 5.8. Scheduling Checks\n for (;;) {\n if (!this.schedulingChecks()) break;\n await timers.setTimeout(20);\n }\n\n // # wait for completion\n const res: number =\n this.checkList.length > 0 ? await this.checkListState.get() : ICE_FAILED;\n\n // # cancel remaining checks\n this.checkList.forEach((check) => check.handle?.cancel());\n\n if (res !== ICE_COMPLETED) {\n throw new Error(\"ICE negotiation failed\");\n }\n\n // # start consent freshness tests\n this.queryConsentHandle = future(this.queryConsent());\n\n this.setState(\"connected\");\n }\n\n private unfreezeInitial() {\n // # unfreeze first pair for the first component\n const firstPair = this.checkList.find(\n (pair) => pair.component === Math.min(...[...this._components])\n );\n if (!firstPair) return;\n if (firstPair.state === CandidatePairState.FROZEN) {\n this.checkState(firstPair, CandidatePairState.WAITING);\n }\n\n // # unfreeze pairs with same component but different foundations\n const seenFoundations = new Set(firstPair.localCandidate.foundation);\n for (const pair of this.checkList) {\n if (\n pair.component === firstPair.component &&\n !seenFoundations.has(pair.localCandidate.foundation) &&\n pair.state === CandidatePairState.FROZEN\n ) {\n this.checkState(pair, CandidatePairState.WAITING);\n seenFoundations.add(pair.localCandidate.foundation);\n }\n }\n }\n\n // 5.8 Scheduling Checks\n private schedulingChecks() {\n // Ordinary Check\n {\n // # find the highest-priority pair that is in the waiting state\n const pair = this.checkList\n .filter((pair) => {\n if (this.options.forceTurn && pair.protocol.type === \"stun\")\n return false;\n return true;\n })\n .find((pair) => pair.state === CandidatePairState.WAITING);\n if (pair) {\n pair.handle = future(this.checkStart(pair));\n return true;\n }\n }\n\n {\n // # find the highest-priority pair that is in the frozen state\n const pair = this.checkList.find(\n (pair) => pair.state === CandidatePairState.FROZEN\n );\n if (pair) {\n pair.handle = future(this.checkStart(pair));\n return true;\n }\n }\n\n // # if we expect more candidates, keep going\n if (!this.remoteCandidatesEnd) {\n return !this.checkListDone;\n }\n\n return false;\n }\n\n // 4.1.1.4 ? 生存確認 life check\n private queryConsent = () =>\n new PCancelable(async (r, f, onCancel) => {\n let failures = 0;\n\n const cancelEvent = new AbortController();\n onCancel(() => {\n failures += CONSENT_FAILURES;\n cancelEvent.abort();\n f(\"cancel\");\n });\n\n // \"\"\"\n // Periodically check consent (RFC 7675).\n // \"\"\"\n\n try {\n while (!this.remoteIsLite && this.state !== \"closed\") {\n // # randomize between 0.8 and 1.2 times CONSENT_INTERVAL\n await timers.setTimeout(\n CONSENT_INTERVAL * (0.8 + 0.4 * Math.random()) * 1000,\n undefined,\n { signal: cancelEvent.signal }\n );\n\n for (const key of this.nominatedKeys) {\n const pair = this.nominated[Number(key)];\n const request = this.buildRequest(pair, false);\n try {\n const [msg, addr] = await pair.protocol.request(\n request,\n pair.remoteAddr,\n Buffer.from(this.remotePassword, \"utf8\"),\n 0\n );\n failures = 0;\n if (this.state === \"disconnected\") {\n this.setState(\"connected\");\n }\n } catch (error) {\n failures++;\n this.setState(\"disconnected\");\n }\n if (failures >= CONSENT_FAILURES) {\n log(\"Consent to send expired\");\n this.queryConsentHandle = undefined;\n // 切断検知\n r(await this.close());\n return;\n }\n }\n }\n } catch (error) {}\n });\n\n async close() {\n // \"\"\"\n // Close the connection.\n // \"\"\"\n\n this.setState(\"closed\");\n\n // # stop consent freshness tests\n if (this.queryConsentHandle && !this.queryConsentHandle.done()) {\n this.queryConsentHandle.cancel();\n try {\n await this.queryConsentHandle.promise;\n } catch (error) {\n // pass\n }\n }\n\n // # stop check list\n if (this.checkList && !this.checkListDone) {\n this.checkListState.put(new Promise((r) => r(ICE_FAILED)));\n }\n\n this.nominated = {};\n for (const protocol of this.protocols) {\n if (protocol.close) {\n await protocol.close();\n }\n }\n\n this.protocols = [];\n this.localCandidates = [];\n }\n\n private setState(state: IceState) {\n this.state = state;\n this.stateChanged.execute(state);\n }\n\n async addRemoteCandidate(remoteCandidate: Candidate | undefined) {\n // \"\"\"\n // Add a remote candidate or signal end-of-candidates.\n\n // To signal end-of-candidates, pass `None`.\n\n // :param remote_candidate: A :class:`Candidate` instance or `None`.\n // \"\"\"\n if (this.remoteCandidatesEnd)\n throw new Error(\"Cannot add remote candidate after end-of-candidates.\");\n\n if (!remoteCandidate) {\n this.pruneComponents();\n this.remoteCandidatesEnd = true;\n return;\n }\n\n if (remoteCandidate.host.includes(\".local\")) {\n await timers.setTimeout(10);\n\n const res = await util\n .promisify(dns.lookup)(remoteCandidate.host)\n .catch((err) => {\n log(err, remoteCandidate);\n });\n if (res) {\n remoteCandidate.host = res.address;\n } else {\n // todo fix\n remoteCandidate.host = \"127.0.0.1\";\n }\n }\n\n try {\n validateRemoteCandidate(remoteCandidate);\n } catch (error) {\n return;\n }\n this.remoteCandidates.push(remoteCandidate);\n\n this.pairRemoteCandidate(remoteCandidate);\n this.sortCheckList();\n }\n\n send = async (data: Buffer) => {\n // \"\"\"\n // Send a datagram on the first component.\n\n // If the connection is not established, a `ConnectionError` is raised.\n\n // :param data: The data to be sent.\n // \"\"\"\n await this.sendTo(data, 1);\n };\n\n private async sendTo(data: Buffer, component: number) {\n // \"\"\"\n // Send a datagram on the specified component.\n\n // If the connection is not established, a `ConnectionError` is raised.\n\n // :param data: The data to be sent.\n // :param component: The component on which to send the data.\n // \"\"\"\n const activePair = this.nominated[component];\n if (activePair) {\n await activePair.protocol.sendData(data, activePair.remoteAddr);\n } else {\n throw new Error(\"Cannot send data, ice not connected\");\n }\n }\n\n getDefaultCandidate(component: number) {\n const candidates = this.localCandidates.sort(\n (a, b) => a.priority - b.priority\n );\n const candidate = candidates.find(\n (candidate) => candidate.component === component\n );\n return candidate;\n }\n\n requestReceived(\n message: Message,\n addr: Address,\n protocol: Protocol,\n rawData: Buffer\n ) {\n if (message.messageMethod !== methods.BINDING) {\n this.respondError(message, addr, protocol, [400, \"Bad Request\"]);\n return;\n }\n\n // # authenticate request\n try {\n parseMessage(rawData, Buffer.from(this.localPassword, \"utf8\"));\n if (!this.remoteUsername) {\n const rxUsername = `${this.localUserName}:${this.remoteUsername}`;\n if (message.attributes[\"USERNAME\"] != rxUsername)\n throw new Error(\"Wrong username\");\n }\n } catch (error) {\n this.respondError(message, addr, protocol, [400, \"Bad Request\"]);\n return;\n }\n\n const { iceControlling } = this;\n\n // 7.2.1.1. Detecting and Repairing Role Conflicts\n if (iceControlling && message.attributesKeys.includes(\"ICE-CONTROLLING\")) {\n if (this._tieBreaker >= message.attributes[\"ICE-CONTROLLING\"]) {\n this.respondError(message, addr, protocol, [487, \"Role Conflict\"]);\n return;\n } else {\n this.switchRole(false);\n }\n } else if (\n !iceControlling &&\n message.attributesKeys.includes(\"ICE-CONTROLLED\")\n ) {\n if (this._tieBreaker < message.attributes[\"ICE-CONTROLLED\"]) {\n this.respondError(message, addr, protocol, [487, \"Role Conflict\"]);\n } else {\n this.switchRole(true);\n return;\n }\n }\n\n // # send binding response\n const response = new Message(\n methods.BINDING,\n classes.RESPONSE,\n message.transactionId\n );\n response.attributes[\"XOR-MAPPED-ADDRESS\"] = addr;\n response.addMessageIntegrity(Buffer.from(this.localPassword, \"utf8\"));\n response.addFingerprint();\n protocol.sendStun(response, addr);\n\n // todo fix\n // if (this.checkList.length === 0) {\n // this.earlyChecks.push([message, addr, protocol]);\n // } else {\n this.checkIncoming(message, addr, protocol);\n // }\n }\n\n dataReceived(data: Buffer, component: number) {\n this.onData.execute(data, component);\n }\n\n // for test only\n set remoteCandidates(value: Candidate[]) {\n if (this.remoteCandidatesEnd)\n throw new Error(\"Cannot set remote candidates after end-of-candidates.\");\n this._remoteCandidates = [];\n for (const remoteCandidate of value) {\n try {\n validateRemoteCandidate(remoteCandidate);\n } catch (error) {\n continue;\n }\n this.remoteCandidates.push(remoteCandidate);\n }\n this.pruneComponents();\n this.remoteCandidatesEnd = true;\n }\n get remoteCandidates() {\n return this._remoteCandidates;\n }\n\n private pruneComponents() {\n const seenComponents = new Set(\n this.remoteCandidates.map((v) => v.component)\n );\n const missingComponents = [...difference(this._components, seenComponents)];\n if (missingComponents.length > 0) {\n this._components = seenComponents;\n }\n }\n\n private sortCheckList() {\n sortCandidatePairs(this.checkList, this.iceControlling);\n }\n\n private findPair(protocol: Protocol, remoteCandidate: Candidate) {\n const pair = this.checkList.find(\n (pair) =>\n isEqual(pair.protocol, protocol) &&\n isEqual(pair.remoteCandidate, remoteCandidate)\n );\n return pair;\n }\n\n private checkState(pair: CandidatePair, state: CandidatePairState) {\n pair.state = state;\n }\n\n private switchRole(iceControlling: boolean) {\n log(\"switch role\", iceControlling);\n this.iceControlling = iceControlling;\n this.sortCheckList();\n }\n\n private checkComplete(pair: CandidatePair) {\n pair.handle = undefined;\n if (pair.state === CandidatePairState.SUCCEEDED) {\n if (pair.nominated) {\n this.nominated[pair.component] = pair;\n\n // 8.1.2. Updating States\n\n // The agent MUST remove all Waiting and Frozen pairs in the check\n // list and triggered check queue for the same component as the\n // nominated pairs for that media stream.\n for (const p of this.checkList) {\n if (\n p.component === pair.component &&\n [CandidatePairState.WAITING, CandidatePairState.FROZEN].includes(\n p.state\n )\n ) {\n this.checkState(p, CandidatePairState.FAILED);\n }\n }\n }\n\n // Once there is at least one nominated pair in the valid list for\n // every component of at least one media stream and the state of the\n // check list is Running:\n if (this.nominatedKeys.length === this._components.size) {\n if (!this.checkListDone) {\n log(\"ICE completed\");\n this.checkListState.put(new Promise((r) => r(ICE_COMPLETED)));\n this.checkListDone = true;\n }\n return;\n }\n\n // 7.1.3.2.3. Updating Pair States\n for (const p of this.checkList) {\n if (\n p.localCandidate.foundation === pair.localCandidate.foundation &&\n p.state === CandidatePairState.FROZEN\n ) {\n this.checkState(p, CandidatePairState.WAITING);\n }\n }\n }\n\n {\n const list = [CandidatePairState.SUCCEEDED, CandidatePairState.FAILED];\n if (this.checkList.find(({ state }) => !list.includes(state))) {\n return;\n }\n }\n\n if (!this.iceControlling) {\n const target = CandidatePairState.SUCCEEDED;\n if (this.checkList.find(({ state }) => state === target)) {\n return;\n }\n }\n\n if (!this.checkListDone) {\n log(\"ICE failed\");\n this.checkListState.put(new Promise((r) => r(ICE_FAILED)));\n this.checkListDone = true;\n }\n }\n\n // 3. Terminology : Check\n checkStart = (pair: CandidatePair) =>\n new PCancelable(async (r, f, onCancel) => {\n onCancel(() => f(\"cancel\"));\n\n // \"\"\"\n // Starts a check.\n // \"\"\"\n\n log(\"check start\", pair.remoteCandidate);\n\n this.checkState(pair, CandidatePairState.IN_PROGRESS);\n\n const nominate = this.iceControlling && !this.remoteIsLite;\n const request = this.buildRequest(pair, nominate);\n\n const result: { response?: Message; addr?: Address } = {};\n try {\n const [response, addr] = await pair.protocol.request(\n request,\n pair.remoteAddr,\n Buffer.from(this.remotePassword, \"utf8\")\n );\n log(\"response\", response, addr);\n result.response = response;\n result.addr = addr;\n } catch (error: any) {\n const exc: TransactionError = error;\n // 7.1.3.1. Failure Cases\n log(\"failure case\", exc.response);\n if (exc.response?.attributes[\"ERROR-CODE\"][0] === 487) {\n if (request.attributesKeys.includes(\"ICE-CONTROLLED\")) {\n this.switchRole(true);\n } else if (request.attributesKeys.includes(\"ICE-CONTROLLING\")) {\n this.switchRole(false);\n }\n await this.checkStart(pair);\n r();\n return;\n } else {\n log(\"CandidatePairState.FAILED\");\n this.checkState(pair, CandidatePairState.FAILED);\n this.checkComplete(pair);\n r();\n return;\n }\n }\n\n // # check remote address matches\n if (!isEqual(result.addr, pair.remoteAddr)) {\n this.checkState(pair, CandidatePairState.FAILED);\n this.checkComplete(pair);\n r();\n return;\n }\n\n // # success\n if (nominate || pair.remoteNominated) {\n // # nominated by agressive nomination or the remote party\n pair.nominated = true;\n } else if (this.iceControlling && !this.nominating.has(pair.component)) {\n // # perform regular nomination\n this.nominating.add(pair.component);\n const request = this.buildRequest(pair, true);\n try {\n await pair.protocol.request(\n request,\n pair.remoteAddr,\n Buffer.from(this.remotePassword, \"utf8\")\n );\n } catch (error) {\n this.checkState(pair, CandidatePairState.FAILED);\n this.checkComplete(pair);\n return;\n }\n pair.nominated = true;\n }\n\n this.checkState(pair, CandidatePairState.SUCCEEDED);\n this.checkComplete(pair);\n r();\n });\n\n // 7.2. STUN Server Procedures\n // 7.2.1.3、7.2.1.4、および7.2.1.5\n checkIncoming(message: Message, addr: Address, protocol: Protocol) {\n // \"\"\"\n // Handle a successful incoming check.\n // \"\"\"\n const component = protocol.localCandidate?.component;\n if (component == undefined) throw new Error();\n\n // find remote candidate\n let remoteCandidate: Candidate | undefined;\n const [host, port] = addr;\n for (const c of this.remoteCandidates) {\n if (c.host === host && c.port === port) {\n remoteCandidate = c;\n if (remoteCandidate.component !== component)\n throw new Error(\"checkIncoming\");\n break;\n }\n }\n if (!remoteCandidate) {\n // 7.2.1.3. Learning Peer Reflexive Candidates\n remoteCandidate = new Candidate(\n randomString(10),\n component,\n \"udp\",\n message.attributes[\"PRIORITY\"],\n host,\n port,\n \"prflx\"\n );\n this.remoteCandidates.push(remoteCandidate);\n }\n\n // find pair\n let pair = this.findPair(protocol, remoteCandidate);\n if (!pair) {\n pair = new CandidatePair(protocol, remoteCandidate);\n pair.state = CandidatePairState.WAITING;\n this.checkList.push(pair);\n this.sortCheckList();\n }\n\n // 7.2.1.4. Triggered Checks\n if (\n [CandidatePairState.WAITING, CandidatePairState.FAILED].includes(\n pair.state\n )\n ) {\n pair.handle = future(this.checkStart(pair));\n }\n\n // 7.2.1.5. Updating the Nominated Flag\n if (\n message.attributesKeys.includes(\"USE-CANDIDATE\") &&\n !this.iceControlling\n ) {\n pair.remoteNominated = true;\n if (pair.state === CandidatePairState.SUCCEEDED) {\n pair.nominated = true;\n this.checkComplete(pair);\n }\n }\n }\n\n private pairRemoteCandidate = (remoteCandidate: Candidate) => {\n for (const protocol of this.protocols) {\n if (\n protocol.localCandidate?.canPairWith(remoteCandidate) &&\n !this.findPair(protocol, remoteCandidate)\n ) {\n const pair = new CandidatePair(protocol, remoteCandidate);\n this.checkList.push(pair);\n }\n }\n };\n\n private buildRequest(pair: CandidatePair, nominate: boolean) {\n const txUsername = `${this.remoteUsername}:${this.localUserName}`;\n const request = new Message(methods.BINDING, classes.REQUEST);\n request.attributes[\"USERNAME\"] = txUsername;\n request.attributes[\"PRIORITY\"] = candidatePriority(pair.component, \"prflx\");\n if (this.iceControlling) {\n request.attributes[\"ICE-CONTROLLING\"] = this._tieBreaker;\n if (nominate) {\n request.attributes[\"USE-CANDIDATE\"] = null;\n }\n } else {\n request.attributes[\"ICE-CONTROLLED\"] = this._tieBreaker;\n }\n return request;\n }\n\n private respondError(\n request: Message,\n addr: Address,\n protocol: Protocol,\n errorCode: [number, string]\n ) {\n const response = new Message(\n request.messageMethod,\n classes.ERROR,\n request.transactionId\n );\n response.attributes[\"ERROR-CODE\"] = errorCode;\n response.addMessageIntegrity(Buffer.from(this.localPassword, \"utf8\"));\n response.addFingerprint();\n protocol.sendStun(response, addr);\n }\n}\n\nexport class CandidatePair {\n handle?: Future;\n nominated = false;\n remoteNominated = false;\n // 5.7.4. Computing States\n state = CandidatePairState.FROZEN;\n\n constructor(public protocol: Protocol, public remoteCandidate: Candidate) {}\n\n get localCandidate() {\n if (!this.protocol.localCandidate)\n throw new Error(\"localCandidate not exist\");\n return this.protocol.localCandidate;\n }\n\n get remoteAddr(): Address {\n return [this.remoteCandidate.host, this.remoteCandidate.port];\n }\n\n get component() {\n return this.localCandidate.component;\n }\n}\n\nconst ICE_COMPLETED = 1 as const;\nconst ICE_FAILED = 2 as const;\n\nconst CONSENT_INTERVAL = 5;\nconst CONSENT_FAILURES = 6;\n\nexport enum CandidatePairState {\n FROZEN = 0,\n WAITING = 1,\n IN_PROGRESS = 2,\n SUCCEEDED = 3,\n FAILED = 4,\n}\n\ntype IceState = \"disconnected\" | \"closed\" | \"completed\" | \"new\" | \"connected\";\n\nexport interface IceOptions {\n components: number;\n stunServer?: Address;\n turnServer?: Address;\n turnUsername?: string;\n turnPassword?: string;\n turnSsl?: boolean;\n turnTransport?: string;\n forceTurn?: boolean;\n useIpv4: boolean;\n useIpv6: boolean;\n portRange?: [number, number];\n}\n\nconst defaultOptions: IceOptions = {\n components: 1,\n useIpv4: true,\n useIpv6: true,\n};\n\nexport function validateRemoteCandidate(candidate: Candidate) {\n // \"\"\"\n // Check the remote candidate is supported.\n // \"\"\"\n if (![\"host\", \"relay\", \"srflx\"].includes(candidate.type))\n throw new Error(`Unexpected candidate type \"${candidate.type}\"`);\n\n // ipaddress.ip_address(candidate.host)\n return candidate;\n}\n\nexport function sortCandidatePairs(\n pairs: CandidatePair[],\n iceControlling: boolean\n) {\n pairs.sort(\n (a, b) =>\n candidatePairPriority(\n a.localCandidate,\n a.remoteCandidate,\n iceControlling\n ) -\n candidatePairPriority(b.localCandidate, b.remoteCandidate, iceControlling)\n );\n}\n\n// 5.7.2. Computing Pair Priority and Ordering Pairs\nexport function candidatePairPriority(\n local: Candidate,\n remote: Candidate,\n iceControlling: boolean\n) {\n const G = (iceControlling && local.priority) || remote.priority;\n const D = (iceControlling && remote.priority) || local.priority;\n return (1 << 32) * Math.min(G, D) + 2 * Math.max(G, D) + (G > D ? 1 : 0);\n}\n\nexport function getHostAddress(useIpv4: boolean, useIpv6: boolean) {\n const address: string[] = [];\n if (useIpv4) address.push(nodeIp.address(\"\", \"ipv4\"));\n if (useIpv6) address.push(nodeIp.address(\"\", \"ipv6\"));\n return address;\n}\n\nexport async function serverReflexiveCandidate(\n protocol: Protocol,\n stunServer: Address\n) {\n // \"\"\"\n // Query STUN server to obtain a server-reflexive candidate.\n // \"\"\"\n\n // # perform STUN query\n const request = new Message(methods.BINDING, classes.REQUEST);\n try {\n const [response] = await protocol.request(request, stunServer);\n\n const localCandidate = protocol.localCandidate;\n if (!localCandidate) throw new Error(\"not exist\");\n\n return new Candidate(\n candidateFoundation(\"srflx\", \"udp\", localCandidate.host),\n localCandidate.component,\n localCandidate.transport,\n candidatePriority(localCandidate.component, \"srflx\"),\n response.attributes[\"XOR-MAPPED-ADDRESS\"][0],\n response.attributes[\"XOR-MAPPED-ADDRESS\"][1],\n \"srflx\",\n localCandidate.host,\n localCandidate.port\n );\n } catch (error) {\n // todo fix\n log(\"error serverReflexiveCandidate\", error);\n }\n}\n\nexport function validateAddress(addr?: Address): Address | undefined {\n if (addr && isNaN(addr[1])) {\n return [addr[0], 443];\n }\n return addr;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ice.js","sourceRoot":"","sources":["../../../../ice/src/ice.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mCAAqC;AACrC,kDAA0B;AAC1B,8CAAsB;AACtB,+CAAwC;AACxC,2CAA6B;AAC7B,6DAAqC;AACrC,yDAAiC;AACjC,6BAA6B;AAC7B,gEAAuC;AACvC,qCAAgC;AAChC,+DAAqC;AACrC,gDAAwB;AAExB,2CAAgF;AAEhF,qCAA4E;AAC5E,wCAAgD;AAChD,4CAAuD;AACvD,8CAA+C;AAC/C,8CAAqD;AAGrD,MAAM,GAAG,GAAG,IAAA,eAAK,EAAC,4CAA4C,CAAC,CAAC;AAEhE,MAAa,UAAU;IAwCrB,YAAmB,cAAuB,EAAE,OAA6B;QAAtD,mBAAc,GAAd,cAAc,CAAS;QAvC1C,kBAAa,GAAG,IAAA,qBAAY,EAAC,CAAC,CAAC,CAAC;QAChC,kBAAa,GAAG,IAAA,qBAAY,EAAC,EAAE,CAAC,CAAC;QACjC,mBAAc,GAAW,EAAE,CAAC;QAC5B,mBAAc,GAAW,EAAE,CAAC;QAC5B,iBAAY,GAAG,KAAK,CAAC;QACrB,cAAS,GAAoB,EAAE,CAAC;QAChC,oBAAe,GAAgB,EAAE,CAAC;QAMlC,wBAAmB,GAAG,KAAK,CAAC;QAE5B,wBAAmB,GAAG,KAAK,CAAC;QAC5B,gBAAW,GAAW,MAAM,CAAC,IAAI,uBAAQ,CAAC,IAAA,oBAAW,EAAC,EAAE,CAAC,CAAC,CAAC,Q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E,KAAK,CAAC,CAAC;KAC9C;AACH,CAAC;AA/BD,4DA+BC;AAED,SAAgB,eAAe,CAAC,IAAc;IAC5C,IAAI,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE;QAC1B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;KACvB;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AALD,0CAKC","sourcesContent":["import { randomBytes } from \"crypto\";\nimport debug from \"debug\";\nimport dns from \"dns\";\nimport { Uint64BE } from \"int64-buffer\";\nimport * as nodeIp from \"ip\";\nimport isEqual from \"lodash/isEqual\";\nimport range from \"lodash/range\";\nimport { isIPv4 } from \"net\";\nimport PCancelable from \"p-cancelable\";\nimport { Event } from \"rx.mini\";\nimport timers from \"timers/promises\";\nimport util from \"util\";\n\nimport { Candidate, candidateFoundation, candidatePriority } from \"./candidate\";\nimport { TransactionError } from \"./exceptions\";\nimport { difference, Future, future, PQueue, randomString } from \"./helper\";\nimport { classes, methods } from \"./stun/const\";\nimport { Message, parseMessage } from \"./stun/message\";\nimport { StunProtocol } from \"./stun/protocol\";\nimport { createTurnEndpoint } from \"./turn/protocol\";\nimport { Address, Protocol } from \"./types/model\";\n\nconst log = debug(\"werift-ice : packages/ice/src/ice.ts : log\");\n\nexport class Connection {\n localUserName = randomString(4);\n localPassword = randomString(22);\n remotePassword: string = \"\";\n remoteUsername: string = \"\";\n remoteIsLite = false;\n checkList: CandidatePair[] = [];\n localCandidates: Candidate[] = [];\n stunServer?: Address;\n turnServer?: Address;\n useIpv4: boolean;\n useIpv6: boolean;\n options: IceOptions;\n remoteCandidatesEnd = false;\n _components: Set<number>;\n _localCandidatesEnd = false;\n _tieBreaker: BigInt = BigInt(new Uint64BE(randomBytes(64)).toString());\n state: IceState = \"new\";\n\n readonly onData = new Event<[Buffer, number]>();\n readonly stateChanged = new Event<[IceState]>();\n\n private _remoteCandidates: Candidate[] = [];\n // P2P接続完了したソケット\n private nominated: { [key: number]: CandidatePair } = {};\n get nominatedKeys() {\n return Object.keys(this.nominated).map((v) => v.toString());\n }\n private nominating = new Set<number>();\n get remoteAddr() {\n return Object.values(this.nominated)[0].remoteAddr;\n }\n private checkListDone = false;\n private checkListState = new PQueue<number>();\n private earlyChecks: [Message, Address, Protocol][] = [];\n private localCandidatesStart = false;\n private protocols: Protocol[] = [];\n private queryConsentHandle?: Future;\n private promiseGatherCandidates?: Event<[]>;\n\n constructor(public iceControlling: boolean, options?: Partial<IceOptions>) {\n this.options = {\n ...defaultOptions,\n ...options,\n };\n const { components, stunServer, turnServer, useIpv4, useIpv6 } =\n this.options;\n this.stunServer = validateAddress(stunServer);\n this.turnServer = validateAddress(turnServer);\n this.useIpv4 = useIpv4;\n this.useIpv6 = useIpv6;\n this._components = new Set(range(1, components + 1));\n }\n\n // 4.1.1 Gathering Candidates\n async gatherCandidates(cb?: (candidate: Candidate) => void) {\n if (!this.localCandidatesStart) {\n this.localCandidatesStart = true;\n this.promiseGatherCandidates = new Event();\n\n const address = getHostAddress(this.useIpv4, this.useIpv6);\n for (const component of this._components) {\n const candidates = await this.getComponentCandidates(\n component,\n address,\n 5,\n cb\n );\n this.localCandidates = [...this.localCandidates, ...candidates];\n }\n\n this._localCandidatesEnd = true;\n this.promiseGatherCandidates.execute();\n }\n this.setState(\"completed\");\n }\n\n private async getComponentCandidates(\n component: number,\n addresses: string[],\n timeout = 5,\n cb?: (candidate: Candidate) => void\n ) {\n let candidates: Candidate[] = [];\n\n for (const address of addresses) {\n // # create transport\n const protocol = new StunProtocol(this);\n await protocol.connectionMade(isIPv4(address), this.options.portRange);\n protocol.localAddress = address;\n this.protocols.push(protocol);\n\n // # add host candidate\n const candidateAddress: Address = [address, protocol.getExtraInfo()[1]];\n\n protocol.localCandidate = new Candidate(\n candidateFoundation(\"host\", \"udp\", candidateAddress[0]),\n component,\n \"udp\",\n candidatePriority(component, \"host\"),\n candidateAddress[0],\n candidateAddress[1],\n \"host\"\n );\n\n candidates.push(protocol.localCandidate);\n if (cb) cb(protocol.localCandidate);\n }\n\n // # query STUN server for server-reflexive candidates (IPv4 only)\n const stunServer = this.stunServer;\n if (stunServer) {\n try {\n const srflxCandidates = (\n await Promise.all<Candidate | void>(\n this.protocols.map(\n (protocol) =>\n new Promise(async (r, f) => {\n const timer = setTimeout(f, timeout * 1000);\n if (\n protocol.localCandidate?.host &&\n isIPv4(protocol.localCandidate?.host)\n ) {\n const candidate = await serverReflexiveCandidate(\n protocol,\n stunServer\n ).catch((error) => log(\"error\", error));\n if (candidate && cb) cb(candidate);\n\n clearTimeout(timer);\n r(candidate);\n } else {\n clearTimeout(timer);\n r();\n }\n })\n )\n )\n ).filter((v): v is Candidate => typeof v !== \"undefined\");\n candidates = [...candidates, ...srflxCandidates];\n } catch (error) {\n log(\"query STUN server\", error);\n }\n }\n\n if (\n this.turnServer &&\n this.options.turnUsername &&\n this.options.turnPassword\n ) {\n const protocol = await createTurnEndpoint(\n this.turnServer,\n this.options.turnUsername,\n this.options.turnPassword,\n { portRange: this.options.portRange }\n );\n this.protocols.push(protocol);\n\n const candidateAddress = protocol.turn.relayedAddress;\n const relatedAddress = protocol.turn.mappedAddress;\n\n log(\"turn candidateAddress\", candidateAddress);\n\n protocol.localCandidate = new Candidate(\n candidateFoundation(\"relay\", \"udp\", candidateAddress[0]),\n component,\n \"udp\",\n candidatePriority(component, \"relay\"),\n candidateAddress[0],\n candidateAddress[1],\n \"relay\",\n relatedAddress[0],\n relatedAddress[1]\n );\n protocol.receiver = this;\n\n if (this.options.forceTurn) {\n candidates = [];\n }\n\n candidates.push(protocol.localCandidate);\n }\n\n return candidates;\n }\n\n async connect() {\n // \"\"\"\n // Perform ICE handshake.\n //\n // This coroutine returns if a candidate pair was successfully nominated\n // and raises an exception otherwise.\n // \"\"\"\n log(\"start connect ice\");\n if (!this._localCandidatesEnd) {\n if (!this.localCandidatesStart)\n throw new Error(\"Local candidates gathering was not performed\");\n if (this.promiseGatherCandidates)\n // wait for GatherCandidates finish\n await this.promiseGatherCandidates.asPromise();\n }\n if (!this.remoteUsername || !this.remotePassword)\n throw new Error(\"Remote username or password is missing\");\n\n // # 5.7.1. Forming Candidate Pairs\n this.remoteCandidates.forEach(this.pairRemoteCandidate);\n this.sortCheckList();\n\n this.unfreezeInitial();\n\n // # handle early checks\n this.earlyChecks.forEach((earlyCheck) => this.checkIncoming(...earlyCheck));\n this.earlyChecks = [];\n\n // # perform checks\n // 5.8. Scheduling Checks\n for (;;) {\n if (!this.schedulingChecks()) break;\n await timers.setTimeout(20);\n }\n\n // # wait for completion\n let res: number;\n if (this.checkList.length > 0) {\n res = await this.checkListState.get();\n } else {\n res = ICE_FAILED;\n }\n\n // # cancel remaining checks\n this.checkList.forEach((check) => check.handle?.cancel());\n\n if (res !== ICE_COMPLETED) {\n throw new Error(\"ICE negotiation failed\");\n }\n\n // # start consent freshness tests\n this.queryConsentHandle = future(this.queryConsent());\n\n this.setState(\"connected\");\n }\n\n private unfreezeInitial() {\n // # unfreeze first pair for the first component\n const firstPair = this.checkList.find(\n (pair) => pair.component === Math.min(...[...this._components])\n );\n if (!firstPair) return;\n if (firstPair.state === CandidatePairState.FROZEN) {\n this.checkState(firstPair, CandidatePairState.WAITING);\n }\n\n // # unfreeze pairs with same component but different foundations\n const seenFoundations = new Set(firstPair.localCandidate.foundation);\n for (const pair of this.checkList) {\n if (\n pair.component === firstPair.component &&\n !seenFoundations.has(pair.localCandidate.foundation) &&\n pair.state === CandidatePairState.FROZEN\n ) {\n this.checkState(pair, CandidatePairState.WAITING);\n seenFoundations.add(pair.localCandidate.foundation);\n }\n }\n }\n\n // 5.8 Scheduling Checks\n private schedulingChecks() {\n // Ordinary Check\n {\n // # find the highest-priority pair that is in the waiting state\n const pair = this.checkList\n .filter((pair) => {\n if (this.options.forceTurn && pair.protocol.type === \"stun\")\n return false;\n return true;\n })\n .find((pair) => pair.state === CandidatePairState.WAITING);\n if (pair) {\n pair.handle = future(this.checkStart(pair));\n return true;\n }\n }\n\n {\n // # find the highest-priority pair that is in the frozen state\n const pair = this.checkList.find(\n (pair) => pair.state === CandidatePairState.FROZEN\n );\n if (pair) {\n pair.handle = future(this.checkStart(pair));\n return true;\n }\n }\n\n // # if we expect more candidates, keep going\n if (!this.remoteCandidatesEnd) {\n return !this.checkListDone;\n }\n\n return false;\n }\n\n // 4.1.1.4 ? 生存確認 life check\n private queryConsent = () =>\n new PCancelable(async (r, f, onCancel) => {\n let failures = 0;\n\n const cancelEvent = new AbortController();\n onCancel(() => {\n failures += CONSENT_FAILURES;\n cancelEvent.abort();\n f(\"cancel\");\n });\n\n // \"\"\"\n // Periodically check consent (RFC 7675).\n // \"\"\"\n\n try {\n while (!this.remoteIsLite && this.state !== \"closed\") {\n // # randomize between 0.8 and 1.2 times CONSENT_INTERVAL\n await timers.setTimeout(\n CONSENT_INTERVAL * (0.8 + 0.4 * Math.random()) * 1000,\n undefined,\n { signal: cancelEvent.signal }\n );\n\n for (const key of this.nominatedKeys) {\n const pair = this.nominated[Number(key)];\n const request = this.buildRequest(pair, false);\n try {\n const [msg, addr] = await pair.protocol.request(\n request,\n pair.remoteAddr,\n Buffer.from(this.remotePassword, \"utf8\"),\n 0\n );\n failures = 0;\n if (this.state === \"disconnected\") {\n this.setState(\"connected\");\n }\n } catch (error) {\n failures++;\n this.setState(\"disconnected\");\n }\n if (failures >= CONSENT_FAILURES) {\n log(\"Consent to send expired\");\n this.queryConsentHandle = undefined;\n // 切断検知\n r(await this.close());\n return;\n }\n }\n }\n } catch (error) {}\n });\n\n async close() {\n // \"\"\"\n // Close the connection.\n // \"\"\"\n\n this.setState(\"closed\");\n\n // # stop consent freshness tests\n if (this.queryConsentHandle && !this.queryConsentHandle.done()) {\n this.queryConsentHandle.cancel();\n try {\n await this.queryConsentHandle.promise;\n } catch (error) {\n // pass\n }\n }\n\n // # stop check list\n if (this.checkList && !this.checkListDone) {\n this.checkListState.put(\n new Promise((r) => {\n r(ICE_FAILED);\n })\n );\n }\n\n this.nominated = {};\n for (const protocol of this.protocols) {\n if (protocol.close) {\n await protocol.close();\n }\n }\n\n this.protocols = [];\n this.localCandidates = [];\n }\n\n private setState(state: IceState) {\n this.state = state;\n this.stateChanged.execute(state);\n }\n\n async addRemoteCandidate(remoteCandidate: Candidate | undefined) {\n // \"\"\"\n // Add a remote candidate or signal end-of-candidates.\n\n // To signal end-of-candidates, pass `None`.\n\n // :param remote_candidate: A :class:`Candidate` instance or `None`.\n // \"\"\"\n if (this.remoteCandidatesEnd)\n throw new Error(\"Cannot add remote candidate after end-of-candidates.\");\n\n if (!remoteCandidate) {\n this.pruneComponents();\n this.remoteCandidatesEnd = true;\n return;\n }\n\n if (remoteCandidate.host.includes(\".local\")) {\n await timers.setTimeout(10);\n\n const res = await util\n .promisify(dns.lookup)(remoteCandidate.host)\n .catch((err) => {\n log(err, remoteCandidate);\n });\n if (res) {\n remoteCandidate.host = res.address;\n } else {\n // todo fix\n remoteCandidate.host = \"127.0.0.1\";\n }\n }\n\n try {\n validateRemoteCandidate(remoteCandidate);\n } catch (error) {\n return;\n }\n this.remoteCandidates.push(remoteCandidate);\n\n this.pairRemoteCandidate(remoteCandidate);\n this.sortCheckList();\n }\n\n send = async (data: Buffer) => {\n // \"\"\"\n // Send a datagram on the first component.\n\n // If the connection is not established, a `ConnectionError` is raised.\n\n // :param data: The data to be sent.\n // \"\"\"\n await this.sendTo(data, 1);\n };\n\n private async sendTo(data: Buffer, component: number) {\n // \"\"\"\n // Send a datagram on the specified component.\n\n // If the connection is not established, a `ConnectionError` is raised.\n\n // :param data: The data to be sent.\n // :param component: The component on which to send the data.\n // \"\"\"\n const activePair = this.nominated[component];\n if (activePair) {\n await activePair.protocol.sendData(data, activePair.remoteAddr);\n } else {\n throw new Error(\"Cannot send data, ice not connected\");\n }\n }\n\n getDefaultCandidate(component: number) {\n const candidates = this.localCandidates.sort(\n (a, b) => a.priority - b.priority\n );\n const candidate = candidates.find(\n (candidate) => candidate.component === component\n );\n return candidate;\n }\n\n requestReceived(\n message: Message,\n addr: Address,\n protocol: Protocol,\n rawData: Buffer\n ) {\n if (message.messageMethod !== methods.BINDING) {\n this.respondError(message, addr, protocol, [400, \"Bad Request\"]);\n return;\n }\n\n // # authenticate request\n try {\n parseMessage(rawData, Buffer.from(this.localPassword, \"utf8\"));\n if (!this.remoteUsername) {\n const rxUsername = `${this.localUserName}:${this.remoteUsername}`;\n if (message.attributes[\"USERNAME\"] != rxUsername)\n throw new Error(\"Wrong username\");\n }\n } catch (error) {\n this.respondError(message, addr, protocol, [400, \"Bad Request\"]);\n return;\n }\n\n const { iceControlling } = this;\n\n // 7.2.1.1. Detecting and Repairing Role Conflicts\n if (iceControlling && message.attributesKeys.includes(\"ICE-CONTROLLING\")) {\n if (this._tieBreaker >= message.attributes[\"ICE-CONTROLLING\"]) {\n this.respondError(message, addr, protocol, [487, \"Role Conflict\"]);\n return;\n } else {\n this.switchRole(false);\n }\n } else if (\n !iceControlling &&\n message.attributesKeys.includes(\"ICE-CONTROLLED\")\n ) {\n if (this._tieBreaker < message.attributes[\"ICE-CONTROLLED\"]) {\n this.respondError(message, addr, protocol, [487, \"Role Conflict\"]);\n } else {\n this.switchRole(true);\n return;\n }\n }\n\n // # send binding response\n const response = new Message(\n methods.BINDING,\n classes.RESPONSE,\n message.transactionId\n );\n response.attributes[\"XOR-MAPPED-ADDRESS\"] = addr;\n response.addMessageIntegrity(Buffer.from(this.localPassword, \"utf8\"));\n response.addFingerprint();\n protocol.sendStun(response, addr);\n\n // todo fix\n // if (this.checkList.length === 0) {\n // this.earlyChecks.push([message, addr, protocol]);\n // } else {\n this.checkIncoming(message, addr, protocol);\n // }\n }\n\n dataReceived(data: Buffer, component: number) {\n this.onData.execute(data, component);\n }\n\n // for test only\n set remoteCandidates(value: Candidate[]) {\n if (this.remoteCandidatesEnd)\n throw new Error(\"Cannot set remote candidates after end-of-candidates.\");\n this._remoteCandidates = [];\n for (const remoteCandidate of value) {\n try {\n validateRemoteCandidate(remoteCandidate);\n } catch (error) {\n continue;\n }\n this.remoteCandidates.push(remoteCandidate);\n }\n this.pruneComponents();\n this.remoteCandidatesEnd = true;\n }\n get remoteCandidates() {\n return this._remoteCandidates;\n }\n\n private pruneComponents() {\n const seenComponents = new Set(\n this.remoteCandidates.map((v) => v.component)\n );\n const missingComponents = [...difference(this._components, seenComponents)];\n if (missingComponents.length > 0) {\n this._components = seenComponents;\n }\n }\n\n private sortCheckList() {\n sortCandidatePairs(this.checkList, this.iceControlling);\n }\n\n private findPair(protocol: Protocol, remoteCandidate: Candidate) {\n const pair = this.checkList.find(\n (pair) =>\n isEqual(pair.protocol, protocol) &&\n isEqual(pair.remoteCandidate, remoteCandidate)\n );\n return pair;\n }\n\n private checkState(pair: CandidatePair, state: CandidatePairState) {\n pair.state = state;\n }\n\n private switchRole(iceControlling: boolean) {\n log(\"switch role\", iceControlling);\n this.iceControlling = iceControlling;\n this.sortCheckList();\n }\n\n private checkComplete(pair: CandidatePair) {\n pair.handle = undefined;\n if (pair.state === CandidatePairState.SUCCEEDED) {\n if (pair.nominated) {\n this.nominated[pair.component] = pair;\n\n // 8.1.2. Updating States\n\n // The agent MUST remove all Waiting and Frozen pairs in the check\n // list and triggered check queue for the same component as the\n // nominated pairs for that media stream.\n for (const p of this.checkList) {\n if (\n p.component === pair.component &&\n [CandidatePairState.WAITING, CandidatePairState.FROZEN].includes(\n p.state\n )\n ) {\n this.checkState(p, CandidatePairState.FAILED);\n }\n }\n }\n\n // Once there is at least one nominated pair in the valid list for\n // every component of at least one media stream and the state of the\n // check list is Running:\n if (this.nominatedKeys.length === this._components.size) {\n if (!this.checkListDone) {\n log(\"ICE completed\");\n this.checkListState.put(new Promise((r) => r(ICE_COMPLETED)));\n this.checkListDone = true;\n }\n return;\n }\n\n // 7.1.3.2.3. Updating Pair States\n for (const p of this.checkList) {\n if (\n p.localCandidate.foundation === pair.localCandidate.foundation &&\n p.state === CandidatePairState.FROZEN\n ) {\n this.checkState(p, CandidatePairState.WAITING);\n }\n }\n }\n\n {\n const list = [CandidatePairState.SUCCEEDED, CandidatePairState.FAILED];\n if (this.checkList.find(({ state }) => !list.includes(state))) {\n return;\n }\n }\n\n if (!this.iceControlling) {\n const target = CandidatePairState.SUCCEEDED;\n if (this.checkList.find(({ state }) => state === target)) {\n return;\n }\n }\n\n if (!this.checkListDone) {\n log(\"ICE failed\");\n this.checkListState.put(\n new Promise((r) => {\n r(ICE_FAILED);\n })\n );\n this.checkListDone = true;\n }\n }\n\n // 3. Terminology : Check\n checkStart = (pair: CandidatePair) =>\n new PCancelable(async (r, f, onCancel) => {\n onCancel(() => f(\"cancel\"));\n\n // \"\"\"\n // Starts a check.\n // \"\"\"\n\n log(\"check start\", pair.remoteCandidate);\n\n this.checkState(pair, CandidatePairState.IN_PROGRESS);\n\n const nominate = this.iceControlling && !this.remoteIsLite;\n const request = this.buildRequest(pair, nominate);\n\n const result: { response?: Message; addr?: Address } = {};\n try {\n const [response, addr] = await pair.protocol.request(\n request,\n pair.remoteAddr,\n Buffer.from(this.remotePassword, \"utf8\")\n );\n log(\"response\", response, addr);\n result.response = response;\n result.addr = addr;\n } catch (error: any) {\n const exc: TransactionError = error;\n // 7.1.3.1. Failure Cases\n log(\"failure case\", exc.response);\n if (exc.response?.attributes[\"ERROR-CODE\"][0] === 487) {\n if (request.attributesKeys.includes(\"ICE-CONTROLLED\")) {\n this.switchRole(true);\n } else if (request.attributesKeys.includes(\"ICE-CONTROLLING\")) {\n this.switchRole(false);\n }\n await this.checkStart(pair);\n r();\n return;\n } else {\n log(\"CandidatePairState.FAILED\");\n this.checkState(pair, CandidatePairState.FAILED);\n this.checkComplete(pair);\n r();\n return;\n }\n }\n\n // # check remote address matches\n if (!isEqual(result.addr, pair.remoteAddr)) {\n this.checkState(pair, CandidatePairState.FAILED);\n this.checkComplete(pair);\n r();\n return;\n }\n\n // # success\n if (nominate || pair.remoteNominated) {\n // # nominated by agressive nomination or the remote party\n pair.nominated = true;\n } else if (this.iceControlling && !this.nominating.has(pair.component)) {\n // # perform regular nomination\n this.nominating.add(pair.component);\n const request = this.buildRequest(pair, true);\n try {\n await pair.protocol.request(\n request,\n pair.remoteAddr,\n Buffer.from(this.remotePassword, \"utf8\")\n );\n } catch (error) {\n this.checkState(pair, CandidatePairState.FAILED);\n this.checkComplete(pair);\n return;\n }\n pair.nominated = true;\n }\n\n this.checkState(pair, CandidatePairState.SUCCEEDED);\n this.checkComplete(pair);\n r();\n });\n\n // 7.2. STUN Server Procedures\n // 7.2.1.3、7.2.1.4、および7.2.1.5\n checkIncoming(message: Message, addr: Address, protocol: Protocol) {\n // \"\"\"\n // Handle a successful incoming check.\n // \"\"\"\n const component = protocol.localCandidate?.component;\n if (component == undefined) throw new Error();\n\n // find remote candidate\n let remoteCandidate: Candidate | undefined;\n const [host, port] = addr;\n for (const c of this.remoteCandidates) {\n if (c.host === host && c.port === port) {\n remoteCandidate = c;\n if (remoteCandidate.component !== component)\n throw new Error(\"checkIncoming\");\n break;\n }\n }\n if (!remoteCandidate) {\n // 7.2.1.3. Learning Peer Reflexive Candidates\n remoteCandidate = new Candidate(\n randomString(10),\n component,\n \"udp\",\n message.attributes[\"PRIORITY\"],\n host,\n port,\n \"prflx\"\n );\n this.remoteCandidates.push(remoteCandidate);\n }\n\n // find pair\n let pair = this.findPair(protocol, remoteCandidate);\n if (!pair) {\n pair = new CandidatePair(protocol, remoteCandidate);\n pair.state = CandidatePairState.WAITING;\n this.checkList.push(pair);\n this.sortCheckList();\n }\n\n // 7.2.1.4. Triggered Checks\n if (\n [CandidatePairState.WAITING, CandidatePairState.FAILED].includes(\n pair.state\n )\n ) {\n pair.handle = future(this.checkStart(pair));\n }\n\n // 7.2.1.5. Updating the Nominated Flag\n if (\n message.attributesKeys.includes(\"USE-CANDIDATE\") &&\n !this.iceControlling\n ) {\n pair.remoteNominated = true;\n if (pair.state === CandidatePairState.SUCCEEDED) {\n pair.nominated = true;\n this.checkComplete(pair);\n }\n }\n }\n\n private pairRemoteCandidate = (remoteCandidate: Candidate) => {\n for (const protocol of this.protocols) {\n if (\n protocol.localCandidate?.canPairWith(remoteCandidate) &&\n !this.findPair(protocol, remoteCandidate)\n ) {\n const pair = new CandidatePair(protocol, remoteCandidate);\n this.checkList.push(pair);\n }\n }\n };\n\n private buildRequest(pair: CandidatePair, nominate: boolean) {\n const txUsername = `${this.remoteUsername}:${this.localUserName}`;\n const request = new Message(methods.BINDING, classes.REQUEST);\n request.attributes[\"USERNAME\"] = txUsername;\n request.attributes[\"PRIORITY\"] = candidatePriority(pair.component, \"prflx\");\n if (this.iceControlling) {\n request.attributes[\"ICE-CONTROLLING\"] = this._tieBreaker;\n if (nominate) {\n request.attributes[\"USE-CANDIDATE\"] = null;\n }\n } else {\n request.attributes[\"ICE-CONTROLLED\"] = this._tieBreaker;\n }\n return request;\n }\n\n private respondError(\n request: Message,\n addr: Address,\n protocol: Protocol,\n errorCode: [number, string]\n ) {\n const response = new Message(\n request.messageMethod,\n classes.ERROR,\n request.transactionId\n );\n response.attributes[\"ERROR-CODE\"] = errorCode;\n response.addMessageIntegrity(Buffer.from(this.localPassword, \"utf8\"));\n response.addFingerprint();\n protocol.sendStun(response, addr);\n }\n}\n\nexport class CandidatePair {\n handle?: Future;\n nominated = false;\n remoteNominated = false;\n // 5.7.4. Computing States\n state = CandidatePairState.FROZEN;\n\n constructor(public protocol: Protocol, public remoteCandidate: Candidate) {}\n\n get localCandidate() {\n if (!this.protocol.localCandidate)\n throw new Error(\"localCandidate not exist\");\n return this.protocol.localCandidate;\n }\n\n get remoteAddr(): Address {\n return [this.remoteCandidate.host, this.remoteCandidate.port];\n }\n\n get component() {\n return this.localCandidate.component;\n }\n}\n\nconst ICE_COMPLETED = 1 as const;\nconst ICE_FAILED = 2 as const;\n\nconst CONSENT_INTERVAL = 5;\nconst CONSENT_FAILURES = 6;\n\nexport enum CandidatePairState {\n FROZEN = 0,\n WAITING = 1,\n IN_PROGRESS = 2,\n SUCCEEDED = 3,\n FAILED = 4,\n}\n\ntype IceState = \"disconnected\" | \"closed\" | \"completed\" | \"new\" | \"connected\";\n\nexport interface IceOptions {\n components: number;\n stunServer?: Address;\n turnServer?: Address;\n turnUsername?: string;\n turnPassword?: string;\n turnSsl?: boolean;\n turnTransport?: string;\n forceTurn?: boolean;\n useIpv4: boolean;\n useIpv6: boolean;\n portRange?: [number, number];\n}\n\nconst defaultOptions: IceOptions = {\n components: 1,\n useIpv4: true,\n useIpv6: true,\n};\n\nexport function validateRemoteCandidate(candidate: Candidate) {\n // \"\"\"\n // Check the remote candidate is supported.\n // \"\"\"\n if (![\"host\", \"relay\", \"srflx\"].includes(candidate.type))\n throw new Error(`Unexpected candidate type \"${candidate.type}\"`);\n\n // ipaddress.ip_address(candidate.host)\n return candidate;\n}\n\nexport function sortCandidatePairs(\n pairs: CandidatePair[],\n iceControlling: boolean\n) {\n pairs.sort(\n (a, b) =>\n candidatePairPriority(\n a.localCandidate,\n a.remoteCandidate,\n iceControlling\n ) -\n candidatePairPriority(b.localCandidate, b.remoteCandidate, iceControlling)\n );\n}\n\n// 5.7.2. Computing Pair Priority and Ordering Pairs\nexport function candidatePairPriority(\n local: Candidate,\n remote: Candidate,\n iceControlling: boolean\n) {\n const G = (iceControlling && local.priority) || remote.priority;\n const D = (iceControlling && remote.priority) || local.priority;\n return (1 << 32) * Math.min(G, D) + 2 * Math.max(G, D) + (G > D ? 1 : 0);\n}\n\nexport function getHostAddress(useIpv4: boolean, useIpv6: boolean) {\n const address: string[] = [];\n if (useIpv4) address.push(nodeIp.address(\"\", \"ipv4\"));\n if (useIpv6) address.push(nodeIp.address(\"\", \"ipv6\"));\n return address;\n}\n\nexport async function serverReflexiveCandidate(\n protocol: Protocol,\n stunServer: Address\n) {\n // \"\"\"\n // Query STUN server to obtain a server-reflexive candidate.\n // \"\"\"\n\n // # perform STUN query\n const request = new Message(methods.BINDING, classes.REQUEST);\n try {\n const [response] = await protocol.request(request, stunServer);\n\n const localCandidate = protocol.localCandidate;\n if (!localCandidate) throw new Error(\"not exist\");\n\n return new Candidate(\n candidateFoundation(\"srflx\", \"udp\", localCandidate.host),\n localCandidate.component,\n localCandidate.transport,\n candidatePriority(localCandidate.component, \"srflx\"),\n response.attributes[\"XOR-MAPPED-ADDRESS\"][0],\n response.attributes[\"XOR-MAPPED-ADDRESS\"][1],\n \"srflx\",\n localCandidate.host,\n localCandidate.port\n );\n } catch (error) {\n // todo fix\n log(\"error serverReflexiveCandidate\", error);\n }\n}\n\nexport function validateAddress(addr?: Address): Address | undefined {\n if (addr && isNaN(addr[1])) {\n return [addr[0], 443];\n }\n return addr;\n}\n"]}
|
|
@@ -59,9 +59,10 @@ class RTCDataChannel extends helper_1.EventTarget {
|
|
|
59
59
|
return this._bufferedAmountLowThreshold;
|
|
60
60
|
}
|
|
61
61
|
set bufferedAmountLowThreshold(value) {
|
|
62
|
-
if (value < 0 || value > 4294967295)
|
|
62
|
+
if (value < 0 || value > 4294967295) {
|
|
63
63
|
throw new Error("bufferedAmountLowThreshold must be in range 0 - 4294967295");
|
|
64
|
-
|
|
64
|
+
}
|
|
65
|
+
this._bufferedAmountLowThreshold = value;
|
|
65
66
|
}
|
|
66
67
|
setId(id) {
|
|
67
68
|
this.id = id;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dataChannel.js","sourceRoot":"","sources":["../../../src/dataChannel.ts"],"names":[],"mappings":";;;;;;AAAA,kDAA0B;AAC1B,qCAAgC;AAEhC,qCAAuC;AAIvC,MAAM,GAAG,GAAG,IAAA,eAAK,EAAC,2BAA2B,CAAC,CAAC;AAE/C,MAAa,cAAe,SAAQ,oBAAW;
|
|
1
|
+
{"version":3,"file":"dataChannel.js","sourceRoot":"","sources":["../../../src/dataChannel.ts"],"names":[],"mappings":";;;;;;AAAA,kDAA0B;AAC1B,qCAAgC;AAEhC,qCAAuC;AAIvC,MAAM,GAAG,GAAG,IAAA,eAAK,EAAC,2BAA2B,CAAC,CAAC;AAE/C,MAAa,cAAe,SAAQ,oBAAW;IAmB7C,YACm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ED,iBAAiB,CAAC,MAAc;QAC9B,MAAM,gBAAgB,GACpB,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,0BAA0B;YACrD,IAAI,CAAC,cAAc,GAAG,MAAM,IAAI,IAAI,CAAC,0BAA0B,CAAC;QAClE,IAAI,CAAC,cAAc,IAAI,MAAM,CAAC;QAC9B,IAAI,gBAAgB,EAAE;YACpB,IAAI,CAAC,iBAAiB,CAAC,OAAO,EAAE,CAAC;YACjC,IAAI,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;SAChC;IACH,CAAC;IAED,IAAI,CAAC,IAAqB;QACxB,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC7C,CAAC;IAED,KAAK;QACH,IAAI,CAAC,SAAS,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;IACxC,CAAC;CACF;AA1HD,wCA0HC;AAID,MAAa,wBAAwB;IAQnC,YAAY,QAA2C,EAAE;QAPzD,UAAK,GAAG,EAAE,CAAC;QAGX,YAAO,GAAG,IAAI,CAAC;QACf,aAAQ,GAAG,EAAE,CAAC;QACd,eAAU,GAAG,KAAK,CAAC;QAGjB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC7B,CAAC;CACF;AAXD,4DAWC","sourcesContent":["import debug from \"debug\";\nimport { Event } from \"rx.mini\";\n\nimport { EventTarget } from \"./helper\";\nimport { RTCSctpTransport } from \"./transport/sctp\";\nimport { Callback, CallbackWithValue } from \"./types/util\";\n\nconst log = debug(\"werift/webrtc/datachannel\");\n\nexport class RTCDataChannel extends EventTarget {\n readonly stateChanged = new Event<[DCState]>();\n readonly message = new Event<[string | Buffer]>();\n // todo impl\n readonly error = new Event<[Error]>();\n readonly bufferedAmountLow = new Event();\n onopen?: Callback;\n onclose?: Callback;\n onclosing?: Callback;\n onmessage?: CallbackWithValue<MessageEvent>;\n // todo impl\n onerror?: CallbackWithValue<RTCErrorEvent>;\n isCreatedByRemote = false;\n id: number = this.parameters.id;\n readyState: DCState = \"connecting\";\n\n bufferedAmount = 0;\n private _bufferedAmountLowThreshold = 0;\n\n constructor(\n private readonly transport: RTCSctpTransport,\n private readonly parameters: RTCDataChannelParameters,\n public readonly sendOpen = true\n ) {\n super();\n\n if (parameters.negotiated) {\n if (this.id == undefined || this.id < 0 || this.id > 65534) {\n throw new Error(\n \"ID must be in range 0-65534 if data channel is negotiated out-of-band\"\n );\n }\n this.transport.dataChannelAddNegotiated(this);\n } else {\n if (sendOpen) {\n this.sendOpen = false;\n this.transport.dataChannelOpen(this);\n }\n }\n }\n\n get ordered() {\n return this.parameters.ordered;\n }\n\n get maxRetransmits() {\n return this.parameters.maxRetransmits;\n }\n\n get maxPacketLifeTime() {\n return this.parameters.maxPacketLifeTime;\n }\n\n get label() {\n return this.parameters.label;\n }\n\n get protocol() {\n return this.parameters.protocol;\n }\n\n get negotiated() {\n return this.parameters.negotiated;\n }\n\n get bufferedAmountLowThreshold() {\n return this._bufferedAmountLowThreshold;\n }\n\n set bufferedAmountLowThreshold(value: number) {\n if (value < 0 || value > 4294967295) {\n throw new Error(\n \"bufferedAmountLowThreshold must be in range 0 - 4294967295\"\n );\n }\n this._bufferedAmountLowThreshold = value;\n }\n\n setId(id: number) {\n this.id = id;\n }\n\n setReadyState(state: DCState) {\n if (state !== this.readyState) {\n this.readyState = state;\n this.stateChanged.execute(state);\n\n switch (state) {\n case \"open\":\n if (this.onopen) this.onopen();\n this.emit(\"open\");\n break;\n case \"closed\":\n if (this.onclose) this.onclose();\n this.emit(\"close\");\n break;\n case \"closing\":\n if (this.onclosing) this.onclosing();\n break;\n }\n log(\"change state\", state);\n }\n }\n\n addBufferedAmount(amount: number) {\n const crossesThreshold =\n this.bufferedAmount > this.bufferedAmountLowThreshold &&\n this.bufferedAmount + amount <= this.bufferedAmountLowThreshold;\n this.bufferedAmount += amount;\n if (crossesThreshold) {\n this.bufferedAmountLow.execute();\n this.emit(\"bufferedamountlow\");\n }\n }\n\n send(data: Buffer | string) {\n this.transport.datachannelSend(this, data);\n }\n\n close() {\n this.transport.dataChannelClose(this);\n }\n}\n\nexport type DCState = \"open\" | \"closed\" | \"connecting\" | \"closing\";\n\nexport class RTCDataChannelParameters {\n label = \"\";\n maxPacketLifeTime?: number; // sec\n maxRetransmits?: number;\n ordered = true;\n protocol = \"\";\n negotiated = false;\n id!: number;\n constructor(props: Partial<RTCDataChannelParameters> = {}) {\n Object.assign(this, props);\n }\n}\n\nexport interface MessageEvent {\n data: string | Buffer;\n}\n\nexport interface RTCErrorEvent {\n error: any;\n}\n"]}
|
|
@@ -7,7 +7,6 @@ import { RTCRtpSender } from "./rtpSender";
|
|
|
7
7
|
import { MediaStreamTrack } from "./track";
|
|
8
8
|
export declare class RTCRtpTransceiver {
|
|
9
9
|
readonly kind: Kind;
|
|
10
|
-
dtlsTransport: RTCDtlsTransport;
|
|
11
10
|
receiver: RTCRtpReceiver;
|
|
12
11
|
sender: RTCRtpSender;
|
|
13
12
|
/**RFC 8829 4.2.4. direction the transceiver was initialized with */
|
|
@@ -30,6 +29,7 @@ export declare class RTCRtpTransceiver {
|
|
|
30
29
|
constructor(kind: Kind, dtlsTransport: RTCDtlsTransport, receiver: RTCRtpReceiver, sender: RTCRtpSender,
|
|
31
30
|
/**RFC 8829 4.2.4. direction the transceiver was initialized with */
|
|
32
31
|
direction: Direction);
|
|
32
|
+
get dtlsTransport(): RTCDtlsTransport;
|
|
33
33
|
setDtlsTransport(dtls: RTCDtlsTransport): void;
|
|
34
34
|
get msid(): string;
|
|
35
35
|
addTrack(track: MediaStreamTrack): void;
|
|
@@ -31,7 +31,6 @@ class RTCRtpTransceiver {
|
|
|
31
31
|
/**RFC 8829 4.2.4. direction the transceiver was initialized with */
|
|
32
32
|
direction) {
|
|
33
33
|
this.kind = kind;
|
|
34
|
-
this.dtlsTransport = dtlsTransport;
|
|
35
34
|
this.receiver = receiver;
|
|
36
35
|
this.sender = sender;
|
|
37
36
|
this.direction = direction;
|
|
@@ -55,6 +54,9 @@ class RTCRtpTransceiver {
|
|
|
55
54
|
get currentDirection() {
|
|
56
55
|
return this._currentDirection;
|
|
57
56
|
}
|
|
57
|
+
get dtlsTransport() {
|
|
58
|
+
return this.receiver.dtlsTransport;
|
|
59
|
+
}
|
|
58
60
|
setDtlsTransport(dtls) {
|
|
59
61
|
this.receiver.setDtlsTransport(dtls);
|
|
60
62
|
this.sender.setDtlsTransport(dtls);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rtpTransceiver.js","sourceRoot":"","sources":["../../../../src/media/rtpTransceiver.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAA4B;AAC5B,2CAA6B;AAG7B,oCAA4C;AAU5C,MAAa,iBAAiB;IAyB5B,YACkB,IAAU,
|
|
1
|
+
{"version":3,"file":"rtpTransceiver.js","sourceRoot":"","sources":["../../../../src/media/rtpTransceiver.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAA4B;AAC5B,2CAA6B;AAG7B,oCAA4C;AAU5C,MAAa,iBAAiB;IAyB5B,YACkB,IAAU,EAC1B,aAA+B,EACxB,QAAwB,EACxB,MAAoB;IAC3B,qEAAqE;IAC9D,SAAoB;QALX,SAAI,GAAJ,IAAI,CAAM;QAEnB,aAAQ,GAAR,QAAQ,CAAgB;QACxB,WAAM,GAAN,MAAM,CAAc;QAEpB,cAAS,GAAT,SAAS,CAAW;QA9BpB,SAAI,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC;QACjB,YAAO,GAAG,IAAI,iBAAK,EAAsB,CAAC;QAGnD,kBAAa,GAAG,KAAK,CAAC;QActB,WAAM,GAA4B,EAAE,CAAC;QACrC,qBAAgB,GAAsC,EAAE,CAAC;QACzD,YAAO,GAAgC,EAAE,CAAC;QAC1C,aAAQ,GAAG,KAAK,CAAC;QACjB,YAAO,GAAG,KAAK,CAAC;QAUd,IAAI,CAAC,gBAAg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QAAQ,CAAC,WAAW,EAAE,CAAC,CAC9D,EAAE,WAAW,CAAC;IACjB,CAAC;CACF;AArED,8CAqEC;AAEY,QAAA,UAAU,GAAG;IACxB,UAAU;IACV,UAAU;IACV,UAAU;IACV,UAAU;CACF,CAAC","sourcesContent":["import Event from \"rx.mini\";\nimport * as uuid from \"uuid\";\n\nimport { RTCDtlsTransport } from \"..\";\nimport { SenderDirections } from \"../const\";\nimport { Kind } from \"../types/domain\";\nimport {\n RTCRtpCodecParameters,\n RTCRtpHeaderExtensionParameters,\n} from \"./parameters\";\nimport { RTCRtpReceiver } from \"./rtpReceiver\";\nimport { RTCRtpSender } from \"./rtpSender\";\nimport { MediaStreamTrack } from \"./track\";\n\nexport class RTCRtpTransceiver {\n readonly uuid = uuid.v4();\n readonly onTrack = new Event<[MediaStreamTrack]>();\n mid?: string;\n mLineIndex?: number;\n usedForSender = false;\n private _currentDirection?: Direction | \"stopped\";\n set currentDirection(direction: Direction | \"stopped\" | undefined) {\n this._currentDirection = direction;\n if (SenderDirections.includes(this._currentDirection || \"\")) {\n this.usedForSender = true;\n }\n }\n /**RFC 8829 4.2.5. last negotiated direction */\n get currentDirection(): Direction | \"stopped\" | undefined {\n return this._currentDirection;\n }\n\n offerDirection!: Direction;\n codecs: RTCRtpCodecParameters[] = [];\n headerExtensions: RTCRtpHeaderExtensionParameters[] = [];\n options: Partial<TransceiverOptions> = {};\n stopping = false;\n stopped = false;\n\n constructor(\n public readonly kind: Kind,\n dtlsTransport: RTCDtlsTransport,\n public receiver: RTCRtpReceiver,\n public sender: RTCRtpSender,\n /**RFC 8829 4.2.4. direction the transceiver was initialized with */\n public direction: Direction\n ) {\n this.setDtlsTransport(dtlsTransport);\n }\n\n get dtlsTransport() {\n return this.receiver.dtlsTransport;\n }\n\n setDtlsTransport(dtls: RTCDtlsTransport) {\n this.receiver.setDtlsTransport(dtls);\n this.sender.setDtlsTransport(dtls);\n }\n\n get msid() {\n return `${this.sender.streamId} ${this.sender.trackId}`;\n }\n\n addTrack(track: MediaStreamTrack) {\n const res = this.receiver.addTrack(track);\n if (res) this.onTrack.execute(track);\n }\n\n // todo impl\n // https://www.w3.org/TR/webrtc/#methods-8\n stop() {\n if (this.stopping) return;\n\n // todo Stop sending and receiving with transceiver.\n\n this.stopping = true;\n }\n\n getPayloadType(mimeType: string) {\n return this.codecs.find((codec) =>\n codec.mimeType.toLowerCase().includes(mimeType.toLowerCase())\n )?.payloadType;\n }\n}\n\nexport const Directions = [\n \"inactive\",\n \"sendonly\",\n \"recvonly\",\n \"sendrecv\",\n] as const;\n\nexport type Direction = typeof Directions[number];\n\ntype SimulcastDirection = \"send\" | \"recv\";\n\nexport interface TransceiverOptions {\n direction: Direction;\n simulcast: { direction: SimulcastDirection; rid: string }[];\n}\n"]}
|
|
@@ -109,7 +109,7 @@ export declare function createMediaDescriptionForTransceiver(transceiver: RTCRtp
|
|
|
109
109
|
export declare function createMediaDescriptionForSctp(sctp: RTCSctpTransport, mid: string): MediaDescription;
|
|
110
110
|
export declare function addTransportDescription(media: MediaDescription, dtlsTransport: RTCDtlsTransport): void;
|
|
111
111
|
export declare function allocateMid(mids: Set<string>): string;
|
|
112
|
-
export declare type BundlePolicy = "max-compat" | "max-bundle";
|
|
112
|
+
export declare type BundlePolicy = "max-compat" | "max-bundle" | "disable";
|
|
113
113
|
export interface PeerConfig {
|
|
114
114
|
codecs: Partial<{
|
|
115
115
|
audio: RTCRtpCodecParameters[];
|
|
@@ -228,11 +228,13 @@ class RTCPeerConnection extends helper_1.EventTarget {
|
|
|
228
228
|
!description.media.find((m) => this.sctpTransport.mid === m.rtp.muxId)) {
|
|
229
229
|
description.media.push(createMediaDescriptionForSctp(this.sctpTransport, allocateMid(this.seenMid)));
|
|
230
230
|
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
231
|
+
if (this.configuration.bundlePolicy !== "disable") {
|
|
232
|
+
const mids = description.media
|
|
233
|
+
.map((m) => m.rtp.muxId)
|
|
234
|
+
.filter((v) => v);
|
|
235
|
+
const bundle = new sdp_1.GroupDescription("BUNDLE", mids);
|
|
236
|
+
description.group.push(bundle);
|
|
237
|
+
}
|
|
236
238
|
return description.toJSON();
|
|
237
239
|
}
|
|
238
240
|
createDataChannel(label, options = {}) {
|
|
@@ -285,6 +287,8 @@ class RTCPeerConnection extends helper_1.EventTarget {
|
|
|
285
287
|
}
|
|
286
288
|
createTransport(srtpProfiles = []) {
|
|
287
289
|
const [existing] = this.iceTransports;
|
|
290
|
+
// Gather ICE candidates for only one track. If the remote endpoint is not bundle-aware, negotiate only one media track.
|
|
291
|
+
// https://w3c.github.io/webrtc-pc/#rtcbundlepolicy-enum
|
|
288
292
|
if (this.configuration.bundlePolicy === "max-bundle") {
|
|
289
293
|
if (existing) {
|
|
290
294
|
return this.dtlsTransports[0];
|
|
@@ -461,12 +465,14 @@ class RTCPeerConnection extends helper_1.EventTarget {
|
|
|
461
465
|
log("dtlsTransport.start failed", err);
|
|
462
466
|
throw err;
|
|
463
467
|
});
|
|
468
|
+
if (this.sctpTransport &&
|
|
469
|
+
this.sctpRemotePort &&
|
|
470
|
+
this.sctpTransport.dtlsTransport.id === dtlsTransport.id) {
|
|
471
|
+
await this.sctpTransport.start(this.sctpRemotePort);
|
|
472
|
+
await this.sctpTransport.sctp.stateChanged.connected.asPromise();
|
|
473
|
+
log("sctp connected");
|
|
474
|
+
}
|
|
464
475
|
}));
|
|
465
|
-
if (this.sctpTransport && this.sctpRemotePort) {
|
|
466
|
-
await this.sctpTransport.start(this.sctpRemotePort);
|
|
467
|
-
await this.sctpTransport.sctp.stateChanged.connected.asPromise();
|
|
468
|
-
log("sctp connected");
|
|
469
|
-
}
|
|
470
476
|
this.masterTransportEstablished = true;
|
|
471
477
|
this.setConnectionState("connected");
|
|
472
478
|
}
|
|
@@ -510,10 +516,17 @@ class RTCPeerConnection extends helper_1.EventTarget {
|
|
|
510
516
|
const remoteSdp = sdp_1.SessionDescription.parse(sessionDescription.sdp);
|
|
511
517
|
remoteSdp.type = sessionDescription.type;
|
|
512
518
|
this.validateDescription(remoteSdp, false);
|
|
513
|
-
|
|
519
|
+
if (remoteSdp.type === "answer") {
|
|
520
|
+
this.currentRemoteDescription = remoteSdp;
|
|
521
|
+
this.pendingRemoteDescription = undefined;
|
|
522
|
+
}
|
|
523
|
+
else {
|
|
524
|
+
this.pendingRemoteDescription = remoteSdp;
|
|
525
|
+
}
|
|
526
|
+
const bundle = remoteSdp.group.find((g) => g.semantic === "BUNDLE" && this.configuration.bundlePolicy !== "disable");
|
|
514
527
|
let bundleTransport;
|
|
515
528
|
// # apply description
|
|
516
|
-
|
|
529
|
+
await Promise.all((0, helper_1.enumerate)(remoteSdp.media).map(async ([i, remoteMedia]) => {
|
|
517
530
|
let dtlsTransport;
|
|
518
531
|
if (["audio", "video"].includes(remoteMedia.kind)) {
|
|
519
532
|
let transceiver = this.transceivers.find((t) => t.kind === remoteMedia.kind &&
|
|
@@ -575,7 +588,7 @@ class RTCPeerConnection extends helper_1.EventTarget {
|
|
|
575
588
|
dtlsTransport.role =
|
|
576
589
|
remoteMedia.dtlsParams.role === "client" ? "server" : "client";
|
|
577
590
|
}
|
|
578
|
-
}
|
|
591
|
+
}));
|
|
579
592
|
// connect transports
|
|
580
593
|
if (remoteSdp.type === "answer") {
|
|
581
594
|
log("caller start connect");
|
|
@@ -590,13 +603,6 @@ class RTCPeerConnection extends helper_1.EventTarget {
|
|
|
590
603
|
else if (remoteSdp.type === "answer") {
|
|
591
604
|
this.setSignalingState("stable");
|
|
592
605
|
}
|
|
593
|
-
if (remoteSdp.type === "answer") {
|
|
594
|
-
this.currentRemoteDescription = remoteSdp;
|
|
595
|
-
this.pendingRemoteDescription = undefined;
|
|
596
|
-
}
|
|
597
|
-
else {
|
|
598
|
-
this.pendingRemoteDescription = remoteSdp;
|
|
599
|
-
}
|
|
600
606
|
this.negotiationneeded = false;
|
|
601
607
|
if (this.shouldNegotiationneeded) {
|
|
602
608
|
this.needNegotiation();
|
|
@@ -855,11 +861,13 @@ class RTCPeerConnection extends helper_1.EventTarget {
|
|
|
855
861
|
}));
|
|
856
862
|
description.media.push(media);
|
|
857
863
|
});
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
864
|
+
if (this.configuration.bundlePolicy !== "disable") {
|
|
865
|
+
const bundle = new sdp_1.GroupDescription("BUNDLE", []);
|
|
866
|
+
description.media.forEach((media) => {
|
|
867
|
+
bundle.items.push(media.rtp.muxId);
|
|
868
|
+
});
|
|
869
|
+
description.group.push(bundle);
|
|
870
|
+
}
|
|
863
871
|
return description.toJSON();
|
|
864
872
|
}
|
|
865
873
|
async close() {
|