Code coverage report for lib/framer.js

Statements: 91.09% (327 / 359)      Branches: 80.16% (101 / 126)      Functions: 94.44% (34 / 36)      Lines: 91.09% (327 / 359)     

All files » lib/ » framer.js
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 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012        1   1   1 1   1   1 1                         1 5 5 5   1         1 22   22   22 22 22   22   22 54     54     22                           1 5 5 5 5 5   1             1 57 57 57 57 31           1 52   52       52     87 87 87 87             87 26 26 26                       87 26 26 26       26 26           26       52                                                                                                       1   1   1   1   1   1 38   38 38 48   38   38 38   38 38 78 78 78 8     38   38 38   38     1 48   48   48 48 48 48 144     48   48                                                                         1   1   1   1 2     1 4 4 4 2       2 2 2       4       4 2   2                                                       1   1   1                                   1 6 4 4 4 4 2   4 4 4   6     1 12 12 12 6       6 6 6       12 8 8 8 8 8 8 8 8     12 6   6                     1   1   1                       1 4 4 4 4 2   4 4   4     1 4 4 4 4 4 4                   1   1   1                     1 2 2 2 2 2     1 2                           1   1   1                                       1 8 8 40 18 18 18     8   8 8 18 18     8     1 6         6       6     6 14 14 14 14     14 14                 1         1           1       1       1           1                           1   1   1                           1 2   2 2 2   2 2     1 4 4 4 2       2 2 2     4 4 4 2   2                             1   1   1       1 2     1 2     2                   1   1   1                                 1 2   2 2 2   2 2 2   2     1 2 2                   1   1   1             1 2   2 2 2   2     1 2     2                                       1   1   1   1 2     1 4 4 4 2       2 2 2     4 2   2                     1   1                                                                                               1     1 2 2 2 2 2 2   2   2 2 2   2   2     1 2 2 2 2 2 2 2                     1   1   1   1     1           1                                         1       1 1 6       6 4     2 2   2 2 10     2 1     1     1 1       2       2       2       1      
// The framer consists of two [Transform Stream][1] subclasses that operate in [object mode][2]:
// the Serializer and the Deserializer
// [1]: http://nodejs.org/api/stream.html#stream_class_stream_transform
// [2]: http://nodejs.org/api/stream.html#stream_new_stream_readable_options
var assert = require('assert');
 
var Transform = require('stream').Transform;
 
exports.Serializer = Serializer;
exports.Deserializer = Deserializer;
 
var logData = Boolean(process.env.HTTP2_LOG_DATA);
 
var MAX_PAYLOAD_SIZE = 16383;
var WINDOW_UPDATE_PAYLOAD_SIZE = 4;
 
// Serializer
// ----------
//
//     Frame Objects
//     * * * * * * * --+---------------------------
//                     |                          |
//                     v                          v           Buffers
//      [] -----> Payload Ser. --[buffers]--> Header Ser. --> * * * *
//     empty      adds payload                adds header
//     array        buffers                     buffer
 
function Serializer(log, sizeLimit) {
  this._log = log.child({ component: 'serializer' });
  this._sizeLimit = sizeLimit || MAX_PAYLOAD_SIZE;
  Transform.call(this, { objectMode: true });
}
Serializer.prototype = Object.create(Transform.prototype, { constructor: { value: Serializer } });
 
// When there's an incoming frame object, it first generates the frame type specific part of the
// frame (payload), and then then adds the header part which holds fields that are common to all
// frame types (like the length of the payload).
Serializer.prototype._transform = function _transform(frame, encoding, done) {
  this._log.trace({ frame: frame }, 'Outgoing frame');
 
  assert(frame.type in Serializer, 'Unknown frame type: ' + frame.type);
 
  var buffers = [];
  Serializer[frame.type](frame, buffers);
  Serializer.commonHeader(frame, buffers);
 
  assert(buffers[0].readUInt16BE(0) <= this._sizeLimit, 'Frame too large!');
 
  for (var i = 0; i < buffers.length; i++) {
    Iif (logData) {
      this._log.trace({ data: buffers[i] }, 'Outgoing data');
    }
    this.push(buffers[i]);
  }
 
  done();
};
 
// Deserializer
// ------------
//
//     Buffers
//     * * * * --------+-------------------------
//                     |                        |
//                     v                        v           Frame Objects
//      {} -----> Header Des. --{frame}--> Payload Des. --> * * * * * * *
//     empty      adds parsed              adds parsed
//     object  header properties        payload properties
 
function Deserializer(log, sizeLimit, role) {
  this._role = role;
  this._log = log.child({ component: 'deserializer' });
  this._sizeLimit = sizeLimit || MAX_PAYLOAD_SIZE;
  Transform.call(this, { objectMode: true });
  this._next(COMMON_HEADER_SIZE);
}
Deserializer.prototype = Object.create(Transform.prototype, { constructor: { value: Deserializer } });
 
