chrstnwhlrt
chrstnwhlrt

Reputation: 351

NodeJS create https from existing tls.Server

is there any possibility to create a https server on top of a existing tls.Server? The documentation says: "This class is a subclass of tls.Server..". I want to use the tls.Server to work with the pure data stream and if needed let the https server handle the rest. (Like express with https, just on a lower layer)

Regards

Upvotes: 0

Views: 507

Answers (1)

Miroslav Bajtoš
Miroslav Bajtoš

Reputation: 10785

There isn't any official/supported way for that.

However if you look at the source code of https server, it's just a glue that connects together TLS server and HTTP connection handler:

function Server(opts, requestListener) {
  if (!(this instanceof Server)) return new Server(opts, requestListener);

  if (process.features.tls_npn && !opts.NPNProtocols) {
    opts.NPNProtocols = ['http/1.1', 'http/1.0'];
  }

  /// This is the part where we instruct TLS server to use 
  /// HTTP code to handle incoming connections.
  tls.Server.call(this, opts, http._connectionListener);

  this.httpAllowHalfOpen = false;

  if (requestListener) {
    this.addListener('request', requestListener);
  }

  this.addListener('clientError', function(err, conn) {
    conn.destroy();
  });

  this.timeout = 2 * 60 * 1000;
}

To switch to HTTPS in your TLS connection handler, you could do something along these lines:

var http = require('http');

function myTlsRequestListener(cleartextStream) {
   if (shouldSwitchToHttps) {
     http._connectionListener(cleartextStream);
   } else {
     // do other stuff
   }
}

The code above is based on version 0.11 (i.e. current master).

WARNING

Using internal Node API might bite you during upgrade to a newer version (i.e. your application might stop working after upgrade).

Upvotes: 2

Related Questions