all files / bpmux/ index.js

100% Statements 361/361
100% Branches 186/186
100% Functions 35/35
100% Lines 351/351
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 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                11852×   11852×   11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852× 11852×   11852×   3130× 3130× 3130×     11852×   2240× 2240×     11852×   11852×                 6504×   2238×         20×       16358×     456879×     752096×   752096×   751456×     752096×       294865×   272×     294593× 294593× 294593×                                                                 1108×   1108×   1108× 1108× 1108× 1108× 1108× 1108× 1108× 1108× 1108× 1108× 1108× 1108× 1108× 1108× 1108× 1108× 1108×   1108×   1108×   536×   673927× 673927×   1347854×         1108×   1108×         1108×   1108×     2149× 1077×   1077×   2024×   2000×       1077×       2149× 1077×   1077×   2020×   2004×       1077×     1108× 1108×   1108× 1108×     64×   64×   48×       64×     1108× 1108× 1108×   1108×   223×   223×   167×       1108×   1370470×   1370470×   2739863× 2739863×   2739863×   1370470×     1369393×   454692×   450680×     454692×   454684×       16×       454668×           914701×     914641× 914641×     914701×   914565×     914561×             914565× 914565×                 1376536×   272× 272×     1376264×       914561×   914545×                     1032× 1032×   1031×         450870× 450870×   450870×     450870×   450870×       450870×   450870×     914545×   5564×       5560× 5560×     914541×   901863×     1059× 1059× 1059× 1059×           450104× 449976× 449976×     450680× 450680× 450680×     16× 16×     901735×     12678×     71× 71×         958× 894× 894×     10913× 10849×   10088× 10088×   10088×   10849× 10849×     10849× 10849× 10849× 10849×   968×       9881×   10849×     10845×   67× 67× 67× 67×   10849× 10849×       716×     16× 16×         2242×   2242×   2238×         3130×   1138×   1138× 1138×   1138×       17326× 17318×   11757×   11757×   10865×     11757×   11757× 11757× 11757×   11757×   10865× 10865×     11757×     11757× 11757×   11757×                         751456×       11957×     739499×     739499×         288797×     450702×   450702×   10×   450692×   1701×       448991×     450702× 450702× 450702× 450702× 450702×   450702×         450702×       773853×   773853×   242×       69008371×       68557683×     450688×               224×       450688×         450688×   450688× 450688× 450688×   450688×   450688× 450688×   450688×   450687×     450688×   450688×   294593× 294593× 294593× 294593× 294593×     450688× 450688×     773611×   1224139× 1224139×   1224139×   2805×     1221334×   1221334×   1221334×   770806×     450528×   450528×   223819×     450528×   450528×   223819×           773853×   773853×       773852×   773852×   773853× 773853×     773852×                                         6298×       6296×       6295×       6294×   6294×     6292×   6292×   5374×   5374×       6292×     6294×   16×     6278×   6278×   6287×   6287×   6276× 6276×     11×            
/**
# bpmux   [![Build Status](https://travis-ci.org/davedoesdev/bpmux.png)](https://travis-ci.org/davedoesdev/bpmux) [![Coverage Status](https://coveralls.io/repos/davedoesdev/bpmux/badge.png?branch=master&service=github)](https://coveralls.io/r/davedoesdev/bpmux?branch=master) [![NPM version](https://badge.fury.io/js/bpmux.png)](http://badge.fury.io/js/bpmux)
 
Node stream multiplexing with back-pressure on each stream.
 
- Run more than one [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex) over a carrier `Duplex`.
- Exerts back-pressure on each multiplexed stream and the underlying carrier stream.
- Each multiplexed stream's back-pressure is handled separately while respecting the carrier's capacity.
- Unit tests with 100% coverage.
- Tested with TCP streams and [Primus](https://github.com/primus/primus) (using [primus-backpressure](https://github.com/davedoesdev/primus-backpressure)) - works in the browser!
- Browser unit tests using [webpack](http://webpack.github.io/) and [nwjs](http://nwjs.io/).
 
The API is described [here](#api).
 
## Example
 
Multiplexing multiple streams over a single TCP stream:
 
```javascript
var net = require('net'),
    crypto = require('crypto'),
    assert = require('assert'),
    BPMux = require('bpmux').BPMux,
    sent = [];
 
net.createServer(function (c)
{
    var received = [], ended = 0;
 
    new BPMux(c).on('handshake', function (duplex)
    {
        var accum = '';
 
        duplex.on('readable', function ()
        {
            var data = this.read();
            if (data)
            {
                accum += data.toString('hex');
            }
        });
 
        duplex.on('end', function ()
        {
            received.push(accum);
 
            ended += 1;
            assert(ended <= 10);
            if (ended === 10)
            {
                assert.deepEqual(received.sort(), sent.sort());
            }
        });
    });
}).listen(7000, function ()
{
    var mux = new BPMux(net.createConnection(7000)), i;
 
    function multiplex(n)
    {
        var data = crypto.randomBytes(n * 100);
        mux.multiplex().end(data);
        sent.push(data.toString('hex'));
    }
 
    for (i = 1; i <= 10; i += 1)
    {
        multiplex(i);
    }
});
```
 
## Another Example
 
Multiple return pipes to the browser, multiplexed over a single Primus connection:
 
```javascript
var PrimusDuplex = require('primus-backpressure').PrimusDuplex,
    BPMux = require('bpmux').BPMux,
    http = require('http'),
    path = require('path'),
    crypto = require('crypto'),
    stream = require('stream'),
    assert = require('assert'),
    finalhandler = require('finalhandler'),
    serve_static = require('serve-static'),
    Primus = require('primus'),
    serve = serve_static(__dirname);
 
http.createServer(function (req, res)
{
    serve(req, res, finalhandler(req, res));
}).listen(7500, function ()
{
    var primus = new Primus(this);
 
    primus.on('connection', function (spark)
    {
        var mux = new BPMux(new PrimusDuplex(spark)), ended = 0, i;
 
        function multiplex(n)
        {
            var buf = crypto.randomBytes(10 * 1024),
                buf_stream = new stream.PassThrough(),
                bufs = [],
                duplex = mux.multiplex({ handshake_data: new Buffer([n]) });
 
            buf_stream.end(buf);
            buf_stream.pipe(duplex);
 
            duplex.on('readable', function ()
            {
                var data;
 
                while (true)
                {
                    data = this.read();
                    if (data === null)
                    {
                        break;
                    }
                    bufs.push(data);
                }
            });
 
            duplex.on('end', function ()
            {
                console.log('end', n);
                ended += 1;
                assert(ended <= 10);
                assert.deepEqual(Buffer.concat(bufs), buf);
            });
        }
 
        for (i = 0; i < 10; i += 1)
        {
            multiplex(i);
        }
    });
    
    console.log('Point your browser to http://localhost:7500/loader.html');
});
```
 
The HTML (`loader.html`) for the browser-side of this example:
 
```html
<html>
  <head>
    <title>BPMux Test Runner</title>
    <script type="text/javascript" src="/primus/primus.js"></script>
    <script type="text/javascript" src="bundle.js"></script>
    <script type="text/javascript" src="loader.js"></script>
  </head>
  <body onload='doit()'>
  </body>
</html>
```
 
The browser-side code (`loader.js`):
 
```javascript
function doit()
{
    var mux = new BPMux(new PrimusDuplex(new Primus({ strategy: false })));
 
    mux.on('handshake', function (duplex, handshake_data)
    {
        console.log("handshake", handshake_data[0]);
        duplex.pipe(duplex);
 
        duplex.on('end', function ()
        {
            console.log('end', handshake_data[0]);
        });
    });
}
```
 
The browser-side dependencies (`bundle.js`) can be produced by webpack from:
 
```javascript
PrimusDuplex = require('primus-backpressure').PrimusDuplex;
BPMux = require('bpmux').BPMux;
```
 
## Installation
 
```shell
npm install bpmux
```
 
## Licence
 
[MIT](LICENCE)
 
## Test
 
Over TCP (long test):
 
```shell
grunt test
```
 
Over TCP (quick test):
 
```shell
grunt test-fast
```
 
Over Primus (using nwjs to run browser- and server-side):
 
```shell
grunt test-browser
```
 
The examples at the top of this page:
 
```shell
grunt test-examples
```
 
## Code Coverage
 
```shell
grunt coverage
```
 
[Instanbul](http://gotwarlost.github.io/istanbul/) results are available [here](http://rawgit.davedoesdev.com/davedoesdev/bpmux/master/coverage/lcov-report/index.html).
 
Coveralls page is [here](https://coveralls.io/r/davedoesdev/bpmux).
 
## Lint
 
```shell
grunt lint
```
 
# API
*/
/*jslint node: true, nomen: true, unparam: true */
'use strict';
 