// The Deserializer is stateful, and it's two main alternating states are: *waiting for header* and
// *waiting for payload*. The state is stored in the boolean property `_waitingForHeader`.
//
// When entering a new state, a `_buffer` is created that will hold the accumulated data (header or
// payload). The `_cursor` is used to track the progress.
Deserializer.prototype._next = function(size) {
  this._cursor = 0;
  this._buffer = new Buffer(size);
  this._waitingForHeader = !this._waitingForHeader;
  if (this._waitingForHeader) {
    this._frame = {};
  }
};
 
// Parsing an incoming buffer is an iterative process because it can hold multiple frames if it's
// large enough. A `cursor` is used to track the progress in parsing the incoming `chunk`.
Deserializer.prototype._transform = function _transform(chunk, encoding, done) {
  var cursor = 0;
 
  Iif (logData) {
    this._log.trace({ data: chunk }, 'Incoming data');
  }
 
  while(cursor < chunk.length) {
    // The content of an incoming buffer is first copied to `_buffer`. If it can't hold the full
    // chunk, then only a part of it is copied.
    var toCopy = Math.min(chunk.length - cursor, this._buffer.length - this._cursor);
    chunk.copy(this._buffer, this._cursor, cursor, cursor + toCopy);
    this._cursor += toCopy;
    cursor += toCopy;
 
    // When `_buffer` is full, it's content gets parsed either as header or payload depending on
    // the actual state.
 
    // If it's header then the parsed data is stored in a temporary variable and then the
    // deserializer waits for the specified length payload.
    if ((this._cursor === this._buffer.length) && this._waitingForHeader) {
      var payloadSize = Deserializer.commonHeader(this._buffer, this._frame);
      Eif (payloadSize <= this._sizeLimit) {
        this._next(payloadSize);
      } else {
        this.emit('error', 'FRAME_SIZE_ERROR');
        return;
      }
    }
 
    // If it's payload then the the frame object is finalized and then gets pushed out.
    // Unknown frame types are ignored.
    //
    // Note: If we just finished the parsing of a header and the payload length is 0, this branch
    // will also run.
    if ((this._cursor === this._buffer.length) && !this._waitingForHeader) {
      Eif (this._frame.type) {
        var error = Deserializer[this._frame.type](this._buffer, this._frame, this._role);
        Iif (error) {
          this._log.error('Incoming frame parsing error: ' + error);
          this.emit('error', error);
        } else {
          this._log.trace({ frame: this._frame }, 'Incoming frame');
          this.push(this._frame);
        }
      } else {
        this._log.error('Unknown type incoming frame');
        this.emit('error', 'PROTOCOL_ERROR');
      }
      this._next(COMMON_HEADER_SIZE);
    }
  }
 
  done();
};
 
// [Frame Header](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-4.1)
// --------------------------------------------------------------
//
// HTTP/2.0 frames share a common base format consisting of an 8-byte header followed by 0 to 65535
// bytes of data.
//
// Additional size limits can be set by specific application uses. HTTP limits the frame size to
// 16,383 octets.
//
//      0                   1                   2                   3
//      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//     | R |     Length (14)           |   Type (8)    |   Flags (8)   |
//     +-+-+---------------------------+---------------+---------------+
//     |R|                 Stream Identifier (31)                      |
//     +-+-------------------------------------------------------------+
//     |                     Frame Data (0...)                       ...
//     +---------------------------------------------------------------+
//
// The fields of the frame header are defined as:
//
// * R:
//   A reserved 2-bit field. The semantics of these bits are undefined and the bits MUST remain
//   unset (0) when sending and MUST be ignored when receiving.
//
// * Length:
//   The length of the frame data expressed as an unsigned 14-bit integer. The 8 bytes of the frame
//   header are not included in this value.
//
// * Type:
//   The 8-bit type of the frame. The frame type determines how the remainder of the frame header
//   and data are interpreted. Implementations MUST ignore unsupported and unrecognized frame types.
//
// * Flags:
//   An 8-bit field reserved for frame-type specific boolean flags.
//
//   Flags are assigned semantics specific to the indicated frame type. Flags that have no defined
//   semantics for a particular frame type MUST be ignored, and MUST be left unset (0) when sending.
//
// * R:
//   A reserved 1-bit field. The semantics of this bit are undefined and the bit MUST remain unset
//   (0) when sending and MUST be ignored when receiving.
//
// * Stream Identifier:
//   A 31-bit stream identifier. The value 0 is reserved for frames that are associated with the
//   connection as a whole as opposed to an individual stream.
//
// The structure and content of the remaining frame data is dependent entirely on the frame type.
 
var COMMON_HEADER_SIZE = 8;
 
var frameTypes = [];
 
var frameFlags = {};
 
var genericAttributes = ['type', 'flags', 'stream'];
 
var typeSpecificAttributes = {};
 
Serializer.commonHeader = function writeCommonHeader(frame, buffers) {
  var headerBuffer = new Buffer(COMMON_HEADER_SIZE);
 
  var size = 0;
  for (var i = 0; i < buffers.length; i++) {
    size += buffers[i].length;
  }
  headerBuffer.writeUInt16BE(size, 0);
 
  var typeId = frameTypes.indexOf(frame.type);  // If we are here then the type is valid for sure
  headerBuffer.writeUInt8(typeId, 2);
 
  var flagByte = 0;
  for (var flag in frame.flags) {
    var position = frameFlags[frame.type].indexOf(flag);
    assert(position !== -1, 'Unknown flag for frame type ' + frame.type + ': ' + flag);
    if (frame.flags[flag]) {
      flagByte |= (1 << position);
    }
  }
  headerBuffer.writeUInt8(flagByte, 3);
 
  assert((0 <= frame.stream) && (frame.stream < 0x7fffffff), frame.stream);
  headerBuffer.writeUInt32BE(frame.stream || 0, 4);
 
  buffers.unshift(headerBuffer);
};
 
