|
8 | 8 | 'use strict';
|
9 | 9 |
|
10 | 10 | import * as dns from 'dns';
|
11 |
| -import * as util from 'node:util'; |
12 |
| -import * as net from 'net'; |
13 | 11 | import * as http from 'http';
|
| 12 | +import * as net from 'net'; |
| 13 | +import * as util from 'node:util'; |
14 | 14 | import { WebSocketServer } from 'ws';
|
15 | 15 | import { debugLog } from './utils';
|
16 | 16 |
|
@@ -146,6 +146,15 @@ async function onWsConnect(client: any, request: http.IncomingMessage) {
|
146 | 146 | return;
|
147 | 147 | }
|
148 | 148 |
|
| 149 | + // Validate port range |
| 150 | + if (reqTargetPort < 0 || reqTargetPort > 65535) { |
| 151 | + clientLog('Invalid port number: ' + reqTargetPort); |
| 152 | + // Send empty binary data to notify requester that connection failed |
| 153 | + client.send([]); |
| 154 | + client.close(3000); |
| 155 | + return; |
| 156 | + } |
| 157 | + |
149 | 158 | // eslint-disable-next-line prefer-const
|
150 | 159 | let target: any;
|
151 | 160 | const recvQueue: Buffer[] = [];
|
@@ -207,7 +216,11 @@ async function onWsConnect(client: any, request: http.IncomingMessage) {
|
207 | 216 | // Send empty binary data to notify requester that connection was
|
208 | 217 | // initiated
|
209 | 218 | client.send([]);
|
210 |
| - client.close(3000); |
| 219 | + // Without this random timeout, PHP sometimes doesn't notice the socket |
| 220 | + // disconnected. TODO: figure out why. |
| 221 | + setTimeout(() => { |
| 222 | + client.close(3000); |
| 223 | + }); |
211 | 224 | return;
|
212 | 225 | }
|
213 | 226 | } else {
|
@@ -238,7 +251,16 @@ async function onWsConnect(client: any, request: http.IncomingMessage) {
|
238 | 251 | });
|
239 | 252 | target.on('error', function (e: any) {
|
240 | 253 | clientLog('target connection error', e);
|
241 |
| - target.end(); |
242 |
| - client.close(3000); |
| 254 | + client.send([]); |
| 255 | + // Without this random timeout, PHP sometimes doesn't notice the socket |
| 256 | + // disconnected. TODO: figure out why. |
| 257 | + setTimeout(() => { |
| 258 | + client.close(3000); |
| 259 | + try { |
| 260 | + target.end(); |
| 261 | + } catch { |
| 262 | + // Ignore |
| 263 | + } |
| 264 | + }); |
243 | 265 | });
|
244 | 266 | }
|
0 commit comments