forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy-server.js
More file actions
191 lines (168 loc) Β· 4.6 KB
/
proxy-server.js
File metadata and controls
191 lines (168 loc) Β· 4.6 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
'use strict';
const net = require('net');
const http = require('http');
const assert = require('assert');
function logRequest(logs, req) {
logs.push({
method: req.method,
url: req.url,
headers: { ...req.headers },
});
}
// This creates a minimal proxy server that logs the requests it gets
// to an array before performing proxying.
exports.createProxyServer = function(options = {}) {
const logs = [];
let proxy;
if (options.https) {
const common = require('../common');
if (!common.hasCrypto) {
common.skip('missing crypto');
}
proxy = require('https').createServer({
cert: require('./fixtures').readKey('agent9-cert.pem'),
key: require('./fixtures').readKey('agent9-key.pem'),
});
} else {
proxy = http.createServer();
}
proxy.on('request', (req, res) => {
logRequest(logs, req);
const [hostname, port] = req.headers.host.split(':');
const targetPort = port || 80;
const url = new URL(req.url);
const options = {
hostname: hostname,
port: targetPort,
path: url.pathname + url.search, // Convert back to relative URL.
method: req.method,
headers: {
...req.headers,
'connection': req.headers['proxy-connection'] || 'close',
},
};
const proxyReq = http.request(options, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
proxyReq.on('error', (err) => {
logs.push({ error: err, source: 'proxy request' });
if (!res.headersSent) {
res.writeHead(500);
}
if (!res.writableEnded) {
res.end(`Proxy error ${err.code}: ${err.message}`);
}
});
res.on('error', (err) => {
logs.push({ error: err, source: 'proxy response' });
});
req.pipe(proxyReq, { end: true });
});
proxy.on('connect', (req, res, head) => {
logRequest(logs, req);
const [hostname, port] = req.url.split(':');
res.on('error', (err) => {
logs.push({ error: err, source: 'proxy response' });
});
const proxyReq = net.connect(port, hostname, () => {
res.write(
'HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n',
);
proxyReq.write(head);
res.pipe(proxyReq);
proxyReq.pipe(res);
});
proxyReq.on('error', (err) => {
logs.push({ error: err, source: 'proxy request' });
res.write('HTTP/1.1 500 Connection Error\r\n\r\n');
res.end('Proxy error: ' + err.message);
});
});
proxy.on('error', (err) => {
logs.push({ error: err, source: 'proxy server' });
});
return { proxy, logs };
};
function spawnPromisified(...args) {
const { spawn } = require('child_process');
let stderr = '';
let stdout = '';
const child = spawn(...args);
child.stderr.setEncoding('utf8');
child.stderr.on('data', (data) => {
console.error('[STDERR]', data);
stderr += data;
});
child.stdout.setEncoding('utf8');
child.stdout.on('data', (data) => {
console.log('[STDOUT]', data);
stdout += data;
});
return new Promise((resolve, reject) => {
child.on('close', (code, signal) => {
console.log('[CLOSE]', code, signal);
resolve({
code,
signal,
stderr,
stdout,
});
});
child.on('error', (code, signal) => {
console.log('[ERROR]', code, signal);
reject({
code,
signal,
stderr,
stdout,
});
});
});
}
exports.checkProxiedFetch = async function(envExtension, expectation, cliArgsExtension = []) {
const fixtures = require('./fixtures');
const { code, signal, stdout, stderr } = await spawnPromisified(
process.execPath,
[...cliArgsExtension, fixtures.path('fetch-and-log.mjs')], {
env: {
...process.env,
...envExtension,
},
});
assert.deepStrictEqual({
stderr: stderr.trim(),
stdout: stdout.trim(),
code,
signal,
}, {
stderr: '',
code: 0,
signal: null,
...expectation,
});
};
exports.runProxiedRequest = async function(envExtension, cliArgsExtension = []) {
const fixtures = require('./fixtures');
return spawnPromisified(
process.execPath,
[...cliArgsExtension, fixtures.path('request-and-log.js')], {
env: {
...process.env,
...envExtension,
},
});
};
exports.runProxiedPOST = async function(envExtension) {
const fixtures = require('./fixtures');
return spawnPromisified(
process.execPath,
[fixtures.path('post-resource-and-log.js')], {
env: {
...process.env,
...envExtension,
},
});
};