Deserializer.commonHeader = function readCommonHeader(buffer, frame) {
  var length = buffer.readUInt16BE(0);
 
  frame.type = frameTypes[buffer.readUInt8(2)];
 
  frame.flags = {};
  var flagByte = buffer.readUInt8(3);
  var definedFlags = frameFlags[frame.type];
  for (var i = 0; i < definedFlags.length; i++) {
    frame.flags[definedFlags[i]] = Boolean(flagByte & (1 << i));
  }
 
  frame.stream = buffer.readUInt32BE(4) & 0x7fffffff;
 
  return length;
};
 
// Frame types
// ===========
 
// Every frame type is registered in the following places:
//
// * `frameTypes`: a register of frame type codes (used by `commonHeader()`)
// * `frameFlags`: a register of valid flags for frame types (used by `commonHeader()`)
// * `typeSpecificAttributes`: a register of frame specific frame object attributes (used by
//   logging code and also serves as documentation for frame objects)
 
// [DATA Frames](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.1)
// ------------------------------------------------------------
//
// DATA frames (type=0x0) convey arbitrary, variable-length sequences of octets associated with a
// stream.
//
// The DATA frame defines the following flags:
//
// * END_STREAM (0x1):
//   Bit 1 being set indicates that this frame is the last that the endpoint will send for the
//   identified stream.
// * END_SEGMENT (0x2):
//   Bit 2 being set indicates that this frame is the last for the current segment. Intermediaries
//   MUST NOT coalesce frames across a segment boundary and MUST preserve segment boundaries when
//   forwarding frames.
// * PAD_LOW (0x08):
//   Bit 4 being set indicates that the Pad Low field is present.
// * PAD_HIGH (0x10):
//   Bit 5 being set indicates that the Pad High field is present. This bit MUST NOT be set unless
//   the PAD_LOW flag is also set. Endpoints that receive a frame with PAD_HIGH set and PAD_LOW
//   cleared MUST treat this as a connection error of type PROTOCOL_ERROR.
// * COMPRESSED (0x20):
//   Bit 6 being set indicates that the data in the frame has been compressed with GZIP compression.
 
frameTypes[0x0] = 'DATA';
 
frameFlags.DATA = ['END_STREAM', 'END_SEGMENT', 'RESERVED4', 'PAD_LOW', 'PAD_HIGH', 'COMPRESSED'];
 
typeSpecificAttributes.DATA = ['data'];
 
Serializer.DATA = function writeData(frame, buffers) {
  buffers.push(frame.data);
};
 
Deserializer.DATA = function readData(buffer, frame) {
  var dataOffset = 0;
  var paddingLength = 0;
  if (frame.flags.PAD_LOW) {
    Iif (frame.flags.PAD_HIGH) {
      paddingLength = (buffer.readUInt8(dataOffset) & 0xff) * 256;
      dataOffset += 1;
    }
    paddingLength += (buffer.readUInt8(dataOffset) & 0xff);
    dataOffset += 1;
  } else Iif (frame.flags.PAD_HIGH) {
    return 'DATA frame got PAD_HIGH without PAD_LOW';
  }
 
  Iif (frame.flags.COMPRESSED) {
    return 'DATA frame received COMPRESSED data (unsupported)';
  }
 
  if (paddingLength) {
    frame.data = buffer.slice(dataOffset, -1 * paddingLength);
  } else {
    frame.data = buffer.slice(dataOffset);
  }
};
 
// [HEADERS](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.2)
// --------------------------------------------------------------
//
// The HEADERS frame (type=0x1) allows the sender to create a stream.
//
// The HEADERS frame defines the following flags:
//
// * END_STREAM (0x1):
//   Bit 1 being set indicates that this frame is the last that the endpoint will send for the
//   identified stream.
// * END_SEGMENT (0x2):
//   Bit 2 being set indicates that this frame is the last for the current segment. Intermediaries
//   MUST NOT coalesce frames across a segment boundary and MUST preserve segment boundaries when
//   forwarding frames.
// * END_HEADERS (0x4):
//   The END_HEADERS bit indicates that this frame contains the entire payload necessary to provide
//   a complete set of headers.
// * PAD_LOW (0x08):
//   Bit 5 being set indicates that the Pad Low field is present.
// * PAD_HIGH (0x10):
//   Bit 6 being set indicates that the Pad High field is present. This bit MUST NOT be set unless
//   the PAD_LOW flag is also set. Endpoints that receive a frame with PAD_HIGH set and PAD_LOW
//   cleared MUST treat this as a connection error of type PROTOCOL_ERROR.
 
frameTypes[0x1] = 'HEADERS';
 