var util = require('util'),
    Duplex = require('stream').Duplex,
    EventEmitter = require('events').EventEmitter,
    frame = require('frame-stream'),
    max_seq = Math.pow(2, 32),
    TYPE_END = 0,
    TYPE_HANDSHAKE = 1,
    TYPE_STATUS = 2,
    TYPE_FINISHED_STATUS = 3,
    TYPE_DATA = 4,
    TYPE_PRE_HANDSHAKE = 5,
    TYPE_ERROR_END = 6;
 
function BPDuplex(options, mux, chan)
{
    Duplex.call(this, options);
 
    options = options || {};
 
    this._mux = mux;
    this._chan = chan;
    this._max_write_size = options.max_write_size || 0;
    this._check_read_overflow = options.check_read_overflow !== false;
    this._seq = 0;
    this._remote_free = 0;
    this._set_remote_free = false;
    this._data = null;
    this._cb = null;
    this._index = 0;
    this._finished = false;
    this._ended = false;
    this._removed = false;
    this._handshake_sent = false;
    this._handshake_received = false;
    this._end_pending = false;
    this._error_end = false;
    this._error_end_pending = false;
 
    this.on('finish', function ()
    {
        this._finished = true;
        this._mux._send_end(this);
        this._check_remove();
    });
 
    this.on('end', function ()
    {
        this._ended = true;
        this._check_remove();
    });
 
    mux.duplexes.set(chan, this);
 
    if ((mux._max_open > 0) && (mux.duplexes.size === mux._max_open))
    {
        setImmediate(function ()
        {
            mux.emit('full');
        });
    }
}
 
