strongloop/express — pull request #2300 by manuelstofer (2014-08-15 09:54:05+00:00)
Title: Leaks in send dependency and in  #sendFile

Hi.

I have been hunting memory and file descriptor leaks in my web service. There are several issues in `#sendFile` and in the `send` dependency when requests are aborted.

The following example leaks open files and I think it also leads to a memory leak that prevents the request and response object from being garbage collected.

```javascript
var express = require('express');
var app = express();
var http = require('http');

app.get('/', function (req, res) {
res.sendFile(__filename);
});
http.createServer(app).listen(3000, 'localhost');
```

I used following script to generate some aborted requests and looked with `lsof` for open files after.

```javascript
var net = require('net');
var headers = [
'GET / HTTP/1.1',
'Host: localhost:3000',
'',
''
].join('\r\n');

function sendCanceledRequest () {
var socket = new net.Socket();
socket.connect(3000, 'localhost', function() {
socket.write(headers, 'utf-8', function () {
socket.destroy();
});
});
}

setInterval(sendCanceledRequest, 1000);
```

`#sendFile` handles the `error` event of the underlying socket. As far as i understand that event fires when the `Content-Length` header is sent and the request is closed before that length is reached. But it does not fire for well-formed requests that close too early (Tested on node v0.10.28)

I think the `end` event should also get handled.

Maybe both events should get handled directly in the `send` dependency.

Send currently does not handle the request `close` and socket `error` event. And also does not provide a public api to clean up once it's started.

The example in the `#sendFile` doc comment suggests that you can do some async stuff in a route and then call `#sendFile` after. This will lead again to the same problem if the `error` event or the `close` event fires before `#sendFile` is called.

I would create a pull request. But i wanted to ask first how you think this should get handled.