frameFlags.HEADERS = ['END_STREAM', 'END_SEGMENT', 'END_HEADERS', 'PAD_LOW', 'PAD_HIGH', 'PRIORITY'];
 
typeSpecificAttributes.HEADERS = ['priorityDependency', 'priorityWeight', 'exclusiveDependency', 'headers', 'data'];
 
//      0                   1                   2                   3
//      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//     | Pad High? (8) |  Pad Low? (8) |
//     +-+-------------+---------------+-------------------------------+
//     |E|                 Stream Dependency? (31)                     |
//     +-+-------------+-----------------------------------------------+
//     |  Weight? (8)  |
//     +-+-------------+-----------------------------------------------+
//     |                   Header Block Fragment (*)                 ...
//     +---------------------------------------------------------------+
//     |                           Padding (*)                       ...
//     +---------------------------------------------------------------+
//
// The payload of a HEADERS frame contains a Headers Block
 
Serializer.HEADERS = function writeHeadersPriority(frame, buffers) {
  if (frame.flags.PRIORITY) {
    var buffer = new Buffer(5);
    assert((0 <= frame.priorityDependency) && (frame.priorityDependency <= 0x7fffffff), frame.priorityDependency);
    buffer.writeUInt32BE(frame.priorityDependency, 0);
    if (frame.exclusiveDependency) {
      buffer[0] |= 0x80;
    }
    assert((0 <= frame.priorityWeight) && (frame.priorityWeight <= 0xff), frame.priorityWeight);
    buffer.writeUInt8(frame.priorityWeight, 4);
    buffers.push(buffer);
  }
  buffers.push(frame.data);
};
 
Deserializer.HEADERS = function readHeadersPriority(buffer, frame) {
  var dataOffset = 0;
  var paddingLength = 0;
  if (frame.flags.PAD_LOW) {
    Iif (frame.flags.PAD_HIGH) {
      paddingLength = (buffer.readUInt8(dataOffset) & 0xff) * 256;
      dataOffset += 1;
    }
    paddingLength += (buffer.readUInt8(dataOffset) & 0xff);
    dataOffset += 1;
  } else Iif (frame.flags.PAD_HIGH) {
    return 'HEADERS frame got PAD_HIGH without PAD_LOW';
  }
 
  if (frame.flags.PRIORITY) {
    var dependencyData = new Buffer(4);
    buffer.copy(dependencyData, 0, dataOffset, dataOffset + 4);
    dataOffset += 4;
    frame.exclusiveDependency = !!(dependencyData[0] & 0x80);
    dependencyData[0] &= 0x7f;
    frame.priorityDependency = dependencyData.readUInt32BE(0);
    frame.priorityWeight = buffer.readUInt8(dataOffset);
    dataOffset += 1;
  }
 
  if (paddingLength) {
    frame.data = buffer.slice(dataOffset, -1 * paddingLength);
  } else {
    frame.data = buffer.slice(dataOffset);
  }
};
 
// [PRIORITY](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.3)
// -------------------------------------------------------
//
// The PRIORITY frame (type=0x2) specifies the sender-advised priority of a stream.
//
// The PRIORITY frame does not define any flags.
 
frameTypes[0x2] = 'PRIORITY';
 
frameFlags.PRIORITY = [];
 
typeSpecificAttributes.PRIORITY = ['priorityDependency', 'priorityWeight', 'exclusiveDependency'];
 
//      0                   1                   2                   3
//      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//     |E|                 Stream Dependency? (31)                     |
//     +-+-------------+-----------------------------------------------+
//     |  Weight? (8)  |
//     +-+-------------+
//
// The payload of a PRIORITY frame contains an exclusive bit, a 31-bit dependency, and an 8-bit weight
 
Serializer.PRIORITY = function writePriority(frame, buffers) {
  var buffer = new Buffer(5);
  assert((0 <= frame.priorityDependency) && (frame.priorityDependency <= 0x7fffffff), frame.priorityDependency);
  buffer.writeUInt32BE(frame.priorityDependency, 0);
  if (frame.exclusiveDependency) {
    buffer[0] |= 0x80;
  }
  assert((0 <= frame.priorityWeight) && (frame.priorityWeight <= 0xff), frame.priorityWeight);
  buffer.writeUInt8(frame.priorityWeight, 4);
 
  buffers.push(buffer);
};
 
Deserializer.PRIORITY = function readPriority(buffer, frame) {
  var dependencyData = new Buffer(4);
  buffer.copy(dependencyData, 0, 0, 4);
  frame.exclusiveDependency = !!(dependencyData[0] & 0x80);
  dependencyData[0] &= 0x7f;
  frame.priorityDependency = dependencyData.readUInt32BE(0);
  frame.priorityWeight = buffer.readUInt8(4);
};
 
// [RST_STREAM](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.4)
// -----------------------------------------------------------
//
// The RST_STREAM frame (type=0x3) allows for abnormal termination of a stream.
//
// No type-flags are defined.
 
frameTypes[0x3] = 'RST_STREAM';
 
frameFlags.RST_STREAM = [];
 
typeSpecificAttributes.RST_STREAM = ['error'];
 