util.inherits(BPDuplex, Duplex);
 
BPDuplex.prototype._check_remove = function ()
{
    if (this._finished && this._ended && !this._removed)
    {
        this._mux._remove(this);
    }
};
 
BPDuplex.prototype.get_channel = function ()
{
    return this._chan;
};
 
BPDuplex.prototype._send_handshake = function (handshake_data)
{
    this._mux._send_handshake(this, handshake_data || new Buffer(0));
};
 
BPDuplex.prototype._read = function () { return undefined; };
 
BPDuplex.prototype.read = function (size, send_status)
{
    var r = Duplex.prototype.read.call(this, size);
 
    if (send_status !== false)
    {
        this._mux._send_status(this);
    }
 
    return r;
};
 
BPDuplex.prototype._write = function (data, encoding, cb)
{
    if (data.length === 0)
    {
        return cb();
    }
 
    this._data = data;
    this._cb = cb;
    this._mux._send();
};
 
BPDuplex.prototype.peer_error_then_end = function (chunk, encoding, cb)
{
    this._error_end = true;
    return this.end(chunk, encoding, cb);
};
 
/**
Constructor for a `BPMux` object which multiplexes more than one [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex) over a carrier `Duplex`.
 
@constructor
@extends events.EventEmitter
 
@param {Duplex} carrier The `Duplex` stream over which other `Duplex` streams will be multiplexed.
 
@param {Object} [options] Configuration options. This is passed down to [`frame-stream`](https://github.com/rkusa/frame-stream). It also supports the following additional properties:
 
  - `{Object} [peer_multiplex_options]` When your `BPMux` object detects a new multiplexed stream from the peer on the carrier, it creates a new `Duplex` and emits a [`peer_multiplex`](#bpmuxeventspeer_multiplexduplex) event. When it creates the `Duplex`, it uses `peer_multiplex_options` to configure it with the following options:
 
    - `{Integer} [max_write_size]` Maximum number of bytes to write to the `Duplex` at once, regardless of how many bytes the peer is free to receive. Defaults to 0 (no limit).
 
    - `{Boolean} [check_read_overflow]` Whether to check if more data than expected is being received. If `true` and the `Duplex`'s high-water mark for reading is exceeded then the `Duplex` emits an `error` event. This should not normally occur unless you add data yourself using [`readable.unshift`](http://nodejs.org/api/stream.html#stream_readable_unshift_chunk) &mdash; in which case you should set `check_read_overflow` to `false`. Defaults to `true`.
 
  - `{Function} [parse_handshake_data(handshake_data)]` When a new stream is multiplexed, the `BPMux` objects at each end of the carrier exchange a handshake message. You can supply application-specific handshake data to add to the handshake message (see [`BPMux.prototype.multiplex`](#bpmuxprototypemultiplexoptions) and [`BPMux.events.handshake`](#bpmuxeventshandshakeduplex-handshake_data-delay_handshake)). By default, when handshake data from the peer is received, it's passed to your application as a raw [`Buffer`](https://nodejs.org/api/buffer.html#buffer_buffer). Use `parse_handshake_data` to specify a custom parser. It will receive the `Buffer` as an argument and should return a value which makes sense to your application.
  
  - `{Boolean} [coalesce_writes]` Whether to batch together writes to the carrier. When the carrier indicates it's ready to receive data, its spare capacity is shared equally between the multiplexed streams. By default, the data from each stream is written separately to the carrier. Specify `true` to write all the data to the carrier in a single write. Depending on the carrier, this can be more performant.
 
  - `{Boolean} [high_channels]` `BPMux` assigns unique channel numbers to multiplexed streams. By default, it assigns numbers in the range [0..2^31). If your application can synchronise the two `BPMux` instances on each end of the carrier stream so they never call [`multiplex`](https://github.com/davedoesdev/bpmux#bpmuxprototypemultiplexoptions) at the same time then you don't need to worry about channel number clashes. For example, one side of the carrier could always call [`multiplex`](https://github.com/davedoesdev/bpmux#bpmuxprototypemultiplexoptions) and the other listen for [`handshake`](https://github.com/davedoesdev/bpmux#bpmuxeventshandshakeduplex-handshake_data-delay_handshake) events. Or they could take it in turns. If you can't synchronise both sides of the carrier, you can get one side to use a different range by specifying `high_channels` as `true`. The `BPMux` with `high_channels` set to `true` will assign channel numbers in the range [2^31..2^32).
 
  - `{Integer} [max_open]` Maximum number of multiplexed streams that can be open at a time. Defaults to 0 (no maximum).
 
  - `{Integer} [max_header_size]` `BPMux` adds a control header to each message it sends, which the receiver reads into memory. The header is of variable length &mdash; for example, handshake messages contain handshake data which can be supplied by the application. `max_header_size` is the maximum number of header bytes to read into memory. If a larger header is received, `BPMux` emits an `error` event. Defaults to 0 (no limit).
*/
function BPMux(carrier, options)
{
    EventEmitter.call(this, options);
 
    options = options || {};
 
    this._max_duplexes = Math.pow(2, 31);
    this._max_open = options.max_open || 0;
    this._max_header_size = options.max_header_size || 0;
    this.duplexes = new Map();
    this._chan = 0;
    this._chan_offset = options.high_channels ? this._max_duplexes : 0;
    this._finished = false;
    this._ended = false;
    this._header_buffers = [];
    this._header_buffer_len = 0;
    this._reading_duplex = null;
    this._peer_multiplex_options = options.peer_multiplex_options;
    this._parse_handshake_data = options.parse_handshake_data;
    this._coalesce_writes = options.coalesce_writes;
    this.carrier = carrier;
    this._sending = false;
    this._send_requested = false;
 
    this._out_stream = frame.encode(options);
 
    if (this._coalesce_writes)
    {
        this._out_stream._pushFrameData = function (bufs)
        {
            var i;
            for (i = 0; i < bufs.length; i += 1)
            {
                this.push(bufs[i]);
            }
        };
    }
 
    this._out_stream.pipe(carrier);
 
    this._in_stream = frame.decode(util._extend(util._extend(
        {}, options),
        {
            unbuffered: true
        }));
    carrier.pipe(this._in_stream);
 
    var ths = this;
 
    function finish()
    {
        if (ths._finished) { return; }
        ths._finished = true;
 
        for (var duplex of ths.duplexes.values())
        {
            if (!duplex._finished)
            {
                duplex.emit('error', new Error('carrier stream finished before duplex finished'));
            }
        }
 
        ths.emit('finish');
    }
 
    function end()
    {
        if (ths._ended) { return; }
        ths._ended = true;
 
        for (var duplex of ths.duplexes.values())
        {
            if (!duplex._ended)
            {
                duplex.emit('error', new Error('carrier stream ended before end message received'));
            }
        }
 
        ths.emit('end');
    }
 
    carrier.on('finish', finish);
    carrier.on('close', finish);
 
    this._in_stream.on('end', end);
    carrier.on('close', end);
 
    function error(err)
    {
        for (var duplex of ths.duplexes.values())
        {
            if (EventEmitter.listenerCount(duplex, 'error') > 0)
            {
                duplex.emit('error', err);
            }
        }
 
        ths.emit('error', err);
    }
 
    carrier.on('error', error);
    this._in_stream.on('error', error);
    this._out_stream.on('error', error);
 
    this._out_stream.on('drain', function ()
    {
        ths._send();
 
        if (this._writableState.length < this._writableState.highWaterMark)
        {
            ths.emit('drain');
        }
    });
 
    this._in_stream.on('readable', function ()
    {
        var data, duplex;
 
        while (true)
        {
            data = this.read();
            duplex = ths._reading_duplex;
 
            if (data === null)
            {
                break;
            }
 
            if (duplex)
            {
                if (data.frameEnd)
                {
                    ths._reading_duplex = null;
                }
 
                if (!duplex._readableState.ended)
                {
                    if (duplex._check_read_overflow &&
                        ((duplex._readableState.length + data.length) >
                         duplex._readableState.highWaterMark))
                    {
                        duplex.emit('error', new Error('too much data'));
                    }
                    else
                    {
                        duplex.push(data);
                    }
                }
            }
            else
            {
                if ((ths._max_header_size <= 0) || 
                    (ths._header_buffer_len < ths._max_header_size))
                {
                    ths._header_buffers.push(data);
                    ths._header_buffer_len += data.length;
                }
 
                if (data.frameEnd)
                {
                    if ((ths._max_header_size <= 0) ||
                        (ths._header_buffer_len < ths._max_header_size))
                    {
                        ths._process_header(Buffer.concat(ths._header_buffers,
                                                          ths._header_buffer_len));
                    }
                    else
                    {
                        ths.emit('error', new Error('header too big'));
                    }
 
                    ths._header_buffers = [];
                    ths._header_buffer_len = 0;
                }
            }
        }
    });
}
 
