joyent/node — pull request #3729 by bnoordhuis (2012-07-17 23:55:02+00:00)
Title: net: fix Socket({ fd: 42 }) api

Make the implementation match the documentation. This should work:

```javascript
var s = new net.Socket({ fd: 42, allowHalfOpen: true };
```

And now it does.

Node won't let you create arbitrary SOCK_STREAM sockets. I couldn't come up with a decent test because of that but here is an (admittedly rather lame) ad-hoc test:

```c
// compile with `gcc -o execfd execfd.c`
#include
#include
#include
#include

extern char **environ;

int main(int argc, char **argv)
{
if (argc < 2) return 1;
close(3);
socket(AF_UNIX, SOCK_STREAM, 0);
execve(argv[1], argv + 1, environ);
return 1;
}
```

Start an echo server:

```bash
$ node -e '\
require("net").createServer(echo).listen("/tmp/sock"); \
function echo(c) { c.pipe(c) }'
```

Now run the test script:

```bash
$ ./execfd node -e '\
var s = new (require("net").Socket)({fd:3}); \
s.connect("/tmp/sock", function() { \
s.pipe(process.stdout); \
s.end("BAM\n"); \
})'
```

Observe how it fails hard without the patch. With the patch, it neatly prints "BAM" and exits.

A separate issue that still needs to be addressed is this:

```bash
$ node -e 'var s = new (require("net").Socket)(3); s.listen(console.log)'

net.js:948
self._listen2(address, port, addressType, backlog, fd);
^
TypeError: Object # has no method '_listen2'
at listen (net.js:948:10)
at Socket.listen (net.js:164:3)
at Object.eval (eval at (eval:1:82))
at Object. (eval:1:70)
at Module._compile (module.js:449:26)
at evalScript (node.js:270:25)
at startup (node.js:76:7)
at node.js:611:3
```