# all files / lib/spdy-transport/protocol/http2/ parser.js

92.31% Statements 240/260
84.89% Branches 118/139
96.77% Functions 30/31
92.13% Lines 234/254

    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
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579

    1×

    1×
    1×
    1×
    1×

    1×
    1×

    1×
    199×

    199×

    199×
    199×
    199×

    199×
    199×
    199×

    1×

    1×
    199×

    1×
    3×

    1×
    1×

    1×

    199×

    199×
    199×

    1×
    1868×

    1808×
    905×

    903×

    903×
    903×
    903×

    903×
    903×
    27×

    876×
    876×
    876×
    876×

    1×
    2×

    2×

    2×

    2×

    1×
    60×

    60×
    60×

    1×
    905×

    905×

    905×

    905×
    905×
    905×
    905×

    905×
    182×

    905×

    1×
    903×

    903×
    181×
    722×
    123×
    599×
    99×
    500×
    159×
    341×
    35×
    306×
    249×
    57×
    17×
    40×
    12×
    28×
    15×
    13×
    10×
    3×
    3×

    1×

    1×
    319×

    319×

    7×
    1×

    6×
    6×
    3×

    3×
    3×
    3×

    1×
    181×

    181×

    181×
    181×

    181×
    181×
    1×

    180×

    1×

    134×

    134×

    134×

    1×

    233×
    233×
    233×
    2×

    231×

    231×
    231×
    231×
    231×
    231×

    231×
    1×

    230×
    133×

    133×
    133×

    133×
    133×
    133×
    2458×

    2458×
    2458×

    2458×

    2458×

    133×
    133×

    133×

    1×

    123×

    123×
    1×

    122×
    122×

    120×
    120×

    120×
    120×
    120×
    120×
    68×
    68×
    68×

    68×

    120×

    120×

    120×

    1×

    99×

    1×
    35×
    2×

    33×
    1×

    32×

    1×
    125×

    125×

    125×

    125×

    1×

    249×
    1×

    248×
    248×
    1×

    247×
    121×

    126×
    1×

    125×
    125×
    364×
    364×
    364×

    364×
    364×

    125×
    125×

    125×

    1×

    17×
    1×

    16×
    16×
    16×
    1×

    15×
    1×

    14×

    14×

    1×
    12×
    2×

    10×
    1×

    9×
    9×

    1×

    15×
    1×

    14×
    1×

    13×

    13×

    13×

    1×

    10×
    3×

    7×
    1×

    6×

    6×

    6×

    6×

    1×

    159×
    2×

    157×
    157×

    157×

    1×

    3×

     'use strict'

    var parser = exports

    var transport = require('../../../spdy-transport')
    var base = transport.protocol.base
    var utils = base.utils
    var constants = require('./').constants

    var assert = require('assert')
    var util = require('util')

    function Parser (options) {
      base.Parser.call(this, options)

      this.isServer = options.isServer

      this.waiting = constants.PREFACE_SIZE
      this.state = 'preface'
      this.pendingHeader = null

      // Header Block queue
      this._lastHeaderBlock = null
      this.maxFrameSize = constants.INITIAL_MAX_FRAME_SIZE
      this.maxHeaderListSize = constants.DEFAULT_MAX_HEADER_LIST_SIZE
    }
    util.inherits(Parser, base.Parser)

    parser.create = function create (options) {
      return new Parser(options)
    }

    Parser.prototype.setMaxFrameSize = function setMaxFrameSize (size) {
      this.maxFrameSize = size
    }

    Parser.prototype.setMaxHeaderListSize = function setMaxHeaderListSize (size) {
      this.maxHeaderListSize = size
    }

    // Only for testing
    Parser.prototype.skipPreface = function skipPreface () {
      // Just some number bigger than 3.1, doesn't really matter for HTTP2
      this.setVersion(4)

      // Parse frame header!
      this.state = 'frame-head'
      this.waiting = constants.FRAME_HEADER_SIZE
    }

    Parser.prototype.execute = function execute (buffer, callback) {
      if (this.state === 'preface') { return this.onPreface(buffer, callback) }

      if (this.state === 'frame-head') {
        return this.onFrameHead(buffer, callback)
      }

      assert(this.state === 'frame-body' && this.pendingHeader !== null)

      var self = this
      var header = this.pendingHeader
      this.pendingHeader = null

      this.onFrameBody(header, buffer, function (err, frame) {
        if (err) {
          return callback(err)
        }

        self.state = 'frame-head'
        self.partial = false
        self.waiting = constants.FRAME_HEADER_SIZE
        callback(null, frame)
      })
    }

    Parser.prototype.executePartial = function executePartial (buffer, callback) {
      var header = this.pendingHeader

      assert.equal(header.flags & constants.flags.PADDED, 0)

      Eif (this.window) { this.window.recv.update(-buffer.size) }

      callback(null, {
        type: 'DATA',
        id: header.id,

        // Partial DATA can't be FIN
        fin: false,
        data: buffer.take(buffer.size)
      })
    }

    Parser.prototype.onPreface = function onPreface (buffer, callback) {
      Iif (buffer.take(buffer.size).toString() !== constants.PREFACE) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Invalid preface'))
      }

      this.skipPreface()
      callback(null, null)
    }

    Parser.prototype.onFrameHead = function onFrameHead (buffer, callback) {
      var header = {
        length: buffer.readUInt24BE(),
        control: true,
        type: buffer.readUInt8(),
        flags: buffer.readUInt8(),
        id: buffer.readUInt32BE() & 0x7fffffff
      }

      Iif (header.length > this.maxFrameSize) {
        return callback(this.error(constants.error.FRAME_SIZE_ERROR,
                                   'Frame length OOB'))
      }

      header.control = header.type !== constants.frameType.DATA

      this.state = 'frame-body'
      this.pendingHeader = header
      this.waiting = header.length
      this.partial = !header.control

      // TODO(indutny): eventually support partial padded DATA
      if (this.partial) {
        this.partial = (header.flags & constants.flags.PADDED) === 0
      }

      callback(null, null)
    }

    Parser.prototype.onFrameBody = function onFrameBody (header, buffer, callback) {
      var frameType = constants.frameType

      if (header.type === frameType.DATA) {
        this.onDataFrame(header, buffer, callback)
      } else if (header.type === frameType.HEADERS) {
        this.onHeadersFrame(header, buffer, callback)
      } else if (header.type === frameType.CONTINUATION) {
        this.onContinuationFrame(header, buffer, callback)
      } else if (header.type === frameType.WINDOW_UPDATE) {
        this.onWindowUpdateFrame(header, buffer, callback)
      } else if (header.type === frameType.RST_STREAM) {
        this.onRSTFrame(header, buffer, callback)
      } else if (header.type === frameType.SETTINGS) {
        this.onSettingsFrame(header, buffer, callback)
      } else if (header.type === frameType.PUSH_PROMISE) {
        this.onPushPromiseFrame(header, buffer, callback)
      } else if (header.type === frameType.PING) {
        this.onPingFrame(header, buffer, callback)
      } else if (header.type === frameType.GOAWAY) {
        this.onGoawayFrame(header, buffer, callback)
      } else if (header.type === frameType.PRIORITY) {
        this.onPriorityFrame(header, buffer, callback)
      } else Eif (header.type === frameType.X_FORWARDED_FOR) {
        this.onXForwardedFrame(header, buffer, callback)
      } else {
        this.onUnknownFrame(header, buffer, callback)
      }
    }

    Parser.prototype.onUnknownFrame = function onUnknownFrame (header, buffer, callback) {
      if (this._lastHeaderBlock !== null) {
        callback(this.error(constants.error.PROTOCOL_ERROR,
                            'Received unknown frame in the middle of a header block'))
        return
      }
      callback(null, { type: 'unknown: ' + header.type })
    }

    Parser.prototype.unpadData = function unpadData (header, body, callback) {
      var isPadded = (header.flags & constants.flags.PADDED) !== 0

      if (!isPadded) { return callback(null, body) }

      if (!body.has(1)) {
        return callback(this.error(constants.error.FRAME_SIZE_ERROR,
                                   'Not enough space for padding'))
      }

      var pad = body.readUInt8()
      if (!body.has(pad)) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Invalid padding size'))
      }

      var contents = body.clone(body.size - pad)
      body.skip(body.size)
      callback(null, contents)
    }

    Parser.prototype.onDataFrame = function onDataFrame (header, body, callback) {
      var isEndStream = (header.flags & constants.flags.END_STREAM) !== 0

      Iif (header.id === 0) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Received DATA frame with stream=0'))
      }

      // Count received bytes
      Eif (this.window) {
        this.window.recv.update(-body.size)
      }

      this.unpadData(header, body, function (err, data) {
        if (err) {
          return callback(err)
        }

        callback(null, {
          type: 'DATA',
          id: header.id,
          fin: isEndStream,
          data: data.take(data.size)
        })
      })
    }

    Parser.prototype.initHeaderBlock = function initHeaderBlock (header,
                                                                frame,
                                                                block,
                                                                callback) {
      Iif (this._lastHeaderBlock) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Duplicate Stream ID'))
      }

      this._lastHeaderBlock = {
        id: header.id,
        frame: frame,
        queue: [],
        size: 0
      }

      this.queueHeaderBlock(header, block, callback)
    }

    Parser.prototype.queueHeaderBlock = function queueHeaderBlock (header,
                                                                  block,
                                                                  callback) {
      var self = this
      var item = this._lastHeaderBlock
      if (!this._lastHeaderBlock || item.id !== header.id) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'No matching stream for continuation'))
      }

      var fin = (header.flags & constants.flags.END_HEADERS) !== 0

      var chunks = block.toChunks()
      for (var i = 0; i < chunks.length; i++) {
        var chunk = chunks[i]
        item.queue.push(chunk)
        item.size += chunk.length
      }

      if (item.size >= self.maxHeaderListSize) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Compressed header list is too large'))
      }

      if (!fin) { return callback(null, null) }
      this._lastHeaderBlock = null

      this.decompress.write(item.queue, function (err, chunks) {
        Iif (err) {
          return callback(self.error(constants.error.COMPRESSION_ERROR,
                                     err.message))
        }

        var headers = {}
        var size = 0
        for (var i = 0; i < chunks.length; i++) {
          var header = chunks[i]

          size += header.name.length + header.value.length + 32
          Iif (size >= self.maxHeaderListSize) {
            return callback(self.error(constants.error.PROTOCOL_ERROR,
                                       'Header list is too large'))
          }

          Iif (/[A-Z]/.test(header.name)) {
            return callback(self.error(constants.error.PROTOCOL_ERROR,
                                       'Header name must be lowercase'))
          }

          utils.addHeaderLine(header.name, header.value, headers)
        }

        item.frame.headers = headers
        item.frame.path = headers[':path']

        callback(null, item.frame)
      })
    }

    Parser.prototype.onHeadersFrame = function onHeadersFrame (header,
                                                              body,
                                                              callback) {
      var self = this

      if (header.id === 0) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Invalid stream id for HEADERS'))
      }

      this.unpadData(header, body, function (err, data) {
        if (err) { return callback(err) }

        var isPriority = (header.flags & constants.flags.PRIORITY) !== 0
        Iif (!data.has(isPriority ? 5 : 0)) {
          return callback(self.error(constants.error.FRAME_SIZE_ERROR,
                                     'Not enough data for HEADERS'))
        }

        var exclusive = false
        var dependency = 0
        var weight = constants.DEFAULT_WEIGHT
        if (isPriority) {
          dependency = data.readUInt32BE()
          exclusive = (dependency & 0x80000000) !== 0
          dependency &= 0x7fffffff

          // Weight's range is [1, 256]
          weight = data.readUInt8() + 1
        }

        Iif (dependency === header.id) {
          return callback(self.error(constants.error.PROTOCOL_ERROR,
                                     'Stream can\'t dependend on itself'))
        }

        var streamInfo = {
          type: 'HEADERS',
          id: header.id,
          priority: {
            parent: dependency,
            exclusive: exclusive,
            weight: weight
          },
          fin: (header.flags & constants.flags.END_STREAM) !== 0,
          writable: true,
          headers: null,
          path: null
        }

        self.initHeaderBlock(header, streamInfo, data, callback)
      })
    }

    Parser.prototype.onContinuationFrame = function onContinuationFrame (header,
                                                                        body,
                                                                        callback) {
      this.queueHeaderBlock(header, body, callback)
    }

    Parser.prototype.onRSTFrame = function onRSTFrame (header, body, callback) {
      if (body.size !== 4) {
        return callback(this.error(constants.error.FRAME_SIZE_ERROR,
                                   'RST_STREAM length not 4'))
      }

      if (header.id === 0) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Invalid stream id for RST_STREAM'))
      }

      callback(null, {
        type: 'RST',
        id: header.id,
        code: constants.errorByCode[body.readUInt32BE()]
      })
    }

    Parser.prototype._validateSettings = function _validateSettings (settings) {
      Iif (settings['enable_push'] !== undefined &&
          settings['enable_push'] !== 0 &&
          settings['enable_push'] !== 1) {
        return this.error(constants.error.PROTOCOL_ERROR,
                          'SETTINGS_ENABLE_PUSH must be 0 or 1')
      }

      Iif (settings['initial_window_size'] !== undefined &&
          (settings['initial_window_size'] > constants.MAX_INITIAL_WINDOW_SIZE ||
           settings['initial_window_size'] < 0)) {
        return this.error(constants.error.FLOW_CONTROL_ERROR,
                          'SETTINGS_INITIAL_WINDOW_SIZE is OOB')
      }

      Iif (settings['max_frame_size'] !== undefined &&
          (settings['max_frame_size'] > constants.ABSOLUTE_MAX_FRAME_SIZE ||
           settings['max_frame_size'] < constants.INITIAL_MAX_FRAME_SIZE)) {
        return this.error(constants.error.PROTOCOL_ERROR,
                          'SETTINGS_MAX_FRAME_SIZE is OOB')
      }

      return undefined
    }

    Parser.prototype.onSettingsFrame = function onSettingsFrame (header,
                                                                body,
                                                                callback) {
      if (header.id !== 0) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Invalid stream id for SETTINGS'))
      }

      var isAck = (header.flags & constants.flags.ACK) !== 0
      if (isAck && body.size !== 0) {
        return callback(this.error(constants.error.FRAME_SIZE_ERROR,
                                   'SETTINGS with ACK and non-zero length'))
      }

      if (isAck) {
        return callback(null, { type: 'ACK_SETTINGS' })
      }

      if (body.size % 6 !== 0) {
        return callback(this.error(constants.error.FRAME_SIZE_ERROR,
                                   'SETTINGS length not multiple of 6'))
      }

      var settings = {}
      while (!body.isEmpty()) {
        var id = body.readUInt16BE()
        var value = body.readUInt32BE()
        var name = constants.settingsIndex[id]

        Eif (name) {
          settings[name] = value
        }
      }

      var err = this._validateSettings(settings)
      Iif (err !== undefined) {
        return callback(err)
      }

      callback(null, {
        type: 'SETTINGS',
        settings: settings
      })
    }

    Parser.prototype.onPushPromiseFrame = function onPushPromiseFrame (header,
                                                                      body,
                                                                      callback) {
      if (header.id === 0) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Invalid stream id for PUSH_PROMISE'))
      }

      var self = this
      this.unpadData(header, body, function (err, data) {
        if (err) {
          return callback(err)
        }

        if (!data.has(4)) {
          return callback(self.error(constants.error.FRAME_SIZE_ERROR,
                                     'PUSH_PROMISE length less than 4'))
        }

        var streamInfo = {
          type: 'PUSH_PROMISE',
          id: header.id,
          fin: false,
          promisedId: data.readUInt32BE() & 0x7fffffff,
          headers: null,
          path: null
        }

        self.initHeaderBlock(header, streamInfo, data, callback)
      })
    }

    Parser.prototype.onPingFrame = function onPingFrame (header, body, callback) {
      if (body.size !== 8) {
        return callback(this.error(constants.error.FRAME_SIZE_ERROR,
                                   'PING length != 8'))
      }

      if (header.id !== 0) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Invalid stream id for PING'))
      }

      var ack = (header.flags & constants.flags.ACK) !== 0
      callback(null, { type: 'PING', opaque: body.take(body.size), ack: ack })
    }

    Parser.prototype.onGoawayFrame = function onGoawayFrame (header,
                                                            body,
                                                            callback) {
      if (!body.has(8)) {
        return callback(this.error(constants.error.FRAME_SIZE_ERROR,
                                   'GOAWAY length < 8'))
      }

      if (header.id !== 0) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Invalid stream id for GOAWAY'))
      }

      var frame = {
        type: 'GOAWAY',
        lastId: body.readUInt32BE(),
        code: constants.goawayByCode[body.readUInt32BE()]
      }

      if (body.size !== 0) { frame.debug = body.take(body.size) }

      callback(null, frame)
    }

    Parser.prototype.onPriorityFrame = function onPriorityFrame (header,
                                                                body,
                                                                callback) {
      if (body.size !== 5) {
        return callback(this.error(constants.error.FRAME_SIZE_ERROR,
                                   'PRIORITY length != 5'))
      }

      if (header.id === 0) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Invalid stream id for PRIORITY'))
      }

      var dependency = body.readUInt32BE()

      // Again the range is from 1 to 256
      var weight = body.readUInt8() + 1

      Iif (dependency === header.id) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'Stream can\'t dependend on itself'))
      }

      callback(null, {
        type: 'PRIORITY',
        id: header.id,
        priority: {
          exclusive: (dependency & 0x80000000) !== 0,
          parent: dependency & 0x7fffffff,
          weight: weight
        }
      })
    }

    Parser.prototype.onWindowUpdateFrame = function onWindowUpdateFrame (header,
                                                                        body,
                                                                        callback) {
      if (body.size !== 4) {
        return callback(this.error(constants.error.FRAME_SIZE_ERROR,
                                   'WINDOW_UPDATE length != 4'))
      }

      var delta = body.readInt32BE()
      Iif (delta === 0) {
        return callback(this.error(constants.error.PROTOCOL_ERROR,
                                   'WINDOW_UPDATE delta == 0'))
      }

      callback(null, {
        type: 'WINDOW_UPDATE',
        id: header.id,
        delta: delta
      })
    }

    Parser.prototype.onXForwardedFrame = function onXForwardedFrame (header,
                                                                    body,
                                                                    callback) {
      callback(null, {
        type: 'X_FORWARDED_FOR',
        host: body.take(body.size).toString()
      })
    }