//      0                   1                   2                   3
//      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//     |                         Error Code (32)                       |
//     +---------------------------------------------------------------+
//
// The RST_STREAM frame contains a single unsigned, 32-bit integer identifying the error
// code (see Error Codes). The error code indicates why the stream is being terminated.
 
Serializer.RST_STREAM = function writeRstStream(frame, buffers) {
  var buffer = new Buffer(4);
  var code = errorCodes.indexOf(frame.error);
  assert((0 <= code) && (code <= 0xffffffff), code);
  buffer.writeUInt32BE(code, 0);
  buffers.push(buffer);
};
 
Deserializer.RST_STREAM = function readRstStream(buffer, frame) {
  frame.error = errorCodes[buffer.readUInt32BE(0)];
};
 
// [SETTINGS](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.5)
// -------------------------------------------------------
//
// The SETTINGS frame (type=0x4) conveys configuration parameters that affect how endpoints
// communicate.
//
// The SETTINGS frame defines the following flag:
 
// * ACK (0x1):
//   Bit 1 being set indicates that this frame acknowledges receipt and application of the peer's
//   SETTINGS frame.
frameTypes[0x4] = 'SETTINGS';
 
frameFlags.SETTINGS = ['ACK'];
 
typeSpecificAttributes.SETTINGS = ['settings'];
 
// The payload of a SETTINGS frame consists of zero or more settings. Each setting consists of an
// 8-bit identifier, and an unsigned 32-bit value.
//
//      0                   1                   2                   3
//      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//     |  Identifier(8)  |                  Value (32)                 |
//     +-----------------+---------------------------------------------+
//     ...Value          |
//     +-----------------+
//
// Each setting in a SETTINGS frame replaces the existing value for that setting.  Settings are
// processed in the order in which they appear, and a receiver of a SETTINGS frame does not need to
// maintain any state other than the current value of settings.  Therefore, the value of a setting
// is the last value that is seen by a receiver. This permits the inclusion of the same settings
// multiple times in the same SETTINGS frame, though doing so does nothing other than waste
// connection capacity.
 
Serializer.SETTINGS = function writeSettings(frame, buffers) {
  var settings = [], settingsLeft = Object.keys(frame.settings);
  definedSettings.forEach(function(setting, id) {
    if (setting.name in frame.settings) {
      settingsLeft.splice(settingsLeft.indexOf(setting.name), 1);
      var value = frame.settings[setting.name];
      settings.push({ id: id, value: setting.flag ? Boolean(value) : value });
    }
  });
  assert(settingsLeft.length === 0, 'Unknown settings: ' + settingsLeft.join(', '));
 
  var buffer = new Buffer(settings.length * 5);
  for (var i = 0; i < settings.length; i++) {
    buffer.writeUInt8(settings[i].id & 0xff, i*5);
    buffer.writeUInt32BE(settings[i].value, i*5 + 1);
  }
 
  buffers.push(buffer);
};
 
Deserializer.SETTINGS = function readSettings(buffer, frame, role) {
  frame.settings = {};
  
  // Receipt of a SETTINGS frame with the ACK flag set and a length
  // field value other than 0 MUST be treated as a connection error
  // (Section 5.4.1) of type FRAME_SIZE_ERROR.
  Iif(frame.flags.ACK && buffer.length != 0) {
    return 'FRAME_SIZE_ERROR';
  }
 
  Iif (buffer.length % 5 !== 0) {
    return 'PROTOCOL_ERROR';
  }
  for (var i = 0; i < buffer.length / 5; i++) {
    var id = buffer.readUInt8(i*5) & 0xff;
    var setting = definedSettings[id];
    Eif (setting) {
      Iif (role == 'CLIENT' && setting.name == 'SETTINGS_ENABLE_PUSH') {
        return 'SETTINGS frame on client got SETTINGS_ENABLE_PUSH';
      }
      var value = buffer.readUInt32BE(i*5 + 1);
      frame.settings[setting.name] = setting.flag ? Boolean(value & 0x1) : value;
    } else {
      /* Unknown setting, protocol error */
      return 'SETTINGS frame got unknown setting type';
    }
  }
};
 
// The following settings are defined:
var definedSettings = [];
 
// * SETTINGS_HEADER_TABLE_SIZE (1):
//   Allows the sender to inform the remote endpoint of the size of the header compression table
//   used to decode header blocks.
definedSettings[1] = { name: 'SETTINGS_HEADER_TABLE_SIZE', flag: false };
 
// * SETTINGS_ENABLE_PUSH (2):
//   This setting can be use to disable server push. An endpoint MUST NOT send a PUSH_PROMISE frame
//   if it receives this setting set to a value of 0. The default value is 1, which indicates that
//   push is permitted.
definedSettings[2] = { name: 'SETTINGS_ENABLE_PUSH', flag: true };
 
// * SETTINGS_MAX_CONCURRENT_STREAMS (3):
//   indicates the maximum number of concurrent streams that the sender will allow.
definedSettings[3] = { name: 'SETTINGS_MAX_CONCURRENT_STREAMS', flag: false };
 
// * SETTINGS_INITIAL_WINDOW_SIZE (4):
//   indicates the sender's initial stream window size (in bytes) for new streams.
definedSettings[4] = { name: 'SETTINGS_INITIAL_WINDOW_SIZE', flag: false };
 
