I want to be able to look at the first chunk of data coming through a regular net socket and then convert it to a tls socket if necessary.
1. establish tcp connection
2. check first packet
3. if tls hello, use tls
4. otherwise use tcp
5. re-emit first packet
I've tried just emitting 'connection' on an http.Server for plain connections that works.
It does NOT work when I try the exact same thing with tls.Server, https.Server, or tls.TLSSocket:
'use strict';
var net = require('net');
var tls = require('tls');
var http = require('http');
var tlsOpts = require('localhost.daplie.com-certificates').merge({});
var plainHttp = http.createServer(function (req, res) {
res.end('Hello, World!');
});
var tcp3000 = net.createServer(function (socket) {
socket.once('data', function (chunk) {
if (/http\/1/i.test(chunk.toString())) {
// works
console.log("looks like http, continue");
plainHttp.emit('connection', socket);
} else {
// does not work
console.log("doesn't look like http, try tls");
// secureHttp.emit('connection', socket);
var tlsSocket = new tls.TLSSocket(socket, { secureContext: tls.createSecureContext(tlsOpts) });
tlsSocket.on('data', function (chunk) {
// this is never called
console.log('chunk', chunk);
});
}
// replay first packet
socket.emit('data', chunk);
});
});
tcp3000.listen(3000, function () {
console.log('listening on 3000');
});