util.inherits(BPMux, EventEmitter);
 
BPMux.prototype._check_buffer = function (buf, size)
{
    if (buf.length < size)
    {
        this.emit('error', new Error('short buffer length ' + buf.length + ' < ' + size));
        return false;
    }
 
    return true;
};
 
BPMux.prototype._process_header = function (buf)
{
    if (!this._check_buffer(buf, 5)) { return; }
 
    var ths = this,
        type = buf.readUInt8(0, true),
        chan = buf.readUInt32BE(1, true),
        duplex = this.duplexes.get(chan),
        handshake_data,
        handshake_delayed = false,
        dhs,
        free,
        seq;
 
    function delay_handshake()
    {
        handshake_delayed = true;
        return function (handshake_data)
        {
            duplex._send_handshake(handshake_data);
        };
    }
 
    function handle_status()
    {
        free = buf.readUInt32BE(5, true);
        seq = buf.length === 13 ? buf.readUInt32BE(9, true) : 0;
 
        free = duplex._max_write_size > 0 ?
                Math.min(free, duplex._max_write_size) : free;
 
        duplex._remote_free = seq + free - duplex._seq;
 
        if (duplex._seq < seq)
        {
            duplex._remote_free -= max_seq;
        }
 
        duplex._set_remote_free = true;
 
        ths._send();
    }
 
    if ((type !== TYPE_FINISHED_STATUS) && !duplex)
    {
        if ((this._max_open > 0) && (this.duplexes.size === this._max_open))
        {
            return this.emit('full');
        }
 
        duplex = new BPDuplex(this._peer_multiplex_options, this, chan);
        this.emit('peer_multiplex', duplex);
    }
 
    if (duplex && duplex._handshake_received)
    {
        switch (type)
        {
            case TYPE_END:
                duplex._ended = true;
                duplex._check_remove();
                duplex.push(null);
                break;
 
            case TYPE_ERROR_END:
                duplex._ended = true;
                duplex._check_remove();
                duplex.emit('error', new Error('peer error'));
                duplex.push(null);
                break;
 
            case TYPE_STATUS:
            case TYPE_FINISHED_STATUS:
                if (!this._check_buffer(buf, 13)) { return; }
                handle_status();
                break;
 
            case TYPE_DATA:
                duplex._remote_seq = buf.slice(5);
                this._reading_duplex = duplex;
                break;
 
            default:
                this.emit('error', new Error('unknown type: ' + type));
                break;
        }
 
        return;
    }
 
    switch (type)
    {
        case TYPE_END:
            duplex._end_pending = true;
            break;
 
        case TYPE_ERROR_END:
            duplex._error_end_pending = true;
            break;
 
        case TYPE_PRE_HANDSHAKE:
            if (!this._check_buffer(buf, 9)) { return; }
            handle_status();
            break;
 
        case TYPE_HANDSHAKE:
            if (!this._check_buffer(buf, 9)) { return; }
            if (duplex._seq === 0)
            {
                free = buf.readUInt32BE(5, true);
                duplex._remote_free = duplex._max_write_size > 0 ?
                        Math.min(free, duplex._max_write_size) : free;
                duplex._set_remote_free = true;
            }
            duplex._handshake_received = true;
            handshake_data = this._parse_handshake_data ?
                    this._parse_handshake_data(buf.slice(9)) :
                    buf.slice(9);
            dhs = duplex._handshake_sent ? null : delay_handshake;
            this.emit('handshake', duplex, handshake_data, dhs);
            duplex.emit('handshake', handshake_data, dhs);
            if (handshake_delayed)
            {
                this._send_handshake(duplex);
            }
            else
            {
                duplex._send_handshake();
            }
            if (duplex._error_end_pending)
            {
                duplex._ended = true;
                duplex._check_remove();
                duplex.emit('error', new Error('peer error'));
                duplex.push(null);
                duplex._end_pending = false;
            }
            else if (duplex._end_pending)
            {
                duplex._ended = true;
                duplex._check_remove();
                duplex.push(null);
                duplex._end_pending = false;
            }
            this._send();
            break;
 
        case TYPE_FINISHED_STATUS:
            // from old duplex
            break;
 
        default:
            this.emit('error', new Error('expected handshake, got: ' + type));
            break;
    }
};
 