// * SETTINGS_COMPRESS_DATA (5):
//   this setting is used to enable GZip compression of DATA frames. A value of 1 indicates that
//   DATA frames MAY be compressed. A value of 0 indicates that compression is not permitted.
//   The initial value is 0.
definedSettings[5] = { name: 'SETTINGS_COMPRESS_DATA', flag: true };
 
// [PUSH_PROMISE](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.6)
// ---------------------------------------------------------------
//
// The PUSH_PROMISE frame (type=0x5) is used to notify the peer endpoint in advance of streams the
// sender intends to initiate.
//
// The PUSH_PROMISE frame defines the following flags:
//
// * END_PUSH_PROMISE (0x4):
//   The END_PUSH_PROMISE bit indicates that this frame contains the entire payload necessary to
//   provide a complete set of headers.
 
frameTypes[0x5] = 'PUSH_PROMISE';
 
frameFlags.PUSH_PROMISE = ['RESERVED1', 'RESERVED2', 'END_PUSH_PROMISE', 'PAD_LOW', 'PAD_HIGH'];
 
typeSpecificAttributes.PUSH_PROMISE = ['promised_stream', 'headers', 'data'];
 
//      0                   1                   2                   3
//      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//     |X|                Promised-Stream-ID (31)                      |
//     +-+-------------------------------------------------------------+
//     |                    Header Block (*)                         ...
//     +---------------------------------------------------------------+
//
// The PUSH_PROMISE frame includes the unsigned 31-bit identifier of
// the stream the endpoint plans to create along with a minimal set of headers that provide
// additional context for the stream.
 
Serializer.PUSH_PROMISE = function writePushPromise(frame, buffers) {
  var buffer = new Buffer(4);
 
  var promised_stream = frame.promised_stream;
  assert((0 <= promised_stream) && (promised_stream <= 0x7fffffff), promised_stream);
  buffer.writeUInt32BE(promised_stream, 0);
 
  buffers.push(buffer);
  buffers.push(frame.data);
};
 
Deserializer.PUSH_PROMISE = function readPushPromise(buffer, frame) {
  var dataOffset = 0;
  var paddingLength = 0;
  if (frame.flags.PAD_LOW) {
    Iif (frame.flags.PAD_HIGH) {
      paddingLength = (buffer.readUInt8(dataOffset) & 0xff) * 256;
      dataOffset += 1;
    }
    paddingLength += (buffer.readUInt8(dataOffset) & 0xff);
    dataOffset += 1;
  } else Iif (frame.flags.PAD_HIGH) {
    return 'PUSH_PROMISE frame got PAD_HIGH without PAD_LOW';
  }
  frame.promised_stream = buffer.readUInt32BE(dataOffset) & 0x7fffffff;
  dataOffset += 4;
  if (paddingLength) {
    frame.data = buffer.slice(dataOffset, -1 * paddingLength);
  } else {
    frame.data = buffer.slice(dataOffset);
  }
};
 
// [PING](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.7)
// -----------------------------------------------
//
// The PING frame (type=0x6) is a mechanism for measuring a minimal round-trip time from the
// sender, as well as determining whether an idle connection is still functional.
//
// The PING frame defines one type-specific flag:
//
// * ACK (0x1):
//   Bit 1 being set indicates that this PING frame is a PING response.
 
frameTypes[0x6] = 'PING';
 
frameFlags.PING = ['ACK'];
 
typeSpecificAttributes.PING = ['data'];
 
// In addition to the frame header, PING frames MUST contain 8 additional octets of opaque data.
 
Serializer.PING = function writePing(frame, buffers) {
  buffers.push(frame.data);
};
 
Deserializer.PING = function readPing(buffer, frame) {
  Iif (buffer.length !== 8) {
    return 'FRAME_SIZE_ERROR';
  }
  frame.data = buffer;
};
 
// [GOAWAY](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.8)
// ---------------------------------------------------
//
// The GOAWAY frame (type=0x7) informs the remote peer to stop creating streams on this connection.
//
// The GOAWAY frame does not define any flags.
 
frameTypes[0x7] = 'GOAWAY';
 
frameFlags.GOAWAY = [];
 
typeSpecificAttributes.GOAWAY = ['last_stream', 'error'];
 
//      0                   1                   2                   3
//      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//     |X|                  Last-Stream-ID (31)                        |
//     +-+-------------------------------------------------------------+
//     |                      Error Code (32)                          |
//     +---------------------------------------------------------------+
//
// The last stream identifier in the GOAWAY frame contains the highest numbered stream identifier
// for which the sender of the GOAWAY frame has received frames on and might have taken some action
// on.
//
// The GOAWAY frame also contains a 32-bit error code (see Error Codes) that contains the reason for
// closing the connection.
 
Serializer.GOAWAY = function writeGoaway(frame, buffers) {
  var buffer = new Buffer(8);
 
  var last_stream = frame.last_stream;
  assert((0 <= last_stream) && (last_stream <= 0x7fffffff), last_stream);
  buffer.writeUInt32BE(last_stream, 0);
 
  var code = errorCodes.indexOf(frame.error);
  assert((0 <= code) && (code <= 0xffffffff), code);
  buffer.writeUInt32BE(code, 4);
 
  buffers.push(buffer);
};
 
