UNPKG

3.15 kBJavaScriptView Raw
1var http = require('http');
2var net = require('net');
3var should = require('should');
4var tunnel = require('../index');
5
6describe('HTTP over HTTP', function() {
7 it('should finish without error', function(done) {
8 var serverPort = 3000;
9 var proxyPort = 3001;
10 var poolSize = 3;
11 var N = 10;
12 var serverConnect = 0;
13 var proxyConnect = 0;
14 var clientConnect = 0;
15 var server;
16 var proxy;
17 var agent;
18
19 server = http.createServer(function(req, res) {
20 tunnel.debug('SERVER: got request');
21 ++serverConnect;
22 res.writeHead(200);
23 res.end('Hello' + req.url);
24 tunnel.debug('SERVER: sending response');
25 });
26 server.listen(serverPort, setupProxy);
27
28 function setupProxy() {
29 proxy = http.createServer(function(req, res) {
30 should.fail();
31 });
32 proxy.on('upgrade', onConnect); // for v0.6
33 proxy.on('connect', onConnect); // for v0.7 or later
34
35 function onConnect(req, clientSocket, head) {
36 tunnel.debug('PROXY: got CONNECT request');
37
38 req.method.should.equal('CONNECT');
39 req.url.should.equal('localhost:' + serverPort);
40 req.headers.should.not.have.property('transfer-encoding');
41 req.headers.should.have.property('proxy-authorization',
42 'Basic ' + new Buffer('user:password').toString('base64'));
43 ++proxyConnect;
44
45 tunnel.debug('PROXY: creating a tunnel');
46 var serverSocket = net.connect(serverPort, function() {
47 tunnel.debug('PROXY: replying to client CONNECT request');
48 clientSocket.write('HTTP/1.1 200 Connection established\r\n\r\n');
49 clientSocket.pipe(serverSocket);
50 serverSocket.write(head);
51 serverSocket.pipe(clientSocket);
52 // workaround, see joyent/node#2524
53 serverSocket.on('end', function() {
54 clientSocket.end();
55 });
56 });
57 }
58 proxy.listen(proxyPort, setupClient);
59 }
60
61 function setupClient() {
62 agent = tunnel.httpOverHttp({
63 maxSockets: poolSize,
64 proxy: {
65 port: proxyPort,
66 proxyAuth: 'user:password'
67 }
68 });
69
70 for (var i = 0; i < N; ++i) {
71 doClientRequest(i);
72 }
73
74 function doClientRequest(i) {
75 tunnel.debug('CLIENT: Making HTTP request (%d)', i);
76 var req = http.get({
77 port: serverPort,
78 path: '/' + i,
79 agent: agent
80 }, function(res) {
81 tunnel.debug('CLIENT: got HTTP response (%d)', i);
82 res.setEncoding('utf8');
83 res.on('data', function(data) {
84 data.should.equal('Hello/' + i);
85 });
86 res.on('end', function() {
87 ++clientConnect;
88 if (clientConnect === N) {
89 proxy.close();
90 server.close();
91 }
92 });
93 });
94 }
95 }
96
97 server.on('close', function() {
98 serverConnect.should.equal(N);
99 proxyConnect.should.equal(poolSize);
100 clientConnect.should.equal(N);
101
102 agent.sockets.should.be.empty;
103 agent.requests.should.be.empty;
104
105 done();
106 });
107 });
108});