Code coverage report for usr/local/google/home/trevj/src/uproxy-lib/build/dev/uproxy-lib/webrtc/peerconnection.js

Statements: 45.13% (88 / 195)      Branches: 14.29% (8 / 56)      Functions: 28.3% (15 / 53)      Lines: 45.13% (88 / 195)      Ignored: none     

All files » usr/local/google/home/trevj/src/uproxy-lib/build/dev/uproxy-lib/webrtc/ » peerconnection.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      1 1 1 1 1 1   1 1 1 1 1   1                                                                 1 1       2 2 2   2                           2                                 2                                                             2                       2       2 1         1         2 1       1 1 1 1           1                                   2                                   2                                               2             2                 2 1 1     2                                     2 1   1     1           2 1 1 1 1               1         2 1 1 1 1                 1           2                         2                                                       2                 2 2 2   2     2     2   2 2       2                 2   2     2     2 2   2                             2 2 2 2       1   1   1     1         1   1 1   1 1             1  
/// <reference path='../../../third_party/typings/es6-promise/es6-promise.d.ts' />
/// <reference path='../../../third_party/freedom-typings/rtcpeerconnection.d.ts' />
/// <reference path='../../../third_party/freedom-typings/freedom-common.d.ts' />
var djb2 = require('../crypto/djb2hash');
var handler = require('../handler/queue');
var datachannel = require('./datachannel');
var signals = require('./signals');
var logging = require('../logging/logging');
var log = new logging.Log('PeerConnection');
// Describes the state of a P2P connection.
(function (State) {
    State[State["WAITING"] = 0] = "WAITING";
    State[State["CONNECTING"] = 1] = "CONNECTING";
    State[State["CONNECTED"] = 2] = "CONNECTED";
    State[State["DISCONNECTED"] = 3] = "DISCONNECTED"; // End-state, cannot change.
})(exports.State || (exports.State = {}));
var State = exports.State;
// A wrapper for peer-connection and it's associated data channels.
// The most important diagram is this one:
// http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSignalingState
//
// Expected call-path to establish a connection...
// FIXME: This is obsolete due to freedom-v0.6 upgrades!
// We start by negotiate connection openning a data channel to make sure that
// the SDP headers have data channels in them.
//   0. negotiateConnection (public version)
//      0.1. openDataChannel -> pc_.createDataChannel
//      0.2. [callback] -> pc_.onnegotiation
//
// Then we start the real connection negotiation...
//   1. [external] negotiateConnection_ (private version)
//      1.1. createOffer_ -> pc_.createOffer
//      1.2. setLocalDescription_ -> pc_.setLocalDescription
//      1.3. signalForPeerQueue.handle -> [external]
//   2. [external] -> handleSignalMessage
//      2.1. setRemoteDescription_ -> pc_.setRemoteDescription
//   3. *[external] -> handleSignalMessage -> pc_.addIceCandidate
//   4. (callback) -> controlDataChannel_.onceOpened
//      4.1. completeConnection_ -> [Fulfill onceConnected]
//
// When the peer starts the connection negotiation:
//   1. [external] -> handleSignalMessage
//      1.1. setRemoteDescription_ -> pc_.setRemoteDescription
//      1.3. createAnswer_
//      1.4. setLocalDescription_
//      1.5. signalForPeerQueue.handle -> [external]
//   2. *[external] -> handleSignalMessage -> pc_.addIceCandidate
//   3. (callback) -> controlDataChannel_.onceOpened
//      3.1. completeConnection_ -> [Fulfill onceConnected]
var PeerConnectionClass = (function () {
    function PeerConnectionClass(pc_, 
        // Public for debugging; note this is not part of the peer connection
        // interface
        peerName_) {
        var _this = this;
        this.pc_ = pc_;
        this.peerName_ = peerName_;
        // Close the peer connection. This function is idempotent.
        this.close = function () {
            log.debug('%1: close', _this.peerName_);
            if (_this.pcState === 1 /* CONNECTING */) {
                _this.rejectConnected_(new Error('close was called while connecting.'));
            }
            _this.pcState = 3 /* DISCONNECTED */;
            _this.fulfillDisconnected_();
            return _this.pc_.getSignalingState().then(function (state) {
                if (state !== 'closed') {
                    // Note is expected to invoke |onSignallingStateChange_|
                    return _this.pc_.close();
                }
            });
        };
        this.closeWithError_ = function (s) {
            if (_this.pcState === 1 /* CONNECTING */) {
                _this.rejectConnected_(new Error(s));
            }
            _this.pcState = 3 /* DISCONNECTED */;
            _this.fulfillDisconnected_();
            _this.pc_.getSignalingState().then(function (state) {
                if (state !== 'closed') {
                    // Note is expected to invoke |onSignallingStateChange_|
                    _this.pc_.close();
                }
            });
        };
        // The RTCPeerConnection signalingState has changed. This state change is
        // the result of either setLocalDescription() or setRemoteDescription()
        // being invoked. Or it can happen when the peer connection gets
        // unexpectedly closed down.
        this.onSignallingStateChange_ = function () {
            _this.pc_.getSignalingState().then(function (state) {
                log.debug('%1: signalling state: %2', _this.peerName_, state);
                if (state === 'closed') {
                    _this.close();
                    return;
                }
                if (state === 'stable' && _this.pcState === 2 /* CONNECTED */) {
                    // This happens when new data channels are created. TODO: file an issue
                    // in Chrome; unclear that this should happen when creating new data
                    // channels.
                    // https://code.google.com/p/webrtc/issues/detail?id=2431
                    return;
                }
                // Non-close signalling state changes should only be happening when state
                // is |CONNECTING|, otherwise this is an error.
                // Right now in chrome in state CONNECTED, re-negotiation can happen and
                // it will trigger non-close signalling state change. Till this behavior
                // changes, include CONNECTED state as well.
                if (_this.pcState !== 1 /* CONNECTING */ && _this.pcState !== 2 /* CONNECTED */) {
                    // Something unexpected happened, better close down properly.
                    _this.closeWithError_('Unexpected onSignallingStateChange in state: ' + State[_this.pcState]);
                    return;
                }
            });
        };
        // The RTCPeerConnection iceConnectionState has changed.  This state change
        // is a result of the browser's ICE operations.  The state changes to
        // 'connected' when the peer is able to ping the other side and receive a
        // response, and goes to 'disconnected' or 'failed' if pings consistently
        // fail.
        this.onIceConnectionStateChange_ = function () {
            var state = _this.pc_.getIceConnectionState().then(function (state) {
                log.debug('%1: ice connection state: %2', _this.peerName_, state);
                // No action is needed when the state reaches 'connected', because
                // |this.completeConnection_| is called by the datachannel's |onopen|.
                if ((state === 'disconnected' || state === 'failed') && _this.pcState != 3 /* DISCONNECTED */) {
                    _this.closeWithError_('Connection lost: ' + state);
                }
            });
        };
        // Once we have connected, we need to fulfill the connection promise and set
        // the state.
        this.completeConnection_ = function () {
            _this.pcState = 2 /* CONNECTED */;
            _this.fulfillConnected_();
        };
        this.negotiateConnection = function () {
            log.debug('%1: negotiateConnection', _this.peerName_);
            // In order for the initial SDP header to include the provision for having
            // data channels (without it, we would have to re-negotiate SDP after the
            // PC is established), we start negotaition by openning a data channel to
            // the peer, this triggers the negotiation needed event.
            return _this.openDataChannel(PeerConnectionClass.CONTROL_CHANNEL_LABEL).then(_this.registerControlChannel_).then(function () {
                return _this.onceConnected;
            });
        };
        // Called when an on onnegotiationneeded event is received.
        this.onNegotiationNeeded_ = function () {
            log.debug('%1: negotiation needed', _this.peerName_);
            // CONSIDER: might we ever need to re-create an onAnswer? Exactly how/when
            // do onnegotiation events get raised? Do they get raised on both sides?
            // Or only for the initiator?
            Eif (_this.pcState === 0 /* WAITING */ || _this.pcState === 2 /* CONNECTED */) {
                _this.pcState = 1 /* CONNECTING */;
                _this.fulfillConnecting_();
                _this.pc_.createOffer().then(function (d) {
                    // Emit the offer signal before calling setLocalDescription, which
                    // initiates ICE candidate gathering. If we did the reverse then
                    // we may emit ICE candidate signals before the offer, confusing
                    // some clients:
                    //   https://github.com/uProxy/uproxy/issues/784
                    _this.emitSignalForPeer_({
                        type: 0 /* OFFER */,
                        description: {
                            type: d.type,
                            sdp: d.sdp
                        }
                    });
                    _this.pc_.setLocalDescription(d);
                }).catch(function (e) {
                    _this.closeWithError_('failed to set local description: ' + e.message);
                });
            }
            else {
                _this.closeWithError_('onnegotiationneeded fired in unexpected state ' + State[_this.pcState]);
            }
        };
        // Fulfills if it is OK to proceed with setting this remote offer, or
        // rejects if there is a local offer with higher hash-precedence.
        this.breakOfferTie_ = function (remoteOffer) {
            return _this.pc_.getSignalingState().then(function (state) {
                if (state === 'have-local-offer') {
                    return _this.pc_.getLocalDescription().then(function (localOffer) {
                        if (djb2.stringHash(JSON.stringify(remoteOffer.sdp)) < djb2.stringHash(JSON.stringify(localOffer.sdp))) {
                            // TODO: implement reset and use their offer.
                            return Promise.reject('Simultaneous offers not yet implemented.');
                        }
                        else {
                            return Promise.resolve();
                        }
                    });
                }
                else {
                    return Promise.resolve();
                }
            });
        };
        this.handleOfferSignalMessage_ = function (description) {
            _this.breakOfferTie_(description).then(function () {
                _this.pcState = 1 /* CONNECTING */;
                _this.fulfillConnecting_();
                // initial offer from peer
                return _this.pc_.setRemoteDescription(description);
            }).then(_this.pc_.createAnswer).then(function (d) {
                // As with the offer, we must emit the signal before
                // setting the local description to ensure that we send the
                // ANSWER before any ICE candidates.
                _this.emitSignalForPeer_({
                    type: 1 /* ANSWER */,
                    description: {
                        type: d.type,
                        sdp: d.sdp
                    }
                });
                _this.pc_.setLocalDescription(d);
            }).then(function () {
                _this.fromPeerCandidateQueue.setHandler(_this.pc_.addIceCandidate);
            }).catch(function (e) {
                _this.closeWithError_('Failed to connect to offer:' + e.toString());
            });
        };
        this.handleAnswerSignalMessage_ = function (description) {
            _this.pc_.setRemoteDescription(description).then(function () {
                _this.fromPeerCandidateQueue.setHandler(_this.pc_.addIceCandidate);
            }).catch(function (e) {
                _this.closeWithError_('Failed to set remote description: ' + JSON.stringify(description) + '; Error: ' + e.toString());
            });
        };
        this.handleCandidateSignalMessage_ = function (candidate) {
            try {
                _this.fromPeerCandidateQueue.handle(candidate);
            }
            catch (e) {
                log.error('%1: addIceCandidate: %2; Error: %3', _this.peerName_, candidate, e.toString());
            }
        };
        // Adds a signalling message to this.signalForPeerQueue.
        this.emitSignalForPeer_ = function (message) {
            log.debug('%1: signal for peer: %2', _this.peerName_, message);
            _this.signalForPeerQueue.handle(message);
        };
        // Handle a signalling message from the remote peer.
        this.handleSignalMessage = function (message) {
            log.debug('%1: handling signal from peer: %2', _this.peerName_, message);
            switch (message.type) {
                case 0 /* OFFER */:
                    _this.handleOfferSignalMessage_(message.description);
                    break;
                case 1 /* ANSWER */:
                    _this.handleAnswerSignalMessage_(message.description);
                    break;
                case 2 /* CANDIDATE */:
                    _this.handleCandidateSignalMessage_(message.candidate);
                    break;
                case 3 /* NO_MORE_CANDIDATES */:
                    break;
                default:
                    log.error('%1: unexpected signalling message type %2', _this.peerName_, message.type);
            }
        };
        // Open a new data channel with the peer.
        this.openDataChannel = function (channelLabel, options) {
            log.debug('%1: creating channel %2 with options: %3', _this.peerName_, channelLabel, options);
            // Only the control data channel can have an empty channel label.
            Iif (_this.controlDataChannel_ != null && channelLabel === '') {
                throw new Error('Channel label can not be an empty string.');
            }
            return _this.pc_.createDataChannel(channelLabel, options).then(_this.addRtcDataChannel_);
        };
        // When a peer creates a data channel, this function is called with the
        // |RTCDataChannelEvent|. We then create the data channel wrapper and add
        // the new |DataChannel| to the |this.peerOpenedChannelQueue| to be
        // handled.
        this.onPeerStartedDataChannel_ = function (channelInfo) {
            _this.addRtcDataChannel_(channelInfo.channel).then(function (dc) {
                var label = dc.getLabel();
                log.debug('%1: peer created channel %2', _this.peerName_, label);
                Iif (label === PeerConnectionClass.CONTROL_CHANNEL_LABEL) {
                    // If the peer has started the control channel, register it
                    // as this user's control channel as well.
                    _this.registerControlChannel_(dc);
                }
                else {
                    // Aside from the control channel, all other channels should be
                    // added to the queue of peer opened channels.
                    _this.peerOpenedChannelQueue.handle(dc);
                }
            });
        };
        // Add a rtc data channel and return the it wrapped as a DataChannel
        this.addRtcDataChannel_ = function (id) {
            return datachannel.createFromFreedomId(id).then(function (dataChannel) {
                var label = dataChannel.getLabel();
                _this.dataChannels[label] = dataChannel;
                dataChannel.onceClosed.then(function () {
                    delete _this.dataChannels[label];
                    if (label === '') {
                        log.debug('%1: discarded control channel', _this.peerName_);
                    }
                    else {
                        log.debug('%1: discarded channel %2 (%3 remaining)', _this.peerName_, label, Object.keys(_this.dataChannels).length);
                    }
                });
                return dataChannel;
            });
        };
        // Saves the given data channel as the control channel for this peer
        // connection. The appropriate callbacks for opening, closing, and
        // initiating a heartbeat is are registered here.
        this.registerControlChannel_ = function (controlChannel) {
            _this.controlDataChannel_ = controlChannel;
            _this.controlDataChannel_.onceClosed.then(_this.close);
            return _this.controlDataChannel_.onceOpened.then(_this.completeConnection_).then(function () {
                _this.initiateHeartbeat_(controlChannel);
            });
        };
        // Heartbeats take the form of a string message sent over the control
        // channel at regular intervals; if no heartbeat is received from the
        // remote peer for >HEARTBEAT_TIMEOUT_MS_ then the peerconnection is
        // closed with an error. The motivation for this is Firefox's poor
        // handling of sudden connection closures:
        //   https://github.com/uProxy/uproxy/issues/1358
        this.initiateHeartbeat_ = function (channel) {
            log.debug('%1: initiating heartbeat', _this.peerName_);
            // Listen for heartbeats from the other side.
            var lastPingTimestamp = Date.now();
            channel.dataFromPeerQueue.setSyncHandler(function (data) {
                if (data.str && data.str === PeerConnectionClass.HEARTBEAT_MESSAGE_) {
                    lastPingTimestamp = Date.now();
                }
                else {
                    log.warn('%1: unexpected data on control channel: %2', _this.peerName_, data);
                }
            });
            // Send and monitors heartbeats.
            var loop = setInterval(function () {
                channel.send({
                    str: PeerConnectionClass.HEARTBEAT_MESSAGE_
                }).catch(function (e) {
                    log.error('%1: error sending heartbeat: %2', _this.peerName_, e.message);
                });
                if (Date.now() - lastPingTimestamp > PeerConnectionClass.HEARTBEAT_TIMEOUT_MS_) {
                    log.debug('%1: heartbeat timeout, terminating', _this.peerName_);
                    _this.closeWithError_('no heartbeat received for >' + PeerConnectionClass.HEARTBEAT_TIMEOUT_MS_ + 'ms');
                    clearInterval(loop);
                }
            }, PeerConnectionClass.HEARTBEAT_INTERVAL_MS_);
        };
        // For debugging: prints the state of the peer connection including all
        // associated data channels.
        this.toString = function () {
            var s = _this.peerName_ + ': { \n';
            var channelLabel;
            for (channelLabel in _this.dataChannels) {
                s += '  ' + channelLabel + ': ' + _this.dataChannels[channelLabel].toString() + '\n';
            }
            s += '}';
            return s;
        };
        this.peerName_ = this.peerName_ || ('unnamed-' + (++PeerConnectionClass.automaticNameIndex_));
        this.onceConnecting = new Promise(function (F, R) {
            _this.fulfillConnecting_ = F;
        });
        this.onceConnected = new Promise(function (F, R) {
            // This ensures that onceConnecting consequences happen before
            // onceConnected.
            _this.fulfillConnected_ = function () {
                _this.onceConnecting.then(F);
            };
            _this.rejectConnected_ = R;
        });
        this.onceDisconnected = new Promise(function (F, R) {
            _this.fulfillDisconnected_ = F;
        });
        // Once connected, add to global listing. Helpful for debugging.
        // Once disconnected, remove from global listing.
        this.onceConnected.then(function () {
            PeerConnectionClass.peerConnections[_this.peerName_] = _this;
            _this.onceDisconnected.then(function () {
                delete PeerConnectionClass.peerConnections[_this.peerName_];
            });
        }, function (e) {
            log.debug('%1: failed to connect, not available for ' + ' debugging in peerConnections', _this.peerName_);
        });
        // New data channels from the peer.
        this.peerOpenedChannelQueue = new handler.Queue();
        // Messages to send to the peer.
        this.signalForPeerQueue = new handler.Queue();
        // candidates form the peer; need to be queued until after remote
        // descrption has been set.
        this.fromPeerCandidateQueue = new handler.Queue();
        // This state variable is an abstraction of the PeerConnection state that
        // simplifies usage and management of state.
        this.pcState = 0 /* WAITING */;
        this.dataChannels = {};
        // Add basic event handlers.
        this.pc_.on('onicecandidate', function (candidate) {
            if (candidate.candidate) {
                log.debug('%1: local ice candidate: %2', _this.peerName_, candidate.candidate);
                _this.emitSignalForPeer_({
                    type: 2 /* CANDIDATE */,
                    candidate: candidate.candidate
                });
            }
            else {
                log.debug('%1: no more ice candidates', _this.peerName_);
                _this.emitSignalForPeer_({
                    type: 3 /* NO_MORE_CANDIDATES */
                });
            }
        });
        this.pc_.on('onnegotiationneeded', this.onNegotiationNeeded_);
        this.pc_.on('ondatachannel', this.onPeerStartedDataChannel_);
        this.pc_.on('onsignalingstatechange', this.onSignallingStateChange_);
        this.pc_.on('oniceconnectionstatechange', this.onIceConnectionStateChange_);
    }
    // Interval, in milliseconds, after which the peerconnection will
    // terminate if no heartbeat is received from the peer.
    PeerConnectionClass.HEARTBEAT_TIMEOUT_MS_ = 30000;
    // Interval, in milliseconds, at which heartbeats are sent to the peer.
    PeerConnectionClass.HEARTBEAT_INTERVAL_MS_ = 5000;
    // Message which is sent for heartbeats.
    PeerConnectionClass.HEARTBEAT_MESSAGE_ = 'heartbeat';
    // Global listing of active peer connections. Helpful for debugging when you
    // are in Freedom.
    PeerConnectionClass.peerConnections = {};
    // Label for the control data channel. Because channel labels must be
    // unique, the empty string was chosen to create a simple naming
    // restriction for new data channels--all other data channels must have
    // non-empty channel labels.
    PeerConnectionClass.CONTROL_CHANNEL_LABEL = '';
    // Number of automatically generated names generated so far.
    PeerConnectionClass.automaticNameIndex_ = 0;
    return PeerConnectionClass;
})();
exports.PeerConnectionClass = PeerConnectionClass; // class PeerConnectionClass
function createPeerConnection(config, debugPcName) {
    var freedomRtcPc = freedom['core.rtcpeerconnection'](config);
    // Note: |peerConnection| will take responsibility for freeing memory and
    // closing down of |freedomRtcPc| once the underlying peer connection is
    // closed.
    return new PeerConnectionClass(freedomRtcPc, debugPcName);
}
exports.createPeerConnection = createPeerConnection;