1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23const common = require('../common');
24if (common.isWindows)
25  common.skip('This test is disabled on windows.');
26
27const assert = require('assert');
28const http = require('http');
29const net = require('net');
30const spawn = require('child_process').spawn;
31
32switch (process.argv[2]) {
33  case 'child': return child();
34  case 'parent': return parent();
35  default: return test();
36}
37
38// Spawn the parent, and listen for it to tell us the pid of the child.
39// WARNING: This is an example of listening on some arbitrary FD number
40// that has already been bound elsewhere in advance.  However, binding
41// server handles to stdio fd's is NOT a good or reliable way to do
42// concurrency in HTTP servers!  Use the cluster module, or if you want
43// a more low-level approach, use child process IPC manually.
44function test() {
45  const parent = spawn(process.execPath, [__filename, 'parent'], {
46    stdio: [ 0, 'pipe', 2 ]
47  });
48  let json = '';
49  parent.stdout.on('data', function(c) {
50    json += c.toString();
51    if (json.includes('\n')) next();
52  });
53  function next() {
54    console.error('output from parent = %s', json);
55    const child = JSON.parse(json);
56    // Now make sure that we can request to the subprocess, then kill it.
57    http.get({
58      server: 'localhost',
59      port: child.port,
60      path: '/',
61    }).on('response', function(res) {
62      let s = '';
63      res.on('data', function(c) {
64        s += c.toString();
65      });
66      res.on('end', function() {
67        // Kill the subprocess before we start doing asserts.
68        // It's really annoying when tests leave orphans!
69        process.kill(child.pid, 'SIGKILL');
70        try {
71          parent.kill();
72        } catch {
73          // Continue regardless of error.
74        }
75
76        assert.strictEqual(s, 'hello from child\n');
77        assert.strictEqual(res.statusCode, 200);
78      });
79    });
80  }
81}
82
83// Listen on port, and then pass the handle to the detached child.
84// Then output the child's pid, and immediately exit.
85function parent() {
86  const server = net.createServer(function(conn) {
87    conn.end('HTTP/1.1 403 Forbidden\r\n\r\nI got problems.\r\n');
88    throw new Error('Should not see connections on parent');
89  }).listen(0, function() {
90    console.error('server listening on %d', this.address().port);
91
92    const child = spawn(process.execPath, [__filename, 'child'], {
93      stdio: [ 0, 1, 2, server._handle ],
94      detached: true
95    });
96
97    console.log('%j\n', { pid: child.pid, port: this.address().port });
98
99    // Now close the parent, so that the child is the only thing
100    // referencing that handle.  Note that connections will still
101    // be accepted, because the child has the fd open, but the parent
102    // will exit gracefully.
103    server.close();
104    child.unref();
105  });
106}
107
108// Run as a child of the parent() mode.
109function child() {
110  // Start a server on fd=3
111  http.createServer(function(req, res) {
112    console.error('request on child');
113    console.error('%s %s', req.method, req.url, req.headers);
114    res.end('hello from child\n');
115  }).listen({ fd: 3 }, function() {
116    console.error('child listening on fd=3');
117  });
118}
119