Deserializer.GOAWAY = function readGoaway(buffer, frame) {
  frame.last_stream = buffer.readUInt32BE(0) & 0x7fffffff;
  frame.error = errorCodes[buffer.readUInt32BE(4)];
};
 
// [WINDOW_UPDATE](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.9)
// -----------------------------------------------------------------
//
// The WINDOW_UPDATE frame (type=0x8) is used to implement flow control.
//
// The WINDOW_UPDATE frame does not define any flags.
 
frameTypes[0x8] = 'WINDOW_UPDATE';
 
frameFlags.WINDOW_UPDATE = [];
 
typeSpecificAttributes.WINDOW_UPDATE = ['window_size'];
 
// The payload of a WINDOW_UPDATE frame is a 32-bit value indicating the additional number of bytes
// that the sender can transmit in addition to the existing flow control window. The legal range
// for this field is 1 to 2^31 - 1 (0x7fffffff) bytes; the most significant bit of this value is
// reserved.
 
Serializer.WINDOW_UPDATE = function writeWindowUpdate(frame, buffers) {
  var buffer = new Buffer(4);
 
  var window_size = frame.window_size;
  assert((0 <= window_size) && (window_size <= 0x7fffffff), window_size);
  buffer.writeUInt32BE(window_size, 0);
 
  buffers.push(buffer);
};
 
Deserializer.WINDOW_UPDATE = function readWindowUpdate(buffer, frame) {
  Iif (buffer.length !== WINDOW_UPDATE_PAYLOAD_SIZE) {
    return 'FRAME_SIZE_ERROR';
  }
  frame.window_size = buffer.readUInt32BE(0) & 0x7fffffff;
};
 
// [CONTINUATION](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.10)
// ------------------------------------------------------------
//
// The CONTINUATION frame (type=0x9) is used to continue a sequence of header block fragments.
//
// The CONTINUATION frame defines the following flag:
//
// * END_HEADERS (0x4):
//   The END_HEADERS bit indicates that this frame ends the sequence of header block fragments
//   necessary to provide a complete set of headers.
// * PAD_LOW (0x08):
//   Bit 5 being set indicates that the Pad Low field is present.
// * PAD_HIGH (0x10):
//   Bit 6 being set indicates that the Pad High field is present. This bit MUST NOT be set unless
//   the PAD_LOW flag is also set. Endpoints that receive a frame with PAD_HIGH set and PAD_LOW
//   cleared MUST treat this as a connection error of type PROTOCOL_ERROR.
 
frameTypes[0x9] = 'CONTINUATION';
 
frameFlags.CONTINUATION = ['RESERVED1', 'RESERVED2', 'END_HEADERS', 'PAD_LOW', 'PAD_HIGH'];
 
typeSpecificAttributes.CONTINUATION = ['headers', 'data'];
 
Serializer.CONTINUATION = function writeContinuation(frame, buffers) {
  buffers.push(frame.data);
};
 
Deserializer.CONTINUATION = function readContinuation(buffer, frame) {
  var dataOffset = 0;
  var paddingLength = 0;
  if (frame.flags.PAD_LOW) {
    Iif (frame.flags.PAD_HIGH) {
      paddingLength = (buffer.readUInt8(dataOffset) & 0xff) * 256;
      dataOffset += 1;
    }
    paddingLength += (buffer.readUInt8(dataOffset) & 0xff);
    dataOffset += 1;
  } else Iif (frame.flags.PAD_HIGH) {
    return 'CONTINUATION frame got PAD_HIGH without PAD_LOW';
  }
  if (paddingLength) {
    frame.data = buffer.slice(dataOffset, -1 * paddingLength);
  } else {
    frame.data = buffer.slice(dataOffset);
  }
};
 
// [ALTSVC](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.11)
// ------------------------------------------------------------
//
// The ALTSVC frame (type=0xA) advertises the availability of an alternative service to the client.
//
// The ALTSVC frame does not define any flags.
 
frameTypes[0xA] = 'ALTSVC';
 
frameFlags.ALTSVC = [];
 
