• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  req.on('close', common.mustCall());
37
38  req.on('connect', common.mustCall(function(res, socket, firstBodyChunk) {
39    console.error('Client got CONNECT request');
40
41    // Make sure this request got removed from the pool.
42    const name = `localhost:${server.address().port}`;
43    assert(!http.globalAgent.sockets.hasOwnProperty(name));
44    assert(!http.globalAgent.requests.hasOwnProperty(name));
45
46    // Make sure this socket has detached.
47    assert(!socket.ondata);
48    assert(!socket.onend);
49    assert.strictEqual(socket.listeners('connect').length, 0);
50    assert.strictEqual(socket.listeners('data').length, 0);
51
52    let data = firstBodyChunk.toString();
53
54    // Test that the firstBodyChunk was not parsed as HTTP
55    assert.strictEqual(data, 'Head');
56
57    socket.on('data', function(buf) {
58      data += buf.toString();
59    });
60    socket.on('end', function() {
61      assert.strictEqual(data, 'HeadRequestEnd');
62      server.close();
63    });
64    socket.end('End');
65  }));
66
67  req.end('Request');
68}));
69