MCPcopy Index your code
hub / github.com/Ptechgithub/pp-worker / handleUDPOutBound

Function handleUDPOutBound

_worker.js:721–785  ·  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 re

(webSocket, vlessResponseHeader, log)

Source from the content-addressed store, hash-verified

719 * @returns {{write: (chunk: Uint8Array) => void}} An object with a write method that accepts a Uint8Array chunk to write to the transform stream.
720 */
721async function handleUDPOutBound(webSocket, vlessResponseHeader, log) {
722
723 let isVlessHeaderSent = false;
724 const transformStream = new TransformStream({
725 start(controller) {
726
727 },
728 transform(chunk, controller) {
729 // udp message 2 byte is the the length of udp data
730 // TODO: this should have bug, beacsue maybe udp chunk can be in two websocket message
731 for (let index = 0; index < chunk.byteLength;) {
732 const lengthBuffer = chunk.slice(index, index + 2);
733 const udpPakcetLength = new DataView(lengthBuffer).getUint16(0);
734 const udpData = new Uint8Array(
735 chunk.slice(index + 2, index + 2 + udpPakcetLength)
736 );
737 index = index + 2 + udpPakcetLength;
738 controller.enqueue(udpData);
739 }
740 },
741 flush(controller) {
742 }
743 });
744
745 // only handle dns udp for now
746 transformStream.readable.pipeTo(new WritableStream({
747 async write(chunk) {
748 const resp = await fetch(dohURL, // dns server url
749 {
750 method: 'POST',
751 headers: {
752 'content-type': 'application/dns-message',
753 },
754 body: chunk,
755 })
756 const dnsQueryResult = await resp.arrayBuffer();
757 const udpSize = dnsQueryResult.byteLength;
758 // console.log([...new Uint8Array(dnsQueryResult)].map((x) => x.toString(16)));
759 const udpSizeBuffer = new Uint8Array([(udpSize >> 8) & 0xff, udpSize & 0xff]);
760 if (webSocket.readyState === WS_READY_STATE_OPEN) {
761 log(`doh success and dns message length is ${udpSize}`);
762 if (isVlessHeaderSent) {
763 webSocket.send(await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer());
764 } else {
765 webSocket.send(await new Blob([vlessResponseHeader, udpSizeBuffer, dnsQueryResult]).arrayBuffer());
766 isVlessHeaderSent = true;
767 }
768 }
769 }
770 })).catch((error) => {
771 log('dns udp has error' + error)
772 });
773
774 const writer = transformStream.writable.getWriter();
775
776 return {
777 /**
778 *

Callers 1

writeFunction · 0.85

Calls 1

logFunction · 0.85

Tested by

no test coverage detected