all files / lib/spdy-transport/protocol/spdy/ framer.js

91.84% Statements 225/245
81.55% Branches 84/103
93.18% Functions 41/44
92.05% Lines 220/239
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520          413×     413×               1409× 1409× 1403× 1370×   33×               332× 332× 147×       332×     332× 332× 332× 1425×     1425×     1421×     1409× 1409× 1409×   1409× 1409×     332× 332×   332× 110×   222×     332×   1409× 468×   941×       1409×     1409× 468×   941×     1409×     332× 332×     2673×             2673×   2673×   2673× 2673× 2673× 2673×   2673×   2673× 2673×   2673× 2673×             2673× 2673×   2673×     211×   211×       211× 211× 211× 211×       211× 70× 70× 70× 70× 70× 70× 11×     141× 141× 141× 141× 141× 141×       211× 211×               211×         211×   211× 211×   211×       211× 211×     211×   211× 211×           178×                           97×   97× 97× 94×     97× 32× 32×   65× 65×       97× 97×               97×         97×   97×     97× 32×     97× 97×           39×   39× 39×   33×                                 24×   24× 24×           24×           24× 24×     24×   24× 24×           1540×           1540×   1540× 1540×   1540× 1540× 1540× 1540×   1540× 1540×             1540× 1540×   1540× 1540× 154× 154×     1540× 1386× 1386×       24×         24×   24× 24×       87×         87×     87×   87×     87×               344×   344×   344× 344× 324× 324× 324×           324×     20× 20× 180× 180×     160× 146×     14× 14×       20×         20×     20×   20× 14×   14× 14×       20×     329×           2171×         2171×     2171×     2171×       33×         33×     33×   33×                                
'use strict'
 
var transport = require('../../../spdy-transport')
var constants = require('./').constants
var base = transport.protocol.base
var utils = base.utils
 
var assert = require('assert')
var util = require('util')
var Buffer = require('buffer').Buffer
var WriteBuffer = require('wbuf')
 
var debug = require('debug')('spdy:framer')
 
function Framer (options) {
  base.Framer.call(this, options)
}
util.inherits(Framer, base.Framer)
module.exports = Framer
 
Framer.create = function create (options) {
  return new Framer(options)
}
 
Framer.prototype.setMaxFrameSize = function setMaxFrameSize (size) {
  // http2-only
}
 
Framer.prototype.headersToDict = function headersToDict (headers,
                                                        preprocess,
                                                        callback) {
  function stringify (value) {
    Eif (value !== undefined) {
      if (Array.isArray(value)) {
        return value.join('\x00')
      } else if (typeof value === 'string') {
        return value
      } else {
        return value.toString()
      }
    } else {
      return ''
    }
  }
 
  // Lower case of all headers keys
  var loweredHeaders = {}
  Object.keys(headers || {}).map(function (key) {
    loweredHeaders[key.toLowerCase()] = headers[key]
  })
 
  // Allow outer code to add custom headers or remove something
  if (preprocess) { preprocess(loweredHeaders) }
 
  // Transform object into kv pairs
  var size = this.version === 2 ? 2 : 4
  var len = size
  var pairs = Object.keys(loweredHeaders).filter(function (key) {
    var lkey = key.toLowerCase()
 
    // Will be in `:host`
    if (lkey === 'host' && this.version >= 3) {
      return false
    }
 
    return lkey !== 'connection' && lkey !== 'keep-alive' &&
           lkey !== 'proxy-connection' && lkey !== 'transfer-encoding'
  }, this).map(function (key) {
    var klen = Buffer.byteLength(key)
    var value = stringify(loweredHeaders[key])
    var vlen = Buffer.byteLength(value)
 
    len += size * 2 + klen + vlen
    return [klen, key, vlen, value]
  })
 
  var block = new WriteBuffer()
  block.reserve(len)
 
  if (this.version === 2) {
    block.writeUInt16BE(pairs.length)
  } else {
    block.writeUInt32BE(pairs.length)
  }
 
  pairs.forEach(function (pair) {
    // Write key length
    if (this.version === 2) {
      block.writeUInt16BE(pair[0])
    } else {
      block.writeUInt32BE(pair[0])
    }
 
    // Write key
    block.write(pair[1])
 
    // Write value length
    if (this.version === 2) {
      block.writeUInt16BE(pair[2])
    } else {
      block.writeUInt32BE(pair[2])
    }
    // Write value
    block.write(pair[3])
  }, this)
 
  assert(this.compress !== null, 'Framer version not initialized')
  this.compress.write(block.render(), callback)
}
 