BPMux.prototype._remove = function (duplex)
{
    duplex._removed = true;
 
    if (this.duplexes.delete(duplex._chan))
    {
        this.emit('removed', duplex);
    }
};
 
BPMux.prototype._send_end = function (duplex)
{
    if (this._finished) { return; }
 
    var buf = new Buffer(1 + 4);
 
    buf.writeUInt8(duplex._error_end ? TYPE_ERROR_END : TYPE_END, 0, true);
    buf.writeUInt32BE(duplex._chan, 1, true);
 
    this._out_stream.write(buf);
};
 
BPMux.prototype._send_handshake = function (duplex, handshake_data)
{
    if (this._finished) { return; }
    if (duplex._handshake_sent) { return this._send(); }
    
    var buf, size = 1 + 4 + 4;
 
    if (handshake_data)
    {
        size += handshake_data.length;
    }
 
    buf = new Buffer(size);
 
    buf.writeUInt8(handshake_data ? TYPE_HANDSHAKE : TYPE_PRE_HANDSHAKE, 0, true);
    buf.writeUInt32BE(duplex._chan, 1, true);
    buf.writeUInt32BE(Math.max(duplex._readableState.highWaterMark - duplex._readableState.length, 0), 5, true);
 
    if (handshake_data)
    {
        handshake_data.copy(buf, 9);
        duplex._handshake_sent = true;
    }
 
    var r = this._out_stream.write(buf),
        evname = handshake_data ? 'handshake_sent' : 'pre_handshake_sent';
 
    this.emit(evname, duplex, r);
    duplex.emit(evname, r);
 
    this._send();
};
 
