# all files / lib/spdy-transport/ connection.js

84.62% Statements 330/390
81.28% Branches 152/187
79.63% Functions 43/54
85.33% Lines 320/375

    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
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838

    1×
    1×

    1×

    1×

    1×

    1×
    448×

    448×
    448×

    448×

    448×

    448×
    448×
    448×
    448×
    448×

    448×

    448×

    448×
    448×

    448×

    448×
    448×

    448×

    448×

    448×
    448×

    448×

    448×

    448×

    448×

    448×

    448×

    448×

    448×
    329×

    448×

    448×

    448×

    1×
    1×

    1×
    448×

    1×
    448×
    448×
    448×

    448×
    1041×

    448×
    5164×

    448×
    448×

    448×

    448×

    448×
    448×

    448×

    448×

    448×
    51×

    1×

    448×
    448×

    448×

    1×
    448×
    448×
    448×
    448×
    448×

    448×
    448×

    448×
    448×
    448×
    448×

    448×

    448×
    226×
    226×

    448×

    448×

    448×

    1×

    1×
    5164×

    5164×
    5164×

    5164×

    5164×

    5164×
    1216×
    4×
    4×
    4×

    1216×
    1216×

    3948×
    4×
    4×

    4×

    3944×

    3313×

    3313×

    3944×
    225×
    225×

    3719×
    3027×
    692×
    449×
    243×

    125×
    24×
    101×
    36×
    65×

    4×
    4×

    61×

    58×

    1×

    1×
    1026×
    1026×
    988×

    1×
    266×

    266×
    266×
    266×

    1×
    513×
    513×
    513×

    513×

    513×

    513×

    513×

    513×
    19×

    494×

    494×
    494×
    494×
    494×
    494×
    78×

    494×
    184×

    494×

    1×
    225×

    225×

    221×
    7×
    7×

    214×

    214×
    11×

    203×

    203×

    15×
    15×

    188×
    22×

    188×

    1×
    1219×
    1219×

    1219×
    1219×

    1219×

    1219×

    1219×

    1×
    227×

    1×
    517×

    1×
    449×

    449×

    449×
    449×

    449×
    2×
    2×

    449×
    120×
    2×

    118×

    1×
    449×
    5×

    444×

    444×
    444×

    444×
    193×
    193×

    193×

    1×
    24×
    24×

    24×
    12×

    12×
    12×

    12×
    12×

    12×
    12×

    12×
    12×

    1×
    36×

    1×
    16×

    16×
    16×
    16×
    16×

    16×
    16×

    1×
    5×

    1×
    221×

    221×
    8×
    8×
    8×

    8×

    213×
    213×
    213×

    213×

    1×
    201×
    201×
    8×
    4×

    4×

    8×

    193×
    6×
    4×

    6×

    187×
    187×

    187×
    179×

    201×

    1×
    184×

    184×
    184×
    184×

    184×
    126×

    1×
    72×
    72×

    72×
    72×

    72×
    64×

    64×
    52×

    12×
    12×

    1×

    72×

    32×

    32×
    32×
    32×

    32×

    40×

    72×

    36×

    36×

    1×
    51×

    51×

    51×
    51×
    51×

    51×
    8×

    51×

    1×
    32×

    32×
    4×

    32×

    1×

    1×
    513×

    1×
    4×

    1×
    4×
    4×
    4×

    1×
    45×

    45×

    45×

    45×

    45×

    45×
    45×

    45×
    37×

    45×

    1×
    59×

    59×

     'use strict'

    var util = require('util')
    var transport = require('../spdy-transport')

    var debug = {
      server: require('debug')('spdy:connection:server'),
      client: require('debug')('spdy:connection:client')
    }
    var EventEmitter = require('events').EventEmitter

    var Stream = transport.Stream

    function Connection (socket, options) {
      EventEmitter.call(this)

      var state = {}
      this._spdyState = state

      // NOTE: There's a big trick here. Connection is used as a `this` argument
      // to the wrapped `connection` event listener.
      // socket end doesn't necessarly mean connection drop
      this.httpAllowHalfOpen = true

      state.timeout = new transport.utils.Timeout(this)

      // Protocol info
      state.protocol = transport.protocol[options.protocol]
      state.version = null
      state.constants = state.protocol.constants
      state.pair = null
      state.isServer = options.isServer

      // Root of priority tree (i.e. stream id = 0)
      state.priorityRoot = new transport.Priority({
        defaultWeight: state.constants.DEFAULT_WEIGHT,
        maxCount: transport.protocol.base.constants.MAX_PRIORITY_STREAMS
      })

      // Defaults
      state.maxStreams = options.maxStreams ||
                         state.constants.MAX_CONCURRENT_STREAMS

      state.autoSpdy31 = options.protocol.name !== 'h2' && options.autoSpdy31
      state.acceptPush = options.acceptPush === undefined
        ? !state.isServer
        : options.acceptPush

      Iif (options.maxChunk === false) { state.maxChunk = Infinity } else Eif (options.maxChunk === undefined) { state.maxChunk = transport.protocol.base.constants.DEFAULT_MAX_CHUNK } else {
        state.maxChunk = options.maxChunk
      }

      // Connection-level flow control
      var windowSize = options.windowSize || 1 << 20
      state.window = new transport.Window({
        id: 0,
        isServer: state.isServer,
        recv: {
          size: state.constants.DEFAULT_WINDOW,
          max: state.constants.MAX_INITIAL_WINDOW_SIZE
        },
        send: {
          size: state.constants.DEFAULT_WINDOW,
          max: state.constants.MAX_INITIAL_WINDOW_SIZE
        }
      })

      // It starts with DEFAULT_WINDOW, update must be sent to change it on client
      state.window.recv.setMax(windowSize)

      // Boilerplate for Stream constructor
      state.streamWindow = new transport.Window({
        id: -1,
        isServer: state.isServer,
        recv: {
          size: windowSize,
          max: state.constants.MAX_INITIAL_WINDOW_SIZE
        },
        send: {
          size: state.constants.DEFAULT_WINDOW,
          max: state.constants.MAX_INITIAL_WINDOW_SIZE
        }
      })

      // Various state info
      state.pool = state.protocol.compressionPool.create(options.headerCompression)
      state.counters = {
        push: 0,
        stream: 0
      }

      // Init streams list
      state.stream = {
        map: {},
        count: 0,
        nextId: state.isServer ? 2 : 1,
        lastId: {
          both: 0,
          received: 0
        }
      }
      state.ping = {
        nextId: state.isServer ? 2 : 1,
        map: {}
      }
      state.goaway = false

      // Debug
      state.debug = state.isServer ? debug.server : debug.client

      // X-Forwarded feature
      state.xForward = null

      // Create parser and hole for framer
      state.parser = state.protocol.parser.create({
        // NOTE: needed to distinguish ping from ping ACK in SPDY
        isServer: state.isServer,
        window: state.window
      })
      state.framer = state.protocol.framer.create({
        window: state.window,
        timeout: state.timeout
      })

      // SPDY has PUSH enabled on servers
      if (state.protocol.name === 'spdy') {
        state.framer.enablePush(state.isServer)
      }

      if (!state.isServer) { state.parser.skipPreface() }

      this.socket = socket

      this._init()
    }
    util.inherits(Connection, EventEmitter)
    exports.Connection = Connection

    Connection.create = function create (socket, options) {
      return new Connection(socket, options)
    }

    Connection.prototype._init = function init () {
      var self = this
      var state = this._spdyState
      var pool = state.pool

      // Initialize session window
      state.window.recv.on('drain', function () {
        self._onSessionWindowDrain()
      })

      // Initialize parser
      state.parser.on('data', function (frame) {
        self._handleFrame(frame)
      })
      state.parser.once('version', function (version) {
        self._onVersion(version)
      })

      // Propagate parser errors
      state.parser.on('error', function (err) {
        self._onParserError(err)
      })

      // Propagate framer errors
      state.framer.on('error', function (err) {
        self.emit('error', err)
      })

      this.socket.pipe(state.parser)
      state.framer.pipe(this.socket)

      // Allow high-level api to catch socket errors
      this.socket.on('error', function onSocketError (e) {
        self.emit('error', e)
      })

      this.socket.once('close', function onclose () {
        var err = new Error('socket hang up')
        err.code = 'ECONNRESET'
        self.destroyStreams(err)
        self.emit('close', err)

        if (state.pair) {
          pool.put(state.pair)
        }

        state.framer.resume()
      })

      // Reset timeout on close
      this.once('close', function () {
        self.setTimeout(0)
      })

      function _onWindowOverflow () {
        self._onWindowOverflow()
      }

      state.window.recv.on('overflow', _onWindowOverflow)
      state.window.send.on('overflow', _onWindowOverflow)

      // Do not allow half-open connections
      this.socket.allowHalfOpen = false
    }

    Connection.prototype._onVersion = function _onVersion (version) {
      var state = this._spdyState
      var prev = state.version
      var parser = state.parser
      var framer = state.framer
      var pool = state.pool

      state.version = version
      state.debug('id=0 version=%d', version)

      // Ignore transition to 3.1
      Eif (!prev) {
        state.pair = pool.get(version)
        parser.setCompression(state.pair)
        framer.setCompression(state.pair)
      }
      framer.setVersion(version)

      if (!state.isServer) {
        framer.prefaceFrame()
        Iif (state.xForward !== null) {
          framer.xForwardedFor({ host: state.xForward })
        }
      }

      // Send preface+settings frame (once)
      framer.settingsFrame({
        max_header_list_size: state.constants.DEFAULT_MAX_HEADER_LIST_SIZE,
        max_concurrent_streams: state.maxStreams,
        enable_push: state.acceptPush ? 1 : 0,
        initial_window_size: state.window.recv.max
      })

      // Update session window
      if (state.version >= 3.1 || (state.isServer && state.autoSpdy31)) { this._onSessionWindowDrain() }

      this.emit('version', version)
    }

    Connection.prototype._onParserError = function _onParserError (err) {
      var state = this._spdyState

      // Prevent further errors
      state.parser.kill()

      // Send GOAWAY
      if (err instanceof transport.protocol.base.utils.ProtocolError) {
        this._goaway({
          lastId: state.stream.lastId.both,
          code: err.code,
          extra: err.message,
          send: true
        })
      }

      this.emit('error', err)
    }

    Connection.prototype._handleFrame = function _handleFrame (frame) {
      var state = this._spdyState

      state.debug('id=0 frame', frame)
      state.timeout.reset()

      // For testing purposes
      this.emit('frame', frame)

      var stream

      // Session window update
      if (frame.type === 'WINDOW_UPDATE' && frame.id === 0) {
        if (state.version < 3.1 && state.autoSpdy31) {
          state.debug('id=0 switch version to 3.1')
          state.version = 3.1
          this.emit('version', 3.1)
        }
        state.window.send.update(frame.delta)
        return
      }

      if (state.isServer && frame.type === 'PUSH_PROMISE') {
        state.debug('id=0 server PUSH_PROMISE')
        this._goaway({
          lastId: state.stream.lastId.both,
          code: 'PROTOCOL_ERROR',
          send: true
        })
        return
      }

      if (!stream && frame.id !== undefined) {
        // Load created one
        stream = state.stream.map[frame.id]

        // Fail if not found
        Iif (!stream &&
            frame.type !== 'HEADERS' &&
            frame.type !== 'PRIORITY' &&
            frame.type !== 'RST') {
          // Other side should destroy the stream upon receiving GOAWAY
          if (this._isGoaway(frame.id)) { return }

          state.debug('id=0 stream=%d not found', frame.id)
          state.framer.rstFrame({ id: frame.id, code: 'INVALID_STREAM' })
          return
        }
      }

      // Create new stream
      if (!stream && frame.type === 'HEADERS') {
        this._handleHeaders(frame)
        return
      }

      if (stream) {
        stream._handleFrame(frame)
      } else if (frame.type === 'SETTINGS') {
        this._handleSettings(frame.settings)
      } else if (frame.type === 'ACK_SETTINGS') {
        // TODO(indutny): handle it one day
      } else if (frame.type === 'PING') {
        this._handlePing(frame)
      } else if (frame.type === 'GOAWAY') {
        this._handleGoaway(frame)
      } else if (frame.type === 'X_FORWARDED_FOR') {
        // Set X-Forwarded-For only once
        Eif (state.xForward === null) {
          state.xForward = frame.host
        }
      } else if (frame.type === 'PRIORITY') {
        // TODO(indutny): handle this
      } else {
        state.debug('id=0 unknown frame type: %s', frame.type)
      }
    }

    Connection.prototype._onWindowOverflow = function _onWindowOverflow () {
      var state = this._spdyState
      state.debug('id=0 window overflow')
      this._goaway({
        lastId: state.stream.lastId.both,
        code: 'FLOW_CONTROL_ERROR',
        send: true
      })
    }

    Connection.prototype._isGoaway = function _isGoaway (id) {
      var state = this._spdyState
      if (state.goaway !== false && state.goaway < id) { return true }
      return false
    }

    Connection.prototype._getId = function _getId () {
      var state = this._spdyState

      var id = state.stream.nextId
      state.stream.nextId += 2
      return id
    }

    Connection.prototype._createStream = function _createStream (uri) {
      var state = this._spdyState
      var id = uri.id
      if (id === undefined) { id = this._getId() }

      var isGoaway = this._isGoaway(id)

      Iif (uri.push && !state.acceptPush) {
        state.debug('id=0 push disabled promisedId=%d', id)

        // Fatal error
        this._goaway({
          lastId: state.stream.lastId.both,
          code: 'PROTOCOL_ERROR',
          send: true
        })
        isGoaway = true
      }

      var stream = new Stream(this, {
        id: id,
        request: uri.request !== false,
        method: uri.method,
        path: uri.path,
        host: uri.host,
        priority: uri.priority,
        headers: uri.headers,
        parent: uri.parent,
        readable: !isGoaway && uri.readable,
        writable: !isGoaway && uri.writable
      })
      var self = this

      // Just an empty stream for API consistency
      if (isGoaway) {
        return stream
      }

      state.stream.lastId.both = Math.max(state.stream.lastId.both, id)

      state.debug('id=0 add stream=%d', stream.id)
      state.stream.map[stream.id] = stream
      state.stream.count++
      state.counters.stream++
      if (stream.parent !== null) {
        state.counters.push++
      }

      stream.once('close', function () {
        self._removeStream(stream)
      })

      return stream
    }

    Connection.prototype._handleHeaders = function _handleHeaders (frame) {
      var state = this._spdyState

      // Must be HEADERS frame after stream close
      if (frame.id <= state.stream.lastId.received) { return }

      // Someone is using our ids!
      if ((frame.id + state.stream.nextId) % 2 === 0) {
        state.framer.rstFrame({ id: frame.id, code: 'PROTOCOL_ERROR' })
        return
      }

      var stream = this._createStream({
        id: frame.id,
        request: false,
        method: frame.headers[':method'],
        path: frame.headers[':path'],
        host: frame.headers[':authority'],
        priority: frame.priority,
        headers: frame.headers,
        writable: frame.writable
      })

      // GOAWAY
      if (this._isGoaway(stream.id)) {
        return
      }

      state.stream.lastId.received = Math.max(state.stream.lastId.received,
                                              stream.id)

      // TODO(indutny) handle stream limit
      if (!this.emit('stream', stream)) {
        // No listeners was set - abort the stream
        stream.abort()
        return
      }

      // Create fake frame to simulate end of the data
      if (frame.fin) {
        stream._handleFrame({ type: 'FIN', fin: true })
      }

      return stream
    }

    Connection.prototype._onSessionWindowDrain = function _onSessionWindowDrain () {
      var state = this._spdyState
      Iif (state.version < 3.1 && !(state.isServer && state.autoSpdy31)) {
        return
      }

      var delta = state.window.recv.getDelta()
      Iif (delta === 0) {
        return
      }

      state.debug('id=0 session window drain, update by %d', delta)

      state.framer.windowUpdateFrame({
        id: 0,
        delta: delta
      })
      state.window.recv.update(delta)
    }

    Connection.prototype.start = function start (version) {
      this._spdyState.parser.setVersion(version)
    }

    // Mostly for testing
    Connection.prototype.getVersion = function getVersion () {
      return this._spdyState.version
    }

    Connection.prototype._handleSettings = function _handleSettings (settings) {
      var state = this._spdyState

      state.framer.ackSettingsFrame()

      this._setDefaultWindow(settings)
      if (settings.max_frame_size) { state.framer.setMaxFrameSize(settings.max_frame_size) }

      // TODO(indutny): handle max_header_list_size
      if (settings.header_table_size) {
        try {
          state.pair.compress.updateTableSize(settings.header_table_size)
        } catch (e) {
          this._goaway({
            lastId: 0,
            code: 'PROTOCOL_ERROR',
            send: true
          })
          return
        }
      }

      // HTTP2 clients needs to enable PUSH streams explicitly
      if (state.protocol.name !== 'spdy') {
        if (settings.enable_push === undefined) {
          state.framer.enablePush(state.isServer)
        } else {
          state.framer.enablePush(settings.enable_push === 1)
        }
      }

      // TODO(indutny): handle max_concurrent_streams
    }

    Connection.prototype._setDefaultWindow = function _setDefaultWindow (settings) {
      if (settings.initial_window_size === undefined) {
        return
      }

      var state = this._spdyState

      // Update defaults
      var window = state.streamWindow
      window.send.setMax(settings.initial_window_size)

      // Update existing streams
      Object.keys(state.stream.map).forEach(function (id) {
        var stream = state.stream.map[id]
        var window = stream._spdyState.window

        window.send.updateMax(settings.initial_window_size)
      })
    }

    Connection.prototype._handlePing = function handlePing (frame) {
      var self = this
      var state = this._spdyState

      // Handle incoming PING
      if (!frame.ack) {
        state.framer.pingFrame({
          opaque: frame.opaque,
          ack: true
        })

        self.emit('ping', frame.opaque)
        return
      }

      // Handle reply PING
      var hex = frame.opaque.toString('hex')
      Iif (!state.ping.map[hex]) {
        return
      }
      var ping = state.ping.map[hex]
      delete state.ping.map[hex]

      Eif (ping.cb) {
        ping.cb(null)
      }
    }

    Connection.prototype._handleGoaway = function handleGoaway (frame) {
      this._goaway({
        lastId: frame.lastId,
        code: frame.code,
        send: false
      })
    }

    Connection.prototype.ping = function ping (callback) {
      var state = this._spdyState

      // HTTP2 is using 8-byte opaque
      var opaque = new Buffer(state.constants.PING_OPAQUE_SIZE)
      opaque.fill(0)
      opaque.writeUInt32BE(state.ping.nextId, opaque.length - 4)
      state.ping.nextId += 2

      state.ping.map[opaque.toString('hex')] = { cb: callback }
      state.framer.pingFrame({
        opaque: opaque,
        ack: false
      })
    }

    Connection.prototype.getCounter = function getCounter (name) {
      return this._spdyState.counters[name]
    }

    Connection.prototype.reserveStream = function reserveStream (uri, callback) {
      var stream = this._createStream(uri)

      // GOAWAY
      if (this._isGoaway(stream.id)) {
        var err = new Error('Can\'t send request after GOAWAY')
        process.nextTick(function () {
          Eif (callback) { callback(err) } else {
            stream.emit('error', err)
          }
        })
        return stream
      }

      Eif (callback) {
        process.nextTick(function () {
          callback(null, stream)
        })
      }

      return stream
    }

    Connection.prototype.request = function request (uri, callback) {
      var stream = this.reserveStream(uri, function (err) {
        if (err) {
          if (callback) {
            callback(err)
          } else {
            stream.emit('error', err)
          }
          return
        }

        if (stream._wasSent()) {
          if (callback) {
            callback(null, stream)
          }
          return
        }

        stream.send(function (err) {
          Iif (err) {
            if (callback) { return callback(err) } else { return stream.emit('error', err) }
          }

          if (callback) {
            callback(null, stream)
          }
        })
      })

      return stream
    }

    Connection.prototype._removeStream = function _removeStream (stream) {
      var state = this._spdyState

      state.debug('id=0 remove stream=%d', stream.id)
      delete state.stream.map[stream.id]
      state.stream.count--

      if (state.stream.count === 0) {
        this.emit('_streamDrain')
      }
    }

    Connection.prototype._goaway = function _goaway (params) {
      var state = this._spdyState
      var self = this

      state.goaway = params.lastId
      state.debug('id=0 goaway from=%d', state.goaway)

      Object.keys(state.stream.map).forEach(function (id) {
        var stream = state.stream.map[id]

        // Abort every stream started after GOAWAY
        if (stream.id <= params.lastId) {
          return
        }

        stream.abort()
        stream.emit('error', new Error('New stream after GOAWAY'))
      })

      function finish () {
        // Destroy socket if there are no streams
        if (state.stream.count === 0 || params.code !== 'OK') {
          // No further frames should be processed
          state.parser.kill()

          process.nextTick(function () {
            var err = new Error('Fatal error: ' + params.code)
            self._onStreamDrain(err)
          })
          return
        }

        self.on('_streamDrain', self._onStreamDrain)
      }

      if (params.send) {
        // Make sure that GOAWAY frame is sent before dumping framer
        state.framer.goawayFrame({
          lastId: params.lastId,
          code: params.code,
          extra: params.extra
        }, finish)
      } else {
        finish()
      }
    }

    Connection.prototype._onStreamDrain = function _onStreamDrain (error) {
      var state = this._spdyState

      state.debug('id=0 _onStreamDrain')

      state.framer.dump()
      state.framer.unpipe(this.socket)
      state.framer.resume()

      if (this.socket.destroySoon) {
        this.socket.destroySoon()
      }
      this.emit('close', error)
    }

    Connection.prototype.end = function end (callback) {
      var state = this._spdyState

      if (callback) {
        this.once('close', callback)
      }
      this._goaway({
        lastId: state.stream.lastId.both,
        code: 'OK',
        send: true
      })
    }

    Connection.prototype.destroyStreams = function destroyStreams (err) {
      var state = this._spdyState
      Object.keys(state.stream.map).forEach(function (id) {
        var stream = state.stream.map[id]

        stream.abort()
        stream.emit('error', err)
      })
    }

    Connection.prototype.isServer = function isServer () {
      return this._spdyState.isServer
    }

    Connection.prototype.getXForwardedFor = function getXForwardFor () {
      return this._spdyState.xForward
    }

    Connection.prototype.sendXForwardedFor = function sendXForwardedFor (host) {
      var state = this._spdyState
      Eif (state.version !== null) {
        state.framer.xForwardedFor({ host: host })
      } else {
        state.xForward = host
      }
    }

    Connection.prototype.pushPromise = function pushPromise (parent, uri, callback) {
      var state = this._spdyState

      var stream = this._createStream({
        request: false,
        parent: parent,
        method: uri.method,
        path: uri.path,
        host: uri.host,
        priority: uri.priority,
        headers: uri.headers,
        readable: false
      })

      var err

      // TODO(indutny): deduplicate this logic somehow
      Iif (this._isGoaway(stream.id)) {
        err = new Error('Can\'t send PUSH_PROMISE after GOAWAY')

        process.nextTick(function () {
          if (callback) {
            callback(err)
          } else {
            stream.emit('error', err)
          }
        })
        return stream
      }

      Iif (uri.push && !state.acceptPush) {
        err = new Error(
            'Can\'t send PUSH_PROMISE, other side won\'t accept it')
        process.nextTick(function () {
          if (callback) { callback(err) } else {
            stream.emit('error', err)
          }
        })
        return stream
      }

      stream._sendPush(uri.status, uri.response, function (err) {
        Iif (!callback) {
          if (err) {
            stream.emit('error', err)
          }
          return
        }

        if (err) { return callback(err) }
        callback(null, stream)
      })

      return stream
    }

    Connection.prototype.setTimeout = function setTimeout (delay, callback) {
      var state = this._spdyState

      state.timeout.set(delay, callback)
    }