-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathserver.ts
More file actions
774 lines (651 loc) · 28.9 KB
/
server.ts
File metadata and controls
774 lines (651 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
/* eslint-disable no-use-before-define */
import { Buffer } from 'node:buffer';
import type dns from 'node:dns';
import { EventEmitter } from 'node:events';
import http from 'node:http';
import https from 'node:https';
import type net from 'node:net';
import { URL } from 'node:url';
import util from 'node:util';
import type { HandlerOpts as ChainOpts } from './chain.js';
import { chain } from './chain.js';
import { chainSocks } from './chain_socks.js';
import { customConnect } from './custom_connect.js';
import type { HandlerOpts as CustomResponseOpts } from './custom_response.js';
import { handleCustomResponse } from './custom_response.js';
import { direct } from './direct.js';
import type { HandlerOpts as ForwardOpts } from './forward.js';
import { forward } from './forward.js';
import { forwardSocks } from './forward_socks.js';
import { RequestError } from './request_error.js';
import type { Socket, TLSSocket } from './socket.js';
import { badGatewayStatusCodes } from './statuses.js';
import { getTargetStats } from './utils/count_target_bytes.js';
import { nodeify } from './utils/nodeify.js';
import { normalizeUrlPort } from './utils/normalize_url_port.js';
import { parseAuthorizationHeader } from './utils/parse_authorization_header.js';
import { redactUrl } from './utils/redact_url.js';
export const SOCKS_PROTOCOLS = ['socks:', 'socks4:', 'socks4a:', 'socks5:', 'socks5h:'];
// TODO:
// - Implement this requirement from rfc7230
// "A proxy MUST forward unrecognized header fields unless the field-name
// is listed in the Connection header field (Section 6.1) or the proxy
// is specifically configured to block, or otherwise transform, such
// fields. Other recipients SHOULD ignore unrecognized header fields.
// These requirements allow HTTP's functionality to be enhanced without
// requiring prior update of deployed intermediaries."
const DEFAULT_AUTH_REALM = 'ProxyChain';
const DEFAULT_PROXY_SERVER_PORT = 8000;
const HTTPS_DEFAULT_OPTIONS = {
// Disable TLS 1.0 and 1.1 (deprecated, insecure).
// All other TLS settings use Node.js defaults for cipher selection (automatically updated).
minVersion: 'TLSv1.2',
} as const satisfies Partial<https.ServerOptions>;
/**
* Connection statistics for bandwidth tracking.
*/
export type ConnectionStats = {
// Bytes sent by proxy to client.
srcTxBytes: number;
// Bytes received by proxy from client.
srcRxBytes: number;
// Bytes sent by proxy to target.
trgTxBytes: number | null;
// Bytes received by proxy from target.
trgRxBytes: number | null;
};
type HandlerOpts = {
server: Server;
id: number;
srcRequest: http.IncomingMessage;
srcResponse: http.ServerResponse | null;
srcHead: Buffer | null;
trgParsed: URL | null;
upstreamProxyUrlParsed: URL | null;
ignoreUpstreamProxyCertificate: boolean;
isHttp: boolean;
customResponseFunction?: CustomResponseOpts['customResponseFunction'] | null;
customConnectServer?: http.Server | null;
localAddress?: string;
ipFamily?: number;
dnsLookup?: typeof dns['lookup'];
customTag?: unknown;
httpAgent?: http.Agent;
httpsAgent?: https.Agent;
};
export type PrepareRequestFunctionOpts = {
connectionId: number;
request: http.IncomingMessage;
username: string;
password: string;
hostname: string;
port: number;
isHttp: boolean;
};
export type PrepareRequestFunctionResult = {
customResponseFunction?: CustomResponseOpts['customResponseFunction'];
customConnectServer?: http.Server | null;
requestAuthentication?: boolean;
failMsg?: string;
upstreamProxyUrl?: string | null;
ignoreUpstreamProxyCertificate?: boolean;
localAddress?: string;
ipFamily?: number;
dnsLookup?: typeof dns['lookup'];
customTag?: unknown;
httpAgent?: http.Agent;
httpsAgent?: https.Agent;
};
type Promisable<T> = T | Promise<T>;
export type PrepareRequestFunction = (opts: PrepareRequestFunctionOpts) => Promisable<undefined | PrepareRequestFunctionResult>;
type ServerOptionsBase = {
port?: number;
host?: string;
prepareRequestFunction?: PrepareRequestFunction;
verbose?: boolean;
authRealm?: unknown;
};
export type HttpServerOptions = ServerOptionsBase & {
serverType?: 'http';
};
export type HttpsServerOptions = ServerOptionsBase & {
serverType: 'https';
httpsOptions: https.ServerOptions;
};
export type ServerOptions = HttpServerOptions | HttpsServerOptions;
/**
* Represents the proxy server.
* It emits the 'requestFailed' event on unexpected request errors, with the following parameter `{ error, request }`.
* It emits the 'connectionClosed' event when connection to proxy server is closed, with parameter `{ connectionId, stats }`.
* It emits the 'tlsError' event on TLS handshake failures (HTTPS servers only), with parameter `{ error, socket }`.
* with parameter `{ connectionId, reason, hasParent, parentType }`.
*/
export class Server extends EventEmitter {
port: number;
host?: string;
prepareRequestFunction?: PrepareRequestFunction;
authRealm: unknown;
verbose: boolean;
server: http.Server | https.Server;
serverType: 'http' | 'https';
lastHandlerId: number;
stats: { httpRequestCount: number; connectRequestCount: number; };
connections: Map<number, Socket>;
/**
* Initializes a new instance of Server class.
* @param options
* @param [options.port] Port where the server will listen. By default 8000.
* @param [options.serverType] Type of server to create: 'http' or 'https'. By default 'http'.
* @param [options.httpsOptions] HTTPS server options (required when serverType is 'https').
* Accepts standard Node.js https.ServerOptions including key, cert, ca, passphrase, etc.
* @param [options.prepareRequestFunction] Custom function to authenticate proxy requests,
* provide URL to upstream proxy or potentially provide a function that generates a custom response to HTTP requests.
* It accepts a single parameter which is an object:
* ```
* {
* connectionId: symbol,
* request: http.IncomingMessage,
* username: string,
* password: string,
* hostname: string,
* port: number,
* isHttp: boolean,
* }
* ```
* and returns an object (or promise resolving to the object) with following form:
* ```
* {
* requestAuthentication: boolean,
* upstreamProxyUrl: string,
* customResponseFunction: Function,
* }
* ```
* If `upstreamProxyUrl` is a falsy value, no upstream proxy is used.
* If `prepareRequestFunction` is not set, the proxy server will not require any authentication
* and will not use any upstream proxy.
* If `customResponseFunction` is set, it will be called to generate a custom response to the HTTP request.
* It should not be used together with `upstreamProxyUrl`.
* @param [options.authRealm] Realm used in the Proxy-Authenticate header and also in the 'Server' HTTP header. By default it's `ProxyChain`.
* @param [options.verbose] If true, the server will output logs
*/
constructor(options: ServerOptions = {}) {
super();
if (options.port === undefined || options.port === null) {
this.port = DEFAULT_PROXY_SERVER_PORT;
} else {
this.port = options.port;
}
this.host = options.host;
this.prepareRequestFunction = options.prepareRequestFunction;
this.authRealm = options.authRealm || DEFAULT_AUTH_REALM;
this.verbose = !!options.verbose;
// Keep legacy behavior (http) as default behavior.
this.serverType = options.serverType === 'https' ? 'https' : 'http';
if (options.serverType === 'https') {
if (!options.httpsOptions) {
throw new Error('httpsOptions is required when serverType is "https"');
}
// Apply secure TLS defaults (user options can override).
const effectiveOptions: https.ServerOptions = {
...HTTPS_DEFAULT_OPTIONS,
honorCipherOrder: true,
...options.httpsOptions,
};
this.server = https.createServer(effectiveOptions);
} else {
this.server = http.createServer();
}
// Attach common event handlers (same for both HTTP and HTTPS).
this.server.on('clientError', this.onClientError.bind(this));
this.server.on('request', this.onRequest.bind(this));
this.server.on('connect', this.onConnect.bind(this));
// Attach connection tracking based on server type.
// Only listen to one connection event to avoid double registration.
if (this.serverType === 'https') {
// For HTTPS: Track only post-TLS-handshake sockets (secureConnection).
// This ensures we track the TLS-wrapped socket with correct bytesRead/bytesWritten.
this.server.on('secureConnection', this.onConnection.bind(this));
// Handle TLS handshake errors to prevent server crashes.
this.server.on('tlsClientError', this.onTLSClientError.bind(this));
} else {
// For HTTP: Track raw TCP sockets (connection).
this.server.on('connection', this.onConnection.bind(this));
}
this.lastHandlerId = 0;
this.stats = {
httpRequestCount: 0,
connectRequestCount: 0,
};
this.connections = new Map();
}
/**
* Handles TLS handshake errors for HTTPS servers.
* Without this handler, unhandled TLS errors can crash the server.
* Common errors: ECONNRESET, ERR_SSL_SSLV3_ALERT_CERTIFICATE_UNKNOWN,
* ERR_SSL_TLSV1_ALERT_PROTOCOL_VERSION, ERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILURE
*/
onTLSClientError(err: NodeJS.ErrnoException, tlsSocket: TLSSocket): void {
const connectionId = (tlsSocket as TLSSocket).proxyChainId;
this.log(connectionId, `TLS handshake failed: ${err.message}`);
// Emit event in first place before any return statement.
this.emit('tlsError', { error: err, socket: tlsSocket });
// If connection already reset or socket not writable, nothing more to do.
if (err.code === 'ECONNRESET' || !tlsSocket.writable) {
return;
}
// TLS handshake failed before HTTP, cannot send HTTP response.
// Destroy the socket to clean up.
tlsSocket.destroy(err);
}
log(connectionId: unknown, str: string): void {
if (this.verbose) {
const logPrefix = connectionId != null ? `${String(connectionId)} | ` : '';
// eslint-disable-next-line no-console
console.log(`ProxyServer[${this.port}]: ${logPrefix}${str}`);
}
}
onClientError(err: NodeJS.ErrnoException, socket: Socket): void {
this.log(socket.proxyChainId, `onClientError: ${err}`);
// https://nodejs.org/api/http.html#http_event_clienterror
if (err.code === 'ECONNRESET' || !socket.writable) {
return;
}
this.sendSocketResponse(socket, 400, {}, 'Invalid request');
}
/**
* Assigns a unique ID to the socket and keeps the register up to date.
* Needed for abrupt close of the server.
*/
registerConnection(socket: Socket): void {
const unique = this.lastHandlerId++;
socket.proxyChainId = unique;
this.connections.set(unique, socket);
socket.on('close', () => {
this.emit('connectionClosed', {
connectionId: unique,
stats: this.getConnectionStats(unique),
});
this.connections.delete(unique);
});
// We have to manually destroy the socket if it timeouts.
// This will prevent connections from leaking and close them properly.
socket.on('timeout', () => {
socket.destroy();
});
}
/**
* Handles incoming sockets, useful for error handling
*/
onConnection(socket: Socket): void {
// https://github.com/nodejs/node/issues/23858
if (!socket.remoteAddress) {
socket.destroy();
return;
}
this.registerConnection(socket);
// We need to consume socket errors, because the handlers are attached asynchronously.
// See https://github.com/apify/proxy-chain/issues/53
socket.on('error', (err) => {
// Handle errors only if there's no other handler
if (socket.listenerCount('error') === 1) {
this.log(socket.proxyChainId, `Source socket emitted error: ${err.stack || err}`);
}
});
}
/**
* Converts known errors to be instance of RequestError.
*/
normalizeHandlerError(error: NodeJS.ErrnoException): NodeJS.ErrnoException {
if (error.message === 'Username contains an invalid colon') {
return new RequestError('Invalid colon in username in upstream proxy credentials', badGatewayStatusCodes.AUTH_FAILED);
}
if (error.message === '407 Proxy Authentication Required') {
return new RequestError('Invalid upstream proxy credentials', badGatewayStatusCodes.AUTH_FAILED);
}
return error;
}
/**
* Handles normal HTTP request by forwarding it to target host or the upstream proxy.
*/
async onRequest(request: http.IncomingMessage, response: http.ServerResponse): Promise<void> {
try {
const handlerOpts = await this.prepareRequestHandling(request);
handlerOpts.srcResponse = response;
const { proxyChainId } = request.socket as Socket;
if (handlerOpts.customResponseFunction) {
this.log(proxyChainId, 'Using handleCustomResponse()');
await handleCustomResponse(request, response, handlerOpts as CustomResponseOpts);
return;
}
if (handlerOpts.upstreamProxyUrlParsed && SOCKS_PROTOCOLS.includes(handlerOpts.upstreamProxyUrlParsed.protocol)) {
this.log(proxyChainId, 'Using forwardSocks()');
await forwardSocks(request, response, handlerOpts as ForwardOpts);
return;
}
this.log(proxyChainId, 'Using forward()');
await forward(request, response, handlerOpts as ForwardOpts);
} catch (error) {
this.failRequest(request, this.normalizeHandlerError(error as NodeJS.ErrnoException));
}
}
/**
* Handles HTTP CONNECT request by setting up a tunnel either to target host or to the upstream proxy.
* @param request
* @param socket
* @param head The first packet of the tunneling stream (may be empty)
*/
async onConnect(request: http.IncomingMessage, socket: Socket, head: Buffer): Promise<void> {
try {
const handlerOpts = await this.prepareRequestHandling(request);
handlerOpts.srcHead = head;
const data = { request, sourceSocket: socket, head, handlerOpts: handlerOpts as ChainOpts, server: this, isPlain: false };
if (handlerOpts.customConnectServer) {
socket.unshift(head); // See chain.ts for why we do this
await customConnect(socket, handlerOpts.customConnectServer);
return;
}
if (handlerOpts.upstreamProxyUrlParsed) {
if (SOCKS_PROTOCOLS.includes(handlerOpts.upstreamProxyUrlParsed.protocol)) {
this.log(socket.proxyChainId, `Using chainSocks() => ${request.url}`);
await chainSocks(data);
return;
}
this.log(socket.proxyChainId, `Using chain() => ${request.url}`);
chain(data);
return;
}
this.log(socket.proxyChainId, `Using direct() => ${request.url}`);
direct(data);
} catch (error) {
this.failRequest(request, this.normalizeHandlerError(error as NodeJS.ErrnoException));
}
}
/**
* Prepares handler options from a request.
* @see {prepareRequestHandling}
*/
getHandlerOpts(request: http.IncomingMessage): HandlerOpts {
const handlerOpts: HandlerOpts = {
server: this,
id: (request.socket as Socket).proxyChainId!,
srcRequest: request,
srcHead: null,
trgParsed: null,
upstreamProxyUrlParsed: null,
ignoreUpstreamProxyCertificate: false,
isHttp: false,
srcResponse: null,
customResponseFunction: null,
customConnectServer: null,
};
this.log((request.socket as Socket).proxyChainId, `!!! Handling ${request.method} ${request.url} HTTP/${request.httpVersion}`);
if (request.method === 'CONNECT') {
// CONNECT server.example.com:80 HTTP/1.1
try {
handlerOpts.trgParsed = new URL(`connect://${request.url}`);
} catch {
throw new RequestError(`Target "${request.url}" could not be parsed`, 400);
}
if (!handlerOpts.trgParsed.hostname || !handlerOpts.trgParsed.port) {
throw new RequestError(`Target "${request.url}" could not be parsed`, 400);
}
this.stats.connectRequestCount++;
} else {
// The request should look like:
// GET http://server.example.com:80/some-path HTTP/1.1
// Note that RFC 7230 says:
// "When making a request to a proxy, other than a CONNECT or server-wide
// OPTIONS request (as detailed below), a client MUST send the target
// URI in absolute-form as the request-target"
let parsed;
try {
parsed = new URL(request.url!);
} catch {
// If URL is invalid, throw HTTP 400 error
throw new RequestError(`Target "${request.url}" could not be parsed`, 400);
}
// Only HTTP is supported, other protocols such as HTTP or FTP must use the CONNECT method
if (parsed.protocol !== 'http:') {
throw new RequestError(`Only HTTP protocol is supported (was ${parsed.protocol})`, 400);
}
handlerOpts.trgParsed = parsed;
handlerOpts.isHttp = true;
this.stats.httpRequestCount++;
}
return handlerOpts;
}
/**
* Calls `this.prepareRequestFunction` with normalized options.
* @param request
* @param handlerOpts
*/
async callPrepareRequestFunction(request: http.IncomingMessage, handlerOpts: HandlerOpts): Promise<PrepareRequestFunctionResult> {
if (this.prepareRequestFunction) {
const funcOpts: PrepareRequestFunctionOpts = {
connectionId: (request.socket as Socket).proxyChainId!,
request,
username: '',
password: '',
hostname: handlerOpts.trgParsed!.hostname,
port: normalizeUrlPort(handlerOpts.trgParsed!),
isHttp: handlerOpts.isHttp,
};
// Authenticate the request using a user function (if provided)
const proxyAuth = request.headers['proxy-authorization'];
if (proxyAuth) {
const auth = parseAuthorizationHeader(proxyAuth);
if (!auth) {
throw new RequestError('Invalid "Proxy-Authorization" header', 400);
}
// https://datatracker.ietf.org/doc/html/rfc7617#page-3
// Note that both scheme and parameter names are matched case-
// insensitively.
if (auth.type.toLowerCase() !== 'basic') {
throw new RequestError('The "Proxy-Authorization" header must have the "Basic" type.', 400);
}
funcOpts.username = auth.username!;
funcOpts.password = auth.password!;
}
const result = await this.prepareRequestFunction(funcOpts);
return result ?? {};
}
return {};
}
/**
* Authenticates a new request and determines upstream proxy URL using the user function.
* Returns a promise resolving to an object that can be used to run a handler.
* @param request
*/
async prepareRequestHandling(request: http.IncomingMessage): Promise<HandlerOpts> {
const handlerOpts = this.getHandlerOpts(request);
const funcResult = await this.callPrepareRequestFunction(request, handlerOpts);
handlerOpts.localAddress = funcResult.localAddress;
handlerOpts.ipFamily = funcResult.ipFamily;
handlerOpts.dnsLookup = funcResult.dnsLookup;
handlerOpts.customConnectServer = funcResult.customConnectServer;
handlerOpts.customTag = funcResult.customTag;
handlerOpts.httpAgent = funcResult.httpAgent;
handlerOpts.httpsAgent = funcResult.httpsAgent;
// If not authenticated, request client to authenticate
if (funcResult.requestAuthentication) {
throw new RequestError(funcResult.failMsg || 'Proxy credentials required.', 407);
}
if (funcResult.upstreamProxyUrl) {
try {
handlerOpts.upstreamProxyUrlParsed = new URL(funcResult.upstreamProxyUrl);
} catch (error) {
throw new Error(`Invalid "upstreamProxyUrl" provided: ${error} (was "${funcResult.upstreamProxyUrl}"`);
}
if (!['http:', 'https:', ...SOCKS_PROTOCOLS].includes(handlerOpts.upstreamProxyUrlParsed.protocol)) {
throw new Error(`Invalid "upstreamProxyUrl" provided: URL must have one of the following protocols: "http", "https", ${SOCKS_PROTOCOLS.map((p) => `"${p.replace(':', '')}"`).join(', ')} (was "${funcResult.upstreamProxyUrl}")`);
}
}
if (funcResult.ignoreUpstreamProxyCertificate !== undefined) {
handlerOpts.ignoreUpstreamProxyCertificate = funcResult.ignoreUpstreamProxyCertificate;
}
const { proxyChainId } = request.socket as Socket;
if (funcResult.customResponseFunction) {
this.log(proxyChainId, 'Using custom response function');
handlerOpts.customResponseFunction = funcResult.customResponseFunction;
if (!handlerOpts.isHttp) {
throw new Error('The "customResponseFunction" option can only be used for HTTP requests.');
}
if (typeof (handlerOpts.customResponseFunction) !== 'function') {
throw new Error('The "customResponseFunction" option must be a function.');
}
}
if (handlerOpts.upstreamProxyUrlParsed) {
this.log(proxyChainId, `Using upstream proxy ${redactUrl(handlerOpts.upstreamProxyUrlParsed)}`);
}
return handlerOpts;
}
/**
* Sends a HTTP error response to the client.
* @param request
* @param error
*/
failRequest(request: http.IncomingMessage, error: NodeJS.ErrnoException): void {
const { proxyChainId } = request.socket as Socket;
if (error.name === 'RequestError') {
const typedError = error as RequestError;
this.log(proxyChainId, `Request failed (status ${typedError.statusCode}): ${error.message}`);
this.sendSocketResponse(request.socket, typedError.statusCode, typedError.headers, error.message);
} else {
this.log(proxyChainId, `Request failed with error: ${error.stack || error}`);
this.sendSocketResponse(request.socket, 500, {}, 'Internal error in proxy server');
this.emit('requestFailed', { error, request });
}
this.log(proxyChainId, 'Closing because request failed with error');
}
/**
* Sends a simple HTTP response to the client and forcibly closes the connection.
* This invalidates the ServerResponse instance (if present).
* We don't know the state of the response anyway.
* Writing directly to the socket seems to be the easiest solution.
* @param socket
* @param statusCode
* @param headers
* @param message
*/
sendSocketResponse(socket: Socket, statusCode = 500, caseSensitiveHeaders = {}, message = ''): void {
try {
const headers = Object.fromEntries(
Object.entries(caseSensitiveHeaders).map(
([name, value]) => [name.toLowerCase(), value],
),
);
headers.connection = 'close';
headers.date = (new Date()).toUTCString();
headers['content-length'] = String(Buffer.byteLength(message));
headers.server = headers.server || this.authRealm;
headers['content-type'] = headers['content-type'] || 'text/plain; charset=utf-8';
if (statusCode === 407 && !headers['proxy-authenticate']) {
headers['proxy-authenticate'] = `Basic realm="${this.authRealm}"`;
}
let msg = `HTTP/1.1 ${statusCode} ${http.STATUS_CODES[statusCode] || 'Unknown Status Code'}\r\n`;
for (const [key, value] of Object.entries(headers)) {
msg += `${key}: ${value}\r\n`;
}
msg += `\r\n${message}`;
// Unfortunately it's not possible to send RST in Node.js yet.
// See https://github.com/nodejs/node/issues/27428
socket.setTimeout(1000, () => {
socket.destroy();
});
// This sends FIN, meaning we still can receive data.
socket.end(msg);
} catch (err) {
this.log(socket.proxyChainId, `Unhandled error in sendResponse(), will be ignored: ${(err as Error).stack || err}`);
}
}
/**
* Starts listening at a port specified in the constructor.
*/
async listen(callback?: (error: NodeJS.ErrnoException | null) => void): Promise<void> {
const promise = new Promise<void>((resolve, reject) => {
// Unfortunately server.listen() is not a normal function that fails on error,
// so we need this trickery
const onError = (error: NodeJS.ErrnoException) => {
this.log(null, `Listen failed: ${error}`);
removeListeners();
reject(error);
};
const onListening = () => {
this.port = (this.server.address() as net.AddressInfo).port;
this.log(null, 'Listening...');
removeListeners();
resolve();
};
const removeListeners = () => {
this.server.removeListener('error', onError);
this.server.removeListener('listening', onListening);
};
this.server.on('error', onError);
this.server.on('listening', onListening);
this.server.listen(this.port, this.host);
});
return nodeify(promise, callback);
}
/**
* Gets array of IDs of all active connections.
*/
getConnectionIds(): number[] {
return [...this.connections.keys()];
}
/**
* Gets data transfer statistics of a specific proxy connection.
*/
getConnectionStats(connectionId: number): ConnectionStats | undefined {
const socket = this.connections.get(connectionId);
if (!socket) return undefined;
const targetStats = getTargetStats(socket);
const result = {
srcTxBytes: socket.bytesWritten,
srcRxBytes: socket.bytesRead,
trgTxBytes: targetStats.bytesWritten,
trgRxBytes: targetStats.bytesRead,
};
return result;
}
/**
* Forcibly close a specific pending proxy connection.
*/
closeConnection(connectionId: number): void {
this.log(null, 'Closing pending socket');
const socket = this.connections.get(connectionId);
if (!socket) return;
socket.destroy();
this.log(null, `Destroyed pending socket`);
}
/**
* Forcibly closes pending proxy connections.
*/
closeConnections(): void {
this.log(null, 'Closing pending sockets');
for (const socket of this.connections.values()) {
socket.destroy();
}
this.log(null, `Destroyed ${this.connections.size} pending sockets`);
}
/**
* Closes the proxy server.
* @param closeConnections If true, pending proxy connections are forcibly closed.
*/
async close(closeConnections: boolean, callback?: (error: NodeJS.ErrnoException | null) => void): Promise<void> {
if (typeof closeConnections === 'function') {
callback = closeConnections;
closeConnections = false;
}
if (closeConnections) {
this.closeConnections();
}
if (this.server) {
const { server } = this;
// @ts-expect-error Let's make sure we can't access the server anymore.
this.server = null;
const promise = util.promisify(server.close).bind(server)();
return nodeify(promise, callback);
}
return nodeify(Promise.resolve(), callback);
}
}