Debian Codegraph @

closure-library/closure/goog/net/xpc/crosspagechannel.js

raw
1 // Copyright 2007 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Provides the class CrossPageChannel, the main class in
17 * goog.net.xpc.
18 *
19 * @see ../../demos/xpc/index.html
20 */
21
22 goog.provide('goog.net.xpc.CrossPageChannel');
23
24 goog.require('goog.Uri');
25 goog.require('goog.async.Deferred');
26 goog.require('goog.async.Delay');
27 goog.require('goog.dispose');
28 goog.require('goog.dom');
29 goog.require('goog.dom.TagName');
30 goog.require('goog.events');
31 goog.require('goog.events.EventHandler');
32 goog.require('goog.events.EventType');
33 goog.require('goog.json');
34 goog.require('goog.log');
35 goog.require('goog.messaging.AbstractChannel');
36 goog.require('goog.net.xpc');
37 goog.require('goog.net.xpc.CfgFields');
38 goog.require('goog.net.xpc.ChannelStates');
39 goog.require('goog.net.xpc.CrossPageChannelRole');
40 goog.require('goog.net.xpc.DirectTransport');
41 goog.require('goog.net.xpc.FrameElementMethodTransport');
42 goog.require('goog.net.xpc.IframePollingTransport');
43 goog.require('goog.net.xpc.IframeRelayTransport');
44 goog.require('goog.net.xpc.NativeMessagingTransport');
45 goog.require('goog.net.xpc.NixTransport');
46 goog.require('goog.net.xpc.TransportTypes');
47 goog.require('goog.net.xpc.UriCfgFields');
48 goog.require('goog.string');
49 goog.require('goog.uri.utils');
50 goog.require('goog.userAgent');
51
52
53
54 /**
55 * A communication channel between two documents from different domains.
56 * Provides asynchronous messaging.
57 *
58 * @param {Object} cfg Channel configuration object.
59 * @param {goog.dom.DomHelper=} opt_domHelper The optional dom helper to
60 * use for looking up elements in the dom.
61 * @constructor
62 * @extends {goog.messaging.AbstractChannel}
63 */
64 goog.net.xpc.CrossPageChannel = function(cfg, opt_domHelper) {
65 goog.net.xpc.CrossPageChannel.base(this, 'constructor');
66
67 for (var i = 0, uriField; uriField = goog.net.xpc.UriCfgFields[i]; i++) {
68 if (uriField in cfg && !/^https?:\/\//.test(cfg[uriField])) {
69 throw new Error(
70 'URI ' + cfg[uriField] + ' is invalid for field ' + uriField);
71 }
72 }
73
74 /**
75 * The configuration for this channel.
76 * @type {Object}
77 * @private
78 */
79 this.cfg_ = cfg;
80
81 /**
82 * The name of the channel. Please use
83 * <code>updateChannelNameAndCatalog</code> to change this from the transports
84 * vs changing the property directly.
85 * @type {string}
86 */
87 this.name = this.cfg_[goog.net.xpc.CfgFields.CHANNEL_NAME] ||
88 goog.net.xpc.getRandomString(10);
89
90 /**
91 * The dom helper to use for accessing the dom.
92 * @type {goog.dom.DomHelper}
93 * @private
94 */
95 this.domHelper_ = opt_domHelper || goog.dom.getDomHelper();
96
97 /**
98 * Collects deferred function calls which will be made once the connection
99 * has been fully set up.
100 * @type {!Array<function()>}
101 * @private
102 */
103 this.deferredDeliveries_ = [];
104
105 /**
106 * An event handler used to listen for load events on peer iframes.
107 * @type {!goog.events.EventHandler<!goog.net.xpc.CrossPageChannel>}
108 * @private
109 */
110 this.peerLoadHandler_ = new goog.events.EventHandler(this);
111
112 // If LOCAL_POLL_URI or PEER_POLL_URI is not available, try using
113 // robots.txt from that host.
114 cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] =
115 cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] ||
116 goog.uri.utils.getHost(this.domHelper_.getWindow().location.href) +
117 '/robots.txt';
118 // PEER_URI is sometimes undefined in tests.
119 cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] =
120 cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] ||
121 goog.uri.utils.getHost(cfg[goog.net.xpc.CfgFields.PEER_URI] || '') +
122 '/robots.txt';
123
124 goog.net.xpc.channels[this.name] = this;
125
126 if (!goog.events.getListener(
127 window, goog.events.EventType.UNLOAD,
128 goog.net.xpc.CrossPageChannel.disposeAll_)) {
129 // Set listener to dispose all registered channels on page unload.
130 goog.events.listenOnce(
131 window, goog.events.EventType.UNLOAD,
132 goog.net.xpc.CrossPageChannel.disposeAll_);
133 }
134
135 goog.log.info(goog.net.xpc.logger, 'CrossPageChannel created: ' + this.name);
136 };
137 goog.inherits(goog.net.xpc.CrossPageChannel, goog.messaging.AbstractChannel);
138
139
140 /**
141 * Regexp for escaping service names.
142 * @type {RegExp}
143 * @private
144 */
145 goog.net.xpc.CrossPageChannel.TRANSPORT_SERVICE_ESCAPE_RE_ =
146 new RegExp('^%*' + goog.net.xpc.TRANSPORT_SERVICE_ + '$');
147
148
149 /**
150 * Regexp for unescaping service names.
151 * @type {RegExp}
152 * @private
153 */
154 goog.net.xpc.CrossPageChannel.TRANSPORT_SERVICE_UNESCAPE_RE_ =
155 new RegExp('^%+' + goog.net.xpc.TRANSPORT_SERVICE_ + '$');
156
157
158 /**
159 * A delay between the transport reporting as connected and the calling of the
160 * connection callback. Sometimes used to paper over timing vulnerabilities.
161 * @type {goog.async.Delay}
162 * @private
163 */
164 goog.net.xpc.CrossPageChannel.prototype.connectionDelay_ = null;
165
166
167 /**
168 * A deferred which is set to non-null while a peer iframe is being created
169 * but has not yet thrown its load event, and which fires when that load event
170 * arrives.
171 * @type {goog.async.Deferred}
172 * @private
173 */
174 goog.net.xpc.CrossPageChannel.prototype.peerWindowDeferred_ = null;
175
176
177 /**
178 * The transport.
179 * @type {goog.net.xpc.Transport?}
180 * @private
181 */
182 goog.net.xpc.CrossPageChannel.prototype.transport_ = null;
183
184
185 /**
186 * The channel state.
187 * @type {number}
188 * @private
189 */
190 goog.net.xpc.CrossPageChannel.prototype.state_ =
191 goog.net.xpc.ChannelStates.NOT_CONNECTED;
192
193
194 /**
195 * @override
196 * @return {boolean} Whether the channel is connected.
197 */
198 goog.net.xpc.CrossPageChannel.prototype.isConnected = function() {
199 return this.state_ == goog.net.xpc.ChannelStates.CONNECTED;
200 };
201
202
203 /**
204 * Reference to the window-object of the peer page.
205 * @type {Object}
206 * @private
207 */
208 goog.net.xpc.CrossPageChannel.prototype.peerWindowObject_ = null;
209
210
211 /**
212 * Reference to the iframe-element.
213 * @type {?HTMLIFrameElement}
214 * @private
215 */
216 goog.net.xpc.CrossPageChannel.prototype.iframeElement_ = null;
217
218
219 /**
220 * Returns the configuration object for this channel.
221 * Package private. Do not call from outside goog.net.xpc.
222 *
223 * @return {Object} The configuration object for this channel.
224 */
225 goog.net.xpc.CrossPageChannel.prototype.getConfig = function() {
226 return this.cfg_;
227 };
228
229
230 /**
231 * Returns a reference to the iframe-element.
232 * Package private. Do not call from outside goog.net.xpc.
233 *
234 * @return {?HTMLIFrameElement} A reference to the iframe-element.
235 */
236 goog.net.xpc.CrossPageChannel.prototype.getIframeElement = function() {
237 return this.iframeElement_;
238 };
239
240
241 /**
242 * Sets the window object the foreign document resides in.
243 *
244 * @param {Object} peerWindowObject The window object of the peer.
245 */
246 goog.net.xpc.CrossPageChannel.prototype.setPeerWindowObject = function(
247 peerWindowObject) {
248 this.peerWindowObject_ = peerWindowObject;
249 };
250
251
252 /**
253 * Returns the window object the foreign document resides in.
254 *
255 * @return {Object} The window object of the peer.
256 * @package
257 */
258 goog.net.xpc.CrossPageChannel.prototype.getPeerWindowObject = function() {
259 return this.peerWindowObject_;
260 };
261
262
263 /**
264 * Determines whether the peer window is available (e.g. not closed).
265 *
266 * @return {boolean} Whether the peer window is available.
267 * @package
268 */
269 goog.net.xpc.CrossPageChannel.prototype.isPeerAvailable = function() {
270 // NOTE(user): This check is not reliable in IE, where a document in an
271 // iframe does not get unloaded when removing the iframe element from the DOM.
272 // TODO(user): Find something that works in IE as well.
273 // NOTE(user): "!this.peerWindowObject_.closed" evaluates to 'false' in IE9
274 // sometimes even though typeof(this.peerWindowObject_.closed) is boolean and
275 // this.peerWindowObject_.closed evaluates to 'false'. Casting it to a Boolean
276 // results in sane evaluation. When this happens, it's in the inner iframe
277 // when querying its parent's 'closed' status. Note that this is a different
278 // case than mibuerge@'s note above.
279 try {
280 return !!this.peerWindowObject_ && !this.peerWindowObject_.closed;
281 } catch (e) {
282 // If the window is closing, an error may be thrown.
283 return false;
284 }
285 };
286
287
288 /**
289 * Determine which transport type to use for this channel / useragent.
290 * @return {goog.net.xpc.TransportTypes|undefined} The best transport type.
291 * @private
292 */
293 goog.net.xpc.CrossPageChannel.prototype.determineTransportType_ = function() {
294 var transportType;
295 if (goog.isFunction(document.postMessage) ||
296 goog.isFunction(window.postMessage) ||
297 // IE8 supports window.postMessage, but
298 // typeof window.postMessage returns "object"
299 (goog.userAgent.IE && window.postMessage)) {
300 transportType = goog.net.xpc.TransportTypes.NATIVE_MESSAGING;
301 } else if (goog.userAgent.GECKO) {
302 transportType = goog.net.xpc.TransportTypes.FRAME_ELEMENT_METHOD;
303 } else if (
304 goog.userAgent.IE && this.cfg_[goog.net.xpc.CfgFields.PEER_RELAY_URI]) {
305 transportType = goog.net.xpc.TransportTypes.IFRAME_RELAY;
306 } else if (goog.userAgent.IE && goog.net.xpc.NixTransport.isNixSupported()) {
307 transportType = goog.net.xpc.TransportTypes.NIX;
308 } else {
309 transportType = goog.net.xpc.TransportTypes.IFRAME_POLLING;
310 }
311 return transportType;
312 };
313
314
315 /**
316 * Creates the transport for this channel. Chooses from the available
317 * transport based on the user agent and the configuration.
318 * @private
319 */
320 goog.net.xpc.CrossPageChannel.prototype.createTransport_ = function() {
321 // return, if the transport has already been created
322 if (this.transport_) {
323 return;
324 }
325
326 // TODO(user): Use goog.scope.
327 var CfgFields = goog.net.xpc.CfgFields;
328
329 if (!this.cfg_[CfgFields.TRANSPORT]) {
330 this.cfg_[CfgFields.TRANSPORT] = this.determineTransportType_();
331 }
332
333 switch (this.cfg_[CfgFields.TRANSPORT]) {
334 case goog.net.xpc.TransportTypes.NATIVE_MESSAGING:
335 var protocolVersion =
336 this.cfg_[CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] || 2;
337 this.transport_ = new goog.net.xpc.NativeMessagingTransport(
338 this, this.cfg_[CfgFields.PEER_HOSTNAME], this.domHelper_,
339 !!this.cfg_[CfgFields.ONE_SIDED_HANDSHAKE], protocolVersion);
340 break;
341 case goog.net.xpc.TransportTypes.NIX:
342 this.transport_ = new goog.net.xpc.NixTransport(this, this.domHelper_);
343 break;
344 case goog.net.xpc.TransportTypes.FRAME_ELEMENT_METHOD:
345 this.transport_ =
346 new goog.net.xpc.FrameElementMethodTransport(this, this.domHelper_);
347 break;
348 case goog.net.xpc.TransportTypes.IFRAME_RELAY:
349 this.transport_ =
350 new goog.net.xpc.IframeRelayTransport(this, this.domHelper_);
351 break;
352 case goog.net.xpc.TransportTypes.IFRAME_POLLING:
353 this.transport_ =
354 new goog.net.xpc.IframePollingTransport(this, this.domHelper_);
355 break;
356 case goog.net.xpc.TransportTypes.DIRECT:
357 if (this.peerWindowObject_ &&
358 goog.net.xpc.DirectTransport.isSupported(
359 /** @type {!Window} */ (this.peerWindowObject_))) {
360 this.transport_ =
361 new goog.net.xpc.DirectTransport(this, this.domHelper_);
362 } else {
363 goog.log.info(
364 goog.net.xpc.logger,
365 'DirectTransport not supported for this window, peer window in' +
366 ' different security context or not set yet.');
367 }
368 break;
369 }
370
371 if (this.transport_) {
372 goog.log.info(
373 goog.net.xpc.logger, 'Transport created: ' + this.transport_.getName());
374 } else {
375 throw new Error('CrossPageChannel: No suitable transport found!');
376 }
377 };
378
379
380 /**
381 * Returns the transport type in use for this channel.
382 * @return {number} Transport-type identifier.
383 */
384 goog.net.xpc.CrossPageChannel.prototype.getTransportType = function() {
385 return this.transport_.getType();
386 };
387
388
389 /**
390 * Returns the tranport name in use for this channel.
391 * @return {string} The transport name.
392 */
393 goog.net.xpc.CrossPageChannel.prototype.getTransportName = function() {
394 return this.transport_.getName();
395 };
396
397
398 /**
399 * @return {!Object} Configuration-object to be used by the peer to
400 * initialize the channel.
401 */
402 goog.net.xpc.CrossPageChannel.prototype.getPeerConfiguration = function() {
403 var peerCfg = {};
404 peerCfg[goog.net.xpc.CfgFields.CHANNEL_NAME] = this.name;
405 peerCfg[goog.net.xpc.CfgFields.TRANSPORT] =
406 this.cfg_[goog.net.xpc.CfgFields.TRANSPORT];
407 peerCfg[goog.net.xpc.CfgFields.ONE_SIDED_HANDSHAKE] =
408 this.cfg_[goog.net.xpc.CfgFields.ONE_SIDED_HANDSHAKE];
409
410 if (this.cfg_[goog.net.xpc.CfgFields.LOCAL_RELAY_URI]) {
411 peerCfg[goog.net.xpc.CfgFields.PEER_RELAY_URI] =
412 this.cfg_[goog.net.xpc.CfgFields.LOCAL_RELAY_URI];
413 }
414 if (this.cfg_[goog.net.xpc.CfgFields.LOCAL_POLL_URI]) {
415 peerCfg[goog.net.xpc.CfgFields.PEER_POLL_URI] =
416 this.cfg_[goog.net.xpc.CfgFields.LOCAL_POLL_URI];
417 }
418 if (this.cfg_[goog.net.xpc.CfgFields.PEER_POLL_URI]) {
419 peerCfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] =
420 this.cfg_[goog.net.xpc.CfgFields.PEER_POLL_URI];
421 }
422 var role = this.cfg_[goog.net.xpc.CfgFields.ROLE];
423 if (role) {
424 peerCfg[goog.net.xpc.CfgFields.ROLE] =
425 role == goog.net.xpc.CrossPageChannelRole.INNER ?
426 goog.net.xpc.CrossPageChannelRole.OUTER :
427 goog.net.xpc.CrossPageChannelRole.INNER;
428 }
429
430 return peerCfg;
431 };
432
433
434 /**
435 * Creates the iframe containing the peer page in a specified parent element.
436 * This method does not connect the channel, connect() still has to be called
437 * separately.
438 *
439 * @param {!Element} parentElm The container element the iframe is appended to.
440 * @param {Function=} opt_configureIframeCb If present, this function gets
441 * called with the iframe element as parameter to allow setting properties
442 * on it before it gets added to the DOM. If absent, the iframe's width and
443 * height are set to '100%'.
444 * @param {boolean=} opt_addCfgParam Whether to add the peer configuration as
445 * URL parameter (default: true).
446 * @return {!HTMLIFrameElement} The iframe element.
447 */
448 goog.net.xpc.CrossPageChannel.prototype.createPeerIframe = function(
449 parentElm, opt_configureIframeCb, opt_addCfgParam) {
450 goog.log.info(goog.net.xpc.logger, 'createPeerIframe()');
451
452 var iframeId = this.cfg_[goog.net.xpc.CfgFields.IFRAME_ID];
453 if (!iframeId) {
454 // Create a randomized ID for the iframe element to avoid
455 // bfcache-related issues.
456 iframeId = this.cfg_[goog.net.xpc.CfgFields.IFRAME_ID] =
457 'xpcpeer' + goog.net.xpc.getRandomString(4);
458 }
459
460 // TODO(user) Opera creates a history-entry when creating an iframe
461 // programmatically as follows. Find a way which avoids this.
462
463 var iframeElm =
464 goog.dom.getDomHelper(parentElm).createElement(goog.dom.TagName.IFRAME);
465 iframeElm.id = iframeElm.name = iframeId;
466 if (opt_configureIframeCb) {
467 opt_configureIframeCb(iframeElm);
468 } else {
469 iframeElm.style.width = iframeElm.style.height = '100%';
470 }
471
472 this.cleanUpIncompleteConnection_();
473 this.peerWindowDeferred_ = new goog.async.Deferred(undefined, this);
474 var peerUri = this.getPeerUri(opt_addCfgParam);
475 this.peerLoadHandler_.listenOnceWithScope(
476 iframeElm, 'load', this.peerWindowDeferred_.callback, false,
477 this.peerWindowDeferred_);
478
479 if (goog.userAgent.GECKO || goog.userAgent.WEBKIT) {
480 // Appending the iframe in a timeout to avoid a weird fastback issue, which
481 // is present in Safari and Gecko.
482 window.setTimeout(goog.bind(function() {
483 parentElm.appendChild(iframeElm);
484 iframeElm.src = peerUri.toString();
485 goog.log.info(
486 goog.net.xpc.logger, 'peer iframe created (' + iframeId + ')');
487 }, this), 1);
488 } else {
489 iframeElm.src = peerUri.toString();
490 parentElm.appendChild(iframeElm);
491 goog.log.info(
492 goog.net.xpc.logger, 'peer iframe created (' + iframeId + ')');
493 }
494
495 return /** @type {!HTMLIFrameElement} */ (iframeElm);
496 };
497
498
499 /**
500 * Clean up after any incomplete attempt to establish and connect to a peer
501 * iframe.
502 * @private
503 */
504 goog.net.xpc.CrossPageChannel.prototype.cleanUpIncompleteConnection_ =
505 function() {
506 if (this.peerWindowDeferred_) {
507 this.peerWindowDeferred_.cancel();
508 this.peerWindowDeferred_ = null;
509 }
510 this.deferredDeliveries_.length = 0;
511 this.peerLoadHandler_.removeAll();
512 };
513
514
515 /**
516 * Returns the peer URI, with an optional URL parameter for configuring the peer
517 * window.
518 *
519 * @param {boolean=} opt_addCfgParam Whether to add the peer configuration as
520 * URL parameter (default: true).
521 * @return {!goog.Uri} The peer URI.
522 */
523 goog.net.xpc.CrossPageChannel.prototype.getPeerUri = function(opt_addCfgParam) {
524 var peerUri = this.cfg_[goog.net.xpc.CfgFields.PEER_URI];
525 if (goog.isString(peerUri)) {
526 peerUri = this.cfg_[goog.net.xpc.CfgFields.PEER_URI] =
527 new goog.Uri(peerUri);
528 }
529
530 // Add the channel configuration used by the peer as URL parameter.
531 if (opt_addCfgParam !== false) {
532 peerUri.setParameterValue(
533 'xpc', goog.json.serialize(this.getPeerConfiguration()));
534 }
535
536 return peerUri;
537 };
538
539
540 /**
541 * Initiates connecting the channel. When this method is called, all the
542 * information needed to connect the channel has to be available.
543 *
544 * @override
545 * @param {Function=} opt_connectCb The function to be called when the
546 * channel has been connected and is ready to be used.
547 */
548 goog.net.xpc.CrossPageChannel.prototype.connect = function(opt_connectCb) {
549 this.connectCb_ = opt_connectCb || goog.nullFunction;
550
551 // If this channel was previously closed, transition back to the NOT_CONNECTED
552 // state to ensure that the connection can proceed (xpcDeliver blocks
553 // transport messages while the connection state is CLOSED).
554 if (this.state_ == goog.net.xpc.ChannelStates.CLOSED) {
555 this.state_ = goog.net.xpc.ChannelStates.NOT_CONNECTED;
556 }
557
558 // If we know of a peer window whose creation has been requested but is not
559 // complete, peerWindowDeferred_ will be non-null, and we should block on it.
560 if (this.peerWindowDeferred_) {
561 this.peerWindowDeferred_.addCallback(this.continueConnection_);
562 } else {
563 this.continueConnection_();
564 }
565 };
566
567
568 /**
569 * Continues the connection process once we're as sure as we can be that the
570 * peer iframe has been created.
571 * @private
572 */
573 goog.net.xpc.CrossPageChannel.prototype.continueConnection_ = function() {
574 goog.log.info(goog.net.xpc.logger, 'continueConnection_()');
575 this.peerWindowDeferred_ = null;
576 if (this.cfg_[goog.net.xpc.CfgFields.IFRAME_ID]) {
577 this.iframeElement_ = /** @type {?HTMLIFrameElement} */ (
578 this.domHelper_.getElement(
579 this.cfg_[goog.net.xpc.CfgFields.IFRAME_ID]));
580 }
581 if (this.iframeElement_) {
582 var winObj = this.iframeElement_.contentWindow;
583 // accessing the window using contentWindow doesn't work in safari
584 if (!winObj) {
585 winObj = window.frames[this.cfg_[goog.net.xpc.CfgFields.IFRAME_ID]];
586 }
587 this.setPeerWindowObject(winObj);
588 }
589
590 // if the peer window object has not been set at this point, we assume
591 // being in an iframe and the channel is meant to be to the containing page
592 if (!this.peerWindowObject_) {
593 // throw an error if we are in the top window (== not in an iframe)
594 if (window == window.top) {
595 throw new Error(
596 'CrossPageChannel: Can\'t connect, peer window-object not set.');
597 } else {
598 this.setPeerWindowObject(window.parent);
599 }
600 }
601
602 this.createTransport_();
603
604 this.transport_.connect();
605
606 // Now we run any deferred deliveries collected while connection was deferred.
607 while (this.deferredDeliveries_.length > 0) {
608 this.deferredDeliveries_.shift()();
609 }
610 };
611
612
613 /**
614 * Closes the channel.
615 */
616 goog.net.xpc.CrossPageChannel.prototype.close = function() {
617 this.cleanUpIncompleteConnection_();
618 this.state_ = goog.net.xpc.ChannelStates.CLOSED;
619 goog.dispose(this.transport_);
620 this.transport_ = null;
621 this.connectCb_ = null;
622 goog.dispose(this.connectionDelay_);
623 this.connectionDelay_ = null;
624 goog.log.info(goog.net.xpc.logger, 'Channel "' + this.name + '" closed');
625 };
626
627
628 /**
629 * Package-private.
630 * Called by the transport when the channel is connected.
631 * @param {number=} opt_delay Delay this number of milliseconds before calling
632 * the connection callback. Usage is discouraged, but can be used to paper
633 * over timing vulnerabilities when there is no alternative.
634 */
635 goog.net.xpc.CrossPageChannel.prototype.notifyConnected = function(opt_delay) {
636 if (this.isConnected() ||
637 (this.connectionDelay_ && this.connectionDelay_.isActive())) {
638 return;
639 }
640 this.state_ = goog.net.xpc.ChannelStates.CONNECTED;
641 goog.log.info(goog.net.xpc.logger, 'Channel "' + this.name + '" connected');
642 goog.dispose(this.connectionDelay_);
643 if (goog.isDef(opt_delay)) {
644 this.connectionDelay_ = new goog.async.Delay(this.connectCb_, opt_delay);
645 this.connectionDelay_.start();
646 } else {
647 this.connectionDelay_ = null;
648 this.connectCb_();
649 }
650 };
651
652
653 /**
654 * Called by the transport in case of an unrecoverable failure.
655 * Package private. Do not call from outside goog.net.xpc.
656 */
657 goog.net.xpc.CrossPageChannel.prototype.notifyTransportError = function() {
658 goog.log.info(goog.net.xpc.logger, 'Transport Error');
659 this.close();
660 };
661
662
663 /** @override */
664 goog.net.xpc.CrossPageChannel.prototype.send = function(serviceName, payload) {
665 if (!this.isConnected()) {
666 goog.log.error(goog.net.xpc.logger, 'Can\'t send. Channel not connected.');
667 return;
668 }
669 // Check if the peer is still around.
670 if (!this.isPeerAvailable()) {
671 goog.log.error(goog.net.xpc.logger, 'Peer has disappeared.');
672 this.close();
673 return;
674 }
675 if (goog.isObject(payload)) {
676 payload = goog.json.serialize(payload);
677 }
678
679 // Partially URL-encode the service name because some characters (: and |) are
680 // used as delimiters for some transports, and we want to allow those
681 // characters in service names.
682 this.transport_.send(this.escapeServiceName_(serviceName), payload);
683 };
684
685
686 /**
687 * Delivers messages to the appropriate service-handler. Named xpcDeliver to
688 * avoid name conflict with {@code deliver} function in superclass
689 * goog.messaging.AbstractChannel.
690 *
691 * @param {string} serviceName The name of the port.
692 * @param {string} payload The payload.
693 * @param {string=} opt_origin An optional origin for the message, where the
694 * underlying transport makes that available. If this is specified, and
695 * the PEER_HOSTNAME parameter was provided, they must match or the message
696 * will be rejected.
697 * @package
698 */
699 goog.net.xpc.CrossPageChannel.prototype.xpcDeliver = function(
700 serviceName, payload, opt_origin) {
701
702 // This check covers the very rare (but producable) case where the inner frame
703 // becomes ready and sends its setup message while the outer frame is
704 // deferring its connect method waiting for the inner frame to be ready. The
705 // resulting deferral ensures the message will not be processed until the
706 // channel is fully configured.
707 if (this.peerWindowDeferred_) {
708 this.deferredDeliveries_.push(
709 goog.bind(this.xpcDeliver, this, serviceName, payload, opt_origin));
710 return;
711 }
712
713 // Check whether the origin of the message is as expected.
714 if (!this.isMessageOriginAcceptable(opt_origin)) {
715 goog.log.warning(
716 goog.net.xpc.logger, 'Message received from unapproved origin "' +
717 opt_origin + '" - rejected.');
718 return;
719 }
720
721 // If there is another channel still open, the native transport's global
722 // postMessage listener will still be active. This will mean that messages
723 // being sent to the now-closed channel will still be received and delivered,
724 // such as transport service traffic from its previous correspondent in the
725 // other frame. Ensure these messages don't cause exceptions.
726 // Example: http://b/12419303
727 if (this.isDisposed() || this.state_ == goog.net.xpc.ChannelStates.CLOSED) {
728 goog.log.warning(
729 goog.net.xpc.logger, 'CrossPageChannel::xpcDeliver(): Channel closed.');
730 } else if (!serviceName || serviceName == goog.net.xpc.TRANSPORT_SERVICE_) {
731 this.transport_.transportServiceHandler(payload);
732 } else {
733 // only deliver messages if connected
734 if (this.isConnected()) {
735 this.deliver(this.unescapeServiceName_(serviceName), payload);
736 } else {
737 goog.log.info(
738 goog.net.xpc.logger,
739 'CrossPageChannel::xpcDeliver(): Not connected.');
740 }
741 }
742 };
743
744
745 /**
746 * Escape the user-provided service name for sending across the channel. This
747 * URL-encodes certain special characters so they don't conflict with delimiters
748 * used by some of the transports, and adds a special prefix if the name
749 * conflicts with the reserved transport service name.
750 *
751 * This is the opposite of {@link #unescapeServiceName_}.
752 *
753 * @param {string} name The name of the service to escape.
754 * @return {string} The escaped service name.
755 * @private
756 */
757 goog.net.xpc.CrossPageChannel.prototype.escapeServiceName_ = function(name) {
758 if (goog.net.xpc.CrossPageChannel.TRANSPORT_SERVICE_ESCAPE_RE_.test(name)) {
759 name = '%' + name;
760 }
761 return name.replace(/[%:|]/g, encodeURIComponent);
762 };
763
764
765 /**
766 * Unescape the escaped service name that was sent across the channel. This is
767 * the opposite of {@link #escapeServiceName_}.
768 *
769 * @param {string} name The name of the service to unescape.
770 * @return {string} The unescaped service name.
771 * @private
772 */
773 goog.net.xpc.CrossPageChannel.prototype.unescapeServiceName_ = function(name) {
774 name = name.replace(/%[0-9a-f]{2}/gi, decodeURIComponent);
775 if (goog.net.xpc.CrossPageChannel.TRANSPORT_SERVICE_UNESCAPE_RE_.test(name)) {
776 return name.substring(1);
777 } else {
778 return name;
779 }
780 };
781
782
783 /**
784 * Returns the role of this channel (either inner or outer).
785 * @return {number} The role of this channel.
786 */
787 goog.net.xpc.CrossPageChannel.prototype.getRole = function() {
788 var role = this.cfg_[goog.net.xpc.CfgFields.ROLE];
789 if (goog.isNumber(role)) {
790 return role;
791 } else {
792 return window.parent == this.peerWindowObject_ ?
793 goog.net.xpc.CrossPageChannelRole.INNER :
794 goog.net.xpc.CrossPageChannelRole.OUTER;
795 }
796 };
797
798
799 /**
800 * Sets the channel name. Note, this doesn't establish a unique channel to
801 * communicate on.
802 * @param {string} name The new channel name.
803 */
804 goog.net.xpc.CrossPageChannel.prototype.updateChannelNameAndCatalog = function(
805 name) {
806 goog.log.fine(goog.net.xpc.logger, 'changing channel name to ' + name);
807 delete goog.net.xpc.channels[this.name];
808 this.name = name;
809 goog.net.xpc.channels[name] = this;
810 };
811
812
813 /**
814 * Returns whether an incoming message with the given origin is acceptable.
815 * If an incoming request comes with a specified (non-empty) origin, and the
816 * PEER_HOSTNAME config parameter has also been provided, the two must match,
817 * or the message is unacceptable.
818 * @param {string=} opt_origin The origin associated with the incoming message.
819 * @return {boolean} Whether the message is acceptable.
820 * @package
821 */
822 goog.net.xpc.CrossPageChannel.prototype.isMessageOriginAcceptable = function(
823 opt_origin) {
824 var peerHostname = this.cfg_[goog.net.xpc.CfgFields.PEER_HOSTNAME];
825 return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(opt_origin)) ||
826 goog.string.isEmptyOrWhitespace(goog.string.makeSafe(peerHostname)) ||
827 opt_origin == this.cfg_[goog.net.xpc.CfgFields.PEER_HOSTNAME];
828 };
829
830
831 /** @override */
832 goog.net.xpc.CrossPageChannel.prototype.disposeInternal = function() {
833 this.close();
834
835 this.peerWindowObject_ = null;
836 this.iframeElement_ = null;
837 delete goog.net.xpc.channels[this.name];
838 goog.dispose(this.peerLoadHandler_);
839 delete this.peerLoadHandler_;
840 goog.net.xpc.CrossPageChannel.base(this, 'disposeInternal');
841 };
842
843
844 /**
845 * Disposes all channels.
846 * @private
847 */
848 goog.net.xpc.CrossPageChannel.disposeAll_ = function() {
849 for (var name in goog.net.xpc.channels) {
850 goog.dispose(goog.net.xpc.channels[name]);
851 }
852 };