BPMux.prototype._send_status = function (duplex)
{
    // Note: Status messages are sent regardless of remote_free
    // (if the remote peer isn't doing anything it could never be sent and it
    // could be waiting for a status update). 
    // This means every time the app calls read(), a status message wlll be sent
    // to the remote peer. If you want to control when status messages are
    // sent then use the second parameter of read(), send_status.
    // To force sending a status message without actually reading any data,
    // call read(0).
 
    if (this._finished ||
        (duplex._remote_seq === undefined) ||
        (this._reading_duplex === duplex))
    {
        return;
    }
 
    var free = Math.max(duplex._readableState.highWaterMark - duplex._readableState.length, 0),
        buf;
 
    if (duplex._prev_status &&
        (duplex._prev_status.free === free) &&
        // we don't care about contents here, just if it's changed
        (duplex._prev_status.seq === duplex._remote_seq))
    {
        return;
    }
 
    var type;
 
    if (!duplex._handshake_sent)
    {
        type = TYPE_PRE_HANDSHAKE;
    }
    else if (duplex._finished)
    {
        type = TYPE_FINISHED_STATUS;
    }
    else
    {
        type = TYPE_STATUS;
    }
 
    buf = new Buffer(1 + 4 + 4 + duplex._remote_seq.length);
    buf.writeUInt8(type, 0, true);
    buf.writeUInt32BE(duplex._chan, 1, true);
    buf.writeUInt32BE(free, 5, true);
    duplex._remote_seq.copy(buf, 9);
 
    duplex._prev_status = {
        free: free,
        seq: duplex._remote_seq
    };
 
    this._out_stream.write(buf);
};
 