Framer.prototype._frame = function _frame (frame, body, callback) {
  Iif (!this.version) {
    this.on('version', function () {
      this._frame(frame, body, callback)
    })
    return
  }
 
  debug('id=%d type=%s', frame.id, frame.type)
 
  var buffer = new WriteBuffer()
 
  buffer.writeUInt16BE(0x8000 | this.version)
  buffer.writeUInt16BE(constants.frameType[frame.type])
  buffer.writeUInt8(frame.flags)
  var len = buffer.skip(3)
 
  body(buffer)
 
  var frameSize = buffer.size - constants.FRAME_HEADER_SIZE
  len.writeUInt24BE(frameSize)
 
  var chunks = buffer.render()
  var toWrite = {
    stream: frame.id,
    priority: false,
    chunks: chunks,
    callback: callback
  }
 
  this._resetTimeout()
  this.schedule(toWrite)
 
  return chunks
}
 
Framer.prototype._synFrame = function _synFrame (frame, callback) {
  var self = this
 
  Iif (!frame.path) {
    throw new Error('`path` is required frame argument')
  }
 
  function preprocess (headers) {
    var method = frame.method || base.constants.DEFAULT_METHOD
    var version = frame.version || 'HTTP/1.1'
    var scheme = frame.scheme || 'https'
    var host = frame.host ||
               frame.headers && frame.headers.host ||
               base.constants.DEFAULT_HOST
 
    if (self.version === 2) {
      headers.method = method
      headers.version = version
      headers.url = frame.path
      headers.scheme = scheme
      headers.host = host
      if (frame.status) {
        headers.status = frame.status
      }
    } else {
      headers[':method'] = method
      headers[':version'] = version
      headers[':path'] = frame.path
      headers[':scheme'] = scheme
      headers[':host'] = host
      if (frame.status) { headers[':status'] = frame.status }
    }
  }
 
  this.headersToDict(frame.headers, preprocess, function (err, chunks) {
    Iif (err) {
      if (callback) {
        return callback(err)
      } else {
        return self.emit('error', err)
      }
    }
 
    self._frame({
      type: 'SYN_STREAM',
      id: frame.id,
      flags: frame.fin ? constants.flags.FLAG_FIN : 0
    }, function (buf) {
      buf.reserve(10)
 
      buf.writeUInt32BE(frame.id & 0x7fffffff)
      buf.writeUInt32BE(frame.associated & 0x7fffffff)
 
      var weight = frame.priority && frame.priority.weight ||
                   constants.DEFAULT_WEIGHT
 
      // We only have 3 bits for priority in SPDY, try to fit it into this
      var priority = utils.weightToPriority(weight)
      buf.writeUInt8(priority << 5)
 
      // CREDENTIALS slot
      buf.writeUInt8(0)
 
      for (var i = 0; i < chunks.length; i++) {
        buf.copyFrom(chunks[i])
      }
    }, callback)
  })
}
 
Framer.prototype.requestFrame = function requestFrame (frame, callback) {
  this._synFrame({
    id: frame.id,
    fin: frame.fin,
    associated: 0,
    method: frame.method,
    version: frame.version,
    scheme: frame.scheme,
    host: frame.host,
    path: frame.path,
    priority: frame.priority,
    headers: frame.headers
  }, callback)
}
 
