Harden content script's message Port against spurious disconnections

Those spurious disconnections have been observed to occur at
uBO's launch time.

Related issue:
- https://github.com/uBlockOrigin/uBlock-issues/issues/403

I have observed that this fixes an issue observed on Firefox 64
(current stable).

The reported Waterfox issue *may* be fixed as a result. If not,
the issue he still considered fixed as Waterfox is not
officially supported.
This commit is contained in:
Raymond Hill 2019-01-27 17:07:40 -05:00
parent 5261da69ac
commit 15100459b3
No known key found for this signature in database
GPG Key ID: 25E1490B761470C2
3 changed files with 89 additions and 60 deletions

View File

@ -1,7 +1,8 @@
/******************************************************************************* /*******************************************************************************
uBlock Origin - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014-2018 The uBlock Origin authors Copyright (C) 2014-present The uBlock Origin authors
Copyright (C) 2015-present Raymond Hill
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -42,7 +43,6 @@ vAPI.randomToken = function() {
}; };
vAPI.sessionId = vAPI.randomToken(); vAPI.sessionId = vAPI.randomToken();
vAPI.chrome = true;
vAPI.setTimeout = vAPI.setTimeout || self.setTimeout.bind(self); vAPI.setTimeout = vAPI.setTimeout || self.setTimeout.bind(self);
/******************************************************************************/ /******************************************************************************/
@ -53,13 +53,13 @@ vAPI.shutdown = {
this.jobs.push(job); this.jobs.push(job);
}, },
exec: function() { exec: function() {
var job; let job;
while ( (job = this.jobs.pop()) ) { while ( (job = this.jobs.pop()) ) {
job(); job();
} }
}, },
remove: function(job) { remove: function(job) {
var pos; let pos;
while ( (pos = this.jobs.indexOf(job)) !== -1 ) { while ( (pos = this.jobs.indexOf(job)) !== -1 ) {
this.jobs.splice(pos, 1); this.jobs.splice(pos, 1);
} }
@ -79,7 +79,7 @@ vAPI.messaging = {
shuttingDown: false, shuttingDown: false,
Connection: function(handler, details) { Connection: function(handler, details) {
var messaging = vAPI.messaging; const messaging = vAPI.messaging;
this.messaging = messaging; this.messaging = messaging;
this.handler = handler; this.handler = handler;
this.id = details.id; this.id = details.id;
@ -87,18 +87,20 @@ vAPI.messaging = {
this.toToken = details.toToken; this.toToken = details.toToken;
this.from = details.from; this.from = details.from;
this.fromToken = details.fromToken; this.fromToken = details.fromToken;
this.checkBound = this.check.bind(this);
this.checkTimer = undefined; this.checkTimer = undefined;
// On Firefox it appears ports are not automatically disconnected when // On Firefox it appears ports are not automatically disconnected
// navigating to another page. // when navigating to another page.
if ( messaging.Connection.pagehide !== undefined ) { return; } const ctor = vAPI.messaging.Connection;
messaging.Connection.pagehide = function() { if ( ctor.pagehide !== undefined ) { return; }
for ( var connection of this.connections.values() ) { ctor.pagehide = ( ) => {
for ( const connection of this.messaging.connections.values() ) {
connection.disconnect(); connection.disconnect();
connection.handler(connection.toDetails('connectionBroken')); connection.handler(
connection.toDetails('connectionBroken')
);
} }
}.bind(messaging); };
window.addEventListener('pagehide', messaging.Connection.pagehide); window.addEventListener('pagehide', ctor.pagehide);
}, },
shutdown: function() { shutdown: function() {
@ -106,9 +108,15 @@ vAPI.messaging = {
this.destroyPort(); this.destroyPort();
}, },
// https://github.com/uBlockOrigin/uBlock-issues/issues/403
// Spurious disconnection can happen, so do not consider such events
// as world-ending, i.e. stay around. Except for embedded frames.
disconnectListener: function() { disconnectListener: function() {
this.port = null; this.port = null;
vAPI.shutdown.exec(); if ( window !== window.top ) {
vAPI.shutdown.exec();
}
}, },
disconnectListenerBound: null, disconnectListenerBound: null,
@ -117,16 +125,15 @@ vAPI.messaging = {
// Sent to all channels // Sent to all channels
if ( details.broadcast ) { if ( details.broadcast ) {
for ( var channelName of this.channels.keys() ) { for ( const channelName of this.channels.keys() ) {
this.sendToChannelListeners(channelName, details.msg); this.sendToChannelListeners(channelName, details.msg);
} }
return; return;
} }
// Response to specific message previously sent // Response to specific message previously sent
var listener;
if ( details.auxProcessId ) { if ( details.auxProcessId ) {
listener = this.pending.get(details.auxProcessId); const listener = this.pending.get(details.auxProcessId);
if ( listener !== undefined ) { if ( listener !== undefined ) {
this.pending.delete(details.auxProcessId); this.pending.delete(details.auxProcessId);
listener(details.msg); listener(details.msg);
@ -137,7 +144,7 @@ vAPI.messaging = {
if ( details.channelName !== 'vapi' ) { return; } if ( details.channelName !== 'vapi' ) { return; }
// Internal handler // Internal handler
var connection; let connection;
switch ( details.msg.what ) { switch ( details.msg.what ) {
case 'connectionAccepted': case 'connectionAccepted':
@ -150,11 +157,11 @@ vAPI.messaging = {
connection.receive(details.msg); connection.receive(details.msg);
break; break;
case 'connectionRequested': case 'connectionRequested':
var listeners = this.channels.get(details.msg.to); const listeners = this.channels.get(details.msg.to);
if ( listeners === undefined ) { return; } if ( listeners === undefined ) { return; }
var port = this.getPort(); const port = this.getPort();
if ( port === null ) { return; } if ( port === null ) { return; }
for ( listener of listeners ) { for ( const listener of listeners ) {
if ( listener(details.msg) !== true ) { continue; } if ( listener(details.msg) !== true ) { continue; }
details.msg.what = 'connectionAccepted'; details.msg.what = 'connectionAccepted';
details.msg.toToken = port.name; details.msg.toToken = port.name;
@ -193,7 +200,7 @@ vAPI.messaging = {
clearTimeout(this.portTimer); clearTimeout(this.portTimer);
this.portTimer = null; this.portTimer = null;
} }
var port = this.port; const port = this.port;
if ( port !== null ) { if ( port !== null ) {
port.disconnect(); port.disconnect();
port.onMessage.removeListener(this.messageListenerCallback); port.onMessage.removeListener(this.messageListenerCallback);
@ -202,16 +209,16 @@ vAPI.messaging = {
} }
this.channels.clear(); this.channels.clear();
if ( this.connections.size !== 0 ) { if ( this.connections.size !== 0 ) {
for ( var connection of this.connections.values() ) { for ( const connection of this.connections.values() ) {
connection.receive({ what: 'connectionBroken' }); connection.receive({ what: 'connectionBroken' });
} }
this.connections.clear(); this.connections.clear();
} }
// service pending callbacks // service pending callbacks
if ( this.pending.size !== 0 ) { if ( this.pending.size !== 0 ) {
var pending = this.pending; const pending = this.pending;
this.pending = new Map(); this.pending = new Map();
for ( var callback of pending.values() ) { for ( const callback of pending.values() ) {
if ( typeof callback === 'function' ) { if ( typeof callback === 'function' ) {
callback(null); callback(null);
} }
@ -257,12 +264,12 @@ vAPI.messaging = {
if ( this.pending.size > 25 ) { if ( this.pending.size > 25 ) {
vAPI.shutdown.exec(); vAPI.shutdown.exec();
} }
var port = this.getPort(); const port = this.getPort();
if ( port === null ) { if ( port === null ) {
if ( typeof callback === 'function' ) { callback(); } if ( typeof callback === 'function' ) { callback(); }
return; return;
} }
var auxProcessId; let auxProcessId;
if ( callback ) { if ( callback ) {
auxProcessId = this.auxProcessId++; auxProcessId = this.auxProcessId++;
this.pending.set(auxProcessId, callback); this.pending.set(auxProcessId, callback);
@ -275,9 +282,9 @@ vAPI.messaging = {
}, },
connectTo: function(from, to, handler) { connectTo: function(from, to, handler) {
var port = this.getPort(); const port = this.getPort();
if ( port === null ) { return; } if ( port === null ) { return; }
var connection = new this.Connection(handler, { const connection = new this.Connection(handler, {
id: from + '-' + to + '-' + vAPI.sessionId, id: from + '-' + to + '-' + vAPI.sessionId,
to: to, to: to,
from: from, from: from,
@ -298,19 +305,19 @@ vAPI.messaging = {
}, },
disconnectFrom: function(connectionId) { disconnectFrom: function(connectionId) {
var connection = this.connections.get(connectionId); const connection = this.connections.get(connectionId);
if ( connection === undefined ) { return; } if ( connection === undefined ) { return; }
connection.disconnect(); connection.disconnect();
}, },
sendTo: function(connectionId, payload) { sendTo: function(connectionId, payload) {
var connection = this.connections.get(connectionId); const connection = this.connections.get(connectionId);
if ( connection === undefined ) { return; } if ( connection === undefined ) { return; }
connection.send(payload); connection.send(payload);
}, },
addChannelListener: function(channelName, listener) { addChannelListener: function(channelName, listener) {
var listeners = this.channels.get(channelName); const listeners = this.channels.get(channelName);
if ( listeners === undefined ) { if ( listeners === undefined ) {
this.channels.set(channelName, [ listener ]); this.channels.set(channelName, [ listener ]);
} else if ( listeners.indexOf(listener) === -1 ) { } else if ( listeners.indexOf(listener) === -1 ) {
@ -320,9 +327,9 @@ vAPI.messaging = {
}, },
removeChannelListener: function(channelName, listener) { removeChannelListener: function(channelName, listener) {
var listeners = this.channels.get(channelName); const listeners = this.channels.get(channelName);
if ( listeners === undefined ) { return; } if ( listeners === undefined ) { return; }
var pos = listeners.indexOf(listener); const pos = listeners.indexOf(listener);
if ( pos === -1 ) { return; } if ( pos === -1 ) { return; }
listeners.splice(pos, 1); listeners.splice(pos, 1);
if ( listeners.length === 0 ) { if ( listeners.length === 0 ) {
@ -335,11 +342,11 @@ vAPI.messaging = {
}, },
sendToChannelListeners: function(channelName, msg) { sendToChannelListeners: function(channelName, msg) {
var listeners = this.channels.get(channelName); let listeners = this.channels.get(channelName);
if ( listeners === undefined ) { return; } if ( listeners === undefined ) { return; }
listeners = listeners.slice(0); listeners = listeners.slice(0);
var response; let response;
for ( var listener of listeners ) { for ( const listener of listeners ) {
response = listener(msg); response = listener(msg);
if ( response !== undefined ) { break; } if ( response !== undefined ) { break; }
} }
@ -367,7 +374,7 @@ vAPI.messaging.Connection.prototype = {
this.checkTimer = undefined; this.checkTimer = undefined;
} }
this.messaging.connections.delete(this.id); this.messaging.connections.delete(this.id);
var port = this.messaging.getPort(); const port = this.messaging.getPort();
if ( port === null ) { return; } if ( port === null ) { return; }
port.postMessage({ port.postMessage({
channelName: 'vapi', channelName: 'vapi',
@ -378,12 +385,15 @@ vAPI.messaging.Connection.prototype = {
if ( this.checkTimer !== undefined ) { if ( this.checkTimer !== undefined ) {
clearTimeout(this.checkTimer); clearTimeout(this.checkTimer);
} }
this.checkTimer = vAPI.setTimeout(this.checkBound, 499); this.checkTimer = vAPI.setTimeout(
( ) => { this.check(); },
499
);
}, },
check: function() { check: function() {
this.checkTimer = undefined; this.checkTimer = undefined;
if ( this.messaging.connections.has(this.id) === false ) { return; } if ( this.messaging.connections.has(this.id) === false ) { return; }
var port = this.messaging.getPort(); const port = this.messaging.getPort();
if ( port === null ) { return; } if ( port === null ) { return; }
port.postMessage({ port.postMessage({
channelName: 'vapi', channelName: 'vapi',
@ -407,7 +417,7 @@ vAPI.messaging.Connection.prototype = {
this.checkAsync(); this.checkAsync();
break; break;
case 'connectionCheck': case 'connectionCheck':
var port = this.messaging.getPort(); const port = this.messaging.getPort();
if ( port === null ) { return; } if ( port === null ) { return; }
if ( this.messaging.connections.has(this.id) ) { if ( this.messaging.connections.has(this.id) ) {
this.checkAsync(); this.checkAsync();
@ -423,7 +433,7 @@ vAPI.messaging.Connection.prototype = {
} }
}, },
send: function(payload) { send: function(payload) {
var port = this.messaging.getPort(); const port = this.messaging.getPort();
if ( port === null ) { return; } if ( port === null ) { return; }
port.postMessage({ port.postMessage({
channelName: 'vapi', channelName: 'vapi',
@ -439,9 +449,6 @@ vAPI.shutdown.add(function() {
window.vAPI = undefined; window.vAPI = undefined;
}); });
// https://www.youtube.com/watch?v=rT5zCHn0tsg
// https://www.youtube.com/watch?v=E-jS4e3zacI
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/

View File

@ -1316,7 +1316,7 @@ vAPI.domSurveyor = (function() {
// Bootstrapping allows all components of the content script to be launched // Bootstrapping allows all components of the content script to be launched
// if/when needed. // if/when needed.
(function bootstrap() { vAPI.bootstrap = (function() {
const bootstrapPhase2 = function() { const bootstrapPhase2 = function() {
// This can happen on Firefox. For instance: // This can happen on Firefox. For instance:
@ -1372,7 +1372,16 @@ vAPI.domSurveyor = (function() {
}); });
}; };
// https://github.com/uBlockOrigin/uBlock-issues/issues/403
// If there was a spurious port disconnection -- in which case the
// response is expressly set to `null`, rather than undefined or
// an object -- let's stay around, we may be given the opportunity
// to try bootstrapping again later.
const bootstrapPhase1 = function(response) { const bootstrapPhase1 = function(response) {
if ( response === null ) { return; }
vAPI.bootstrap = undefined;
// cosmetic filtering engine aka 'cfe' // cosmetic filtering engine aka 'cfe'
const cfeDetails = response && response.specificCosmeticFilters; const cfeDetails = response && response.specificCosmeticFilters;
if ( !cfeDetails || !cfeDetails.ready ) { if ( !cfeDetails || !cfeDetails.ready ) {
@ -1451,19 +1460,23 @@ vAPI.domSurveyor = (function() {
} }
}; };
// This starts bootstrap process. return function() {
vAPI.messaging.send( vAPI.messaging.send(
'contentscript', 'contentscript',
{ {
what: 'retrieveContentScriptParameters', what: 'retrieveContentScriptParameters',
url: window.location.href, url: window.location.href,
isRootFrame: window === window.top, isRootFrame: window === window.top,
charset: document.characterSet charset: document.characterSet,
}, },
bootstrapPhase1 bootstrapPhase1
); );
};
})(); })();
// This starts bootstrap process.
vAPI.bootstrap();
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/

View File

@ -23,11 +23,20 @@
// If content scripts are already injected, we need to respond with `false`, // If content scripts are already injected, we need to respond with `false`,
// to "should inject content scripts?" // to "should inject content scripts?"
//
// https://github.com/uBlockOrigin/uBlock-issues/issues/403
// If the content script was not boostrapped, give it another try.
(function() { (function() {
try { try {
return vAPI.uBO !== true; let status = vAPI.uBO !== true;
if ( status === false && vAPI.bootstrap ) {
self.requestIdleCallback(( ) => {
return vAPI && vAPI.bootstrap();
});
}
return status;
} catch(ex) { } catch(ex) {
} }
return true; return true;
})(); })();