BPMux.prototype.__send = function ()
{
    var ths = this, space, output, n;
 
    if (this._finished)
    {
        return;
    }
 
    function push_output(duplex)
    {
        if ((duplex._data === null) ||
            (duplex._remote_free <= 0) ||
            !duplex._handshake_sent)
        {
            return;
        }
 
        output.push(
        {
            duplex: duplex,
            size: Math.min(duplex._remote_free, duplex._data.length - duplex._index)
        });
    }
 
    function sort_output(a, b)
    {
        return a.size < b.size;
    }
 
    function write_output(info)
    {
        var size = Math.min(info.size, Math.max(Math.floor(space / n), 1)),
            buf = new Buffer(1 + 4 + 4),
            buf2 = info.duplex._data.slice(info.duplex._index, info.duplex._index + size),
            cb;
 
        info.duplex._seq = (info.duplex._seq + size) % max_seq;
        
        buf.writeUInt8(TYPE_DATA, 0, true);
        buf.writeUInt32BE(info.duplex._chan, 1, true);
        buf.writeUInt32BE(info.duplex._seq, 5, true);
 
        info.duplex._set_remote_free = false;
 
        ths._out_stream.write(buf);
        ths._out_stream.write(buf2);
 
        if (!info.duplex._set_remote_free)
        {
            info.duplex._remote_free -= size;
        }
 
        info.duplex._index += size;
 
        if (info.duplex._index === info.duplex._data.length)
        {
            info.duplex._data = null;
            info.duplex._index = 0;
            cb = info.duplex._cb;
            info.duplex._cb = null;
            setImmediate(cb);
        }
 
        space = Math.max(space - size, 0);
        n -= 1;
    }
 
    while (true)
    {
        space = this._out_stream._writableState.highWaterMark - this._out_stream._writableState.length;
        output = [];
 
        if (space <= 0)
        {
            break;
        }
        
        this.duplexes.forEach(push_output);
        
        n = output.length;
 
        if (n === 0)
        {
            break;
        }
 
        output.sort(sort_output);
 
        if (this._coalesce_writes)
        {
            this.carrier.cork();
        }
 
        output.forEach(write_output);
        
        if (this._coalesce_writes)
        {
            this.carrier.uncork();
        }
    }
};
 