Framer.prototype.responseFrame = function responseFrame (frame, callback) {
  var self = this
 
  var reason = frame.reason
  if (!reason) {
    reason = constants.statusReason[frame.status]
  }
 
  function preprocess (headers) {
    if (self.version === 2) {
      headers.status = frame.status + ' ' + reason
      headers.version = 'HTTP/1.1'
    } else {
      headers[':status'] = frame.status + ' ' + reason
      headers[':version'] = 'HTTP/1.1'
    }
  }
 
  this.headersToDict(frame.headers, preprocess, function (err, chunks) {
    Iif (err) {
      if (callback) {
        return callback(err)
      } else {
        return self.emit('error', err)
      }
    }
 
    self._frame({
      type: 'SYN_REPLY',
      id: frame.id,
      flags: 0
    }, function (buf) {
      buf.reserve(self.version === 2 ? 6 : 4)
 
      buf.writeUInt32BE(frame.id & 0x7fffffff)
 
      // Unused data
      if (self.version === 2) {
        buf.writeUInt16BE(0)
      }
 
      for (var i = 0; i < chunks.length; i++) {
        buf.copyFrom(chunks[i])
      }
    }, callback)
  })
}
 
Framer.prototype.pushFrame = function pushFrame (frame, callback) {
  var self = this
 
  this._checkPush(function (err) {
    if (err) { return callback(err) }
 
    self._synFrame({
      id: frame.promisedId,
      associated: frame.id,
      method: frame.method,
      status: frame.status || 200,
      version: frame.version,
      scheme: frame.scheme,
      host: frame.host,
      path: frame.path,
      priority: frame.priority,
 
      // Merge everything together, there is no difference in SPDY protocol
      headers: util._extend(util._extend({}, frame.headers), frame.response)
    }, callback)
  })
}
 
Framer.prototype.headersFrame = function headersFrame (frame, callback) {
  var self = this
 
  this.headersToDict(frame.headers, null, function (err, chunks) {
    Iif (err) {
      if (callback) { return callback(err) } else {
        return self.emit('error', err)
      }
    }
 
    self._frame({
      type: 'HEADERS',
      id: frame.id,
      priority: false,
      flags: 0
    }, function (buf) {
      buf.reserve(4 + (self.version === 2 ? 2 : 0))
      buf.writeUInt32BE(frame.id & 0x7fffffff)
 
      // Unused data
      if (self.version === 2) { buf.writeUInt16BE(0) }
 
      for (var i = 0; i < chunks.length; i++) {
        buf.copyFrom(chunks[i])
      }
    }, callback)
  })
}
 
Framer.prototype.dataFrame = function dataFrame (frame, callback) {
  Iif (!this.version) {
    return this.on('version', function () {
      this.dataFrame(frame, callback)
    })
  }
 
  debug('id=%d type=DATA', frame.id)
 
  var buffer = new WriteBuffer()
  buffer.reserve(8 + frame.data.length)
 
  buffer.writeUInt32BE(frame.id & 0x7fffffff)
  buffer.writeUInt8(frame.fin ? 0x01 : 0x0)
  buffer.writeUInt24BE(frame.data.length)
  buffer.copyFrom(frame.data)
 
  var chunks = buffer.render()
  var toWrite = {
    stream: frame.id,
    priority: frame.priority,
    chunks: chunks,
    callback: callback
  }
 
  var self = this
  this._resetTimeout()
 
  var bypass = this.version < 3.1
  this.window.send.update(-frame.data.length, bypass ? undefined : function () {
    self._resetTimeout()
    self.schedule(toWrite)
  })
 
  if (bypass) {
    this._resetTimeout()
    this.schedule(toWrite)
  }
}
 
