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

96.15% Statements 225/234
86.73% Branches 98/113
100% Functions 51/51
96.46% Lines 218/226
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 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540        149×   149×     149×         663×   663×   663× 663× 663× 663× 663×   663×   663× 663×   663× 663×             663× 175× 175× 175× 175× 175×     488× 488×     663×     300× 1212×   300× 300×   284× 284× 263×   284×   284× 284×   284×           300×         128×   128× 145× 145×   145×     145× 127×     145×             145×   145× 1058×       128×                       128× 2101×     2101×                   2094×       2093×   2093× 2093×               2091×                 128× 128× 128×     116×   68×         75×       75×       75× 75× 75×               104×   104× 63× 41× 33×     104× 104× 104×               104×       104× 104×   104×     104× 13×     104×             104× 47×     57×   57×         63×     33×         15×   24× 24×               24×       12×           12×       12× 12× 12×     12×       12×             12×     11×   11×       15× 15×     12×         12× 12×   12× 12× 12× 12×                             172×         172×   172× 172× 139× 139× 139× 136×     139×           139× 139×         172× 36×                                   32×         32×       60× 60× 60×               125×   125× 125× 117× 117× 117×           117×     56× 56×       48× 34×     14× 14×                 14×   14× 14×           121×                   156×         156× 156×       11×         11×     11×   11×     11×                    
'use strict'
 
var transport = require('../../../spdy-transport')
var base = transport.protocol.base
var constants = require('./').constants
 
var assert = require('assert')
var util = require('util')
var WriteBuffer = require('wbuf')
var OffsetBuffer = require('obuf')
var debug = require('debug')('spdy:framer')
var debugExtra = require('debug')('spdy:framer:extra')
 
function Framer (options) {
  base.Framer.call(this, options)
 
  this.maxFrameSize = constants.INITIAL_MAX_FRAME_SIZE
}
util.inherits(Framer, base.Framer)
module.exports = Framer
 
Framer.create = function create (options) {
  return new Framer(options)
}
 
Framer.prototype.setMaxFrameSize = function setMaxFrameSize (size) {
  this.maxFrameSize = size
}
 
Framer.prototype._frame = function _frame (frame, body, callback) {
  debug('id=%d type=%s', frame.id, frame.type)
 
  var buffer = new WriteBuffer()
 
  buffer.reserve(constants.FRAME_HEADER_SIZE)
  var len = buffer.skip(3)
  buffer.writeUInt8(constants.frameType[frame.type])
  buffer.writeUInt8(frame.flags)
  buffer.writeUInt32BE(frame.id & 0x7fffffff)
 
  body(buffer)
 
  var frameSize = buffer.size - constants.FRAME_HEADER_SIZE
  len.writeUInt24BE(frameSize)
 
  var chunks = buffer.render()
  var toWrite = {
    stream: frame.id,
    priority: frame.priority === undefined ? false : frame.priority,
    chunks: chunks,
    callback: callback
  }
 
  if (this.window && frame.type === 'DATA') {
    var self = this
    this._resetTimeout()
    this.window.send.update(-frameSize, function () {
      self._resetTimeout()
      self.schedule(toWrite)
    })
  } else {
    this._resetTimeout()
    this.schedule(toWrite)
  }
 
  return chunks
}
 
Framer.prototype._split = function _split (frame) {
  var buf = new OffsetBuffer()
  for (var i = 0; i < frame.chunks.length; i++) { buf.push(frame.chunks[i]) }
 
  var frames = []
  while (!buf.isEmpty()) {
    // First frame may have reserved bytes in it
    var size = this.maxFrameSize
    if (frames.length === 0) {
      size -= frame.reserve
    }
    size = Math.min(size, buf.size)
 
    var frameBuf = buf.clone(size)
    buf.skip(size)
 
    frames.push({
      size: frameBuf.size,
      chunks: frameBuf.toChunks()
    })
  }
 
  return frames
}
 
Framer.prototype._continuationFrame = function _continuationFrame (frame,
                                                                  body,
                                                                  callback) {
  var frames = this._split(frame)
 
  frames.forEach(function (subFrame, i) {
    var isFirst = i === 0
    var isLast = i === frames.length - 1
 
    var flags = isLast ? constants.flags.END_HEADERS : 0
 
    // PRIORITY and friends
    if (isFirst) {
      flags |= frame.flags
    }
 
    this._frame({
      id: frame.id,
      priority: false,
      type: isFirst ? frame.type : 'CONTINUATION',
      flags: flags
    }, function (buf) {
      // Fill those reserved bytes
      if (isFirst && body) { body(buf) }
 
      buf.reserve(subFrame.size)
      for (var i = 0; i < subFrame.chunks.length; i++) { buf.copyFrom(subFrame.chunks[i]) }
    }, isLast ? callback : null)
  }, this)
 
  if (frames.length === 0) {
    this._frame({
      id: frame.id,
      priority: false,
      type: frame.type,
      flags: frame.flags | constants.flags.END_HEADERS
    }, function (buf) {
      Eif (body) { body(buf) }
    }, callback)
  }
}
 
