MCPcopy Create free account
hub / github.com/Ptechgithub/configs / handleUDPOutBound

Function handleUDPOutBound

worker.js:645–709  ·  view source on GitHub ↗

* Handles outbound UDP traffic by transforming the data into DNS queries and sending them over a WebSocket connection. * @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket connection to send the DNS queries over. * @param {ArrayBuffer} vlessResponseHeader The VLESS resp

(webSocket, vlessResponseHeader, log)

Source from the content-addressed store, hash-verified

643 * @returns {{write: (chunk: Uint8Array) => void}} An object with a write method that accepts a Uint8Array chunk to write to the transform stream.
644 */
645async function handleUDPOutBound(webSocket, vlessResponseHeader, log) {
646
647 let isVlessHeaderSent = false;
648 const transformStream = new TransformStream({
649 start(controller) {
650
651 },
652 transform(chunk, controller) {
653 // udp message 2 byte is the the length of udp data
654 // TODO: this should have bug, beacsue maybe udp chunk can be in two websocket message
655 for (let index = 0; index < chunk.byteLength;) {
656 const lengthBuffer = chunk.slice(index, index + 2);
657 const udpPakcetLength = new DataView(lengthBuffer).getUint16(0);
658 const udpData = new Uint8Array(
659 chunk.slice(index + 2, index + 2 + udpPakcetLength)
660 );
661 index = index + 2 + udpPakcetLength;
662 controller.enqueue(udpData);
663 }
664 },
665 flush(controller) {
666 }
667 });
668
669 // only handle dns udp for now
670 transformStream.readable.pipeTo(new WritableStream({
671 async write(chunk) {
672 const resp = await fetch(dohURL, // dns server url
673 {
674 method: 'POST',
675 headers: {
676 'content-type': 'application/dns-message',
677 },
678 body: chunk,
679 })
680 const dnsQueryResult = await resp.arrayBuffer();
681 const udpSize = dnsQueryResult.byteLength;
682 // console.log([...new Uint8Array(dnsQueryResult)].map((x) => x.toString(16)));
683 const udpSizeBuffer = new Uint8Array([(udpSize >> 8) & 0xff, udpSize & 0xff]);
684 if (webSocket.readyState === WS_READY_STATE_OPEN) {
685 log(`doh success and dns message length is ${udpSize}`);
686 if (isVlessHeaderSent) {
687 webSocket.send(await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer());
688 } else {
689 webSocket.send(await new Blob([vlessResponseHeader, udpSizeBuffer, dnsQueryResult]).arrayBuffer());
690 isVlessHeaderSent = true;
691 }
692 }
693 }
694 })).catch((error) => {
695 log('dns udp has error' + error)
696 });
697
698 const writer = transformStream.writable.getWriter();
699
700 return {
701 /**
702 *

Callers 1

writeFunction · 0.85

Calls 1

logFunction · 0.85

Tested by

no test coverage detected