How to mux tcp and tls on the same port?

87 views
Skip to first unread message

CoolAJ86

unread,
Sep 24, 2016, 5:18:07 PM9/24/16
to nodejs
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.

Breaking that down:
  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');
    });

Any thoughts or ideas?

CoolAJ86

unread,
Oct 3, 2016, 9:10:07 AM10/3/16
to nodejs
Reply all
Reply to author
Forward
0 new messages