//     0                   1                   2                   3
//     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |                          Max-Age (32)                         |
//    +-------------------------------+----------------+--------------+
//    |            Port (16)          |  Reserved (8)  | PID_LEN (8)  |
//    +-------------------------------+----------------+--------------+
//    |                        Protocol-ID (*)                        |
//    +---------------+-----------------------------------------------+
//    | HOST_LEN (8)  |                   Host (*)                  ...
//    +---------------+-----------------------------------------------+
//    |                          Origin? (*)                        ...
//    +---------------------------------------------------------------+
//
// The ALTSVC frame contains the following fields:
//
// Max-Age: An unsigned, 32-bit integer indicating the freshness
//    lifetime of the alternative service association, as per [ALT-SVC](http://tools.ietf.org/html/draft-ietf-httpbis-alt-svc-01)
//    section 2.2.
//
// Port: An unsigned, 16-bit integer indicating the port that the
//    alternative service is available upon.
//
// Reserved: For future use. Senders MUST set these bits to '0', and
//    recipients MUST ignore them.
//
// PID_LEN: An unsigned, 8-bit integer indicating the length, in
//    octets, of the Protocol-ID field.
//
// Protocol-ID: A sequence of bytes (length determined by PID_LEN)
//    containing the ALPN protocol identifier of the alternative
//    service.
//
// HOST_LEN: An unsigned, 8-bit integer indicating the length, in
//    octets, of the Host field.
//
// Host: A sequence of characters (length determined by HOST_LEN)
//    containing an ASCII string indicating the host that the
//    alternative service is available upon. An internationalized
//    domain [IDNA] MUST be expressed using A-labels.
//
// Origin: An optional sequence of characters (length determined by
//    subtracting the length of all lpreceding fields from the frame
//    length) containing ASCII serialisation of an origin ([RFC6454](http://tools.ietf.org/html/rfc6454),
//    Section 6.2) that the alternate service is applicable to.
 
typeSpecificAttributes.ALTSVC = ['maxAge', 'port', 'protocolID', 'host',
                                 'origin'];
 
Serializer.ALTSVC = function writeAltSvc(frame, buffers) {
  var buffer = new Buffer(8);
  buffer.writeUInt32BE(frame.maxAge, 0);
  buffer.writeUInt16BE(frame.port, 4);
  buffer.writeUInt8(0, 6);
  buffer.writeUInt8(frame.protocolID.length, 7);
  buffers.push(buffer);
 
  buffers.push(new Buffer(frame.protocolID, 'ascii'));
 
  buffer = new Buffer(1);
  buffer.writeUInt8(frame.host.length, 0);
  buffers.push(buffer);
 
  buffers.push(new Buffer(frame.host, 'ascii'));
 
  buffers.push(new Buffer(frame.origin, 'ascii'));
};
 
Deserializer.ALTSVC = function readAltSvc(buffer, frame) {
  frame.maxAge = buffer.readUInt32BE(0);
  frame.port = buffer.readUInt16BE(4);
  var pidLength = buffer.readUInt8(7);
  frame.protocolID = buffer.toString('ascii', 8, 8 + pidLength);
  var hostLength = buffer.readUInt8(8 + pidLength);
  frame.host = buffer.toString('ascii', 9 + pidLength, 9 + pidLength + hostLength);
  frame.origin = buffer.toString('ascii', 9 + pidLength + hostLength);
};
 
// [BLOCKED](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-6.12)
// ------------------------------------------------------------
//
// The BLOCKED frame (type=0xB) indicates that the sender is unable to send data
// due to a closed flow control window.
//
// The BLOCKED frame does not define any flags and contains no payload.
 
frameTypes[0xB] = 'BLOCKED';
 
frameFlags.BLOCKED = [];
 
typeSpecificAttributes.BLOCKED = [];
 
Serializer.BLOCKED = function writeBlocked(frame, buffers) {
};
 
Deserializer.BLOCKED = function readBlocked(buffer, frame) {
};
 
// [Error Codes](http://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-7)
// ------------------------------------------------------------
 
var errorCodes = [
  'NO_ERROR',
  'PROTOCOL_ERROR',
  'INTERNAL_ERROR',
  'FLOW_CONTROL_ERROR',
  'SETTINGS_TIMEOUT',
  'STREAM_CLOSED',
  'FRAME_SIZE_ERROR',
  'REFUSED_STREAM',
  'CANCEL',
  'COMPRESSION_ERROR',
  'CONNECT_ERROR',
  'ENHANCE_YOUR_CALM',
  'INADEQUATE_SECURITY'
];
 
// Logging
// -------
 
// [Bunyan serializers](https://github.com/trentm/node-bunyan#serializers) to improve logging output
// for debug messages emitted in this component.
exports.serializers = {};
 
// * `frame` serializer: it transforms data attributes from Buffers to hex strings and filters out
//   flags that are not present.
var frameCounter = 0;
exports.serializers.frame = function(frame) {
  Iif (!frame) {
    return null;
  }
 
  if ('id' in frame) {
    return frame.id;
  }
 
  frame.id = frameCounter;
  frameCounter += 1;
 
  var logEntry = { id: frame.id };
  genericAttributes.concat(typeSpecificAttributes[frame.type]).forEach(function(name) {
    logEntry[name] = frame[name];
  });
 
  if (frame.data instanceof Buffer) {
    Iif (logEntry.data.length > 50) {
      logEntry.data = frame.data.slice(0, 47).toString('hex') + '...';
    } else {
      logEntry.data = frame.data.toString('hex');
    }
 
    Eif (!('length' in logEntry)) {
      logEntry.length = frame.data.length;
    }
  }
 
  Iif (frame.promised_stream instanceof Object) {
    logEntry.promised_stream = 'stream-' + frame.promised_stream.id;
  }
 
  logEntry.flags = Object.keys(frame.flags || {}).filter(function(name) {
    return frame.flags[name] === true;
  });
 
  return logEntry;
};
 
// * `data` serializer: it simply transforms a buffer to a hex string.
exports.serializers.data = function(data) {
  return data.toString('hex');
};