import changes from `dev' branch of rmottola/Arctic-Fox:

- Bug 904479 - Added createPromiseWithId() that returns id of resolver r=kanru,nsm (2ac672d882)
- Bug 1166580 - Disable mozHasPendingMessage tests on non-browser platform. r=me (03c689964b)
- Bug 1162281 - Invalid system message handler in an App Manifest can break the entire system. r=fabrice (e192a95f9c)
- Bug 1198988 - Turn off some useless dump() calls r=ferjm (34fc83b236)
- Bug 1164498: Remove |DispatchBluetoothReply|, r=btian (6143335efa)
- Bug 1001757 - Add ability to store core apps outside of profile on desktop b2g; r=fabrice (f6b605e7aa)
- Bug 1155245 - Set the app status correctly for hosted certified apps in developer mode. r=fabrice (131178b80e)
- Bug 1179052 - Add some raptor markers to b2g gecko startup r=gwagner (222256fad8)
- Bug 1163904 - handle -url command line argument. r=fabrice (ee61af1ff9)
- Bug 1167275 - JS error in shell.js handleCmdLine() r=me (32e75c604f)
- Bug 1167197 - Fix GMPProvider on Android r=cpearce Bug 1181209 - Make changes to Gecko needed for b2gdroid to boot. r=fabrice (b35d3a372f)
- Bug 1158544 - Remove FTPChannelChild::mWasOpened and make the base class mWasOpened protected; r=mcmanus (9111e1bc00)
- Bug 1171716 - Part 2: Use NS_ReleaseOnMainThread in nsBaseChannel. r=froydnj (f138124f14)
- partial of Bug 1177175 - Add a UITour target inside the TP panel. (603cc719b3)
- Bug 1175545 - Dont process alt-svc on 421 r=hurley (ad0f2f6e91)
- Bug 1191291 - convert nsHttpChannel::RetargetDeliveryTo warning to log r=michal.novotny (b9c6003df8)
- Bug 1182487 - Don't try to write to HTTP cache entry in nsHttpChannel when entry is open for reading only. r=michal (b36d7014a0)
- Bug 1173069 - Don't accumulate the cache hit telemetry for intercepted channels; r=mayhemer,jdm (aaed79183d)
- Bug 1208755 HttpBaseChannel::ShouldIntercept() should not assume every channel has a LoadInfo. r=ckerschb (d55be94901)
- Bug 1201229 - Return an empty string for a header when an error occurs; r=dragana (256d0462c8)
- Bug 1048048 - add preload content policy types - web platform test updates (r=dveditz) (baa1004dd6)
- Bug 1048048 - add preload content policy types - csp changes (r=dveditz) (17914dadba)
- Bug 1048048 - add preload content policy types for stylesheets (r=cam) (29af13263a)
- Bug 1048048 - add preload content policy types (r=ehsan) (f58a32d51b)
- Bug 1201747 - Don't inspect the subject principal in StorageAllowedForPrincipal. r=mystor (4f2c100882)
- Bug 1176829 - Remove custom elements base element queue. r=smaug (03a520c13d)
- Bug 1176829 follow-up, finish removing unused member to fix bustage. CLOSED TREE (29c6150af8)
- Bug 1179909: Build fix. r=me CLOSED TREE (40e3bdb971)
- Bug 1188932 - Allow the User-Agent header to be explicitly set by requests, r=bkelly, r=jgraham (37aacbd37d)
This commit is contained in:
2022-04-01 23:06:55 +08:00
parent 50e77397ba
commit fe0509a62e
83 changed files with 1117 additions and 506 deletions
+2
View File
@@ -6,6 +6,8 @@
"use strict";
window.performance.mark('gecko-settings-loadstart');
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
+6 -3
View File
@@ -3,7 +3,7 @@
- License, v. 2.0. If a copy of the MPL was not distributed with this file,
- You can obtain one at http://mozilla.org/MPL/2.0/. -->
<html xmlns="http://www.w3.org/1999/xhtml "
<html xmlns="http://www.w3.org/1999/xhtml"
id="shell"
windowtype="navigator:browser"
#ifdef ANDROID
@@ -16,13 +16,16 @@
#ifdef FXOS_SIMULATOR
<link rel="stylesheet" href="desktop.css" type="text/css">
#endif
<script type="text/javascript">
<!-- Add raptor performance marker -->
window.performance.mark('gecko-shell-html-load');
</script>
<script type="application/javascript;version=1.8"
src="chrome://b2g/content/settings.js"> </script>
<script type="application/javascript;version=1.8"
src="chrome://b2g/content/shell.js"> </script>
#ifndef MOZ_WIDGET_GONK
#ifndef ANDROID
<!-- various task that has to happen only on desktop -->
<script type="application/javascript;version=1.8"
src="chrome://b2g/content/desktop.js"> </script>
+38 -1
View File
@@ -4,6 +4,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
window.performance.mark('gecko-shell-loadstart');
Cu.import('resource://gre/modules/ContactService.jsm');
Cu.import('resource://gre/modules/DataStoreChangeNotifier.jsm');
Cu.import('resource://gre/modules/AlarmService.jsm');
@@ -73,6 +75,8 @@ XPCOMUtils.defineLazyServiceGetter(Services, 'captivePortalDetector',
'@mozilla.org/toolkit/captive-detector;1',
'nsICaptivePortalDetector');
window.performance.measure('gecko-shell-jsm-loaded', 'gecko-shell-loadstart');
function getContentWindow() {
return shell.contentBrowser.contentWindow;
}
@@ -214,6 +218,12 @@ var shell = {
},
bootstrap: function() {
#ifdef MOZ_B2GDROID
Cc["@mozilla.org/b2g/b2gdroid-setup;1"]
.getService(Ci.nsIObserver).observe(window, "shell-startup", null);
#endif
window.performance.mark('gecko-shell-bootstrap');
let startManifestURL =
Cc['@mozilla.org/commandlinehandler/general-startup;1?type=b2gbootstrap']
.getService(Ci.nsISupports).wrappedJSObject.startManifestURL;
@@ -228,6 +238,7 @@ var shell = {
},
start: function shell_start() {
window.performance.mark('gecko-shell-start');
this._started = true;
// This forces the initialization of the cookie service before we hit the
@@ -347,6 +358,8 @@ var shell = {
this.contentBrowser.src = homeURL;
this.isHomeLoaded = false;
window.performance.mark('gecko-shell-system-frame-set');
ppmm.addMessageListener("content-handler", this);
ppmm.addMessageListener("dial-handler", this);
ppmm.addMessageListener("sms-handler", this);
@@ -613,6 +626,7 @@ var shell = {
},
notifyContentStart: function shell_notifyContentStart() {
window.performance.mark('gecko-shell-notify-content-start');
this.contentBrowser.removeEventListener('mozbrowserloadstart', this, true);
this.contentBrowser.removeEventListener('mozbrowserlocationchange', this, true);
@@ -650,7 +664,28 @@ var shell = {
}
delete shell.pendingChromeEvents;
});
}
shell.handleCmdLine();
},
handleCmdLine: function shell_handleCmdLine() {
// This isn't supported on devices.
#ifndef ANDROID
let b2gcmds = Cc["@mozilla.org/commandlinehandler/general-startup;1?type=b2gcmds"]
.getService(Ci.nsISupports);
let args = b2gcmds.wrappedJSObject.cmdLine;
try {
// Returns null if -url is not present
let url = args.handleFlagWithParam("url", false);
if (url) {
this.sendChromeEvent({type: "mozbrowseropenwindow", url});
args.preventDefault = true;
}
} catch(e) {
// Throws if -url is present with no params
}
#endif
},
};
Services.obs.addObserver(function onFullscreenOriginChange(subject, topic, data) {
@@ -905,6 +940,7 @@ window.addEventListener('ContentStart', function update_onContentStart() {
Cu.import('resource://gre/modules/WebappsUpdater.jsm');
WebappsUpdater.handleContentStart(shell);
#ifdef MOZ_UPDATER
let promptCc = Cc["@mozilla.org/updates/update-prompt;1"];
if (!promptCc) {
return;
@@ -916,6 +952,7 @@ window.addEventListener('ContentStart', function update_onContentStart() {
}
updatePrompt.wrappedJSObject.handleContentStart(shell);
#endif
});
(function geolocationStatusTracker() {
+7
View File
@@ -16,10 +16,15 @@ contract @mozilla.org/updates/update-prompt;1 {88b3eb21-d072-4e3b-886d-f89d8c49f
category system-update-provider MozillaProvider @mozilla.org/updates/update-prompt;1,{88b3eb21-d072-4e3b-886d-f89d8c49fe59}
#endif
# On b2gdroid we want to use the android implementation of the directory service.
#ifndef MOZ_B2GDROID
#ifdef MOZ_B2G
# DirectoryProvider.js
component {9181eb7c-6f87-11e1-90b1-4f59d80dd2e5} DirectoryProvider.js
contract @mozilla.org/b2g/directory-provider;1 {9181eb7c-6f87-11e1-90b1-4f59d80dd2e5}
category xpcom-directory-providers b2g-directory-provider @mozilla.org/b2g/directory-provider;1
#endif
#endif
# ActivitiesGlue.js
component {3a54788b-48cc-4ab4-93d6-0d6a8ef74f8e} ActivitiesGlue.js
@@ -87,6 +92,7 @@ contract @mozilla.org/fxaccounts/fxaccounts-ui-glue;1 {51875c14-91d7-4b8c-b65d-3
component {710322af-e6ae-4b0c-b2c9-1474a87b077e} HelperAppDialog.js
contract @mozilla.org/helperapplauncherdialog;1 {710322af-e6ae-4b0c-b2c9-1474a87b077e}
#ifndef MOZ_B2GDROID
#ifndef MOZ_WIDGET_GONK
component {c83c02c0-5d43-4e3e-987f-9173b313e880} SimulatorScreen.js
contract @mozilla.org/simulator-screen;1 {c83c02c0-5d43-4e3e-987f-9173b313e880}
@@ -100,6 +106,7 @@ component {385993fe-8710-4621-9fb1-00a09d8bec37} CommandLine.js
contract @mozilla.org/commandlinehandler/general-startup;1?type=b2gcmds {385993fe-8710-4621-9fb1-00a09d8bec37}
category command-line-handler m-b2gcmds @mozilla.org/commandlinehandler/general-startup;1?type=b2gcmds
#endif
#endif
# BootstrapCommandLine.js
component {fd663ec8-cf3f-4c2b-aacb-17a6915ccb44} BootstrapCommandLine.js
+4
View File
@@ -15,6 +15,10 @@ function CommandlineHandler() {
CommandlineHandler.prototype = {
handle: function(cmdLine) {
this.cmdLine = cmdLine;
let win = Services.wm.getMostRecentWindow("navigator:browser");
if (win && win.shell) {
win.shell.handleCmdLine();
}
},
helpInfo: "",
+21 -5
View File
@@ -15,6 +15,7 @@ const UPDATE_ARCHIVE_DIR = "UpdArchD"
const LOCAL_DIR = "/data/local";
const UPDATES_DIR = "updates/0";
const FOTA_DIR = "updates/fota";
const COREAPPSDIR_PREF = "b2g.coreappsdir"
XPCOMUtils.defineLazyServiceGetter(Services, "env",
"@mozilla.org/process/environment;1",
@@ -97,12 +98,27 @@ DirectoryProvider.prototype = {
return this.getUpdateDir(persistent, FOTA_DIR, 1.1);
}
#else
// In desktop builds, coreAppsDir is the same as the profile directory.
// We just need to get the path from the parent, and it is then used to
// build jar:remoteopenfile:// uris.
// In desktop builds, coreAppsDir is the same as the profile
// directory unless otherwise specified. We just need to get the
// path from the parent, and it is then used to build
// jar:remoteopenfile:// uris.
if (prop == "coreAppsDir") {
let appsDir = Services.dirsvc.get("ProfD", Ci.nsIFile);
appsDir.append("webapps");
let coreAppsDirPref;
try {
coreAppsDirPref = Services.prefs.getCharPref(COREAPPSDIR_PREF);
} catch (e) {
// coreAppsDirPref may not exist if we're on an older version
// of gaia, so just fail silently.
}
let appsDir;
// If pref doesn't exist or isn't set, default to old value
if (!coreAppsDirPref || coreAppsDirPref == "") {
appsDir = Services.dirsvc.get("ProfD", Ci.nsIFile);
appsDir.append("webapps");
} else {
appsDir = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile)
appsDir.initWithPath(coreAppsDirPref);
}
persistent.value = true;
return appsDir;
} else if (prop == "ProfD") {
+7 -3
View File
@@ -31,7 +31,7 @@ EXTRA_COMPONENTS += [
'WebappsUpdateTimer.js',
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk' and CONFIG['MOZ_WIDGET_TOOLKIT'] != 'android':
EXTRA_COMPONENTS += [
'CommandLine.js',
'OopCommandLine.js',
@@ -40,10 +40,14 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
EXTRA_PP_COMPONENTS += [
'B2GComponents.manifest',
'DirectoryProvider.js',
'RecoveryService.js',
]
if CONFIG['MOZ_B2G'] and not CONFIG['MOZ_B2GDROID']:
EXTRA_PP_COMPONENTS += [
'DirectoryProvider.js',
'RecoveryService.js',
]
if CONFIG['MOZ_UPDATER']:
EXTRA_PP_COMPONENTS += [
'UpdatePrompt.js',
Binary file not shown.
Binary file not shown.
+10 -1
View File
@@ -95,10 +95,14 @@ http://example.net:80 privileged
# Used to test that clearing Service Workers for domain example.com, does not clear prefixexample.com
http://prefixexample.com:80
# The first HTTPS location is used to generate the Common Name (CN) value of the
# certificate's Issued To field.
https://example.com:443 privileged
https://example.org:443 privileged
https://test1.example.com:443 privileged
https://test2.example.com:443 privileged
https://example.org:443 privileged
https://test1.example.org:443 privileged
https://test2.example.org:443 privileged
https://sub1.test1.example.com:443 privileged
https://sub1.test2.example.com:443 privileged
https://sub2.test1.example.com:443 privileged
@@ -168,6 +172,11 @@ http://tracking.example.com:80
http://not-tracking.example.com:80
http://tracking.example.org:80
https://malware.example.com:443
https://tracking.example.com:443
https://not-tracking.example.com:443
https://tracking.example.org:443
# Bug 483437, 484111
https://www.bank1.com:443 privileged,cert=escapeattack1
+4
View File
@@ -4003,6 +4003,10 @@ b2g/dev)
;;
esac
if test -n "$MOZ_B2GDROID"; then
AC_DEFINE(MOZ_B2GDROID)
fi
AC_SUBST(MOZ_BUILD_APP)
AC_SUBST(MOZ_PHOENIX)
AC_SUBST(MOZ_XULRUNNER)
+21 -43
View File
@@ -316,7 +316,7 @@ WebappsRegistry.prototype = {
}
this.addMessageListeners(["Webapps:GetLocalizationResource:Return"]);
return this.createPromise((aResolve, aReject) => {
return this.createPromiseWithId((aResolverId) => {
cpmm.sendAsyncMessage("Webapps:GetLocalizationResource", {
manifestURL: manifestURL,
lang: aLanguage,
@@ -325,10 +325,7 @@ WebappsRegistry.prototype = {
dataType: aType,
oid: this._id,
topId: this._topId,
requestID: this.getPromiseResolverId({
resolve: aResolve,
reject: aReject
})
requestID: aResolverId
});
});
},
@@ -609,7 +606,7 @@ WebappsApplication.prototype = {
connect: function(aKeyword, aRules) {
this.addMessageListeners(["Webapps:Connect:Return:OK",
"Webapps:Connect:Return:KO"]);
return this.createPromise(function (aResolve, aReject) {
return this.createPromiseWithId((aResolverId) => {
let from = this._window.location.origin + this._window.location.pathname;
cpmm.sendAsyncMessage("Webapps:Connect", {
keyword: aKeyword,
@@ -618,27 +615,21 @@ WebappsApplication.prototype = {
pubPageURL: from,
outerWindowID: this._id,
topWindowID: this._topId,
requestID: this.getPromiseResolverId({
resolve: aResolve,
reject: aReject
})
requestID: aResolverId
});
}.bind(this));
});
},
getConnections: function() {
this.addMessageListeners("Webapps:GetConnections:Return:OK");
return this.createPromise(function (aResolve, aReject) {
return this.createPromiseWithId((aResolverId) => {
cpmm.sendAsyncMessage("Webapps:GetConnections", {
manifestURL: this.manifestURL,
outerWindowID: this._id,
topWindowID: this._topId,
requestID: this.getPromiseResolverId({
resolve: aResolve,
reject: aReject
})
requestID: aResolverId
});
}.bind(this));
});
},
addReceipt: function(receipt) {
@@ -689,22 +680,19 @@ WebappsApplication.prototype = {
export: function() {
this.addMessageListeners(["Webapps:Export:Return"]);
return this.createPromise((aResolve, aReject) => {
return this.createPromiseWithId((aResolverId) => {
cpmm.sendAsyncMessage("Webapps:Export",
{ manifestURL: this.manifestURL,
oid: this._id,
topId: this._topId,
requestID: this.getPromiseResolverId({
resolve: aResolve,
reject: aReject
})
requestID: aResolverId
});
});
},
getLocalizedValue: function(aProperty, aLang, aEntryPoint) {
this.addMessageListeners(["Webapps:GetLocalizedValue:Return"]);
return this.createPromise((aResolve, aReject) => {
return this.createPromiseWithId((aResolverId) => {
cpmm.sendAsyncMessage("Webapps:GetLocalizedValue",
{ manifestURL: this.manifestURL,
oid: this._id,
@@ -712,10 +700,7 @@ WebappsApplication.prototype = {
property: aProperty,
lang: aLang,
entryPoint: aEntryPoint,
requestID: this.getPromiseResolverId({
resolve: aResolve,
reject: aReject
})
requestID: aResolverId
});
});
},
@@ -958,19 +943,16 @@ WebappsApplicationMgmt.prototype = {
},
getIcon: function(aApp, aIconID, aEntryPoint) {
return this.createPromise(function(aResolve, aReject) {
return this.createPromiseWithId((aResolverId) => {
cpmm.sendAsyncMessage("Webapps:GetIcon", {
oid: this._id,
topId: this._topId,
manifestURL: aApp.manifestURL,
iconID: aIconID,
entryPoint: aEntryPoint,
requestID: this.getPromiseResolverId({
resolve: aResolve,
reject: aReject
})
requestID: aResolverId
});
}.bind(this));
});
},
getNotInstalled: function() {
@@ -988,29 +970,25 @@ WebappsApplicationMgmt.prototype = {
import: function(aBlob) {
let principal = this._window.document.nodePrincipal;
return this.createPromise((aResolve, aReject) => {
return this.createPromiseWithId((aResolverId) => {
cpmm.sendAsyncMessage("Webapps:Import",
{ blob: aBlob,
oid: this._id,
topId: this._topId,
requestID: this.getPromiseResolverId({
resolve: aResolve,
reject: aReject
})}, null, principal);
requestID: aResolverId
}, null, principal);
});
},
extractManifest: function(aBlob) {
let principal = this._window.document.nodePrincipal;
return this.createPromise((aResolve, aReject) => {
return this.createPromiseWithId((aResolverId) => {
cpmm.sendAsyncMessage("Webapps:ExtractManifest",
{ blob: aBlob,
oid: this._id,
topId: this._topId,
requestID: this.getPromiseResolverId({
resolve: aResolve,
reject: aReject
})}, null, principal);
requestID: aResolverId
}, null, principal);
});
},
+45 -24
View File
@@ -85,6 +85,9 @@ XPCOMUtils.defineLazyModuleGetter(this, "Langpacks",
XPCOMUtils.defineLazyModuleGetter(this, "ImportExport",
"resource://gre/modules/ImportExport.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
"resource://gre/modules/AppConstants.jsm");
#ifdef MOZ_WIDGET_GONK
XPCOMUtils.defineLazyGetter(this, "libcutils", function() {
Cu.import("resource://gre/modules/systemlibs.js");
@@ -774,9 +777,9 @@ this.DOMApplicationRegistry = {
}
}
#ifdef MOZ_WIDGET_GONK
yield this.installSystemApps();
#endif
if (AppConstants.MOZ_B2GDROID || AppConstants.MOZ_B2G) {
yield this.installSystemApps();
}
// At first run, install preloaded apps and set up their permissions.
for (let id in this.webapps) {
@@ -851,8 +854,16 @@ this.DOMApplicationRegistry = {
root = aManifest.entry_points[aEntryPoint];
}
if (!root.messages || !Array.isArray(root.messages) ||
root.messages.length == 0) {
if (!root.messages) {
// This application just doesn't use system messages.
return;
}
if (!Array.isArray(root.messages) || root.messages.length == 0) {
dump("Could not register invalid system message entry for " + aApp.manifestURL + "\n");
try {
dump(JSON.stringify(root.messages) + "\n");
} catch(e) {}
return;
}
@@ -862,28 +873,32 @@ this.DOMApplicationRegistry = {
root.messages.forEach(function registerPages(aMessage) {
let handlerPageURI = launchPathURI;
let messageName;
if (typeof(aMessage) === "object" && Object.keys(aMessage).length === 1) {
messageName = Object.keys(aMessage)[0];
let handlerPath = aMessage[messageName];
// Resolve the handler path from origin. If |handler_path| is absent,
// simply skip.
let fullHandlerPath;
if (typeof(aMessage) !== "object" || Object.keys(aMessage).length !== 1) {
dump("Could not register invalid system message entry for " + aApp.manifestURL + "\n");
try {
if (handlerPath && handlerPath.trim()) {
fullHandlerPath = manifest.resolveURL(handlerPath);
} else {
throw new Error("Empty or blank handler path.");
}
} catch(e) {
debug("system message handler path (" + handlerPath + ") is " +
"invalid, skipping. Error is: " + e);
return;
}
handlerPageURI = Services.io.newURI(fullHandlerPath, null, null);
} else {
messageName = aMessage;
dump(JSON.stringify(aMessage) + "\n");
} catch(e) {}
return;
}
messageName = Object.keys(aMessage)[0];
let handlerPath = aMessage[messageName];
// Resolve the handler path from origin. If |handler_path| is absent,
// simply skip.
let fullHandlerPath;
try {
if (handlerPath && handlerPath.trim()) {
fullHandlerPath = manifest.resolveURL(handlerPath);
} else {
throw new Error("Empty or blank handler path.");
}
} catch(e) {
debug("system message handler path (" + handlerPath + ") is " +
"invalid, skipping. Error is: " + e);
return;
}
handlerPageURI = Services.io.newURI(fullHandlerPath, null, null);
if (SystemMessagePermissionsChecker
.isSystemMessagePermittedToRegister(messageName,
aApp.manifestURL,
@@ -2939,6 +2954,12 @@ this.DOMApplicationRegistry = {
// don't update the permissions yet.
if (!aData.isPackage) {
if (supportUseCurrentProfile()) {
try {
if (Services.prefs.getBoolPref("dom.apps.developer_mode")) {
this.webapps[id].appStatus =
AppsUtils.getAppManifestStatus(app.manifest);
}
} catch(e) {};
PermissionsInstaller.installPermissions(
{
origin: appObject.origin,
+11
View File
@@ -298,6 +298,17 @@ DOMRequestIpcHelper.prototype = {
return new this._window.Promise(aPromiseInit);
},
/**
* createPromiseWithId() creates a new Promise, accepting a callback
* which is immediately called with the generated resolverId.
*/
createPromiseWithId: function(aCallback) {
return this.createPromise(function(aResolve, aReject) {
let resolverId = this.getPromiseResolverId({ resolve: aResolve, reject: aReject });
aCallback(resolverId);
}.bind(this));
},
forEachRequest: function(aCallback) {
if (!this._requests) {
return;
+40 -35
View File
@@ -93,41 +93,46 @@ inline const char *
NS_CP_ContentTypeName(uint32_t contentType)
{
switch (contentType) {
CASE_RETURN( TYPE_OTHER );
CASE_RETURN( TYPE_SCRIPT );
CASE_RETURN( TYPE_IMAGE );
CASE_RETURN( TYPE_STYLESHEET );
CASE_RETURN( TYPE_OBJECT );
CASE_RETURN( TYPE_DOCUMENT );
CASE_RETURN( TYPE_SUBDOCUMENT );
CASE_RETURN( TYPE_REFRESH );
CASE_RETURN( TYPE_XBL );
CASE_RETURN( TYPE_PING );
CASE_RETURN( TYPE_XMLHTTPREQUEST );
CASE_RETURN( TYPE_OBJECT_SUBREQUEST );
CASE_RETURN( TYPE_DTD );
CASE_RETURN( TYPE_FONT );
CASE_RETURN( TYPE_MEDIA );
CASE_RETURN( TYPE_WEBSOCKET );
CASE_RETURN( TYPE_CSP_REPORT );
CASE_RETURN( TYPE_XSLT );
CASE_RETURN( TYPE_BEACON );
CASE_RETURN( TYPE_FETCH );
CASE_RETURN( TYPE_IMAGESET );
CASE_RETURN( TYPE_WEB_MANIFEST );
CASE_RETURN( TYPE_INTERNAL_SCRIPT );
CASE_RETURN( TYPE_INTERNAL_WORKER );
CASE_RETURN( TYPE_INTERNAL_SHARED_WORKER );
CASE_RETURN( TYPE_INTERNAL_EMBED );
CASE_RETURN( TYPE_INTERNAL_OBJECT );
CASE_RETURN( TYPE_INTERNAL_FRAME );
CASE_RETURN( TYPE_INTERNAL_IFRAME );
CASE_RETURN( TYPE_INTERNAL_AUDIO );
CASE_RETURN( TYPE_INTERNAL_VIDEO );
CASE_RETURN( TYPE_INTERNAL_TRACK );
CASE_RETURN( TYPE_INTERNAL_XMLHTTPREQUEST );
CASE_RETURN( TYPE_INTERNAL_EVENTSOURCE );
CASE_RETURN( TYPE_INTERNAL_SERVICE_WORKER );
CASE_RETURN( TYPE_OTHER );
CASE_RETURN( TYPE_SCRIPT );
CASE_RETURN( TYPE_IMAGE );
CASE_RETURN( TYPE_STYLESHEET );
CASE_RETURN( TYPE_OBJECT );
CASE_RETURN( TYPE_DOCUMENT );
CASE_RETURN( TYPE_SUBDOCUMENT );
CASE_RETURN( TYPE_REFRESH );
CASE_RETURN( TYPE_XBL );
CASE_RETURN( TYPE_PING );
CASE_RETURN( TYPE_XMLHTTPREQUEST );
CASE_RETURN( TYPE_OBJECT_SUBREQUEST );
CASE_RETURN( TYPE_DTD );
CASE_RETURN( TYPE_FONT );
CASE_RETURN( TYPE_MEDIA );
CASE_RETURN( TYPE_WEBSOCKET );
CASE_RETURN( TYPE_CSP_REPORT );
CASE_RETURN( TYPE_XSLT );
CASE_RETURN( TYPE_BEACON );
CASE_RETURN( TYPE_FETCH );
CASE_RETURN( TYPE_IMAGESET );
CASE_RETURN( TYPE_WEB_MANIFEST );
CASE_RETURN( TYPE_INTERNAL_SCRIPT );
CASE_RETURN( TYPE_INTERNAL_WORKER );
CASE_RETURN( TYPE_INTERNAL_SHARED_WORKER );
CASE_RETURN( TYPE_INTERNAL_EMBED );
CASE_RETURN( TYPE_INTERNAL_OBJECT );
CASE_RETURN( TYPE_INTERNAL_FRAME );
CASE_RETURN( TYPE_INTERNAL_IFRAME );
CASE_RETURN( TYPE_INTERNAL_AUDIO );
CASE_RETURN( TYPE_INTERNAL_VIDEO );
CASE_RETURN( TYPE_INTERNAL_TRACK );
CASE_RETURN( TYPE_INTERNAL_XMLHTTPREQUEST );
CASE_RETURN( TYPE_INTERNAL_EVENTSOURCE );
CASE_RETURN( TYPE_INTERNAL_SERVICE_WORKER );
CASE_RETURN( TYPE_INTERNAL_SCRIPT_PRELOAD );
CASE_RETURN( TYPE_INTERNAL_IMAGE );
CASE_RETURN( TYPE_INTERNAL_IMAGE_PRELOAD );
CASE_RETURN( TYPE_INTERNAL_STYLESHEET );
CASE_RETURN( TYPE_INTERNAL_STYLESHEET_PRELOAD );
default:
return "<Unknown Type>";
}
+17 -23
View File
@@ -95,7 +95,6 @@
#include "nsHostObjectProtocolHandler.h"
#include "nsHtml5Module.h"
#include "nsHtml5StringParser.h"
#include "nsIAppShell.h"
#include "nsIAsyncVerifyRedirectCallback.h"
#include "nsICategoryManager.h"
#include "nsIChannelEventSink.h"
@@ -357,7 +356,6 @@ namespace {
static NS_DEFINE_CID(kParserServiceCID, NS_PARSERSERVICE_CID);
static NS_DEFINE_CID(kCParserCID, NS_PARSER_CID);
static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID);
static PLDHashTable* sEventListenerManagersHash;
@@ -5266,7 +5264,6 @@ nsContentUtils::LeaveMicroTask()
MOZ_ASSERT(NS_IsMainThread());
if (--sMicroTaskLevel == 0) {
PerformMainThreadMicroTaskCheckpoint();
nsDocument::ProcessBaseElementQueue();
}
}
@@ -7173,7 +7170,7 @@ nsContentUtils::IsForbiddenSystemRequestHeader(const nsACString& aHeader)
"access-control-request-method", "connection", "content-length",
"cookie", "cookie2", "content-transfer-encoding", "date", "dnt",
"expect", "host", "keep-alive", "origin", "referer", "te", "trailer",
"transfer-encoding", "upgrade", "user-agent", "via"
"transfer-encoding", "upgrade", "via"
};
for (uint32_t i = 0; i < ArrayLength(kInvalidHeaders); ++i) {
if (aHeader.LowerCaseEqualsASCII(kInvalidHeaders[i])) {
@@ -7972,13 +7969,13 @@ nsContentUtils::GetWindowRoot(nsIDocument* aDoc)
return nullptr;
}
/* static */
nsContentPolicyType
nsContentUtils::InternalContentPolicyTypeToExternal(nsContentPolicyType aType)
{
switch (aType) {
case nsIContentPolicy::TYPE_INTERNAL_SCRIPT:
case nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD:
case nsIContentPolicy::TYPE_INTERNAL_WORKER:
case nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER:
case nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER:
@@ -8001,6 +7998,14 @@ nsContentUtils::InternalContentPolicyTypeToExternal(nsContentPolicyType aType)
case nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE:
return nsIContentPolicy::TYPE_XMLHTTPREQUEST;
case nsIContentPolicy::TYPE_INTERNAL_IMAGE:
case nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD:
return nsIContentPolicy::TYPE_IMAGE;
case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET:
case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD:
return nsIContentPolicy::TYPE_STYLESHEET;
default:
return aType;
}
@@ -8211,28 +8216,17 @@ nsContentUtils::InternalStorageAllowedForPrincipal(nsIPrincipal* aPrincipal,
access = std::min(StorageAccess::eSessionScoped, access);
}
// If the caller is chrome privileged, then it is allowed to access any
// storage it likes, no matter whether the storage for that window/principal
// would normally be permitted.
if (IsSystemPrincipal(SubjectPrincipal())) {
return access;
}
if (!SubjectPrincipal()->Subsumes(aPrincipal)) {
NS_WARNING("A principal is attempting to access storage for a principal "
"which it doesn't subsume!");
return StorageAccess::eDeny;
}
// About URIs are allowed to access storage, even if they don't have chrome
// privileges. If this is not desired, than the consumer will have to
// implement their own restriction functionality.
nsCOMPtr<nsIURI> uri;
MOZ_ALWAYS_TRUE(NS_SUCCEEDED(aPrincipal->GetURI(getter_AddRefs(uri))));
bool isAbout = false;
MOZ_ALWAYS_TRUE(NS_SUCCEEDED(uri->SchemeIs("about", &isAbout)));
if (isAbout) {
return access;
nsresult rv = aPrincipal->GetURI(getter_AddRefs(uri));
if (NS_SUCCEEDED(rv) && uri) {
bool isAbout = false;
MOZ_ALWAYS_TRUE(NS_SUCCEEDED(uri->SchemeIs("about", &isAbout)));
if (isAbout) {
return access;
}
}
nsCOMPtr<nsIPermissionManager> permissionManager =
+6 -57
View File
@@ -5915,29 +5915,6 @@ nsDocument::RegisterUnresolvedElement(Element* aElement, nsIAtom* aTypeName)
return NS_OK;
}
namespace {
class ProcessStackRunner final : public nsIRunnable
{
~ProcessStackRunner() {}
public:
explicit ProcessStackRunner(bool aIsBaseQueue = false)
: mIsBaseQueue(aIsBaseQueue)
{
}
NS_DECL_ISUPPORTS
NS_IMETHOD Run() override
{
nsDocument::ProcessTopElementQueue(mIsBaseQueue);
return NS_OK;
}
bool mIsBaseQueue;
};
NS_IMPL_ISUPPORTS(ProcessStackRunner, nsIRunnable);
} // namespace
void
nsDocument::EnqueueLifecycleCallback(nsIDocument::ElementCallbackType aType,
Element* aCustomElement,
@@ -6039,10 +6016,7 @@ nsDocument::EnqueueLifecycleCallback(nsIDocument::ElementCallbackType aType,
// A new element queue needs to be pushed if the queue at the
// top of the stack is associated with another microtask level.
// Don't push a queue for the level 0 microtask (base element queue)
// because we don't want to process the queue until the
// microtask checkpoint.
bool shouldPushElementQueue = nsContentUtils::MicroTaskLevel() > 0 &&
bool shouldPushElementQueue =
(!lastData || lastData->mAssociatedMicroTask <
static_cast<int32_t>(nsContentUtils::MicroTaskLevel()));
@@ -6065,39 +6039,22 @@ nsDocument::EnqueueLifecycleCallback(nsIDocument::ElementCallbackType aType,
// should be invoked prior to returning control back to script.
// Create a script runner to process the top of the processing
// stack as soon as it is safe to run script.
nsContentUtils::AddScriptRunner(new ProcessStackRunner());
nsCOMPtr<nsIRunnable> runnable =
NS_NewRunnableFunction(&nsDocument::ProcessTopElementQueue);
nsContentUtils::AddScriptRunner(runnable);
}
}
}
// static
void
nsDocument::ProcessBaseElementQueue()
{
// Prevent re-entrance. Also, if a microtask checkpoint is reached
// and there is no processing stack to process, then we are done.
if (sProcessingBaseElementQueue || !sProcessingStack) {
return;
}
MOZ_ASSERT(nsContentUtils::MicroTaskLevel() == 0);
sProcessingBaseElementQueue = true;
nsContentUtils::AddScriptRunner(new ProcessStackRunner(true));
}
// static
void
nsDocument::ProcessTopElementQueue(bool aIsBaseQueue)
nsDocument::ProcessTopElementQueue()
{
MOZ_ASSERT(nsContentUtils::IsSafeToRunScript());
nsTArray<nsRefPtr<CustomElementData>>& stack = *sProcessingStack;
uint32_t firstQueue = stack.LastIndexOf((CustomElementData*) nullptr);
if (aIsBaseQueue && firstQueue != 0) {
return;
}
for (uint32_t i = firstQueue + 1; i < stack.Length(); ++i) {
// Callback queue may have already been processed in an earlier
// element queue or in an element queue that was popped
@@ -6115,7 +6072,6 @@ nsDocument::ProcessTopElementQueue(bool aIsBaseQueue)
} else {
// Don't pop sentinel for base element queue.
stack.SetLength(1);
sProcessingBaseElementQueue = false;
}
}
@@ -6131,10 +6087,6 @@ nsDocument::RegisterEnabled()
Maybe<nsTArray<nsRefPtr<mozilla::dom::CustomElementData>>>
nsDocument::sProcessingStack;
// static
bool
nsDocument::sProcessingBaseElementQueue;
void
nsDocument::RegisterElement(JSContext* aCx, const nsAString& aType,
const ElementRegistrationOptions& aOptions,
@@ -8594,9 +8546,6 @@ nsDocument::RetrieveRelevantHeaders(nsIChannel *aChannel)
// The misspelled key 'referer' is as per the HTTP spec
rv = httpChannel->GetRequestHeader(NS_LITERAL_CSTRING("referer"),
mReferrer);
if (NS_FAILED(rv)) {
mReferrer.Truncate();
}
static const char *const headers[] = {
"default-style",
@@ -9907,7 +9856,7 @@ nsDocument::PreloadStyle(nsIURI* uri, const nsAString& charset,
nsCOMPtr<nsICSSLoaderObserver> obs = new StubCSSLoaderObserver();
// Charset names are always ASCII.
CSSLoader()->LoadSheet(uri, NodePrincipal(),
CSSLoader()->LoadSheet(uri, true, NodePrincipal(),
NS_LossyConvertUTF16toASCII(charset),
obs,
Element::StringToCORSMode(aCrossOriginAttr),
+1 -7
View File
@@ -1296,7 +1296,7 @@ public:
mozilla::dom::LifecycleCallbackArgs* aArgs = nullptr,
mozilla::dom::CustomElementDefinition* aDefinition = nullptr) override;
static void ProcessTopElementQueue(bool aIsBaseQueue = false);
static void ProcessTopElementQueue();
void GetCustomPrototype(int32_t aNamespaceID,
nsIAtom* aAtom,
@@ -1584,15 +1584,9 @@ private:
// queue in the stack is the base element queue.
static mozilla::Maybe<nsTArray<nsRefPtr<mozilla::dom::CustomElementData>>> sProcessingStack;
// Flag to prevent re-entrance into base element queue as described in the
// custom elements speicification.
static bool sProcessingBaseElementQueue;
static bool CustomElementConstructor(JSContext* aCx, unsigned aArgc, JS::Value* aVp);
public:
static void ProcessBaseElementQueue();
// Enqueue created callback or register upgrade candidate for
// newly created custom elements, possibly extending an existing type.
// ex. <x-button>, <button is="x-button> (type extension)
+1 -1
View File
@@ -20,7 +20,7 @@ interface nsIPrincipal;
* by launching a dialog to prompt the user for something).
*/
[scriptable,uuid(ce321216-c404-40a7-a711-d80454ec6b76)]
[scriptable,uuid(caad4f1f-d047-46ac-ae9d-dc598e4fb91b)]
interface nsIContentPolicy : nsIContentPolicyBase
{
/**
+1 -1
View File
@@ -24,7 +24,7 @@ typedef unsigned long nsContentPolicyType;
* by launching a dialog to prompt the user for something).
*/
[scriptable,uuid(8527ae0d-0c43-4413-bc46-85c0bcb66876)]
[scriptable,uuid(17418187-d86f-48dd-92d1-238838df0a4e)]
interface nsIContentPolicyBase : nsISupports
{
/**
@@ -0,0 +1,8 @@
function handleRequest(request, response)
{
if (request.hasHeader("User-Agent")) {
response.setHeader("Result-User-Agent",
request.getHeader("User-Agent"));
}
response.write("");
}
+2
View File
@@ -250,6 +250,7 @@ support-files =
iframe_postMessages.html
test_performance_observer.js
performance_observer.html
file_explicit_user_agent.sjs
[test_anonymousContent_api.html]
[test_anonymousContent_append_after_reflow.html]
@@ -818,3 +819,4 @@ support-files = worker_postMessages.js
[test_window_proto.html]
[test_frameLoader_switchProcess.html]
skip-if = e10s || os != 'linux' || buildapp != 'browser'
[test_explicit_user_agent.html]
+12
View File
@@ -400,6 +400,18 @@
ok(promise instanceof Promise, "Returned a Promise");
promise.then(next);
},
function() {
info("== Test createPromiseWithId()");
var _resolverId;
var promise = dummy.createPromiseWithId(function(resolverId) {
_resolverId = resolverId;
});
var resolver = dummy.getPromiseResolver(_resolverId);
ok(promise instanceof Promise, "Returned a Promise");
ok(typeof _resolverId === "string", "resolverId is a string");
ok(resolver != null, "resolverId is a valid id");
next();
},
function() {
info("== Test getResolver()");
var id;
@@ -0,0 +1,65 @@
<!DOCTYPE HTML>
<html>
<head>
<title>Test for XMLHttpRequest.GetResponseHeader(foo) byte-inflates the output</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<meta charset="utf-8">
</head>
<body>
<p id="display"></p>
<div id="content" style="display: none">
</div>
<pre id="test">
<script class="testbody" type="application/javascript;version=1.7">
"use strict";
add_task(function*() {
yield new Promise((r) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'file_explicit_user_agent.sjs', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
is(xhr.getResponseHeader("Result-User-Agent"), navigator.userAgent,
"The resulting user-agent is the navigator's UA");
r();
}
}
xhr.send(null);
});
yield new Promise((r) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'file_explicit_user_agent.sjs', true);
xhr.setRequestHeader('User-Agent', 'custom-ua/10.0');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
is(xhr.getResponseHeader("Result-User-Agent"), 'custom-ua/10.0',
"The resulting user-agent is the custom UA");
r();
}
}
xhr.send(null);
});
var response = yield fetch('file_explicit_user_agent.sjs', {
method: 'GET'
});
is(response.headers.get("Result-User-Agent"), navigator.userAgent,
"The user-agent is the navigator's UA");
var headers = new Headers();
headers.set('User-Agent', 'custom-ua/20.0');
var response2 = yield fetch('file_explicit_user_agent.sjs', {
method: 'GET',
headers: headers,
});
is(response2.headers.get("Result-User-Agent"), 'custom-ua/20.0',
"The user-agent is the custom UA");
});
</script>
</pre>
</body>
</html>
@@ -40,7 +40,6 @@ var headers = [
"trAiLer",
"trANsfEr-eNcoDiNg",
"uPGraDe",
"user-AGENT",
"viA",
"pRoxy-",
"sEc-",
+2 -6
View File
@@ -411,7 +411,6 @@ DispatchToBtThread(nsIRunnable* aRunnable)
return sBluetoothThread->Dispatch(aRunnable, NS_DISPATCH_NORMAL);
}
#ifdef MOZ_B2G_BT_API_V2
static void
DispatchBluetoothReply(BluetoothReplyRunnable* aRunnable,
const BluetoothValue& aValue,
@@ -423,9 +422,6 @@ DispatchBluetoothReply(BluetoothReplyRunnable* aRunnable,
DispatchReplySuccess(aRunnable, aValue);
}
}
#else
// Missing in bluetooth1
#endif
BluetoothDBusService::BluetoothDBusService()
{
@@ -4275,14 +4271,14 @@ BluetoothDBusService::UpdateNotification(ControlEventId aEventId,
void
BluetoothDBusService::StartLeScanInternal(
const nsTArray<nsString>& aServiceUuids,
BluetoothReplyRunnable* aRunnable);
BluetoothReplyRunnable* aRunnable)
{
}
void
BluetoothDBusService::StopLeScanInternal(
const nsAString& aAppUuid,
BluetoothReplyRunnable* aRunnable);
BluetoothReplyRunnable* aRunnable)
{
}
+6 -27
View File
@@ -221,8 +221,10 @@ BroadcastSystemMessage(const nsAString& aType,
return false;
}
nsCOMPtr<nsISupports> promise;
systemMessenger->BroadcastMessage(aType, value,
JS::UndefinedHandleValue);
JS::UndefinedHandleValue,
getter_AddRefs(promise));
return true;
}
@@ -251,8 +253,10 @@ BroadcastSystemMessage(const nsAString& aType,
NS_ENSURE_TRUE(systemMessenger, false);
JS::Rooted<JS::Value> value(cx, JS::ObjectValue(*obj));
nsCOMPtr<nsISupports> promise;
systemMessenger->BroadcastMessage(aType, value,
JS::UndefinedHandleValue);
JS::UndefinedHandleValue,
getter_AddRefs(promise));
return true;
}
@@ -306,31 +310,6 @@ DispatchReplyError(BluetoothReplyRunnable* aRunnable,
NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(aRunnable)));
}
#if MOZ_B2G_BT_API_V2
// TODO: remove with bluetooth1
#else
void
DispatchBluetoothReply(BluetoothReplyRunnable* aRunnable,
const BluetoothValue& aValue,
const nsAString& aErrorStr)
{
// Reply will be deleted by the runnable after running on main thread
BluetoothReply* reply;
if (!aErrorStr.IsEmpty()) {
nsString err(aErrorStr);
reply = new BluetoothReply(BluetoothReplyError(err));
} else {
MOZ_ASSERT(aValue.type() != BluetoothValue::T__None);
reply = new BluetoothReply(BluetoothReplySuccess(aValue));
}
aRunnable->SetReply(reply);
if (NS_FAILED(NS_DispatchToMainThread(aRunnable))) {
BT_WARNING("Failed to dispatch to main thread!");
}
}
#endif
void
DispatchStatusChangedEvent(const nsAString& aType,
const nsAString& aAddress,
-9
View File
@@ -161,15 +161,6 @@ void
DispatchReplyError(BluetoothReplyRunnable* aRunnable,
const enum BluetoothStatus aStatus);
#if MOZ_B2G_BT_API_V2
// TODO: remove with bluetooth1
#else
void
DispatchBluetoothReply(BluetoothReplyRunnable* aRunnable,
const BluetoothValue& aValue,
const nsAString& aErrorStr);
#endif
void
DispatchStatusChangedEvent(const nsAString& aType,
const nsAString& aDeviceAddress,
+6 -1
View File
@@ -275,7 +275,12 @@ static_assert(nsIContentPolicy::TYPE_INVALID == 0 &&
nsIContentPolicy::TYPE_INTERNAL_TRACK == 32 &&
nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST == 33 &&
nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE == 34 &&
nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER == 35,
nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER == 35 &&
nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD == 36 &&
nsIContentPolicy::TYPE_INTERNAL_IMAGE == 37 &&
nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD == 38 &&
nsIContentPolicy::TYPE_INTERNAL_STYLESHEET == 39 &&
nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD == 40,
"nsContentPolicyType values are as expected");
namespace {
+8 -14
View File
@@ -52,36 +52,30 @@ EngineeringModeAPI.prototype = {
// This returns a Promise<DOMString>
getValue: function getValue(aName) {
debug("getValue " + aName);
let promiseInit = function(resolve, reject) {
debug("promise init called for getValue " + aName);
let resolverId = this.getPromiseResolverId({resolve: resolve,
reject: reject });
debug("promise init " + resolverId);
let promiseInit = function(aResolverId) {
debug("promise init called for getValue " + aName + " has resolverId " + aResolverId);
cpmm.sendAsyncMessage("EngineeringMode:GetValue", {
requestId: resolverId,
requestId: aResolverId,
name: aName
});
}.bind(this);
return this.createPromise(promiseInit);
return this.createPromiseWithId(promiseInit);
},
// This returns a Promise<void>
setValue: function setValue(aName, aValue) {
debug("setValue " + aName + ' as ' + aValue );
let promiseInit = function(resolve, reject) {
debug("promise init called for setValue " + aName);
let resolverId = this.getPromiseResolverId({resolve: resolve,
reject: reject });
debug("promise init " + resolverId);
let promiseInit = function(aResolverId) {
debug("promise init called for getValue " + aName + " has resolverId " + aResolverId);
cpmm.sendAsyncMessage("EngineeringMode:SetValue", {
requestId: resolverId,
requestId: aResolverId,
name: aName,
value: aValue
});
}.bind(this);
return this.createPromise(promiseInit);
return this.createPromiseWithId(promiseInit);
},
set onmessage(aHandler) {
+5 -2
View File
@@ -116,6 +116,7 @@ InternalRequest::MapContentPolicyTypeToRequestContext(nsContentPolicyType aConte
context = RequestContext::Internal;
break;
case nsIContentPolicy::TYPE_INTERNAL_SCRIPT:
case nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD:
case nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER:
context = RequestContext::Script;
break;
@@ -125,10 +126,12 @@ InternalRequest::MapContentPolicyTypeToRequestContext(nsContentPolicyType aConte
case nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER:
context = RequestContext::Sharedworker;
break;
case nsIContentPolicy::TYPE_IMAGE:
case nsIContentPolicy::TYPE_INTERNAL_IMAGE:
case nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD:
context = RequestContext::Image;
break;
case nsIContentPolicy::TYPE_STYLESHEET:
case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET:
case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD:
context = RequestContext::Style;
break;
case nsIContentPolicy::TYPE_INTERNAL_OBJECT:
+3 -3
View File
@@ -43,7 +43,7 @@ namespace dom {
* frame | TYPE_INTERNAL_FRAME
* hyperlink |
* iframe | TYPE_INTERNAL_IFRAME
* image | TYPE_IMAGE
* image | TYPE_INTERNAL_IMAGE, TYPE_INTERNAL_IMAGE_PRELOAD
* imageset | TYPE_IMAGESET
* import | Not supported by Gecko
* internal | TYPE_DOCUMENT, TYPE_XBL, TYPE_OTHER
@@ -53,10 +53,10 @@ namespace dom {
* ping | TYPE_PING
* plugin | TYPE_OBJECT_SUBREQUEST
* prefetch |
* script | TYPE_INTERNAL_SCRIPT
* script | TYPE_INTERNAL_SCRIPT, TYPE_INTERNAL_SCRIPT_PRELOAD
* sharedworker | TYPE_INTERNAL_SHARED_WORKER
* subresource | Not supported by Gecko
* style | TYPE_STYLESHEET
* style | TYPE_INTERNAL_STYLESHEET, TYPE_INTERNAL_STYLESHEET_PRELOAD
* track | TYPE_INTERNAL_TRACK
* video | TYPE_INTERNAL_VIDEO
* worker | TYPE_INTERNAL_WORKER
+4 -13
View File
@@ -394,7 +394,7 @@ MozInputMethod.prototype = {
},
removeInput: function(inputId) {
return this._sendPromise(function(resolverId) {
return this.createPromiseWithId(function(resolverId) {
let appId = this._window.document.nodePrincipal.appId;
cpmm.sendAsyncMessage('InputRegistry:Remove', {
@@ -435,14 +435,6 @@ MozInputMethod.prototype = {
if (!this._isSystem) {
throw new this._window.Error("Should have 'input-manage' permssion.");
}
},
_sendPromise: function(callback) {
let self = this;
return this.createPromise(function(resolve, reject) {
let resolverId = self.getPromiseResolverId({ resolve: resolve, reject: reject });
callback(resolverId);
});
}
};
@@ -788,14 +780,13 @@ MozInputContext.prototype = {
_sendPromise: function(callback) {
let self = this;
return this._ipcHelper.createPromise(function(resolve, reject) {
let resolverId = self._ipcHelper.getPromiseResolverId({ resolve: resolve, reject: reject });
return this._ipcHelper.createPromiseWithId(function(aResolverId) {
if (!WindowMap.isActive(self._window)) {
self._ipcHelper.removePromiseResolver(resolverId);
self._ipcHelper.removePromiseResolver(aResolverId);
reject('Input method is not active.');
return;
}
callback(resolverId);
callback(aResolverId);
});
}
};
+42 -29
View File
@@ -272,7 +272,7 @@ SystemMessageInternal.prototype = {
type: aType,
msg: aMessage,
extra: aExtra });
return;
return Promise.resolve();
}
// Give this message an ID so that we can identify the message and
@@ -284,37 +284,50 @@ SystemMessageInternal.prototype = {
let shouldDispatchFunc = this._getMessageConfigurator(aType).shouldDispatch;
// Find pages that registered an handler for this type.
this._pages.forEach(function(aPage) {
if (aPage.type !== aType) {
return;
}
if (!this._pages.length) {
return Promise.resolve();
}
let doDispatch = () => {
let result = this._sendMessageCommon(aType,
aMessage,
messageID,
aPage.pageURL,
aPage.manifestURL,
aExtra);
debug("Returned status of sending message: " + result);
};
if ('function' !== typeof shouldDispatchFunc) {
// If the configurator has no 'shouldDispatch' defined,
// always dispatch this message.
doDispatch();
return;
}
shouldDispatchFunc(aPage.manifestURL, aPage.pageURL, aType, aMessage, aExtra)
.then(aShouldDispatch => {
if (aShouldDispatch) {
doDispatch();
// Find pages that registered a handler for this type.
let promises = [];
for (let i = 0; i < this._pages.length; i++) {
let promise = ((page) => {
return new Promise((resolve, reject) => {
if (page.type !== aType) {
resolve();
return;
}
});
}, this);
let doDispatch = () => {
let result = this._sendMessageCommon(aType,
aMessage,
messageID,
page.pageURL,
page.manifestURL,
aExtra);
debug("Returned status of sending message: " + result);
resolve();
};
if ('function' !== typeof shouldDispatchFunc) {
// If the configurator has no 'shouldDispatch' defined,
// always dispatch this message.
doDispatch();
return;
}
shouldDispatchFunc(page.manifestURL, page.pageURL, aType, aMessage, aExtra)
.then(aShouldDispatch => {
if (aShouldDispatch) {
doDispatch();
}
});
});
})(this._pages[i]);
promises.push(promise);
}
return Promise.all(promises);
},
registerPage: function(aType, aPageURI, aManifestURI) {
@@ -10,7 +10,7 @@ interface nsIMessageSender;
// Implemented by the contract id @mozilla.org/system-message-internal;1
[scriptable, uuid(54c8e274-decb-4258-9a24-4ebfcbf3d00a)]
[scriptable, uuid(59b6beda-f911-4d47-a296-8c81e6abcfb9)]
interface nsISystemMessagesInternal : nsISupports
{
/*
@@ -36,8 +36,10 @@ interface nsISystemMessagesInternal : nsISupports
* @param message The message payload.
* @param extra Extra opaque information that will be passed around in the observer
* notification to open the page.
* returns a Promise
*/
void broadcastMessage(in DOMString type, in jsval message, [optional] in jsval extra);
nsISupports broadcastMessage(in DOMString type, in jsval message,
[optional] in jsval extra);
/*
* Registration of a page that wants to be notified of a message type.
+10 -1
View File
@@ -1,2 +1,11 @@
[DEFAULT]
skip-if = (buildapp != "browser") || e10s
support-files =
file_hasPendingMessage.html
invalid_manifest.webapp
invalid_manifest.webapp^headers^
manifest.webapp
manifest.webapp^headers^
[test_hasPendingMessage.html]
support-files = file_hasPendingMessage.html
[test_sysmsg_registration.html]
@@ -0,0 +1,8 @@
{
"name": "Random app",
"launch_path": "/index.html",
"messages": [{
"dummy-system-message": "/index.html",
"dummy-system-message2": "/index.html"
}]
}
@@ -0,0 +1 @@
Content-Type: application/manifest+json
+9
View File
@@ -0,0 +1,9 @@
{
"name": "Random app",
"launch_path": "/index.html",
"messages": [{
"dummy-system-message": "/index.html"
}, {
"dummy-system-message2": "/index.html"
}]
}
@@ -0,0 +1 @@
Content-Type: application/manifest+json
+15 -1
View File
@@ -11,6 +11,7 @@
const { utils: Cu, interfaces: Ci, classes: Cc } = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
SimpleTest.waitForExplicitFinish();
@@ -70,10 +71,23 @@
test_frame.src = testURL + "#setMessageHandler2";
return expectAlert(test_frame, "handle message", "message handled");
}).then(() => {
// Setp 7. Check hasPendingMessages2
// Step 7. Check hasPendingMessages2
return expectAlert(test_frame, "no hasPendingMessages",
"no hasPendingMessages after mozSetMessageHandler");
}).then(() => {
// Be nice with the rest of the tests and clean up what we registered.
let appsSvc = Cc["@mozilla.org/AppsService;1"]
.getService(Ci.nsIAppsService);
let appId = appsSvc.getAppLocalIdByManifestURL(manifestURL);
let subject = {
appId: appId,
browserOnly: false,
QueryInterface: XPCOMUtils.generateQI([
Ci.mozIApplicationClearPrivateDataParams
])
};
Services.obs.notifyObservers(subject, "webapps-clear-data", null);
test_frame.remove();
finish();
});
@@ -0,0 +1,232 @@
<!DOCTYPE html>
<html>
<head>
<title>System messages registration tests</title>
<script type="application/javascript"
src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
<script type="application/javascript"
src="chrome://mochikit/content/chrome-harness.js"></script>
<link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
</head>
<body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1162281}">Mozilla Bug {1162281}</a>
<p id="display"></p>
<div id="content" style="display: none">
</div>
<pre id="test">
<script class="testbody" type="application/javascript;version=1.7">
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
// We need to keep the same CID as the one used on activities tests.
// Check https://bugzilla.mozilla.org/show_bug.cgi?id=1176712#c13
const SYS_MSG_GLUE_CID = Components.ID("{b0b6b9af-bc4e-4200-bffe-fb7691065ec9}");
XPCOMUtils.defineLazyGetter(this, "messenger", () => {
return Cc["@mozilla.org/system-message-internal;1"]
.getService(Ci.nsISystemMessagesInternal);
});
let gRootUrl = "http://test/chrome/dom/messages/test/";
let validAppUrl = gRootUrl + "manifest.webapp";
let invalidAppUrl = gRootUrl + "invalid_manifest.webapp";
let validApp;
let initialAppsCount;
let index = 0;
SimpleTest.waitForExplicitFinish();
function go() {
SpecialPowers.pushPermissions(
[{ "type": "webapps-manage", "allow": 1, "context": document },
{ "type": "browser", "allow": 1, "context": document },
{ "type": "embed-apps", "allow": 1, "context": document }],
function() {
SpecialPowers.pushPrefEnv(
{'set': [["dom.mozBrowserFramesEnabled", true],
["dom.sysmsg.enabled", true]]},
next) });
}
function finish() {
unregisterComponent(SystemMessageGlue);
SimpleTest.finish();
}
function next() {
info("Step " + index);
if (index >= steps.length) {
ok(false, "Shouldn't get here!");
return;
}
try {
let i = index++;
steps[i]();
} catch(ex) {
ok(false, "Caught exception", ex);
}
}
function cbError(aEvent) {
ok(false, "Error callback invoked " +
aEvent.target.error.name + " " + aEvent.target.error.message);
finish();
}
function uninstall(aApp) {
info("Uninstalling " + (aApp ? aApp.manifestURL : "NO APP!!"));
}
function registerComponent(aObject, aDescription, aContract) {
info("Registering " + SYS_MSG_GLUE_CID);
let componentManager =
Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
componentManager.registerFactory(SYS_MSG_GLUE_CID, aDescription, aContract, aObject);
}
function unregisterComponent(aObject) {
info("Unregistering " + SYS_MSG_GLUE_CID);
let componentManager =
Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
componentManager.unregisterFactory(SYS_MSG_GLUE_CID, aObject);
}
let SystemMessageGlue = {
// nsISupports implementation.
QueryInterface: function(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIFactory) ||
iid.equals(Ci.nsISystemMessageGlue)) {
return this;
}
throw Cr.NS_ERROR_NO_INTERFACE;
},
// nsIFactory implementation.
createInstance: function(outer, iid) {
return this.QueryInterface(iid);
},
_lastManifestURL: null,
// nsISystemMessageGlue implementation.
openApp(pageURL, manifestURL, type, target, showApp, onlyShowApp, extra) {
this._lastManifestURL = manifestURL;
}
};
registerComponent(SystemMessageGlue,
"System Message Glue",
"@mozilla.org/dom/messages/system-message-glue;1");
function testBroadcastMessage(aMessage, aExpectedManifestURL, aMsg) {
SystemMessageGlue._lastManifestURL = null;
messenger.broadcastMessage(aMessage, {}, {})
.then(() => {
is(SystemMessageGlue._lastManifestURL, aExpectedManifestURL, aMsg);
next();
})
.catch(cbError);
}
/**
* TESTS
*/
let steps = [() => {
Services.obs.notifyObservers(null, "webapps-registry-ready", null);
SpecialPowers.setAllAppsLaunchable(true);
SpecialPowers.autoConfirmAppInstall(next);
}, () => {
SpecialPowers.autoConfirmAppUninstall(next);
}, () => {
// Check how many apps we are starting with.
let request = navigator.mozApps.mgmt.getAll();
request.onerror = cbError;
request.onsuccess = () => {
initialAppsCount = request.result.length;
info("Starting with " + initialAppsCount + " apps installed.");
next();
};
}, () => {
// We still have not installed any app handling dummy-system-message.
testBroadcastMessage("dummy-system-message", null,
"no system message should be sent");
}, () => {
testBroadcastMessage("dummy-system-message2", null,
"no system message should be sent");
}, () => {
navigator.mozApps.mgmt.oninstall = () => {
validApp = request.result;
next();
};
let request = navigator.mozApps.install(validAppUrl, { });
request.error = cbError;
request.onsuccess = () => {
validApp = request.result;
};
}, () => {
// Installing the test app should register the system message.
testBroadcastMessage("dummy-system-message", validAppUrl,
"system message should be sent");
}, () => {
// Installing the test app should register the system message.
testBroadcastMessage("dummy-system-message2", validAppUrl,
"system message should be sent");
}, () => {
navigator.mozApps.mgmt.onuninstall = () => {
validApp = null;
next();
};
let request = navigator.mozApps.mgmt.uninstall(validApp);
request.onerror = cbError;
}, () => {
// Uninstalling the app should unregister the system messages.
testBroadcastMessage("dummy-system-message", null,
"no system message should be sent");
}, () => {
// Uninstalling the app should unregister the system messages.
testBroadcastMessage("dummy-system-message2", null,
"no system message should be sent");
}, () => {
navigator.mozApps.mgmt.oninstall = () => {
validApp = request.result;
next();
};
let request = navigator.mozApps.install(invalidAppUrl, { });
request.onerror = () => {
ok(true, "should not install invalid app");
next();
};
request.onsuccess = () => {
ok(false, "should not install invalid app");
finish();
};
}, () => {
testBroadcastMessage("dummy-system-message", null,
"no system message should be sent");
}, () => {
testBroadcastMessage("dummy-system-message2", null,
"no system message should be sent");
}, () => {
// Check how many apps we are finishing with.
let request = navigator.mozApps.mgmt.getAll();
request.onerror = cbError;
request.onsuccess = () => {
info("Finishing with " + request.result.length + " apps installed.");
is(initialAppsCount, request.result.length, "All apps are uninstalled");
next();
};
}, finish];
addLoadEvent(go);
</script>
</pre>
</body>
</html>
+2 -5
View File
@@ -37,11 +37,8 @@ NfcCallback.prototype = {
_requestId: null,
_createPromise: function _createPromise() {
this.promise = this.createPromise((aResolve, aReject) => {
this._requestId = btoa(this.getPromiseResolverId({
resolve: aResolve,
reject: aReject
}));
this.promise = this.createPromiseWithId((aResolverId) => {
this._requestId = btoa(aResolverId);
});
},
@@ -104,10 +104,9 @@ PresentationDeviceInfoManager.prototype = {
getAll: function() {
log("getAll");
let self = this;
return this.createPromise(function(aResolve, aReject) {
let resolverId = self.getPromiseResolverId({ resolve: aResolve, reject: aReject });
return this.createPromiseWithId(function(aResolverId) {
cpmm.sendAsyncMessage("PresentationDeviceInfoManager:GetAll", {
requestId: resolverId,
requestId: aResolverId,
});
});
},
+2 -3
View File
@@ -46,9 +46,8 @@ RequestSyncManager.prototype = {
sendMessage: function(aMsg, aObj) {
let self = this;
return this.createPromise(function(aResolve, aReject) {
aObj.requestID =
self.getPromiseResolverId({ resolve: aResolve, reject: aReject });
return this.createPromiseWithId(function(aResolverId) {
aObj.requestID = aResolverId;
cpmm.sendAsyncMessage(aMsg, aObj, null,
self._window.document.nodePrincipal);
});
+2 -3
View File
@@ -68,9 +68,8 @@ RequestSyncScheduler.prototype = {
sendMessage: function(aMsg, aObj) {
let self = this;
return this.createPromise(function(aResolve, aReject) {
aObj.requestID =
self.getPromiseResolverId({ resolve: aResolve, reject: aReject });
return this.createPromiseWithId(function(aResolverId) {
aObj.requestID = aResolverId;
cpmm.sendAsyncMessage(aMsg, aObj, null,
self._window.document.nodePrincipal);
});
+8 -20
View File
@@ -146,18 +146,6 @@ function ResourceStatsManager() {
ResourceStatsManager.prototype = {
__proto__: DOMRequestIpcHelper.prototype,
_getPromise: function(aCallback) {
let self = this;
return this.createPromise(function(aResolve, aReject) {
let resolverId = self.getPromiseResolverId({
resolve: aResolve,
reject: aReject
});
aCallback(resolverId);
});
},
// Check time range.
_checkTimeRange: function(aStart, aEnd) {
if (DEBUG) {
@@ -180,7 +168,7 @@ ResourceStatsManager.prototype = {
// Create Promise.
let self = this;
return this._getPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
self.cpmm.sendAsyncMessage("ResourceStats:GetStats", {
resolverId: aResolverId,
type: self.type,
@@ -198,7 +186,7 @@ ResourceStatsManager.prototype = {
// Create Promise.
let self = this;
return this._getPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
self.cpmm.sendAsyncMessage("ResourceStats:ClearStats", {
resolverId: aResolverId,
type: self.type,
@@ -213,7 +201,7 @@ ResourceStatsManager.prototype = {
clearAllStats: function() {
// Create Promise.
let self = this;
return this._getPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
self.cpmm.sendAsyncMessage("ResourceStats:ClearAllStats", {
resolverId: aResolverId,
type: self.type,
@@ -239,7 +227,7 @@ ResourceStatsManager.prototype = {
// Create Promise.
let self = this;
return this._getPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
self.cpmm.sendAsyncMessage("ResourceStats:AddAlarm", {
resolverId: aResolverId,
type: self.type,
@@ -255,7 +243,7 @@ ResourceStatsManager.prototype = {
getAlarms: function(aStatsOptions) {
// Create Promise.
let self = this;
return this._getPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
self.cpmm.sendAsyncMessage("ResourceStats:GetAlarms", {
resolverId: aResolverId,
type: self.type,
@@ -268,7 +256,7 @@ ResourceStatsManager.prototype = {
removeAlarm: function(aAlarmId) {
// Create Promise.
let self = this;
return this._getPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
self.cpmm.sendAsyncMessage("ResourceStats:RemoveAlarm", {
resolverId: aResolverId,
type: self.type,
@@ -281,7 +269,7 @@ ResourceStatsManager.prototype = {
removeAllAlarms: function() {
// Create Promise.
let self = this;
return this._getPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
self.cpmm.sendAsyncMessage("ResourceStats:RemoveAllAlarms", {
resolverId: aResolverId,
type: self.type,
@@ -293,7 +281,7 @@ ResourceStatsManager.prototype = {
getAvailableComponents: function() {
// Create Promise.
let self = this;
return this._getPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
self.cpmm.sendAsyncMessage("ResourceStats:GetComponents", {
resolverId: aResolverId,
type: self.type,
+2 -6
View File
@@ -52,12 +52,8 @@ PromiseHelpersSubclass.prototype = {
callback(resolverId);
};
return this.createPromise((resolve, reject) => {
let resolverId = this.getPromiseResolverId({
resolve: resolve,
reject: reject
});
ctxCallback(resolverId);
return this.createPromiseWithId((aResolverId) => {
ctxCallback(aResolverId);
});
},
+7 -24
View File
@@ -115,6 +115,10 @@ nsCSPContext::ShouldLoad(nsContentPolicyType aContentType,
CSPCONTEXTLOG(("nsCSPContext::ShouldLoad, aContentLocation: %s", spec.get()));
}
bool isStyleOrScriptPreLoad =
(aContentType == nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD ||
aContentType == nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD);
// Since we know whether we are dealing with a preload, we have to convert
// the internal policytype ot the external policy type before moving on.
// We still need to know if this is a worker so child-src can handle that
@@ -151,29 +155,8 @@ nsCSPContext::ShouldLoad(nsContentPolicyType aContentType,
return NS_OK;
}
// This may be a load or a preload. If it is a preload, the document will
// not have been fully parsed yet, and aRequestContext will be an
// nsIDOMHTMLDocument rather than the nsIDOMHTMLElement associated with the
// resource. As a result, we cannot extract the element's corresponding
// nonce attribute, and so we cannot correctly check the nonce on a preload.
//
// Therefore, the decision returned here for a preload may be *incorrect* as
// it cannot take the nonce into account. We will still check the load, but
// we will not cache the result or report a violation. When the "real load"
// happens subsequently, we will re-check with the additional context to
// make a final decision.
//
// We don't just return false because that would block all preloads and
// degrade performance. However, we do want to block preloads that are
// clearly blocked (their urls are not whitelisted) by CSP.
nsCOMPtr<nsIDOMHTMLDocument> doc = do_QueryInterface(aRequestContext);
bool isPreload = doc &&
(aContentType == nsIContentPolicy::TYPE_SCRIPT ||
aContentType == nsIContentPolicy::TYPE_STYLESHEET);
nsAutoString nonce;
if (!isPreload) {
if (!isStyleOrScriptPreLoad) {
if (aContentType == nsIContentPolicy::TYPE_SCRIPT ||
aContentType == nsIContentPolicy::TYPE_STYLESHEET) {
nsCOMPtr<nsIDOMHTMLElement> htmlElement = do_QueryInterface(aRequestContext);
@@ -193,7 +176,7 @@ nsCSPContext::ShouldLoad(nsContentPolicyType aContentType,
originalURI,
nonce,
wasRedirected,
isPreload,
isStyleOrScriptPreLoad,
false, // allow fallback to default-src
true, // send violation reports
true); // send blocked URI in violation reports
@@ -202,7 +185,7 @@ nsCSPContext::ShouldLoad(nsContentPolicyType aContentType,
: nsIContentPolicy::REJECT_SERVER;
// Done looping, cache any relevant result
if (cacheKey.Length() > 0 && !isPreload) {
if (cacheKey.Length() > 0 && !isStyleOrScriptPreLoad) {
mShouldLoadCache.Put(cacheKey, *outDecision);
}
+6 -4
View File
@@ -105,8 +105,9 @@ CSPService::ShouldLoad(uint32_t aContentType,
nsIPrincipal *aRequestPrincipal,
int16_t *aDecision)
{
MOZ_ASSERT(aContentType == nsContentUtils::InternalContentPolicyTypeToExternal(aContentType),
"We should only see external content policy types here.");
MOZ_ASSERT(aContentType ==
nsContentUtils::InternalContentPolicyTypeToExternalOrPreload(aContentType),
"We should only see external content policy types or preloads here.");
if (!aContentLocation) {
return NS_ERROR_FAILURE;
@@ -251,8 +252,9 @@ CSPService::ShouldProcess(uint32_t aContentType,
nsIPrincipal *aRequestPrincipal,
int16_t *aDecision)
{
MOZ_ASSERT(aContentType == nsContentUtils::InternalContentPolicyTypeToExternal(aContentType),
"We should only see external content policy types here.");
MOZ_ASSERT(aContentType ==
nsContentUtils::InternalContentPolicyTypeToExternalOrPreload(aContentType),
"We should only see external content policy types or preloads here.");
if (!aContentLocation)
return NS_ERROR_FAILURE;
@@ -165,6 +165,15 @@ function runTest() {
headers: { "myheader": "" },
allowMethods: "myheader",
},
{ pass: 1,
method: "GET",
headers: { "User-Agent": "myValue" },
allowHeaders: "User-Agent",
},
{ pass: 0,
method: "GET",
headers: { "User-Agent": "myValue" },
},
// Multiple custom headers
{ pass: 1,
+3 -12
View File
@@ -225,7 +225,7 @@ SystemUpdateManager.prototype = {
},
getProviders: function() {
return this._sendPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
cpmm.sendAsyncMessage("SystemUpdate:GetProviders", {
requestId: aResolverId,
});
@@ -233,7 +233,7 @@ SystemUpdateManager.prototype = {
},
getActiveProvider: function() {
return this._sendPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
cpmm.sendAsyncMessage("SystemUpdate:GetActiveProvider", {
requestId: aResolverId,
});
@@ -241,21 +241,12 @@ SystemUpdateManager.prototype = {
},
setActiveProvider: function(aUuid) {
return this._sendPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
cpmm.sendAsyncMessage("SystemUpdate:SetActiveProvider", {
requestId: aResolverId,
uuid: aUuid
});
});
},
_sendPromise: function(aCallback) {
let self = this;
return this.createPromise(function(aResolve, aReject) {
let resolverId = self.getPromiseResolverId({resolve: aResolve,
reject: aReject});
aCallback(resolverId);
});
}
};
@@ -264,6 +264,15 @@ function testModeCors() {
headers: { "myheader": "" },
allowMethods: "myheader",
},
{ pass: 1,
method: "GET",
headers: { "User-Agent": "myValue" },
allowHeaders: "User-Agent",
},
{ pass: 0,
method: "GET",
headers: { "User-Agent": "myValue" },
},
// Multiple custom headers
{ pass: 1,
@@ -0,0 +1,156 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Test Fetch Headers - Basic</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<script type="text/javascript" src="test_headers_common.js"> </script>
<script type="text/javascript">
// Main thread specific tests because they need SpecialPowers. Expects
// test_headers_common.js to already be loaded.
function TestRequestHeaders() {
is(typeof Headers, "function", "Headers global constructor exists.");
var headers = new Headers();
ok(headers, "Constructed empty Headers object");
SpecialPowers.wrap(headers).guard = "request";
TestCoreBehavior(headers, "foo");
var forbidden = [
"Accept-Charset",
"Accept-Encoding",
"Access-Control-Request-Headers",
"Access-Control-Request-Method",
"Connection",
"Content-Length",
"Cookie",
"Cookie2",
"Date",
"DNT",
"Expect",
"Host",
"Keep-Alive",
"Origin",
"Referer",
"TE",
"Trailer",
"Transfer-Encoding",
"Upgrade",
"Via",
"Proxy-Authorization",
"Proxy-blarg",
"Proxy-",
"Sec-foo",
"Sec-"
];
for (var i = 0, n = forbidden.length; i < n; ++i) {
var name = forbidden[i];
headers.append(name, "hmm");
checkNotHas(headers, name, "Should not be able to append " + name + " to request headers");
headers.set(name, "hmm");
checkNotHas(headers, name, "Should not be able to set " + name + " on request headers");
}
}
function TestRequestNoCorsHeaders() {
is(typeof Headers, "function", "Headers global constructor exists.");
var headers = new Headers();
ok(headers, "Constructed empty Headers object");
SpecialPowers.wrap(headers).guard = "request-no-cors";
headers.append("foo", "bar");
checkNotHas(headers, "foo", "Should not be able to append arbitrary headers to request-no-cors headers.");
headers.set("foo", "bar");
checkNotHas(headers, "foo", "Should not be able to set arbitrary headers on request-no-cors headers.");
var simpleNames = [
"Accept",
"Accept-Language",
"Content-Language"
];
var simpleContentTypes = [
"application/x-www-form-urlencoded",
"multipart/form-data",
"text/plain",
"application/x-www-form-urlencoded; charset=utf-8",
"multipart/form-data; charset=utf-8",
"text/plain; charset=utf-8"
];
for (var i = 0, n = simpleNames.length; i < n; ++i) {
var name = simpleNames[i];
headers.append(name, "hmm");
checkHas(headers, name, "Should be able to append " + name + " to request-no-cors headers");
headers.set(name, "hmm");
checkHas(headers, name, "Should be able to set " + name + " on request-no-cors headers");
}
for (var i = 0, n = simpleContentTypes.length; i < n; ++i) {
var value = simpleContentTypes[i];
headers.append("Content-Type", value);
checkHas(headers, "Content-Type", "Should be able to append " + value + " Content-Type to request-no-cors headers");
headers.delete("Content-Type");
headers.set("Content-Type", value);
checkHas(headers, "Content-Type", "Should be able to set " + value + " Content-Type on request-no-cors headers");
}
}
function TestResponseHeaders() {
is(typeof Headers, "function", "Headers global constructor exists.");
var headers = new Headers();
ok(headers, "Constructed empty Headers object");
SpecialPowers.wrap(headers).guard = "response";
TestCoreBehavior(headers, "foo");
var forbidden = [
"Set-Cookie",
"Set-Cookie2"
];
for (var i = 0, n = forbidden.length; i < n; ++i) {
var name = forbidden[i];
headers.append(name, "hmm");
checkNotHas(headers, name, "Should not be able to append " + name + " to response headers");
headers.set(name, "hmm");
checkNotHas(headers, name, "Should not be able to set " + name + " on response headers");
}
}
function TestImmutableHeaders() {
is(typeof Headers, "function", "Headers global constructor exists.");
var headers = new Headers();
ok(headers, "Constructed empty Headers object");
TestCoreBehavior(headers, "foo");
headers.append("foo", "atleastone");
SpecialPowers.wrap(headers).guard = "immutable";
shouldThrow(function() {
headers.append("foo", "wat");
}, TypeError, "Should not be able to append to immutable headers");
shouldThrow(function() {
headers.set("foo", "wat");
}, TypeError, "Should not be able to set immutable headers");
shouldThrow(function() {
headers.delete("foo");
}, TypeError, "Should not be able to delete immutable headers");
checkHas(headers, "foo", "Should be able to check immutable headers");
ok(headers.get("foo"), "Should be able to get immutable headers");
ok(headers.getAll("foo").length, "Should be able to get all immutable headers");
}
TestRequestHeaders();
TestRequestNoCorsHeaders();
TestResponseHeaders();
TestImmutableHeaders();
</script>
</body>
</html>
@@ -7,7 +7,8 @@
task(function* () {
// We just check if we can access storage as chrome using special powers!
yield chromePower();
var params = new URLSearchParams(location.search.substr(1));
yield chromePower(params.get('allowed') == 'yes', params.get('blockSessionStorage') == 'yes');
});
</script>
@@ -62,44 +62,49 @@ function runWorker(url) {
});
}
function chromePower() {
function chromePower(allowed, blockSessionStorage) {
// localStorage is affected by storage policy.
try {
SpecialPowers.wrap(window).localStorage.getItem("X");
ok(true, "getting localStorage didn't throw");
ok(allowed, "getting localStorage from chrome didn't throw");
} catch (e) {
ok(false, "getting localStorage should not throw");
ok(!allowed, "getting localStorage from chrome threw");
}
// sessionStorage is not. See bug 1183968.
try {
SpecialPowers.wrap(window).sessionStorage.getItem("X");
ok(true, "getting sessionStorage didn't throw");
ok(!blockSessionStorage, "getting sessionStorage from chrome didn't throw");
} catch (e) {
ok(false, "getting sessionStorage should not throw");
ok(blockSessionStorage, "getting sessionStorage from chrome threw");
}
// indexedDB is affected by storage policy.
try {
SpecialPowers.wrap(window).indexedDB;
ok(true, "getting indexedDB didn't throw");
ok(allowed, "getting indexedDB from chrome didn't throw");
} catch (e) {
ok(false, "getting indexedDB should not throw");
ok(!allowed, "getting indexedDB from chrome threw");
}
// Same with caches, along with the additional https-only requirement.
try {
var shouldResolve = allowed && location.protocol == "https:";
var promise = SpecialPowers.wrap(window).caches.keys();
ok(true, "getting caches didn't throw");
ok(true, "getting caches from chrome should never throw");
return new Promise((resolve, reject) => {
promise.then(function() {
ok(location.protocol == "https:", "The promise was not rejected");
ok(shouldResolve, "The promise was resolved for chrome");
resolve();
}, function(e) {
ok(location.protocol != "https:", "The promise should not have been rejected: " + e);
ok(!shouldResolve, "The promise was rejected for chrome: " + e);
resolve();
});
});
} catch (e) {
ok(false, "getting caches should not have thrown");
return Promise.resolve();
ok(false, "getting caches from chrome threw");
}
}
@@ -20,7 +20,7 @@ task(function* () {
// Same origin iframes should be allowed, unless they redirect to a URI with the null principal
yield runIFrame("frameStorageAllowed.html");
yield runIFrame("frameStorageNullprincipal.sjs");
yield runIFrame("frameStorageChrome.html");
yield runIFrame("frameStorageChrome.html?allowed=yes");
// Sandboxed iframes should have the null principal, and thus can't access storage
document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
@@ -31,7 +31,7 @@ task(function* () {
// Thirdparty iframes should be allowed, unless they redirect to a URI with the null principal
yield runIFrame(thirdparty + "frameStorageAllowed.html");
yield runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
yield runIFrame(thirdparty + "frameStorageChrome.html");
yield runIFrame(thirdparty + "frameStorageChrome.html?allowed=yes");
// Workers should be able to access storage
yield runWorker("workerStorageAllowed.js");
@@ -17,10 +17,12 @@ task(function* () {
// We should be able to access storage
yield storageAllowed();
// Same origin iframes should be prevented, unless they have chrome privileges
// Same origin iframes should be allowed.
yield runIFrame("frameStorageAllowed.html");
yield runIFrame("frameStorageChrome.html?allowed=yes");
// Null principal iframes should not.
yield runIFrame("frameStorageNullprincipal.sjs");
yield runIFrame("frameStorageChrome.html");
// Sandboxed iframes should have the null principal, and thus can't access storage
document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
@@ -28,10 +30,10 @@ task(function* () {
yield runIFrame("frameStorageNullprincipal.sjs");
document.querySelector('iframe').removeAttribute('sandbox');
// Thirdparty iframes should be blocked, unless they have chrome privileges
// Thirdparty iframes should be blocked, even when accessed from chrome over Xrays.
yield runIFrame(thirdparty + "frameStoragePrevented.html#thirdparty");
yield runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
yield runIFrame(thirdparty + "frameStorageChrome.html");
yield runIFrame(thirdparty + "frameStorageChrome.html?allowed=no");
// Workers should be unable to access storage
yield runWorker("workerStorageAllowed.js");
@@ -17,10 +17,10 @@ task(function* () {
// We should be unable to access storage
yield storagePrevented();
// Same origin iframes should be prevented, unless they have chrome privileges
// Same origin iframes should be blocked.
yield runIFrame("frameStoragePrevented.html");
yield runIFrame("frameStorageNullprincipal.sjs");
yield runIFrame("frameStorageChrome.html");
yield runIFrame("frameStorageChrome.html?allowed=no&blockSessionStorage=yes");
// Sandboxed iframes should have the null principal, and thus can't access storage
document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
@@ -28,9 +28,10 @@ task(function* () {
yield runIFrame("frameStorageNullprincipal.sjs");
document.querySelector('iframe').removeAttribute('sandbox');
// thirdparty iframes should be blocked, unless they have chrome privileges
// thirdparty iframes should be blocked.
yield runIFrame(thirdparty + "frameStoragePrevented.html");
yield runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
yield runIFrame(thirdparty + "frameStorageChrome.html?allowed=no&blockSessionStorage=yes");
// Workers should be unable to access storage
yield runWorker("workerStoragePrevented.js");
@@ -20,7 +20,7 @@ task(function* () {
// Same origin iframes should be allowed, unless they redirect to a URI with the null principal
yield runIFrame("frameStorageAllowed.html");
yield runIFrame("frameStorageNullprincipal.sjs");
yield runIFrame("frameStorageChrome.html");
yield runIFrame("frameStorageChrome.html?allowed=yes");
// Sandboxed iframes should have the null principal, and thus can't access storage
document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
@@ -28,10 +28,10 @@ task(function* () {
yield runIFrame("frameStorageNullprincipal.sjs");
document.querySelector('iframe').removeAttribute('sandbox');
// thirdparty iframes should be blocked, unless they have chrome privileges
// thirdparty iframes should be blocked.
yield runIFrame(thirdparty + "frameStoragePrevented.html#thirdparty");
yield runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
yield runIFrame(thirdparty + "frameStorageChrome.html");
yield runIFrame(thirdparty + "frameStorageChrome.html?allowed=no");
// Workers should be able to access storage
yield runWorker("workerStorageAllowed.js");
+2 -15
View File
@@ -40,19 +40,6 @@ TetheringManager.prototype = {
this.initDOMRequestHelper(aWindow, messages);
},
_getPromise: function(aCallback) {
let self = this;
return this.createPromise(function(aResolve, aReject) {
let resolverId = self.getPromiseResolverId({
resolve: aResolve,
reject: aReject
});
aCallback(resolverId);
});
},
// TODO : aMessage format may be different after supporting bt/usb.
// for now, use wifi format first.
receiveMessage: function(aMessage) {
@@ -77,7 +64,7 @@ TetheringManager.prototype = {
let self = this;
switch (aType) {
case TETHERING_TYPE_WIFI:
return this._getPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
let data = { resolverId: aResolverId, enabled: aEnabled, config: aConfig };
cpmm.sendAsyncMessage("WifiManager:setWifiTethering", { data: data});
});
@@ -85,7 +72,7 @@ TetheringManager.prototype = {
case TETHERING_TYPE_USB:
default:
debug("tethering type(" + aType + ") doesn't support");
return this._getPromise(function(aResolverId) {
return this.createPromiseWithId(function(aResolverId) {
self.takePromiseResolver(aResolverId).reject();
});
}
+1 -1
View File
@@ -151,7 +151,7 @@ nsXBLResourceLoader::LoadResources(bool* aResult)
}
else
{
rv = cssLoader->LoadSheet(url, docPrincipal, EmptyCString(), this);
rv = cssLoader->LoadSheet(url, false, docPrincipal, EmptyCString(), this);
if (NS_SUCCEEDED(rv))
++mPendingSheets;
}
@@ -424,7 +424,7 @@ txCompileObserver::loadURI(const nsAString& aUri,
// Content Policy
int16_t shouldLoad = nsIContentPolicy::ACCEPT;
rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_STYLESHEET,
rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_INTERNAL_STYLESHEET,
uri,
referrerPrincipal,
mLoaderDocument,
@@ -524,7 +524,7 @@ TX_LoadSheet(nsIURI* aUri, txMozillaXSLTProcessor* aProcessor,
// Content Policy
int16_t shouldLoad = nsIContentPolicy::ACCEPT;
nsresult rv =
NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_STYLESHEET,
NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_INTERNAL_STYLESHEET,
aUri,
principal,
aLoaderDocument,
@@ -666,7 +666,7 @@ txSyncCompileObserver::loadURI(const nsAString& aUri,
// Content Policy
int16_t shouldLoad = nsIContentPolicy::ACCEPT;
rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_STYLESHEET,
rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_INTERNAL_STYLESHEET,
uri,
referrerPrincipal,
nullptr,
+1 -1
View File
@@ -2793,7 +2793,7 @@ nsHTMLEditor::ReplaceStyleSheet(const nsAString& aURL)
NS_ENSURE_SUCCESS(rv, rv);
return ps->GetDocument()->CSSLoader()->
LoadSheet(uaURI, nullptr, EmptyCString(), this);
LoadSheet(uaURI, false, nullptr, EmptyCString(), this);
}
NS_IMETHODIMP
+7 -2
View File
@@ -141,7 +141,12 @@ GetCurrentScreenConfiguration(ScreenConfiguration* aScreenConfiguration)
bool
LockScreenOrientation(const ScreenOrientationInternal& aOrientation)
{
switch (aOrientation) {
// Force the default orientation to be portrait-primary.
ScreenOrientationInternal orientation =
aOrientation == eScreenOrientation_Default ? eScreenOrientation_PortraitPrimary
: aOrientation;
switch (orientation) {
// The Android backend only supports these orientations.
case eScreenOrientation_PortraitPrimary:
case eScreenOrientation_PortraitSecondary:
@@ -150,7 +155,7 @@ LockScreenOrientation(const ScreenOrientationInternal& aOrientation)
case eScreenOrientation_LandscapeSecondary:
case eScreenOrientation_LandscapePrimary | eScreenOrientation_LandscapeSecondary:
case eScreenOrientation_Default:
mozilla::widget::GeckoAppShell::LockScreenOrientation(aOrientation);
mozilla::widget::GeckoAppShell::LockScreenOrientation(orientation);
return true;
default:
return false;
+29 -17
View File
@@ -607,7 +607,7 @@ Loader::SetPreferredSheet(const nsAString& aTitle)
mDatasToNotifyOn += arr.Length();
for (uint32_t i = 0; i < arr.Length(); ++i) {
--mDatasToNotifyOn;
LoadSheet(arr[i], eSheetNeedsParser);
LoadSheet(arr[i], eSheetNeedsParser, false);
}
}
@@ -1025,7 +1025,8 @@ Loader::ObsoleteSheet(nsIURI* aURI)
nsresult
Loader::CheckLoadAllowed(nsIPrincipal* aSourcePrincipal,
nsIURI* aTargetURI,
nsISupports* aContext)
nsISupports* aContext,
bool aIsPreload)
{
LOG(("css::Loader::CheckLoadAllowed"));
@@ -1044,9 +1045,12 @@ Loader::CheckLoadAllowed(nsIPrincipal* aSourcePrincipal,
LOG((" Passed security check"));
// Check with content policy
nsContentPolicyType contentPolicyType =
aIsPreload ? nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD
: nsIContentPolicy::TYPE_INTERNAL_STYLESHEET;
int16_t shouldLoad = nsIContentPolicy::ACCEPT;
rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_STYLESHEET,
rv = NS_CheckContentLoadPolicy(contentPolicyType,
aTargetURI,
aSourcePrincipal,
aContext,
@@ -1411,7 +1415,9 @@ Loader::InsertChildSheet(CSSStyleSheet* aSheet,
* a new load is kicked off asynchronously.
*/
nsresult
Loader::LoadSheet(SheetLoadData* aLoadData, StyleSheetState aSheetState)
Loader::LoadSheet(SheetLoadData* aLoadData,
StyleSheetState aSheetState,
bool aIsPreload)
{
LOG(("css::Loader::LoadSheet"));
NS_PRECONDITION(aLoadData, "Need a load data");
@@ -1561,7 +1567,7 @@ Loader::LoadSheet(SheetLoadData* aLoadData, StyleSheetState aSheetState)
mSheets->mPendingDatas.Remove(&key);
LOG((" Forcing load of pending data"));
return LoadSheet(existingData, eSheetNeedsParser);
return LoadSheet(existingData, eSheetNeedsParser, aIsPreload);
}
// All done here; once the load completes we'll be marked complete
// automatically
@@ -1583,6 +1589,10 @@ Loader::LoadSheet(SheetLoadData* aLoadData, StyleSheetState aSheetState)
securityFlags |= nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
}
nsContentPolicyType contentPolicyType =
aIsPreload ? nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD
: nsIContentPolicy::TYPE_INTERNAL_STYLESHEET;
nsCOMPtr<nsIChannel> channel;
// Note we are calling NS_NewChannelWithTriggeringPrincipal here with a node
// and a principal. This is because of a case where the node is the document
@@ -1594,7 +1604,7 @@ Loader::LoadSheet(SheetLoadData* aLoadData, StyleSheetState aSheetState)
aLoadData->mRequestingNode,
triggeringPrincipal,
securityFlags,
nsIContentPolicy::TYPE_STYLESHEET,
contentPolicyType,
loadGroup,
nullptr, // aCallbacks
nsIChannel::LOAD_NORMAL |
@@ -1610,7 +1620,7 @@ Loader::LoadSheet(SheetLoadData* aLoadData, StyleSheetState aSheetState)
aLoadData->mURI,
triggeringPrincipal,
securityFlags,
nsIContentPolicy::TYPE_STYLESHEET,
contentPolicyType,
loadGroup,
nullptr, // aCallbacks
nsIChannel::LOAD_NORMAL |
@@ -2044,7 +2054,7 @@ Loader::LoadStyleLink(nsIContent* aElement,
if (!context) {
context = mDocument;
}
nsresult rv = CheckLoadAllowed(principal, aURL, context);
nsresult rv = CheckLoadAllowed(principal, aURL, context, false);
if (NS_FAILED(rv)) return rv;
LOG((" Passed load check"));
@@ -2100,7 +2110,7 @@ Loader::LoadStyleLink(nsIContent* aElement,
}
// Load completion will free the data
rv = LoadSheet(data, state);
rv = LoadSheet(data, state, false);
NS_ENSURE_SUCCESS(rv, rv);
data->mMustNotify = true;
@@ -2178,7 +2188,7 @@ Loader::LoadChildSheet(CSSStyleSheet* aParentSheet,
}
nsIPrincipal* principal = aParentSheet->Principal();
nsresult rv = CheckLoadAllowed(principal, aURL, context);
nsresult rv = CheckLoadAllowed(principal, aURL, context, false);
if (NS_FAILED(rv)) return rv;
LOG((" Passed load check"));
@@ -2242,7 +2252,7 @@ Loader::LoadChildSheet(CSSStyleSheet* aParentSheet,
bool syncLoad = data->mSyncLoad;
// Load completion will release the data
rv = LoadSheet(data, state);
rv = LoadSheet(data, state, false);
NS_ENSURE_SUCCESS(rv, rv);
// If syncLoad is true, |data| will be deleted by now.
@@ -2258,7 +2268,7 @@ Loader::LoadSheetSync(nsIURI* aURL, bool aAllowUnsafeRules,
CSSStyleSheet** aSheet)
{
LOG(("css::Loader::LoadSheetSync"));
return InternalLoadNonDocumentSheet(aURL, aAllowUnsafeRules,
return InternalLoadNonDocumentSheet(aURL, false, aAllowUnsafeRules,
aUseSystemPrincipal, nullptr,
EmptyCString(), aSheet, nullptr);
}
@@ -2272,13 +2282,14 @@ Loader::LoadSheet(nsIURI* aURL,
{
LOG(("css::Loader::LoadSheet(aURL, aObserver, aSheet) api call"));
NS_PRECONDITION(aSheet, "aSheet is null");
return InternalLoadNonDocumentSheet(aURL, false, false,
return InternalLoadNonDocumentSheet(aURL, false, false, false,
aOriginPrincipal, aCharset,
aSheet, aObserver);
}
nsresult
Loader::LoadSheet(nsIURI* aURL,
bool aIsPreload,
nsIPrincipal* aOriginPrincipal,
const nsCString& aCharset,
nsICSSLoaderObserver* aObserver,
@@ -2287,7 +2298,7 @@ Loader::LoadSheet(nsIURI* aURL,
const nsAString& aIntegrity)
{
LOG(("css::Loader::LoadSheet(aURL, aObserver) api call"));
return InternalLoadNonDocumentSheet(aURL, false, false,
return InternalLoadNonDocumentSheet(aURL, aIsPreload, false, false,
aOriginPrincipal, aCharset,
nullptr, aObserver, aCORSMode,
aReferrerPolicy, aIntegrity);
@@ -2295,6 +2306,7 @@ Loader::LoadSheet(nsIURI* aURL,
nsresult
Loader::InternalLoadNonDocumentSheet(nsIURI* aURL,
bool aIsPreload,
bool aAllowUnsafeRules,
bool aUseSystemPrincipal,
nsIPrincipal* aOriginPrincipal,
@@ -2322,7 +2334,7 @@ Loader::InternalLoadNonDocumentSheet(nsIURI* aURL,
return NS_ERROR_NOT_AVAILABLE;
}
nsresult rv = CheckLoadAllowed(aOriginPrincipal, aURL, mDocument);
nsresult rv = CheckLoadAllowed(aOriginPrincipal, aURL, mDocument, aIsPreload);
if (NS_FAILED(rv)) {
return rv;
}
@@ -2357,7 +2369,7 @@ Loader::InternalLoadNonDocumentSheet(nsIURI* aURL,
aOriginPrincipal, mDocument);
NS_ADDREF(data);
rv = LoadSheet(data, state);
rv = LoadSheet(data, state, aIsPreload);
NS_ENSURE_SUCCESS(rv, rv);
if (aSheet) {
@@ -2549,7 +2561,7 @@ Loader::StartAlternateLoads()
mDatasToNotifyOn += arr.Length();
for (uint32_t i = 0; i < arr.Length(); ++i) {
--mDatasToNotifyOn;
LoadSheet(arr[i], eSheetNeedsParser);
LoadSheet(arr[i], eSheetNeedsParser, false);
}
}
+9 -2
View File
@@ -317,6 +317,7 @@ public:
* not-yet-loaded sheet.
*/
nsresult LoadSheet(nsIURI* aURL,
bool aIsPreload,
nsIPrincipal* aOriginPrincipal,
const nsCString& aCharset,
nsICSSLoaderObserver* aObserver,
@@ -405,9 +406,12 @@ private:
// Note: null aSourcePrincipal indicates that the content policy and
// CheckLoadURI checks should be skipped.
// aIsPreload indicates whether the html parser preloads that
// stylesheet or if it is a regular load.
nsresult CheckLoadAllowed(nsIPrincipal* aSourcePrincipal,
nsIURI* aTargetURI,
nsISupports* aContext);
nsISupports* aContext,
bool aIsPreload);
// For inline style, the aURI param is null, but the aLinkingContent
@@ -446,6 +450,7 @@ private:
ImportRule* aParentRule);
nsresult InternalLoadNonDocumentSheet(nsIURI* aURL,
bool aIsPreload,
bool aAllowUnsafeRules,
bool aUseSystemPrincipal,
nsIPrincipal* aOriginPrincipal,
@@ -477,7 +482,9 @@ private:
// Note: LoadSheet is responsible for releasing aLoadData and setting the
// sheet to complete on failure.
nsresult LoadSheet(SheetLoadData* aLoadData, StyleSheetState aSheetState);
nsresult LoadSheet(SheetLoadData* aLoadData,
StyleSheetState aSheetState,
bool aIsPreLoad);
// Parse the stylesheet in aLoadData. The sheet data comes from aInput.
// Set aCompleted to true if the parse finished, false otherwise (e.g. if the
+1 -1
View File
@@ -878,7 +878,7 @@ nsJARChannel::ShouldIntercept()
NS_GET_IID(nsINetworkInterceptController),
getter_AddRefs(controller));
bool shouldIntercept = false;
if (controller && !mForceNoIntercept) {
if (controller && !mForceNoIntercept && mLoadInfo) {
bool isNavigation = mLoadFlags & LOAD_DOCUMENT_URI;
nsContentPolicyType type = mLoadInfo->InternalContentPolicyType();
nsresult rv = controller->ShouldPrepareForIntercept(mAppURI,
+2 -9
View File
@@ -64,25 +64,18 @@ nsBaseChannel::nsBaseChannel()
, mQueriedProgressSink(true)
, mSynthProgressEvents(false)
, mAllowThreadRetargeting(true)
, mWasOpened(false)
, mWaitingOnAsyncRedirect(false)
, mStatus(NS_OK)
, mContentDispositionHint(UINT32_MAX)
, mContentLength(-1)
, mWasOpened(false)
{
mContentType.AssignLiteral(UNKNOWN_CONTENT_TYPE);
}
nsBaseChannel::~nsBaseChannel()
{
if (mLoadInfo) {
nsCOMPtr<nsIThread> mainThread;
NS_GetMainThread(getter_AddRefs(mainThread));
nsILoadInfo *forgetableLoadInfo;
mLoadInfo.forget(&forgetableLoadInfo);
NS_ProxyRelease(mainThread, forgetableLoadInfo, false);
}
NS_ReleaseOnMainThread(mLoadInfo);
}
nsresult
+1 -1
View File
@@ -277,7 +277,6 @@ private:
bool mQueriedProgressSink;
bool mSynthProgressEvents;
bool mAllowThreadRetargeting;
bool mWasOpened;
bool mWaitingOnAsyncRedirect;
bool mOpenRedirectChannel;
uint32_t mRedirectFlags;
@@ -293,6 +292,7 @@ protected:
uint32_t mContentDispositionHint;
nsAutoPtr<nsString> mContentDispositionFilename;
int64_t mContentLength;
bool mWasOpened;
friend class mozilla::net::PrivateBrowsingChannel<nsBaseChannel>;
};
-1
View File
@@ -32,7 +32,6 @@ FTPChannelChild::FTPChannelChild(nsIURI* uri)
, mCanceled(false)
, mSuspendCount(0)
, mIsPending(false)
, mWasOpened(false)
, mLastModifiedTime(0)
, mStartPos(0)
, mDivertingToParent(false)
+1 -2
View File
@@ -119,8 +119,7 @@ private:
bool mCanceled;
uint32_t mSuspendCount;
bool mIsPending;
bool mWasOpened;
PRTime mLastModifiedTime;
uint64_t mStartPos;
nsCString mEntityID;
+5 -1
View File
@@ -1428,6 +1428,8 @@ NS_IMETHODIMP
HttpBaseChannel::GetRequestHeader(const nsACString& aHeader,
nsACString& aValue)
{
aValue.Truncate();
// XXX might be better to search the header list directly instead of
// hitting the http atom hash table.
nsHttpAtom atom = nsHttp::ResolveAtom(aHeader);
@@ -1503,6 +1505,8 @@ HttpBaseChannel::VisitNonDefaultRequestHeaders(nsIHttpHeaderVisitor *visitor)
NS_IMETHODIMP
HttpBaseChannel::GetResponseHeader(const nsACString &header, nsACString &value)
{
value.Truncate();
if (!mResponseHead)
return NS_ERROR_NOT_AVAILABLE;
@@ -2309,7 +2313,7 @@ HttpBaseChannel::ShouldIntercept()
nsCOMPtr<nsINetworkInterceptController> controller;
GetCallback(controller);
bool shouldIntercept = false;
if (controller && !mForceNoIntercept) {
if (controller && !mForceNoIntercept && mLoadInfo) {
nsContentPolicyType type = mLoadInfo->InternalContentPolicyType();
nsresult rv = controller->ShouldPrepareForIntercept(mURI,
IsNavigation(),
@@ -95,6 +95,7 @@ NullHttpChannel::SetReferrerWithPolicy(nsIURI *referrer, uint32_t referrerPolicy
NS_IMETHODIMP
NullHttpChannel::GetRequestHeader(const nsACString & aHeader, nsACString & _retval)
{
_retval.Truncate();
return NS_ERROR_NOT_IMPLEMENTED;
}
@@ -179,6 +180,7 @@ NullHttpChannel::GetRequestSucceeded(bool *aRequestSucceeded)
NS_IMETHODIMP
NullHttpChannel::GetResponseHeader(const nsACString & header, nsACString & _retval)
{
_retval.Truncate();
return NS_ERROR_NOT_IMPLEMENTED;
}
@@ -639,7 +639,6 @@ nsCORSListenerProxy::CheckRequestApproved(nsIRequest* aRequest)
// The "Access-Control-Allow-Headers" header contains a comma separated
// list of header names.
headerVal.Truncate();
http->GetResponseHeader(NS_LITERAL_CSTRING("Access-Control-Allow-Headers"),
headerVal);
nsTArray<nsCString> headers;
@@ -1151,7 +1150,6 @@ nsCORSPreflightListener::AddResultToCache(nsIRequest *aRequest)
// The "Access-Control-Allow-Methods" header contains a comma separated
// list of method names.
headerVal.Truncate();
http->GetResponseHeader(NS_LITERAL_CSTRING("Access-Control-Allow-Methods"),
headerVal);
@@ -1182,7 +1180,6 @@ nsCORSPreflightListener::AddResultToCache(nsIRequest *aRequest)
// The "Access-Control-Allow-Headers" header contains a comma separated
// list of method names.
headerVal.Truncate();
http->GetResponseHeader(NS_LITERAL_CSTRING("Access-Control-Allow-Headers"),
headerVal);
+7 -3
View File
@@ -1624,7 +1624,7 @@ nsHttpChannel::ProcessResponse()
// happen after OnExamineResponse.
if (!mTransaction->ProxyConnectFailed() && (httpStatus != 407)) {
SetCookie(mResponseHead->PeekHeader(nsHttp::Set_Cookie));
if (httpStatus < 500) {
if ((httpStatus < 500) && (httpStatus != 421)) {
ProcessAltService();
}
}
@@ -1891,7 +1891,7 @@ nsHttpChannel::ContinueProcessNormal(nsresult rv)
if (NS_FAILED(rv)) return rv;
// install cache listener if we still have a cache entry open
if (mCacheEntry && !mLoadedFromApplicationCache) {
if (mCacheEntry && !mCacheEntryIsReadOnly) {
rv = InstallCacheListener();
if (NS_FAILED(rv)) return rv;
}
@@ -6122,7 +6122,11 @@ nsHttpChannel::RetargetDeliveryTo(nsIEventTarget* aNewTarget)
NS_WARNING("Retargeting delivery to same thread");
return NS_OK;
}
NS_ENSURE_TRUE(mTransactionPump || mCachePump, NS_ERROR_NOT_AVAILABLE);
if (!mTransactionPump && !mCachePump) {
LOG(("nsHttpChannel::RetargetDeliveryTo %p %p no pump available\n",
this, aNewTarget));
return NS_ERROR_NOT_AVAILABLE;
}
nsresult rv = NS_OK;
// If both cache pump and transaction pump exist, we're probably dealing
@@ -733,6 +733,7 @@ NS_IMETHODIMP
nsViewSourceChannel::GetRequestHeader(const nsACString & aHeader,
nsACString & aValue)
{
aValue.Truncate();
return !mHttpChannel ? NS_ERROR_NULL_POINTER :
mHttpChannel->GetRequestHeader(aHeader, aValue);
}
@@ -834,6 +835,7 @@ NS_IMETHODIMP
nsViewSourceChannel::GetResponseHeader(const nsACString & aHeader,
nsACString & aValue)
{
aValue.Truncate();
if (!mHttpChannel)
return NS_ERROR_NULL_POINTER;
@@ -845,10 +847,9 @@ nsViewSourceChannel::GetResponseHeader(const nsACString & aHeader,
nsCaseInsensitiveCStringComparator()) &&
!aHeader.Equals(NS_LITERAL_CSTRING("X-Frame-Options"),
nsCaseInsensitiveCStringComparator())) {
aValue.Truncate();
return NS_OK;
}
return mHttpChannel->GetResponseHeader(aHeader, aValue);
}
+1 -1
View File
@@ -25,7 +25,7 @@ if CONFIG['MOZ_SERVICES_METRICS']:
if CONFIG['MOZ_SERVICES_SYNC']:
DIRS += ['sync']
if CONFIG['MOZ_B2G']:
if CONFIG['MOZ_B2G'] or CONFIG['MOZ_B2GDROID']:
DIRS += ['mobileid']
if CONFIG['MOZ_SERVICES_CLOUDSYNC']:
@@ -1,5 +0,0 @@
[style-src-3_4.html]
type: testharness
[Violation report status OK.]
expected: FAIL
@@ -456,7 +456,7 @@ let OldStyleSheetActor = protocol.ActorClass({
}
let options = {
policy: Ci.nsIContentPolicy.TYPE_STYLESHEET,
policy: Ci.nsIContentPolicy.TYPE_INTERNAL_STYLESHEET,
window: this.window,
charset: this._getCSSCharset()
};
@@ -586,7 +586,7 @@ let StyleSheetActor = protocol.ActorClass({
let options = {
loadFromCache: true,
policy: Ci.nsIContentPolicy.TYPE_STYLESHEET,
policy: Ci.nsIContentPolicy.TYPE_INTERNAL_STYLESHEET,
window: this.window,
charset: this._getCSSCharset()
};
@@ -672,7 +672,7 @@ let StyleSheetActor = protocol.ActorClass({
url = normalize(url, this.href);
let options = {
loadFromCache: false,
policy: Ci.nsIContentPolicy.TYPE_STYLESHEET,
policy: Ci.nsIContentPolicy.TYPE_INTERNAL_STYLESHEET,
window: this.window
};
let map = fetch(url, options)
@@ -1047,7 +1047,7 @@ let OriginalSourceActor = protocol.ActorClass({
return promise.resolve(content);
}
let options = {
policy: Ci.nsIContentPolicy.TYPE_STYLESHEET,
policy: Ci.nsIContentPolicy.TYPE_INTERNAL_STYLESHEET,
window: this.window
};
return fetch(this.url, options).then(({content}) => {
@@ -18,6 +18,7 @@ Cu.import("resource://gre/modules/osfile.jsm");
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/GMPUtils.jsm");
Cu.import("resource://gre/modules/AppConstants.jsm");
XPCOMUtils.defineLazyModuleGetter(
this, "GMPInstallManager", "resource://gre/modules/GMPInstallManager.jsm");
@@ -64,11 +65,13 @@ XPCOMUtils.defineLazyGetter(this, "pluginsBundle",
XPCOMUtils.defineLazyGetter(this, "gmpService",
() => Cc["@mozilla.org/gecko-media-plugin-service;1"].getService(Ci.mozIGeckoMediaPluginChromeService));
let messageManager = Cc["@mozilla.org/globalmessagemanager;1"]
XPCOMUtils.defineLazyGetter(this, "telemetryService", () => Services.telemetry);
var messageManager = Cc["@mozilla.org/globalmessagemanager;1"]
.getService(Ci.nsIMessageListenerManager);
let gLogger;
let gLogAppenderDump = null;
var gLogger;
var gLogAppenderDump = null;
function configureLogging() {
if (!gLogger) {
@@ -441,9 +444,72 @@ GMPWrapper.prototype = {
}
return this._updateTask;
},
_arePluginFilesOnDisk: function () {
let fileExists = function(aGmpPath, aFileName) {
let f = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
let path = OS.Path.join(aGmpPath, aFileName);
f.initWithPath(path);
return f.exists();
};
let id = this._plugin.id.substring(4);
let libName = AppConstants.DLL_PREFIX + id + AppConstants.DLL_SUFFIX;
return {
libraryMissing: !fileExists(this.gmpPath, libName),
infoMissing: !fileExists(this.gmpPath, id + ".info"),
voucherMissing: this._plugin.id == EME_ADOBE_ID
&& !fileExists(this.gmpPath, id + ".voucher"),
};
},
validate: function() {
if (!this.isInstalled) {
// Not installed -> Valid.
return { installed: false, valid: true };
}
let abi = GMPPrefs.get(GMPPrefs.KEY_PLUGIN_ABI, GMPUtils.ABI(), this._plugin.id);
if (abi != GMPUtils.ABI()) {
// ABI doesn't match. Possibly this is a profile migrated across platforms
// or from 32 -> 64 bit.
return {
installed: true,
mismatchedABI: true,
valid: false
};
}
// Installed -> Check if files are missing.
let status = this._arePluginFilesOnDisk();
status.installed = true;
status.mismatchedABI = false;
status.valid = true;
status.missing = [];
status.telemetry = 0;
if (status.libraryMissing) {
status.valid = false;
status.missing.push('library');
status.telemetry += 1;
}
if (status.infoMissing) {
status.valid = false;
status.missing.push('info');
status.telemetry += 2;
}
if (status.voucherMissing) {
status.valid = false;
status.missing.push('voucher');
status.telemetry += 4;
}
return status;
},
};
let GMPProvider = {
var GMPProvider = {
get name() { return "GMPProvider"; },
_plugins: null,
@@ -484,7 +550,8 @@ let GMPProvider = {
}
}
if (Preferences.get(GMPPrefs.KEY_EME_ENABLED, false)) {
var emeEnabled = Preferences.get(GMPPrefs.KEY_EME_ENABLED, false);
if (emeEnabled) {
try {
let greDir = Services.dirsvc.get(NS_GRE_DIR,
Ci.nsILocalFile);
@@ -4,13 +4,17 @@
"use strict";
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
let GMPScope = Cu.import("resource://gre/modules/addons/GMPProvider.jsm");
var GMPScope = Cu.import("resource://gre/modules/addons/GMPProvider.jsm");
Cu.import("resource://gre/modules/AppConstants.jsm");
XPCOMUtils.defineLazyGetter(this, "pluginsBundle",
() => Services.strings.createBundle("chrome://global/locale/plugins.properties"));
let gMockAddons = new Map();
let gMockEmeAddons = new Map();
XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
"resource://gre/modules/FileUtils.jsm");
var gMockAddons = new Map();
var gMockEmeAddons = new Map();
for (let plugin of GMPScope.GMP_PLUGINS) {
let mockAddon = Object.freeze({
@@ -26,9 +30,9 @@ for (let plugin of GMPScope.GMP_PLUGINS) {
}
}
let gInstalledAddonId = "";
let gPrefs = Services.prefs;
let gGetKey = GMPScope.GMPPrefs.getPrefKey;
var gInstalledAddonId = "";
var gPrefs = Services.prefs;
var gGetKey = GMPScope.GMPPrefs.getPrefKey;
function MockGMPInstallManager() {
}
@@ -216,6 +220,32 @@ add_task(function* test_autoUpdatePrefPersistance() {
}
});
function createMockPluginFilesIfNeeded(aFile, aPluginId) {
function createFile(aFileName) {
let f = aFile.clone();
f.append(aFileName);
if (!f.exists()) {
f.create(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
}
};
let id = aPluginId.substring(4);
let libName = AppConstants.DLL_PREFIX + id + AppConstants.DLL_SUFFIX;
createFile(libName);
createFile(id + ".info");
if (aPluginId == "gmp-eme-adobe")
createFile(id + ".voucher");
}
// Array.includes() is only in Nightly channel, so polyfill so we don't fail
// on other branches.
if (![].includes) {
Array.prototype.includes = function(element) {
return Object(this).indexOf(element) != -1;
}
}
add_task(function* test_pluginRegistration() {
const TEST_VERSION = "1.2.3.4";
@@ -259,7 +289,7 @@ add_task(function* test_pluginRegistration() {
// Changing the pref mid-session should cause unregistration and registration.
gPrefs.setCharPref(gGetKey(GMPScope.GMPPrefs.KEY_PLUGIN_VERSION, addon.id),
TEST_VERSION);
TEST_VERSION);
clearPaths();
const TEST_VERSION_2 = "5.6.7.8";
let file2 = Services.dirsvc.get("ProfD", Ci.nsIFile);
@@ -272,7 +302,7 @@ add_task(function* test_pluginRegistration() {
// Disabling the plugin should cause unregistration.
gPrefs.setCharPref(gGetKey(GMPScope.GMPPrefs.KEY_PLUGIN_VERSION, addon.id),
TEST_VERSION);
TEST_VERSION);
clearPaths();
gPrefs.setBoolPref(gGetKey(GMPScope.GMPPrefs.KEY_PLUGIN_ENABLED, addon.id), false);
Assert.deepEqual(addedPaths, []);