Framer.prototype._compressHeaders = function _compressHeaders (headers,
                                                              pairs,
                                                              callback) {
  Object.keys(headers || {}).forEach(function (name) {
    var lowName = name.toLowerCase()
 
    // Not allowed in HTTP2
    switch (lowName) {
      case 'host':
      case 'connection':
      case 'keep-alive':
      case 'proxy-connection':
      case 'transfer-encoding':
      case 'upgrade':
        return
    }
 
    // Should be in `pairs`
    if (/^:/.test(lowName)) {
      return
    }
 
    // Do not compress, or index Cookie field (for security reasons)
    var neverIndex = lowName === 'cookie' || lowName === 'set-cookie'
 
    var value = headers[name]
    if (Array.isArray(value)) {
      for (var i = 0; i < value.length; i++) {
        pairs.push({
          name: lowName,
          value: value[i] + '',
          neverIndex: neverIndex,
          huffman: !neverIndex
        })
      }
    } else {
      pairs.push({
        name: lowName,
        value: value + '',
        neverIndex: neverIndex,
        huffman: !neverIndex
      })
    }
  })
 
  assert(this.compress !== null, 'Framer version not initialized')
  debugExtra('compressing headers=%j', pairs)
  this.compress.write([ pairs ], callback)
}
 
Framer.prototype._isDefaultPriority = function _isDefaultPriority (priority) {
  if (!priority) { return true }
 
  return !priority.parent &&
         priority.weight === constants.DEFAULT &&
         !priority.exclusive
}
 
Framer.prototype._defaultHeaders = function _defaultHeaders (frame, pairs) {
  Iif (!frame.path) {
    throw new Error('`path` is required frame argument')
  }
 
  pairs.push({
    name: ':method',
    value: frame.method || base.constants.DEFAULT_METHOD
  })
  pairs.push({ name: ':path', value: frame.path })
  pairs.push({ name: ':scheme', value: frame.scheme || 'https' })
  pairs.push({
    name: ':authority',
    value: frame.host ||
           frame.headers && frame.headers.host ||
           base.constants.DEFAULT_HOST
  })
}
 
Framer.prototype._headersFrame = function _headersFrame (kind, frame, callback) {
  var pairs = []
 
  if (kind === 'request') {
    this._defaultHeaders(frame, pairs)
  } else if (kind === 'response') {
    pairs.push({ name: ':status', value: (frame.status || 200) + '' })
  }
 
  var self = this
  this._compressHeaders(frame.headers, pairs, function (err, chunks) {
    Iif (err) {
      if (callback) {
        return callback(err)
      } else {
        return self.emit('error', err)
      }
    }
 
    var reserve = 0
 
    // If priority info is present, and the values are not default ones
    // reserve space for the priority info and add PRIORITY flag
    var priority = frame.priority
    if (!self._isDefaultPriority(priority)) { reserve = 5 }
 
    var flags = reserve === 0 ? 0 : constants.flags.PRIORITY
 
    // Mostly for testing
    if (frame.fin) {
      flags |= constants.flags.END_STREAM
    }
 
    self._continuationFrame({
      id: frame.id,
      type: 'HEADERS',
      flags: flags,
      reserve: reserve,
      chunks: chunks
    }, function (buf) {
      if (reserve === 0) {
        return
      }
 
      buf.writeUInt32BE((priority.exclusive ? 0x80000000 : 0) |
                        priority.parent)
      buf.writeUInt8((priority.weight | 0) - 1)
    }, callback)
  })
}
 
Framer.prototype.requestFrame = function requestFrame (frame, callback) {
  return this._headersFrame('request', frame, callback)
}
 
Framer.prototype.responseFrame = function responseFrame (frame, callback) {
  return this._headersFrame('response', frame, callback)
}
 
Framer.prototype.headersFrame = function headersFrame (frame, callback) {
  return this._headersFrame('headers', frame, callback)
}
 
Framer.prototype.pushFrame = function pushFrame (frame, callback) {
  var self = this
 
  function compress (headers, pairs, callback) {
    self._compressHeaders(headers, pairs, function (err, chunks) {
      Iif (err) {
        if (callback) {
          return callback(err)
        } else {
          return self.emit('error', err)
        }
      }
 
      callback(chunks)
    })
  }
 
  function sendPromise (chunks) {
    self._continuationFrame({
      id: frame.id,
      type: 'PUSH_PROMISE',
      reserve: 4,
      chunks: chunks
    }, function (buf) {
      buf.writeUInt32BE(frame.promisedId)
    })
  }
 
  function sendResponse (chunks, callback) {
    var priority = frame.priority
    var isDefaultPriority = self._isDefaultPriority(priority)
    var flags = isDefaultPriority ? 0 : constants.flags.PRIORITY
 
    // Mostly for testing
    Iif (frame.fin) {
      flags |= constants.flags.END_STREAM
    }
 
    self._continuationFrame({
      id: frame.promisedId,
      type: 'HEADERS',
      flags: flags,
      reserve: isDefaultPriority ? 0 : 5,
      chunks: chunks
    }, function (buf) {
      if (isDefaultPriority) {
        return
      }
 
      buf.writeUInt32BE((priority.exclusive ? 0x80000000 : 0) |
                        priority.parent)
      buf.writeUInt8((priority.weight | 0) - 1)
    }, callback)
  }
 
  this._checkPush(function (err) {
    if (err) {
      return callback(err)
    }
 
    var pairs = {
      promise: [],
      response: []
    }
 
    self._defaultHeaders(frame, pairs.promise)
    pairs.response.push({ name: ':status', value: (frame.status || 200) + '' })
 
    compress(frame.headers, pairs.promise, function (promiseChunks) {
      sendPromise(promiseChunks)
      compress(frame.response, pairs.response, function (responseChunks) {
        sendResponse(responseChunks, callback)
      })
    })
  })
}
 