Framer.prototype.pingFrame = function pingFrame (frame, callback) {
  this._frame({
    type: 'PING',
    id: 0,
    flags: 0
  }, function (buf, callback) {
    buf.reserve(4)
 
    var opaque = frame.opaque
    buf.writeUInt32BE(opaque.readUInt32BE(opaque.length - 4, true))
  }, callback)
}
 
Framer.prototype.rstFrame = function rstFrame (frame, callback) {
  this._frame({
    type: 'RST_STREAM',
    id: frame.id,
    flags: 0
  }, function (buf) {
    buf.reserve(8)
 
    // Stream ID
    buf.writeUInt32BE(frame.id & 0x7fffffff)
    // Status Code
    buf.writeUInt32BE(constants.error[frame.code])
 
    // Extra debugging information
    Iif (frame.extra) {
      buf.write(frame.extra)
    }
  }, callback)
}
 
Framer.prototype.prefaceFrame = function prefaceFrame () {
}
 
Framer.prototype.settingsFrame = function settingsFrame (options, callback) {
  var self = this
 
  var key = this.version + '/' + JSON.stringify(options)
 
  var settings = Framer.settingsCache[key]
  if (settings) {
    debug('cached settings')
    this._resetTimeout()
    this.schedule({
      stream: 0,
      priority: false,
      chunks: settings,
      callback: callback
    })
    return
  }
 
  var params = []
  for (var i = 0; i < constants.settingsIndex.length; i++) {
    var name = constants.settingsIndex[i]
    if (!name) { continue }
 
    // value: Infinity
    if (!isFinite(options[name])) {
      continue
    }
 
    Eif (options[name] !== undefined) {
      params.push({ key: i, value: options[name] })
    }
  }
 
  var frame = this._frame({
    type: 'SETTINGS',
    id: 0,
    flags: 0
  }, function (buf) {
    buf.reserve(4 + 8 * params.length)
 
    // Count of entries
    buf.writeUInt32BE(params.length)
 
    params.forEach(function (param) {
      var flag = constants.settings.FLAG_SETTINGS_PERSIST_VALUE << 24
 
      if (self.version === 2) {
        buf.writeUInt32LE(flag | param.key)
      } else { buf.writeUInt32BE(flag | param.key) }
      buf.writeUInt32BE(param.value & 0x7fffffff)
    })
  }, callback)
 
  Framer.settingsCache[key] = frame
}
Framer.settingsCache = {}
 
Framer.prototype.ackSettingsFrame = function ackSettingsFrame (callback) {
  Iif (callback) {
    process.nextTick(callback)
  }
}
 
Framer.prototype.windowUpdateFrame = function windowUpdateFrame (frame,
                                                                callback) {
  this._frame({
    type: 'WINDOW_UPDATE',
    id: frame.id,
    flags: 0
  }, function (buf) {
    buf.reserve(8)
 
    // ID
    buf.writeUInt32BE(frame.id & 0x7fffffff)
 
    // Delta
    buf.writeInt32BE(frame.delta)
  }, callback)
}
 
Framer.prototype.goawayFrame = function goawayFrame (frame, callback) {
  this._frame({
    type: 'GOAWAY',
    id: 0,
    flags: 0
  }, function (buf) {
    buf.reserve(8)
 
    // Last-good-stream-ID
    buf.writeUInt32BE(frame.lastId & 0x7fffffff)
    // Status
    buf.writeUInt32BE(constants.goaway[frame.code])
  }, callback)
}
 
Framer.prototype.priorityFrame = function priorityFrame (frame, callback) {
  // No such thing in SPDY
  if (callback) {
    process.nextTick(callback)
  }
}
 
Framer.prototype.xForwardedFor = function xForwardedFor (frame, callback) {
  this._frame({
    type: 'X_FORWARDED_FOR',
    id: 0,
    flags: 0
  }, function (buf) {
    buf.writeUInt32BE(Buffer.byteLength(frame.host))
    buf.write(frame.host)
  }, callback)
}