server.js 7.3 KB

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