1'use strict'; 2const common = require('../common'); 3const assert = require('assert'); 4const http = require('http'); 5 6const server = http.createServer(common.mustNotCall()); 7server.on('connect', common.mustCall(function(req, socket, firstBodyChunk) { 8 assert.strictEqual(req.method, 'CONNECT'); 9 assert.strictEqual(req.url, 'example.com:443'); 10 console.error('Server got CONNECT request'); 11 12 // It is legal for the server to send some data intended for the client 13 // along with the CONNECT response 14 socket.write( 15 'HTTP/1.1 200 Connection established\r\n' + 16 'Date: Tue, 15 Nov 1994 08:12:31 GMT\r\n' + 17 '\r\n' + 18 'Head' 19 ); 20 21 let data = firstBodyChunk.toString(); 22 socket.on('data', function(buf) { 23 data += buf.toString(); 24 }); 25 socket.on('end', function() { 26 socket.end(data); 27 }); 28})); 29server.listen(0, common.mustCall(function() { 30 const req = http.request({ 31 port: this.address().port, 32 method: 'CONNECT', 33 path: 'example.com:443' 34 }, common.mustNotCall()); 35 36 assert.strictEqual(req.destroyed, false); 37 req.on('close', common.mustCall(() => { 38 assert.strictEqual(req.destroyed, true); 39 })); 40 41 req.on('connect', common.mustCall(function(res, socket, firstBodyChunk) { 42 console.error('Client got CONNECT request'); 43 44 // Make sure this request got removed from the pool. 45 const name = `localhost:${server.address().port}`; 46 assert(!(name in http.globalAgent.sockets)); 47 assert(!(name in http.globalAgent.requests)); 48 49 // Make sure this socket has detached. 50 assert(!socket.ondata); 51 assert(!socket.onend); 52 assert.strictEqual(socket.listeners('connect').length, 0); 53 assert.strictEqual(socket.listeners('data').length, 0); 54 55 let data = firstBodyChunk.toString(); 56 57 // Test that the firstBodyChunk was not parsed as HTTP 58 assert.strictEqual(data, 'Head'); 59 60 socket.on('data', function(buf) { 61 data += buf.toString(); 62 }); 63 socket.on('end', function() { 64 assert.strictEqual(data, 'HeadRequestEnd'); 65 server.close(); 66 }); 67 socket.end('End'); 68 })); 69 70 req.end('Request'); 71})); 72