BPMux.prototype._send = function ()
{
    this._send_requested = true;
 
    if (this._sending)
    {
        return;
    }
 
    this._sending = true;
 
    while (this._send_requested)
    {
        this._send_requested = false;
        this.__send();
    }
 
    this._sending = false;
};
 
/**
Multiplex a new `stream.Duplex` over the carrier.
 
@param {Object} [options] Configuration options:
 
  - `{Buffer} [handshake_data]` Application-specific handshake data to send to the peer. When a new stream is multiplexed, the `BPMux` objects at each end of the carrier exchange a handshake message. You can optionally supply handshake data to add to the handshake message here. The peer application will receive this when its `BPMux` object emits a [`handshake`](#bpmuxeventshandshakeduplex-handshake_data-delay_handshake) event. Defaults to a zero-length `Buffer`.
  
  - `{Integer} [max_write_size]` Maximum number of bytes to write to the `Duplex` at once, regardless of how many bytes the peer is free to receive. Defaults to 0 (no limit).
 
  - `{Boolean} [check_read_overflow]` Whether to check if more data than expected is being received. If `true` and the `Duplex`'s high-water mark for reading is exceeded then the `Duplex` emits an `error` event. This should not normally occur unless you add data yourself using [`readable.unshift`](http://nodejs.org/api/stream.html#stream_readable_unshift_chunk) &mdash; in which case you should set `check_read_overflow` to `false`. Defaults to `true`.
 
  - `{Integer} [channel]` Unique number for the new stream. `BPMux` identifies each multiplexed stream by giving it a unique number, which it allocates automatically. If you want to do the allocation yourself, specify a channel number here. It's very unlikely you'll need to do this but the option is there. `Duplex` objects managed by `BPMux` expose a `get_channel` method to retrieve their channel number. Defaults to automatic allocation.
  
@return {Duplex} The new `Duplex` which is multiplexed over the carrier. This supports back-pressure using the stream [`readable`](https://nodejs.org/dist/latest-v4.x/docs/api/stream.html#stream_event_readable) event and [`write`](https://nodejs.org/dist/latest-v4.x/docs/api/stream.html#stream_writable_write_chunk_encoding_callback) method.
 
@throws {Error} If there are no channel numbers left to allocate to the new stream, the maximum number of open multiplexed streams would be exceeded or the carrier has finished or ended.
*/
BPMux.prototype.multiplex = function (options)
{
    if ((this._max_open > 0) && (this.duplexes.size === this._max_open))
    {
        this.emit('full');
        throw new Error('full');
    }
 
    if (this.carrier._writableState.finished)
    {
        throw new Error('finished');
    }
 
    if (this.carrier._readableState.ended)
    {
        throw new Error('ended');
    }
 
    var ths = this, chan, next;
 
    options = options || {};
 
    function done(channel)
    {
        var duplex = new BPDuplex(options, ths, channel);
 
        if (!options._delay_handshake)
        {
            setImmediate(function ()
            {
                duplex._send_handshake(options.handshake_data);
            });
        }
 
        return duplex;
    }
 
    if (options.channel !== undefined)
    {
        return done(options.channel);
    }
 
    chan = this._chan;
 
    do
    {
        next = (chan + 1) % this._max_duplexes;
 
        if (!this.duplexes.has(chan + this._chan_offset))
        {
            this._chan = next;
            return done(chan + this._chan_offset);
        }
 
        chan = next;
    }
    while (chan !== this._chan);
 
    this.emit('full');
    throw new Error('full');
};
 
exports.BPMux = BPMux;