server.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. 'use strict'
  2. var assert = require('assert')
  3. var https = require('https')
  4. var http = require('http')
  5. var tls = require('tls')
  6. var net = require('net')
  7. var util = require('util')
  8. var selectHose = require('select-hose')
  9. var transport = require('spdy-transport')
  10. var debug = require('debug')('spdy:server')
  11. var EventEmitter = require('events').EventEmitter
  12. // Node.js 0.8, 0.10 and 0.12 support
  13. Object.assign = process.versions.modules >= 46
  14. ? Object.assign // eslint-disable-next-line
  15. : util._extend
  16. var spdy = require('../spdy')
  17. var proto = {}
  18. function instantiate (base) {
  19. function Server (options, handler) {
  20. this._init(base, options, handler)
  21. }
  22. util.inherits(Server, base)
  23. Server.create = function create (options, handler) {
  24. return new Server(options, handler)
  25. }
  26. Object.keys(proto).forEach(function (key) {
  27. Server.prototype[key] = proto[key]
  28. })
  29. return Server
  30. }
  31. proto._init = function _init (base, options, handler) {
  32. var state = {}
  33. this._spdyState = state
  34. state.options = options.spdy || {}
  35. var protocols = state.options.protocols || [
  36. 'h2',
  37. 'spdy/3.1', 'spdy/3', 'spdy/2',
  38. 'http/1.1', 'http/1.0'
  39. ]
  40. var actualOptions = Object.assign({
  41. NPNProtocols: protocols,
  42. // Future-proof
  43. ALPNProtocols: protocols
  44. }, options)
  45. state.secure = this instanceof tls.Server
  46. if (state.secure) {
  47. base.call(this, actualOptions)
  48. } else {
  49. base.call(this)
  50. }
  51. // Support HEADERS+FIN
  52. this.httpAllowHalfOpen = true
  53. var event = state.secure ? 'secureConnection' : 'connection'
  54. state.listeners = this.listeners(event).slice()
  55. assert(state.listeners.length > 0, 'Server does not have default listeners')
  56. this.removeAllListeners(event)
  57. if (state.options.plain) {
  58. this.on(event, this._onPlainConnection)
  59. } else { this.on(event, this._onConnection) }
  60. if (handler) {
  61. this.on('request', handler)
  62. }
  63. debug('server init secure=%d', state.secure)
  64. }
  65. proto._onConnection = function _onConnection (socket) {
  66. var state = this._spdyState
  67. var protocol
  68. if (state.secure) {
  69. protocol = socket.npnProtocol || socket.alpnProtocol
  70. }
  71. this._handleConnection(socket, protocol)
  72. }
  73. proto._handleConnection = function _handleConnection (socket, protocol) {
  74. var state = this._spdyState
  75. if (!protocol) {
  76. protocol = state.options.protocol
  77. }
  78. debug('incoming socket protocol=%j', protocol)
  79. // No way we can do anything with the socket
  80. if (!protocol || protocol === 'http/1.1' || protocol === 'http/1.0') {
  81. debug('to default handler it goes')
  82. return this._invokeDefault(socket)
  83. }
  84. socket.setNoDelay(true)
  85. var connection = transport.connection.create(socket, Object.assign({
  86. protocol: /spdy/.test(protocol) ? 'spdy' : 'http2',
  87. isServer: true
  88. }, state.options.connection || {}))
  89. // Set version when we are certain
  90. if (protocol === 'http2') { connection.start(4) } else if (protocol === 'spdy/3.1') {
  91. connection.start(3.1)
  92. } else if (protocol === 'spdy/3') { connection.start(3) } else if (protocol === 'spdy/2') {
  93. connection.start(2)
  94. }
  95. connection.on('error', function () {
  96. socket.destroy()
  97. })
  98. var self = this
  99. connection.on('stream', function (stream) {
  100. self._onStream(stream)
  101. })
  102. }
  103. // HTTP2 preface
  104. var PREFACE = 'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'
  105. var PREFACE_BUFFER = Buffer.from(PREFACE)
  106. function hoseFilter (data, callback) {
  107. if (data.length < 1) {
  108. return callback(null, null)
  109. }
  110. // SPDY!
  111. if (data[0] === 0x80) { return callback(null, 'spdy') }
  112. var avail = Math.min(data.length, PREFACE_BUFFER.length)
  113. for (var i = 0; i < avail; i++) {
  114. if (data[i] !== PREFACE_BUFFER[i]) { return callback(null, 'http/1.1') }
  115. }
  116. // Not enough bytes to be sure about HTTP2
  117. if (avail !== PREFACE_BUFFER.length) { return callback(null, null) }
  118. return callback(null, 'h2')
  119. }
  120. proto._onPlainConnection = function _onPlainConnection (socket) {
  121. var hose = selectHose.create(socket, {}, hoseFilter)
  122. var self = this
  123. hose.on('select', function (protocol, socket) {
  124. self._handleConnection(socket, protocol)
  125. })
  126. hose.on('error', function (err) {
  127. debug('hose error %j', err.message)
  128. socket.destroy()
  129. })
  130. }
  131. proto._invokeDefault = function _invokeDefault (socket) {
  132. var state = this._spdyState
  133. for (var i = 0; i < state.listeners.length; i++) { state.listeners[i].call(this, socket) }
  134. }
  135. proto._onStream = function _onStream (stream) {
  136. var state = this._spdyState
  137. var handle = spdy.handle.create(this._spdyState.options, stream)
  138. var socketOptions = {
  139. handle: handle,
  140. allowHalfOpen: true
  141. }
  142. var socket
  143. if (state.secure) {
  144. socket = new spdy.Socket(stream.connection.socket, socketOptions)
  145. } else {
  146. socket = new net.Socket(socketOptions)
  147. }
  148. // This is needed because the `error` listener, added by the default
  149. // `connection` listener, no longer has bound arguments. It relies instead
  150. // on the `server` property of the socket. See https://github.com/nodejs/node/pull/11926
  151. // for more details.
  152. // This is only done for Node.js >= 4 in order to not break compatibility
  153. // with older versions of the platform.
  154. if (process.versions.modules >= 46) { socket.server = this }
  155. handle.assignSocket(socket)
  156. // For v0.8
  157. socket.readable = true
  158. socket.writable = true
  159. this._invokeDefault(socket)
  160. // For v0.8, 0.10 and 0.12
  161. if (process.versions.modules < 46) {
  162. // eslint-disable-next-line
  163. this.listenerCount = EventEmitter.listenerCount.bind(this)
  164. }
  165. // Add lazy `checkContinue` listener, otherwise `res.writeContinue` will be
  166. // called before the response object was patched by us.
  167. if (stream.headers.expect !== undefined &&
  168. /100-continue/i.test(stream.headers.expect) &&
  169. this.listenerCount('checkContinue') === 0) {
  170. this.once('checkContinue', function (req, res) {
  171. res.writeContinue()
  172. this.emit('request', req, res)
  173. })
  174. }
  175. handle.emitRequest()
  176. }
  177. proto.emit = function emit (event, req, res) {
  178. if (event !== 'request' && event !== 'checkContinue') {
  179. return EventEmitter.prototype.emit.apply(this, arguments)
  180. }
  181. if (!(req.socket._handle instanceof spdy.handle)) {
  182. debug('not spdy req/res')
  183. req.isSpdy = false
  184. req.spdyVersion = 1
  185. res.isSpdy = false
  186. res.spdyVersion = 1
  187. return EventEmitter.prototype.emit.apply(this, arguments)
  188. }
  189. var handle = req.connection._handle
  190. req.isSpdy = true
  191. req.spdyVersion = handle.getStream().connection.getVersion()
  192. res.isSpdy = true
  193. res.spdyVersion = req.spdyVersion
  194. req.spdyStream = handle.getStream()
  195. debug('override req/res')
  196. res.writeHead = spdy.response.writeHead
  197. res.end = spdy.response.end
  198. res.push = spdy.response.push
  199. res.writeContinue = spdy.response.writeContinue
  200. res.spdyStream = handle.getStream()
  201. res._req = req
  202. handle.assignRequest(req)
  203. handle.assignResponse(res)
  204. return EventEmitter.prototype.emit.apply(this, arguments)
  205. }
  206. exports.Server = instantiate(https.Server)
  207. exports.PlainServer = instantiate(http.Server)
  208. exports.create = function create (base, options, handler) {
  209. if (typeof base === 'object') {
  210. handler = options
  211. options = base
  212. base = null
  213. }
  214. if (base) {
  215. return instantiate(base).create(options, handler)
  216. }
  217. if (options.spdy && options.spdy.plain) { return exports.PlainServer.create(options, handler) } else {
  218. return exports.Server.create(options, handler)
  219. }
  220. }