Framer.prototype.priorityFrame = function priorityFrame (frame, callback) {
  this._frame({
    id: frame.id,
    priority: false,
    type: 'PRIORITY',
    flags: 0
  }, function (buf) {
    var priority = frame.priority
    buf.writeUInt32BE((priority.exclusive ? 0x80000000 : 0) |
                      priority.parent)
    buf.writeUInt8((priority.weight | 0) - 1)
  }, callback)
}
 
Framer.prototype.dataFrame = function dataFrame (frame, callback) {
  var frames = this._split({
    reserve: 0,
    chunks: [ frame.data ]
  })
 
  var fin = frame.fin ? constants.flags.END_STREAM : 0
 
  var self = this
  frames.forEach(function (subFrame, i) {
    var isLast = i === frames.length - 1
    var flags = 0
    if (isLast) {
      flags |= fin
    }
 
    self._frame({
      id: frame.id,
      priority: frame.priority,
      type: 'DATA',
      flags: flags
    }, function (buf) {
      buf.reserve(subFrame.size)
      for (var i = 0; i < subFrame.chunks.length; i++) { buf.copyFrom(subFrame.chunks[i]) }
    }, isLast ? callback : null)
  })
 
  // Empty DATA
  if (frames.length === 0) {
    this._frame({
      id: frame.id,
      priority: frame.priority,
      type: 'DATA',
      flags: fin
    }, function (buf) {
      // No-op
    }, callback)
  }
}
 
Framer.prototype.pingFrame = function pingFrame (frame, callback) {
  this._frame({
    id: 0,
    type: 'PING',
    flags: frame.ack ? constants.flags.ACK : 0
  }, function (buf) {
    buf.copyFrom(frame.opaque)
  }, callback)
}
 
Framer.prototype.rstFrame = function rstFrame (frame, callback) {
  this._frame({
    id: frame.id,
    type: 'RST_STREAM',
    flags: 0
  }, function (buf) {
    buf.writeUInt32BE(constants.error[frame.code])
  }, callback)
}
 
Framer.prototype.prefaceFrame = function prefaceFrame (callback) {
  debug('preface')
  this._resetTimeout()
  this.schedule({
    stream: 0,
    priority: false,
    chunks: [ constants.PREFACE_BUFFER ],
    callback: callback
  })
}
 
Framer.prototype.settingsFrame = function settingsFrame (options, callback) {
  var key = JSON.stringify(options)
 
  var settings = Framer.settingsCache[key]
  if (settings) {
    debug('cached settings')
    this._resetTimeout()
    this.schedule({
      id: 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 bodySize = params.length * 6
 
  var chunks = this._frame({
    id: 0,
    type: 'SETTINGS',
    flags: 0
  }, function (buffer) {
    buffer.reserve(bodySize)
    for (var i = 0; i < params.length; i++) {
      var param = params[i]
 
      buffer.writeUInt16BE(param.key)
      buffer.writeUInt32BE(param.value)
    }
  }, callback)
 
  Framer.settingsCache[key] = chunks
}
Framer.settingsCache = {}
 
Framer.prototype.ackSettingsFrame = function ackSettingsFrame (callback) {
  /* var chunks = */ this._frame({
    id: 0,
    type: 'SETTINGS',
    flags: constants.flags.ACK
  }, function (buffer) {
    // No-op
  }, callback)
}
 
Framer.prototype.windowUpdateFrame = function windowUpdateFrame (frame,
                                                                callback) {
  this._frame({
    id: frame.id,
    type: 'WINDOW_UPDATE',
    flags: 0
  }, function (buffer) {
    buffer.reserve(4)
    buffer.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)
    // Code
    buf.writeUInt32BE(constants.goaway[frame.code])
 
    // Extra debugging information
    Iif (frame.extra) { buf.write(frame.extra) }
  }, callback)
}
 
Framer.prototype.xForwardedFor = function xForwardedFor (frame, callback) {
  this._frame({
    type: 'X_FORWARDED_FOR',
    id: 0,
    flags: 0
  }, function (buf) {
    buf.write(frame.host)
  }, callback)
}