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

- Bug 1160428 - Fix theoretical take picture memory leak uncovered by coverity. r=aosmond (2b72701ba)
- Bug 1112469 - Part 2: Update the service workers in the parent and all child processes every day; r=nsm (d8eaeaedd)
- Bug 1112469 - Part 3: Add a unit test for ensuring that the nsIServiceWorkerManager.updateAllRegistrations() API works correctly; r=nsm (072b9ec24)
- Bug 1115495 - Part 1: Support app info for PAC. r=mcmanus (794b17e4c)
- Bug 1115495 - Part 2: PAC generator for browsing and system wide proxy. r=mcmanus, r=echen (1b6dca51f)
- Bug 1148996 - Remove selected lightweight theme for mochitest and xpcshell tests;r=jmaher (0dc3f12a6)
- Bug 1112469 - Part 4: Disable periodic updates of service workers when running tests; r=nsm (9246723ec)
- Bug 1112469 - Part 5: Actually test the code path that handles the idle-daily message; r=nsm (e36f40711)
- Bug 1112469 follow-up: Disable the test everywhere for now since it seems that bug 1151974 hits more than just Windows (07456472e)
This commit is contained in:
2020-03-19 22:11:42 +08:00
parent 15985b5125
commit 23315ea023
44 changed files with 1081 additions and 33 deletions
+7
View File
@@ -929,6 +929,13 @@ pref("b2g.theme.origin", "app://theme.gaiamobile.org");
pref("dom.mozApps.themable", true);
pref("dom.mozApps.selected_theme", "default_theme.gaiamobile.org");
// Enable PAC generator for B2G.
pref("network.proxy.pac_generator", true);
// List of app origins to apply browsing traffic proxy setting, separated by
// comma. Specify '*' in the list to apply to all apps.
pref("network.proxy.browsing.app_origins", "app://system.gaiamobile.org");
// Enable Web Speech synthesis API
pref("media.webspeech.synth.enabled", true);
+38
View File
@@ -30,6 +30,10 @@ XPCOMUtils.defineLazyServiceGetter(this, "uuidgen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator");
XPCOMUtils.defineLazyServiceGetter(this, "gPACGenerator",
"@mozilla.org/pac-generator;1",
"nsIPACGenerator");
// Once Bug 731746 - Allow chrome JS object to implement nsIDOMEventTarget
// is resolved this helper could be removed.
var SettingsListener = {
@@ -482,6 +486,40 @@ SettingsListener.observe("theme.selected",
}
});
// =================== Proxy server ======================
(function setupBrowsingProxySettings() {
function setPAC() {
let usePAC;
try {
usePAC = Services.prefs.getBoolPref('network.proxy.pac_generator');
} catch (ex) {}
if (usePAC) {
Services.prefs.setCharPref('network.proxy.autoconfig_url',
gPACGenerator.generate());
Services.prefs.setIntPref('network.proxy.type',
Ci.nsIProtocolProxyService.PROXYCONFIG_PAC);
}
}
SettingsListener.observe('browser.proxy.enabled', false, function(value) {
Services.prefs.setBoolPref('network.proxy.browsing.enabled', value);
setPAC();
});
SettingsListener.observe('browser.proxy.host', '', function(value) {
Services.prefs.setCharPref('network.proxy.browsing.host', value);
setPAC();
});
SettingsListener.observe('browser.proxy.port', 0, function(value) {
Services.prefs.setIntPref('network.proxy.browsing.port', value);
setPAC();
});
setPAC();
})();
// =================== Various simple mapping ======================
let settingsToObserve = {
'accessibility.screenreader_quicknav_modes': {
+3
View File
@@ -645,6 +645,9 @@
@BINPATH@/components/TestInterfaceJS.manifest
#endif
@RESPATH@/components/PACGenerator.js
@RESPATH@/components/PACGenerator.manifest
; Modules
@BINPATH@/modules/*
+3
View File
@@ -642,6 +642,9 @@
@RESPATH@/components/TestInterfaceJS.manifest
#endif
@RESPATH@/components/PACGenerator.js
@RESPATH@/components/PACGenerator.manifest
; Modules
@RESPATH@/browser/modules/*
@RESPATH@/modules/*
+7
View File
@@ -362,9 +362,16 @@ DOMCameraControlListener::OnTakePictureComplete(uint8_t* aData, uint32_t aLength
static_cast<uint64_t>(mLength),
mMimeType);
aDOMCameraControl->OnTakePictureComplete(picture);
mData = NULL;
}
protected:
virtual
~Callback()
{
free(mData);
}
uint8_t* mData;
uint32_t mLength;
nsString mMimeType;
@@ -33,7 +33,7 @@ interface nsIServiceWorkerInfo : nsISupports
readonly attribute DOMString waitingCacheName;
};
[scriptable, builtinclass, uuid(3cd3acce-8c80-4fcc-9265-067ebe8cab92)]
[scriptable, builtinclass, uuid(c05b3b45-7f39-458c-8097-afafc7d69b01)]
interface nsIServiceWorkerManager : nsISupports
{
/**
@@ -124,6 +124,8 @@ interface nsIServiceWorkerManager : nsISupports
void sendPushEvent(in ACString scope, in DOMString data);
void sendPushSubscriptionChangedEvent(in ACString scope);
void updateAllRegistrations();
};
%{ C++
+11
View File
@@ -75,6 +75,7 @@
#include "nsIMutable.h"
#include "nsIObserverService.h"
#include "nsIScriptSecurityManager.h"
#include "nsIServiceWorkerManager.h"
#include "nsScreenManagerProxy.h"
#include "nsMemoryInfoDumper.h"
#include "nsServiceManagerUtils.h"
@@ -1246,6 +1247,16 @@ ContentChild::RecvSpeakerManagerNotify()
return false;
}
bool
ContentChild::RecvUpdateServiceWorkerRegistrations()
{
nsCOMPtr<nsIServiceWorkerManager> swm = mozilla::services::GetServiceWorkerManager();
if (swm) {
swm->UpdateAllRegistrations();
}
return true;
}
static CancelableTask* sFirstIdleTask;
static void FirstIdle(void)
+2
View File
@@ -287,6 +287,8 @@ public:
virtual bool RecvSpeakerManagerNotify() override;
virtual bool RecvUpdateServiceWorkerRegistrations() override;
virtual bool RecvNotifyVisited(const URIParams& aURI) override;
// auto remove when alertfinished is received.
nsresult AddRemoteAlertObserver(const nsString& aData, nsIObserver* aObserver);
+2
View File
@@ -443,6 +443,8 @@ child:
async SpeakerManagerNotify();
async UpdateServiceWorkerRegistrations();
async DataStoreNotify(uint32_t aAppId, nsString aName,
nsString aManifestURL);
+33 -5
View File
@@ -19,6 +19,10 @@ XPCOMUtils.defineLazyServiceGetter(this, "gNetworkWorker",
"@mozilla.org/network/worker;1",
"nsINetworkWorker");
XPCOMUtils.defineLazyServiceGetter(this, "gPACGenerator",
"@mozilla.org/pac-generator;1",
"nsIPACGenerator");
// 1xx - Requested action is proceeding
const NETD_COMMAND_PROCEEDING = 100;
// 2xx - Requested action has been successfully completed
@@ -33,7 +37,8 @@ const NETD_COMMAND_UNSOLICITED = 600;
const WIFI_CTRL_INTERFACE = "wl0.1";
const MANUAL_PROXY_CONFIGURATION = 1;
const PROXY_TYPE_MANUAL = Ci.nsIProtocolProxyService.PROXYCONFIG_MANUAL;
const PROXY_TYPE_PAC = Ci.nsIProtocolProxyService.PROXYCONFIG_PAC;
let DEBUG = false;
@@ -484,9 +489,7 @@ NetworkService.prototype = {
return;
}
if (DEBUG) debug("Going to set proxy settings for " + network.name + " network interface.");
// Sets manual proxy configuration.
Services.prefs.setIntPref("network.proxy.type", MANUAL_PROXY_CONFIGURATION);
debug("Going to set proxy settings for " + network.name + " network interface.");
// Do not use this proxy server for all protocols.
Services.prefs.setBoolPref("network.proxy.share_proxy_settings", false);
Services.prefs.setCharPref("network.proxy.http", network.httpProxyHost);
@@ -494,6 +497,19 @@ NetworkService.prototype = {
let port = network.httpProxyPort === 0 ? 8080 : network.httpProxyPort;
Services.prefs.setIntPref("network.proxy.http_port", port);
Services.prefs.setIntPref("network.proxy.ssl_port", port);
let usePAC;
try {
usePAC = Services.prefs.getBoolPref("network.proxy.pac_generator");
} catch (ex) {}
if (usePAC) {
Services.prefs.setCharPref("network.proxy.autoconfig_url",
gPACGenerator.generate());
Services.prefs.setIntPref("network.proxy.type", PROXY_TYPE_PAC);
} else {
Services.prefs.setIntPref("network.proxy.type", PROXY_TYPE_MANUAL);
}
} catch(ex) {
if (DEBUG) debug("Exception " + ex + ". Unable to set proxy setting for " +
network.name + " network interface.");
@@ -503,12 +519,24 @@ NetworkService.prototype = {
clearNetworkProxy: function() {
if (DEBUG) debug("Going to clear all network proxy.");
Services.prefs.clearUserPref("network.proxy.type");
Services.prefs.clearUserPref("network.proxy.share_proxy_settings");
Services.prefs.clearUserPref("network.proxy.http");
Services.prefs.clearUserPref("network.proxy.http_port");
Services.prefs.clearUserPref("network.proxy.ssl");
Services.prefs.clearUserPref("network.proxy.ssl_port");
let usePAC;
try {
usePAC = Services.prefs.getBoolPref("network.proxy.pac_generator");
} catch (ex) {}
if (usePAC) {
Services.prefs.setCharPref("network.proxy.autoconfig_url",
gPACGenerator.generate());
Services.prefs.setIntPref("network.proxy.type", PROXY_TYPE_PAC);
} else {
Services.prefs.clearUserPref("network.proxy.type");
}
},
// Enable/Disable DHCP server.
@@ -6,7 +6,8 @@ MARIONETTE_HEAD_JS = "head.js";
const HTTP_PROXY = "10.0.2.200";
const HTTP_PROXY_PORT = "8080";
const MANUAL_PROXY_CONFIGURATION = 1;
const PROXY_TYPE_MANUAL = Ci.nsIProtocolProxyService.PROXYCONFIG_MANUAL;
const PROXY_TYPE_PAC = Ci.nsIProtocolProxyService.PROXYCONFIG_PAC;
// Test initial State
function verifyInitialState() {
@@ -38,6 +39,7 @@ function waitForHttpProxyVerified(aShouldBeSet) {
return new Promise(function(aResolve, aReject) {
try {
waitFor(aResolve, () => {
let usePAC = SpecialPowers.getBoolPref("network.proxy.pac_generator");
let proxyType = SpecialPowers.getIntPref("network.proxy.type");
let httpProxy = SpecialPowers.getCharPref("network.proxy.http");
let sslProxy = SpecialPowers.getCharPref("network.proxy.ssl");
@@ -45,13 +47,16 @@ function waitForHttpProxyVerified(aShouldBeSet) {
let sslProxyPort = SpecialPowers.getIntPref("network.proxy.ssl_port");
if ((aShouldBeSet &&
proxyType == MANUAL_PROXY_CONFIGURATION &&
(usePAC ? proxyType == PROXY_TYPE_PAC :
proxyType == PROXY_TYPE_MANUAL) &&
httpProxy == HTTP_PROXY &&
sslProxy == HTTP_PROXY &&
httpProxyPort == HTTP_PROXY_PORT &&
sslProxyPort == HTTP_PROXY_PORT) ||
(!aShouldBeSet && proxyType != MANUAL_PROXY_CONFIGURATION &&
!httpProxy && !sslProxy && !httpProxyPort && !sslProxyPort)) {
(!aShouldBeSet &&
(usePAC ? proxyType == PROXY_TYPE_PAC :
proxyType != PROXY_TYPE_MANUAL) &&
!httpProxy && !sslProxy && !httpProxyPort && !sslProxyPort)) {
return true;
}
+23
View File
@@ -34,6 +34,7 @@
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "mozilla/unused.h"
#include "nsContentUtils.h"
#include "nsGlobalWindow.h"
@@ -3103,6 +3104,28 @@ ServiceWorkerManager::GetAllRegistrations(nsIArray** aResult)
return NS_OK;
}
static PLDHashOperator
UpdateEachRegistration(const nsACString& aKey,
ServiceWorkerRegistrationInfo* aInfo,
void* aUserArg) {
auto This = static_cast<ServiceWorkerManager*>(aUserArg);
MOZ_ASSERT(!aInfo->mScope.IsEmpty());
nsresult res = This->Update(NS_ConvertUTF8toUTF16(aInfo->mScope));
unused << NS_WARN_IF(NS_FAILED(res));
return PL_DHASH_NEXT;
}
NS_IMETHODIMP
ServiceWorkerManager::UpdateAllRegistrations()
{
AssertIsOnMainThread();
mServiceWorkerRegistrationInfos.EnumerateRead(UpdateEachRegistration, this);
return NS_OK;
}
void
ServiceWorkerInfo::AppendWorker(ServiceWorker* aWorker)
{
+25 -2
View File
@@ -6,6 +6,11 @@
#include "ServiceWorkerPeriodicUpdater.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/unused.h"
#include "mozilla/Services.h"
#include "mozilla/Preferences.h"
#include "mozilla/dom/ContentParent.h"
#include "nsIServiceWorkerManager.h"
#define OBSERVER_TOPIC_IDLE_DAILY "idle-daily"
@@ -17,6 +22,8 @@ NS_IMPL_ISUPPORTS(ServiceWorkerPeriodicUpdater, nsIObserver)
StaticRefPtr<ServiceWorkerPeriodicUpdater>
ServiceWorkerPeriodicUpdater::sInstance;
bool
ServiceWorkerPeriodicUpdater::sPeriodicUpdatesEnabled = true;
already_AddRefed<ServiceWorkerPeriodicUpdater>
ServiceWorkerPeriodicUpdater::GetSingleton()
@@ -33,6 +40,9 @@ ServiceWorkerPeriodicUpdater::GetSingleton()
ServiceWorkerPeriodicUpdater::ServiceWorkerPeriodicUpdater()
{
Preferences::AddBoolVarCache(&sPeriodicUpdatesEnabled,
"dom.serviceWorkers.periodic-updates.enabled",
true);
}
ServiceWorkerPeriodicUpdater::~ServiceWorkerPeriodicUpdater()
@@ -44,8 +54,21 @@ ServiceWorkerPeriodicUpdater::Observe(nsISupports* aSubject,
const char* aTopic,
const char16_t* aData)
{
if (strcmp(aTopic, OBSERVER_TOPIC_IDLE_DAILY) == 0) {
// TODO: Update the service workers NOW!!!!!
if (strcmp(aTopic, OBSERVER_TOPIC_IDLE_DAILY) == 0 &&
sPeriodicUpdatesEnabled) {
// First, update all registrations in the parent process.
nsCOMPtr<nsIServiceWorkerManager> swm =
mozilla::services::GetServiceWorkerManager();
if (swm) {
swm->UpdateAllRegistrations();
}
// Now, tell all child processes to update their registrations as well.
nsTArray<ContentParent*> children;
ContentParent::GetAll(children);
for (uint32_t i = 0; i < children.Length(); i++) {
unused << children[i]->SendUpdateServiceWorkerRegistrations();
}
}
return NS_OK;
@@ -15,6 +15,14 @@ namespace mozilla {
namespace dom {
namespace workers {
/**
* This XPCOM component is main-process only, which means that it will never
* get instantiated in child processes. When we receive the idle-daily
* notification in this component, we iterate over all PContent children, and
* send each one a message that will trigger a call to
* nsIServiceWorkerManager::UpdateAllRegistrations() in all child processes.
*/
class ServiceWorkerPeriodicUpdater final : public nsIObserver
{
public:
@@ -28,6 +36,7 @@ private:
~ServiceWorkerPeriodicUpdater();
static StaticRefPtr<ServiceWorkerPeriodicUpdater> sInstance;
static bool sPeriodicUpdatesEnabled;
};
} // namespace workers
@@ -68,6 +68,10 @@ support-files =
bug1151916_worker.js
bug1151916_driver.html
empty.js
periodic.sjs
periodic/frame.html
periodic/register.html
periodic/unregister.html
[test_unregister.html]
skip-if = true # Bug 1133805
@@ -99,3 +103,5 @@ skip-if = true # Bug 1133805
[test_client_focus.html]
[test_bug1151916.html]
[test_empty_serviceworker.html]
[test_periodic_update.html]
skip-if = true # bug 1151974
@@ -0,0 +1,18 @@
function handleRequest(request, response) {
if (!getState('periodiccounter')) {
setState('periodiccounter', '1');
} else {
// Make sure that we pass a string value to setState!
setState('periodiccounter', "" + (parseInt(getState('periodiccounter')) + 1));
}
response.setHeader("Content-Type", "application/javascript", false);
response.write(getScript());
}
function getScript() {
return "onfetch = function(e) {" +
"if (e.request.url.indexOf('get-sw-version') > -1) {" +
"e.respondWith(new Response('" + getState('periodiccounter') + "'));" +
"}" +
"};";
}
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<script>
fetch("get-sw-version").then(function(r) {
return r.text();
}).then(function(body) {
parent.callback(body);
});
</script>
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<script>
var isDone = false;
function done() {
if (!isDone) {
parent.callback();
isDone = true;
}
}
navigator.serviceWorker.register("../periodic.sjs", {scope: "."})
.then(function(registration) {
if (registration.installing) {
registration.installing.onstatechange = function(e) {
done();
};
} else {
done();
}
});
</script>
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<script>
navigator.serviceWorker.getRegistration(".").then(function(registration) {
registration.unregister().then(function(success) {
if (success) {
parent.callback();
} else {
dump("Unregister failed\n");
}
});
});
</script>
@@ -0,0 +1,98 @@
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE HTML>
<html>
<head>
<title>Bug 1112469 - Test the periodic update of service workers</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<p id="display"></p>
<div id="content" style="display: none"></div>
<pre id="test"></pre>
<script class="testbody" type="text/javascript">
var oldSWVersion, newSWVersion;
function start() {
const Cc = SpecialPowers.Cc;
const Ci = SpecialPowers.Ci;
function testVersion(sw) {
// Verify that the service worker has been correctly updated.
testFrame("periodic/frame.html").then(function(body) {
newSWVersion = parseInt(body);
todo_is(newSWVersion, "2", "Expected correct new version");
ok(newSWVersion > oldSWVersion,
"The SW should be successfully updated, old: " + oldSWVersion +
", new: " + newSWVersion);
unregisterSW().then(function() {
SimpleTest.finish();
});
});
}
registerSW().then(function() {
return testFrame("periodic/frame.html").then(function(body) {
oldSWVersion = parseInt(body);
todo_is(oldSWVersion, "1", "Expected correct old version");
});
}).then(function() {
return navigator.serviceWorker.getRegistration("periodic/foo");
}).then(function(reg) {
reg.onupdatefound = function() {
reg.onupdatefound = null;
var sw = reg.installing;
sw.onstatechange = function() {
sw.onstatechange = null;
ok(!reg.waiting && reg.active, "New worker must get activated immediately");
testVersion(reg.active);
};
};
}).then(function() {
SpecialPowers.startPeriodicServiceWorkerUpdates();
});
}
function testFrame(src) {
return new Promise(function(resolve, reject) {
var iframe = document.createElement("iframe");
iframe.src = src;
window.callback = function(result) {
iframe.src = "about:blank";
document.body.removeChild(iframe);
iframe = null;
SpecialPowers.exactGC(window, function() {
resolve(result);
});
};
document.body.appendChild(iframe);
});
}
function registerSW() {
return testFrame("periodic/register.html");
}
function unregisterSW() {
return testFrame("periodic/unregister.html");
}
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({"set": [
["dom.serviceWorkers.exemptFromPerDomainMax", true],
["dom.serviceWorkers.enabled", true],
["dom.serviceWorkers.testing.enabled", true],
["dom.serviceWorkers.periodic-updates.enabled", true],
]}, function() {
start();
});
</script>
</pre>
</body>
</html>
+2
View File
@@ -140,6 +140,8 @@ class B2GDesktopReftest(RefTest):
# Set a future policy version to avoid the telemetry prompt.
prefs["toolkit.telemetry.prompted"] = 999
prefs["toolkit.telemetry.notifiedOptOut"] = 999
# Disable periodic updates of service workers
prefs["dom.serviceWorkers.periodic-updates.enabled"] = False
# Set the extra prefs.
profile.set_preferences(prefs)
@@ -61,3 +61,6 @@
// Make sure SelfSupport doesn't hit the network.
branch.setCharPref("browser.selfsupport.url", "https://%(server)s/selfsupport-dummy/");
// Disable periodic updates of service workers.
branch.setBoolPref("dom.serviceWorkers.periodic-updates.enabled", false);
+2
View File
@@ -450,6 +450,8 @@ class B2GRemoteReftest(RefTest):
# Disable tiles also
prefs["browser.newtabpage.directory.source"] = ""
prefs["browser.newtabpage.directory.ping"] = ""
# Disable periodic updates of service workers
prefs["dom.serviceWorkers.periodic-updates.enabled"] = False
if options.oop:
prefs['browser.tabs.remote.autostart'] = True
+165
View File
@@ -0,0 +1,165 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* 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/. */
"use strict";
const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
Cu.import('resource://gre/modules/XPCOMUtils.jsm');
Cu.import('resource://gre/modules/Services.jsm');
let DEBUG = false;
if (DEBUG) {
debug = function (s) { dump("-*- PACGenerator: " + s + "\n"); };
}
else {
debug = function (s) {};
}
const PACGENERATOR_CONTRACTID = "@mozilla.org/pac-generator;1";
const PACGENERATOR_CID = Components.ID("{788507c4-eb5f-4de8-b19b-e0d531974e8a}");
//
// RFC 2396 section 3.2.2:
//
// host = hostname | IPv4address
// hostname = *( domainlabel "." ) toplabel [ "." ]
// domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
// toplabel = alpha | alpha *( alphanum | "-" ) alphanum
// IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit
//
const HOST_REGEX =
new RegExp("^(?:" +
// *( domainlabel "." )
"(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)*" +
// toplabel
"[a-z](?:[a-z0-9-]*[a-z0-9])?" +
"|" +
// IPv4 address
"\\d+\\.\\d+\\.\\d+\\.\\d+" +
")$",
"i");
function PACGenerator() {
debug("Starting PAC Generator service.");
}
PACGenerator.prototype = {
classID : PACGENERATOR_CID,
QueryInterface : XPCOMUtils.generateQI([Ci.nsIPACGenerator]),
classInfo : XPCOMUtils.generateCI({classID: PACGENERATOR_CID,
contractID: PACGENERATOR_CONTRACTID,
classDescription: "PACGenerator",
interfaces: [Ci.nsIPACGenerator]}),
/**
* Validate the the host.
*/
isValidHost: function isValidHost(host) {
if (!HOST_REGEX.test(host)) {
debug("Unexpected host: '" + host + "'");
return false;
}
return true;
},
/**
* Returns a PAC string based on proxy settings in the preference.
* Only effective when the network.proxy.pac_generator preference is true.
*/
generate: function generate() {
let enabled, host, port, proxy;
try {
enabled = Services.prefs.getBoolPref("network.proxy.pac_generator");
} catch (ex) {}
if (!enabled) {
debug("PAC Generator disabled.");
return "";
}
let pac = "data:text/plain,function FindProxyForURL(url, host) { ";
// Direct connection for localhost.
pac += "if (shExpMatch(host, 'localhost') || " +
"shExpMatch(host, '127.0.0.1')) {" +
" return 'DIRECT'; } ";
// Rules for browsing proxy.
try {
enabled = Services.prefs.getBoolPref("network.proxy.browsing.enabled");
host = Services.prefs.getCharPref("network.proxy.browsing.host");
port = Services.prefs.getIntPref("network.proxy.browsing.port");
} catch (ex) {}
if (enabled && host && this.isValidHost(host)) {
proxy = host + ":" + ((port && port !== 0) ? port : 8080);
let appOrigins;
try {
appOrigins = Services.prefs.getCharPref("network.proxy.browsing.app_origins");
} catch (ex) {}
pac += "var origins ='" + appOrigins +
"'.split(/[ ,]+/).filter(Boolean); " +
"if ((origins.indexOf('*') > -1 || origins.indexOf(myAppOrigin()) > -1)" +
" && isInBrowser()) { return 'PROXY " + proxy + "'; } ";
}
// Rules for system proxy.
let share;
try {
share = Services.prefs.getBoolPref("network.proxy.share_proxy_settings");
} catch (ex) {}
if (share) {
// Add rules for all protocols.
try {
host = Services.prefs.getCharPref("network.proxy.http");
port = Services.prefs.getIntPref("network.proxy.http_port");
} catch (ex) {}
if (host && this.isValidHost(host)) {
proxy = host + ":" + ((port && port !== 0) ? port : 8080);
pac += "return 'PROXY " + proxy + "'; "
} else {
pac += "return 'DIRECT'; ";
}
} else {
// Add rules for specific protocols.
const proxyTypes = [
{"scheme": "http:", "pref": "http"},
{"scheme": "https:", "pref": "ssl"},
{"scheme": "ftp:", "pref": "ftp"}
];
for (let i = 0; i < proxyTypes.length; i++) {
try {
host = Services.prefs.getCharPref("network.proxy." +
proxyTypes[i]["pref"]);
port = Services.prefs.getIntPref("network.proxy." +
proxyTypes[i]["pref"] + "_port");
} catch (ex) {}
if (host && this.isValidHost(host)) {
proxy = host + ":" + (port === 0 ? 8080 : port);
pac += "if (url.substring(0, " + (proxyTypes[i]["scheme"]).length +
") == '" + proxyTypes[i]["scheme"] + "') { return 'PROXY " +
proxy + "'; } ";
}
}
pac += "return 'DIRECT'; ";
}
pac += "}";
debug("PAC: " + pac);
return pac;
}
};
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([PACGenerator]);
+2
View File
@@ -0,0 +1,2 @@
component {788507c4-eb5f-4de8-b19b-e0d531974e8a} PACGenerator.js
contract @mozilla.org/pac-generator;1 {788507c4-eb5f-4de8-b19b-e0d531974e8a}
+94 -1
View File
@@ -462,6 +462,63 @@ bool PACMyIpAddress(JSContext *cx, unsigned int argc, JS::Value *vp)
return GetRunning()->MyIPAddress(args);
}
// myAppId() javascript implementation
static
bool PACMyAppId(JSContext *cx, unsigned int argc, JS::Value *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (NS_IsMainThread()) {
NS_WARNING("PACMyAppId on Main Thread. How did that happen?");
return false;
}
if (!GetRunning()) {
NS_WARNING("PACMyAppId without a running ProxyAutoConfig object");
return false;
}
return GetRunning()->MyAppId(args);
}
// myAppOrigin() javascript implementation
static
bool PACMyAppOrigin(JSContext *cx, unsigned int argc, JS::Value *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (NS_IsMainThread()) {
NS_WARNING("PACMyAppOrigin on Main Thread. How did that happen?");
return false;
}
if (!GetRunning()) {
NS_WARNING("PACMyAppOrigin without a running ProxyAutoConfig object");
return false;
}
return GetRunning()->MyAppOrigin(args);
}
// IsInBrowser() javascript implementation
static
bool PACIsInBrowser(JSContext *cx, unsigned int argc, JS::Value *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (NS_IsMainThread()) {
NS_WARNING("PACIsInBrowser on Main Thread. How did that happen?");
return false;
}
if (!GetRunning()) {
NS_WARNING("PACIsInBrowser without a running ProxyAutoConfig object");
return false;
}
return GetRunning()->IsInBrowser(args);
}
// proxyAlert(msg) javascript implementation
static
bool PACProxyAlert(JSContext *cx, unsigned int argc, JS::Value *vp)
@@ -495,7 +552,9 @@ static const JSFunctionSpec PACGlobalFunctions[] = {
// a global "var pacUseMultihomedDNS = true;" will change behavior
// of myIpAddress to actively use DNS
JS_FS("myIpAddress", PACMyIpAddress, 0, 0),
JS_FS("myAppId", PACMyAppId, 0, 0),
JS_FS("myAppOrigin", PACMyAppOrigin, 0, 0),
JS_FS("isInBrowser", PACIsInBrowser, 0, 0),
JS_FS("alert", PACProxyAlert, 1, 0),
JS_FS_END
};
@@ -703,6 +762,9 @@ ProxyAutoConfig::SetupJS()
nsresult
ProxyAutoConfig::GetProxyForURI(const nsCString &aTestURI,
const nsCString &aTestHost,
uint32_t aAppId,
const nsString &aAppOrigin,
bool aIsInBrowser,
nsACString &result)
{
if (mJSNeedsSetup)
@@ -719,6 +781,9 @@ ProxyAutoConfig::GetProxyForURI(const nsCString &aTestURI,
// while the event loop is spinning on a DNS function. Don't early return.
SetRunning(this);
mRunningHost = aTestHost;
mRunningAppId = aAppId;
mRunningAppOrigin = aAppOrigin;
mRunningIsInBrowser = aIsInBrowser;
nsresult rv = NS_ERROR_FAILURE;
JS::RootedString uriString(cx, JS_NewStringCopyZ(cx, aTestURI.get()));
@@ -928,5 +993,33 @@ ProxyAutoConfig::MyIPAddress(const JS::CallArgs &aArgs)
return true;
}
bool
ProxyAutoConfig::MyAppId(const JS::CallArgs &aArgs)
{
aArgs.rval().setNumber(mRunningAppId);
return true;
}
bool
ProxyAutoConfig::MyAppOrigin(const JS::CallArgs &aArgs)
{
JSContext *cx = mJSRuntime->Context();
JSString *origin =
JS_NewStringCopyZ(cx, NS_ConvertUTF16toUTF8(mRunningAppOrigin).get());
if (!origin) {
return false;
}
aArgs.rval().setString(origin);
return true;
}
bool
ProxyAutoConfig::IsInBrowser(const JS::CallArgs &aArgs)
{
aArgs.rval().setBoolean(mRunningIsInBrowser);
return true;
}
} // namespace net
} // namespace mozilla
+15
View File
@@ -35,6 +35,9 @@ public:
void Shutdown();
void GC();
bool MyIPAddress(const JS::CallArgs &aArgs);
bool MyAppId(const JS::CallArgs &aArgs);
bool MyAppOrigin(const JS::CallArgs &aArgs);
bool IsInBrowser(const JS::CallArgs &aArgs);
bool ResolveAddress(const nsCString &aHostName,
NetAddr *aNetAddr, unsigned int aTimeout);
@@ -68,12 +71,21 @@ public:
* The URI as an ASCII string to test.
* @param aTestHost
* The ASCII hostname to test.
* @param aAppId
* The id of the app requesting connection.
* @param aAppOrigin
* The origin of the app requesting connection.
* @param aIsInBrowser
* True if the iframe has mozbrowser but has no mozapp attribute.
*
* @param result
* result string as defined above.
*/
nsresult GetProxyForURI(const nsCString &aTestURI,
const nsCString &aTestHost,
uint32_t aAppId,
const nsString &aAppOrigin,
bool aIsInBrowser,
nsACString &result);
private:
@@ -93,6 +105,9 @@ private:
nsCString mPACScript;
nsCString mPACURI;
nsCString mRunningHost;
uint32_t mRunningAppId;
nsString mRunningAppOrigin;
bool mRunningIsInBrowser;
nsCOMPtr<nsITimer> mTimer;
};
+6
View File
@@ -67,6 +67,7 @@ XPIDL_SOURCES += [
'nsINetworkProperties.idl',
'nsINSSErrorsService.idl',
'nsINullChannel.idl',
'nsIPACGenerator.idl',
'nsIParentChannel.idl',
'nsIParentRedirectingChannel.idl',
'nsIPermission.idl',
@@ -262,6 +263,11 @@ if CONFIG['MOZ_ENABLE_QTNETWORK']:
'nsAutodialQt.cpp',
]
EXTRA_COMPONENTS += [
'PACGenerator.js',
'PACGenerator.manifest'
]
EXTRA_JS_MODULES += [
'NetUtil.jsm',
]
+15
View File
@@ -0,0 +1,15 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* 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/. */
#include "nsISupports.idl"
[scriptable, uuid(4b3eeeea-1108-4aa0-8f26-e3ebdeb0454c)]
interface nsIPACGenerator : nsISupports
{
/**
* Returns a PAC string based on proxy settings in the preference.
* Only effective when the network.proxy.pac_generator preference is true.
*/
DOMString generate();
};
+25 -3
View File
@@ -5,6 +5,8 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsPACMan.h"
#include "mozIApplication.h"
#include "nsIAppsService.h"
#include "nsThreadUtils.h"
#include "nsIAuthPrompt.h"
#include "nsIPromptFactory.h"
@@ -231,9 +233,12 @@ private:
//-----------------------------------------------------------------------------
PendingPACQuery::PendingPACQuery(nsPACMan *pacMan, nsIURI *uri,
uint32_t appId, bool isInBrowser,
nsPACManCallback *callback,
bool mainThreadResponse)
: mPACMan(pacMan)
, mAppId(appId)
, mIsInBrowser(isInBrowser)
, mCallback(callback)
, mOnMainThreadOnly(mainThreadResponse)
{
@@ -241,6 +246,18 @@ PendingPACQuery::PendingPACQuery(nsPACMan *pacMan, nsIURI *uri,
uri->GetAsciiHost(mHost);
uri->GetScheme(mScheme);
uri->GetPort(&mPort);
nsCOMPtr<nsIAppsService> appsService =
do_GetService(APPS_SERVICE_CONTRACTID);
if (!appsService) {
return;
}
nsCOMPtr<mozIApplication> mozApp;
nsresult rv = appsService->GetAppByLocalId(appId, getter_AddRefs(mozApp));
if (NS_FAILED(rv) || !mozApp) {
return;
}
mozApp->GetOrigin(mAppOrigin);
}
void
@@ -329,7 +346,8 @@ nsPACMan::Shutdown()
}
nsresult
nsPACMan::AsyncGetProxyForURI(nsIURI *uri, nsPACManCallback *callback,
nsPACMan::AsyncGetProxyForURI(nsIURI *uri, uint32_t appId,
bool isInBrowser, nsPACManCallback *callback,
bool mainThreadResponse)
{
MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
@@ -342,7 +360,8 @@ nsPACMan::AsyncGetProxyForURI(nsIURI *uri, nsPACManCallback *callback,
LoadPACFromURI(EmptyCString());
nsRefPtr<PendingPACQuery> query =
new PendingPACQuery(this, uri, callback, mainThreadResponse);
new PendingPACQuery(this, uri, appId, isInBrowser, callback,
mainThreadResponse);
if (IsPACURI(uri)) {
// deal with this directly instead of queueing it
@@ -595,7 +614,10 @@ nsPACMan::ProcessPending()
// the systemproxysettings didn't complete the resolution. try via PAC
if (!completed) {
nsresult status = mPAC.GetProxyForURI(query->mSpec, query->mHost, pacString);
nsresult status = mPAC.GetProxyForURI(query->mSpec, query->mHost,
query->mAppId, query->mAppOrigin,
query->mIsInBrowser,
pacString);
query->Complete(status, pacString);
}
+18 -4
View File
@@ -54,9 +54,10 @@ class PendingPACQuery final : public nsRunnable,
public mozilla::LinkedListElement<PendingPACQuery>
{
public:
PendingPACQuery(nsPACMan *pacMan, nsIURI *uri,
nsPACManCallback *callback, bool mainThreadResponse);
PendingPACQuery(nsPACMan *pacMan, nsIURI *uri, uint32_t appId,
bool isInBrowser, nsPACManCallback *callback,
bool mainThreadResponse);
// can be called from either thread
void Complete(nsresult status, const nsCString &pacString);
void UseAlternatePACFile(const nsCString &pacURL);
@@ -70,6 +71,13 @@ public:
private:
nsPACMan *mPACMan; // weak reference
public:
uint32_t mAppId;
bool mIsInBrowser;
nsString mAppOrigin;
private:
nsRefPtr<nsPACManCallback> mCallback;
bool mOnMainThreadOnly;
};
@@ -103,12 +111,18 @@ public:
*
* @param uri
* The URI to query.
* @param appId
* The appId of the app making the connection.
* @param isInBrowser
* True if the iframe has mozbrowser but has no mozapp attribute.
* @param callback
* The callback to run once the PAC result is available.
* @param mustCallbackOnMainThread
* If set to false the callback can be made from the PAC thread
*/
nsresult AsyncGetProxyForURI(nsIURI *uri, nsPACManCallback *callback,
nsresult AsyncGetProxyForURI(nsIURI *uri, uint32_t appId,
bool isInBrowser,
nsPACManCallback *callback,
bool mustCallbackOnMainThread);
/**
+27 -7
View File
@@ -104,6 +104,7 @@ public:
NS_DECL_THREADSAFE_ISUPPORTS
nsAsyncResolveRequest(nsProtocolProxyService *pps, nsIChannel *channel,
uint32_t aAppId, bool aIsInBrowser,
uint32_t aResolveFlags,
nsIProtocolProxyCallback *callback)
: mStatus(NS_OK)
@@ -112,6 +113,8 @@ public:
, mPPS(pps)
, mXPComPPS(pps)
, mChannel(channel)
, mAppId(aAppId)
, mIsInBrowser(aIsInBrowser)
, mCallback(callback)
{
NS_ASSERTION(mCallback, "null callback");
@@ -263,8 +266,13 @@ private:
if (NS_SUCCEEDED(rv)) {
// now that the load is triggered, we can resubmit the query
nsRefPtr<nsAsyncResolveRequest> newRequest =
new nsAsyncResolveRequest(mPPS, mChannel, mResolveFlags, mCallback);
rv = mPPS->mPACMan->AsyncGetProxyForURI(proxyURI, newRequest, true);
new nsAsyncResolveRequest(mPPS, mChannel, mAppId,
mIsInBrowser, mResolveFlags,
mCallback);
rv = mPPS->mPACMan->AsyncGetProxyForURI(proxyURI, mAppId,
mIsInBrowser,
newRequest,
true);
}
if (NS_FAILED(rv))
@@ -301,6 +309,8 @@ private:
nsProtocolProxyService *mPPS;
nsCOMPtr<nsIProtocolProxyService> mXPComPPS;
nsCOMPtr<nsIChannel> mChannel;
uint32_t mAppId;
bool mIsInBrowser;
nsCOMPtr<nsIProtocolProxyCallback> mCallback;
nsCOMPtr<nsIProxyInfo> mProxyInfo;
};
@@ -1159,7 +1169,8 @@ nsProtocolProxyService::DeprecatedBlockingResolve(nsIChannel *aChannel,
// but if neither of them are in use, we can just do the work
// right here and directly invoke the callback
rv = Resolve_Internal(aChannel, info, aFlags, &usePACThread, getter_AddRefs(pi));
rv = Resolve_Internal(aChannel, NECKO_NO_APP_ID, false, info, aFlags,
&usePACThread, getter_AddRefs(pi));
if (NS_FAILED(rv))
return rv;
@@ -1173,7 +1184,8 @@ nsProtocolProxyService::DeprecatedBlockingResolve(nsIChannel *aChannel,
// code, but block this thread on that completion.
nsRefPtr<nsAsyncBridgeRequest> ctx = new nsAsyncBridgeRequest();
ctx->Lock();
if (NS_SUCCEEDED(mPACMan->AsyncGetProxyForURI(uri, ctx, false))) {
if (NS_SUCCEEDED(mPACMan->AsyncGetProxyForURI(uri, NECKO_NO_APP_ID, false,
ctx, false))) {
// this can really block the main thread, so cap it at 3 seconds
ctx->Wait();
}
@@ -1225,9 +1237,14 @@ nsProtocolProxyService::AsyncResolveInternal(nsIChannel *channel, uint32_t flags
nsresult rv = GetProxyURI(channel, getter_AddRefs(uri));
if (NS_FAILED(rv)) return rv;
uint32_t appId = NECKO_NO_APP_ID;
bool isInBrowser = false;
NS_GetAppInfo(channel, &appId, &isInBrowser);
*result = nullptr;
nsRefPtr<nsAsyncResolveRequest> ctx =
new nsAsyncResolveRequest(this, channel, flags, callback);
new nsAsyncResolveRequest(this, channel, appId, isInBrowser, flags,
callback);
nsProtocolInfo info;
rv = GetProtocolInfo(uri, &info);
@@ -1241,7 +1258,8 @@ nsProtocolProxyService::AsyncResolveInternal(nsIChannel *channel, uint32_t flags
// but if neither of them are in use, we can just do the work
// right here and directly invoke the callback
rv = Resolve_Internal(channel, info, flags, &usePACThread, getter_AddRefs(pi));
rv = Resolve_Internal(channel, appId, isInBrowser, info, flags,
&usePACThread, getter_AddRefs(pi));
if (NS_FAILED(rv))
return rv;
@@ -1262,7 +1280,7 @@ nsProtocolProxyService::AsyncResolveInternal(nsIChannel *channel, uint32_t flags
// else kick off a PAC thread query
rv = mPACMan->AsyncGetProxyForURI(uri, ctx, true);
rv = mPACMan->AsyncGetProxyForURI(uri, appId, isInBrowser, ctx, true);
if (NS_SUCCEEDED(rv))
ctx.forget(result);
return rv;
@@ -1702,6 +1720,8 @@ nsProtocolProxyService::NewProxyInfo_Internal(const char *aType,
nsresult
nsProtocolProxyService::Resolve_Internal(nsIChannel *channel,
uint32_t appId,
bool isInBrowser,
const nsProtocolInfo &info,
uint32_t flags,
bool *usePACThread,
+10 -4
View File
@@ -211,6 +211,10 @@ protected:
*
* @param channel
* The channel to test.
* @param appId
* The id of the app making the query.
* @param isInBrowser
* True if the iframe has mozbrowser but has no mozapp attribute.
* @param info
* Information about the URI's protocol.
* @param flags
@@ -222,10 +226,12 @@ protected:
* The resulting proxy info or null.
*/
nsresult Resolve_Internal(nsIChannel *channel,
const nsProtocolInfo &info,
uint32_t flags,
bool *usePAC,
nsIProxyInfo **result);
uint32_t appId,
bool isInBrowser,
const nsProtocolInfo &info,
uint32_t flags,
bool *usePAC,
nsIProxyInfo **result);
/**
* This method applies the registered filters to the given proxy info
+238
View File
@@ -0,0 +1,238 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
Cu.import("resource://gre/modules/Services.jsm");
let ios = Cc["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
let pps = Cc["@mozilla.org/network/protocol-proxy-service;1"].getService();
let prefs = Cc["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
let pgen = Cc["@mozilla.org/pac-generator;1"]
.getService(Components.interfaces.nsIPACGenerator);
const TARGET_HOST ="www.mozilla.org";
const HTTP_HOST = "httpHost";
const HTTP_PORT = 1111;
const HTTPS_HOST = "httpsHost";
const HTTPS_PORT = 2222;
const FTP_HOST= "ftpHost";
const FTP_PORT = 3333;
const MY_APP_ID = 10;
const MY_APP_ORIGIN = "apps://browser.gaiamobile.com";
const APP_ORIGINS_LIST = "apps://test1.com, apps://browser.gaiamobile.com";
const BROWSING_HOST = "browsingHost";
const BROWSING_PORT = 4444;
const PROXY_TYPE_PAC = Ci.nsIProtocolProxyService.PROXYCONFIG_PAC;
const proxyTypes = {
"http": {"pref": "http", "host": HTTP_HOST, "port": HTTP_PORT},
"https": {"pref": "ssl", "host": HTTPS_HOST, "port": HTTPS_PORT},
"ftp": {"pref": "ftp", "host": FTP_HOST, "port": FTP_PORT}
};
function default_proxy_settings() {
prefs.setBoolPref("network.proxy.pac_generator", true);
prefs.setIntPref("network.proxy.type", 0);
prefs.setCharPref("network.proxy.autoconfig_url", "");
for (let i in proxyTypes) {
let p = proxyTypes[i];
prefs.setCharPref("network.proxy." + p["pref"], p["host"]);
prefs.setIntPref("network.proxy." + p["pref"] + "_port", p["port"]);
}
}
function TestResolveCallback(type, host, callback) {
this.type = type;
this.host = host;
this.callback = callback;
}
TestResolveCallback.prototype = {
QueryInterface:
function TestResolveCallback_QueryInterface(iid) {
if (iid.equals(Components.interfaces.nsIProtocolProxyCallback) ||
iid.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_ERROR_NO_INTERFACE;
},
onProxyAvailable:
function TestResolveCallback_onProxyAvailable(req, channel, pi, status) {
if (this.type) {
// Check for localhost.
if (this.host == "localhost" || this.host == "127.0.0.1") {
do_check_eq(pi, null);
this.callback();
return;
}
// Check for browsing proxy.
let browsingEnabled;
try {
browsingEnabled = prefs.getBoolPref("network.proxy.browsing.enabled");
} catch (ex) {}
if (browsingEnabled) {
let proxyHost, proxyPort;
try {
proxyHost = prefs.getCharPref("network.proxy.browsing.host");
proxyPort = prefs.getIntPref("network.proxy.browsing.port");
} catch (ex) {}
if (proxyHost) {
do_check_eq(pi.host, proxyHost);
do_check_eq(pi.port, proxyPort);
this.callback();
return;
}
}
// Check for system proxy.
let share;
try {
share = prefs.getBoolPref("network.proxy.share_proxy_settings");
} catch (ex) {}
let p = share ? proxyTypes["http"] : proxyTypes[this.type];
if (p) {
let proxyHost, proxyPort;
try {
proxyHost = prefs.getCharPref("network.proxy." + p["pref"]);
proxyPort = prefs.getIntPref("network.proxy." + p["pref"] + "_port");
} catch (ex) {}
if (proxyHost) {
// Connection through proxy.
do_check_neq(pi, null);
do_check_eq(pi.host, proxyHost);
do_check_eq(pi.port, proxyPort);
} else {
// Direct connection.
do_check_eq(pi, null);
}
}
}
this.callback();
}
};
function test_resolve_type(type, host, callback) {
// We have to setup a profile, otherwise indexed db used by webapps
// will throw random exception when trying to get profile folder.
do_get_profile();
// We also need a valid nsIXulAppInfo service as Webapps.jsm is querying it.
Cu.import("resource://testing-common/AppInfo.jsm");
updateAppInfo();
// Mock getAppByLocalId() to return testing app origin.
Cu.import("resource://gre/modules/AppsUtils.jsm");
AppsUtils.getAppByLocalId = function(aAppId) {
let app = { origin: MY_APP_ORIGIN};
return app;
};
let channel = ios.newChannel2(type + "://" + host + "/",
null,
null,
null, // aLoadingNode
Services.scriptSecurityManager.getSystemPrincipal(),
null, // aTriggeringPrincipal
Ci.nsILoadInfo.SEC_NORMAL,
Ci.nsIContentPolicy.TYPE_OTHER);
channel.notificationCallbacks =
AppsUtils.createLoadContext(MY_APP_ID, true);
let req = pps.asyncResolve(channel, 0, new TestResolveCallback(type, host, callback));
}
function test_resolve(host, callback) {
test_resolve_type("http", host, function() {
test_resolve_type("https", host, function() {
test_resolve_type("ftp", host, run_next_test);
});
});
}
add_test(function test_localhost() {
default_proxy_settings();
prefs.setBoolPref("network.proxy.share_proxy_settings", true);
Services.prefs.setCharPref("network.proxy.autoconfig_url", pgen.generate());
Services.prefs.setIntPref("network.proxy.type", PROXY_TYPE_PAC);
test_resolve("localhost", run_next_test);
});
add_test(function test_share_on_proxy() {
default_proxy_settings();
prefs.setBoolPref("network.proxy.share_proxy_settings", true);
Services.prefs.setCharPref("network.proxy.autoconfig_url", pgen.generate());
Services.prefs.setIntPref("network.proxy.type", PROXY_TYPE_PAC);
test_resolve(TARGET_HOST, run_next_test);
});
add_test(function test_share_on_direct() {
default_proxy_settings();
prefs.setBoolPref("network.proxy.share_proxy_settings", true);
prefs.setCharPref("network.proxy.http", "");
prefs.setCharPref("network.proxy.ssl", "");
prefs.setCharPref("network.proxy.ftp", "");
Services.prefs.setCharPref("network.proxy.autoconfig_url", pgen.generate());
Services.prefs.setIntPref("network.proxy.type", PROXY_TYPE_PAC);
test_resolve(TARGET_HOST, run_next_test);
});
add_test(function test_share_off_proxy() {
default_proxy_settings();
prefs.setBoolPref("network.proxy.share_proxy_settings", false);
Services.prefs.setCharPref("network.proxy.autoconfig_url", pgen.generate());
Services.prefs.setIntPref("network.proxy.type", PROXY_TYPE_PAC);
test_resolve(TARGET_HOST, run_next_test);
});
add_test(function test_share_off_direct() {
default_proxy_settings();
prefs.setBoolPref("network.proxy.share_proxy_settings", false);
prefs.setCharPref("network.proxy.http", "");
prefs.setCharPref("network.proxy.ssl", "");
prefs.setCharPref("network.proxy.ftp", "");
Services.prefs.setCharPref("network.proxy.autoconfig_url", pgen.generate());
Services.prefs.setIntPref("network.proxy.type", PROXY_TYPE_PAC);
test_resolve(TARGET_HOST, run_next_test);
});
add_test(function test_browsing_proxy() {
default_proxy_settings();
prefs.setBoolPref("network.proxy.browsing.enabled", true);
prefs.setCharPref("network.proxy.browsing.host", BROWSING_HOST);
prefs.setIntPref("network.proxy.browsing.port", BROWSING_PORT);
prefs.setCharPref("network.proxy.browsing.app_origins", APP_ORIGINS_LIST);
Services.prefs.setCharPref("network.proxy.autoconfig_url", pgen.generate());
Services.prefs.setIntPref("network.proxy.type", PROXY_TYPE_PAC);
test_resolve(TARGET_HOST, run_next_test);
});
function run_test(){
do_register_cleanup(() => {
prefs.clearUserPref("network.proxy.pac_generator");
prefs.clearUserPref("network.proxy.type");
prefs.clearUserPref("network.proxy.autoconfig_url");
prefs.clearUserPref("network.proxy.share_proxy_settings");
prefs.clearUserPref("network.proxy.http");
prefs.clearUserPref("network.proxy.http_port");
prefs.clearUserPref("network.proxy.ssl");
prefs.clearUserPref("network.proxy.ssl_port");
prefs.clearUserPref("network.proxy.ftp");
prefs.clearUserPref("network.proxy.ftp_port");
prefs.clearUserPref("network.proxy.browsing.enabled");
prefs.clearUserPref("network.proxy.browsing.host");
prefs.clearUserPref("network.proxy.browsing.port");
prefs.clearUserPref("network.proxy.browsing.app_origins");
});
run_next_test();
}
+46 -1
View File
@@ -629,7 +629,52 @@ function run_pac3_test() {
prefs.setCharPref("network.proxy.autoconfig_url", pac);
prefs.setBoolPref("network.proxy.proxy_over_tls", false);
var req = pps.asyncResolve(channel, 0, new TestResolveCallback(null, finish_pac_test));
var req = pps.asyncResolve(channel, 0, new TestResolveCallback(null, run_pac4_test));
}
function run_pac4_test() {
var appId = 10;
var isInBrowser = true;
var appOrigin = "apps://browser.gaiamobile.com";
// We have to setup a profile, otherwise indexed db used by webapps
// will throw random exception when trying to get profile folder.
do_get_profile();
// We also need a valid nsIXulAppInfo service as Webapps.jsm is querying it.
Cu.import("resource://testing-common/AppInfo.jsm");
updateAppInfo();
// Mock getAppByLocalId() to return testing app origin.
Cu.import("resource://gre/modules/AppsUtils.jsm");
AppsUtils.getAppByLocalId = function(aAppId) {
var app = { origin: appOrigin };
return app;
};
var pac = 'data:text/plain,' +
'function FindProxyForURL(url, host) {' +
' if (myAppId() == ' + appId +
' && isInBrowser() == ' + isInBrowser +
' && myAppOrigin() == "' + appOrigin + '")' +
' return "PROXY foopy:8080; DIRECT";' +
'}';
var channel = ios.newChannel2("http://www.mozilla.org/",
null,
null,
null, // aLoadingNode
Services.scriptSecurityManager.getSystemPrincipal(),
null, // aTriggeringPrincipal
Ci.nsILoadInfo.SEC_NORMAL,
Ci.nsIContentPolicy.TYPE_OTHER);
channel.notificationCallbacks =
AppsUtils.createLoadContext(appId, isInBrowser);
// Configure PAC
prefs.setIntPref("network.proxy.type", 2);
prefs.setCharPref("network.proxy.autoconfig_url", pac);
var req = pps.asyncResolve(channel, 0, new TestResolveCallback("http", finish_pac_test));
}
function finish_pac_test() {
+1
View File
@@ -224,6 +224,7 @@ skip-if = bits != 32
skip-if = os == "win"
[test_nojsredir.js]
[test_offline_status.js]
[test_pac_generator.js]
[test_parse_content_type.js]
[test_permmgr.js]
[test_plaintext_sniff.js]
@@ -367,6 +367,8 @@ class FirefoxProfile(Profile):
'toolkit.startup.max_resumed_crashes' : -1,
# Don't report telemetry information
'toolkit.telemetry.enabled' : False,
# Disable periodic updates of service workers
'dom.serviceWorkers.periodic-updates.enabled': False,
}
class MetroFirefoxProfile(Profile):
@@ -410,6 +412,8 @@ class MetroFirefoxProfile(Profile):
'toolkit.startup.max_resumed_crashes' : -1,
# Don't report telemetry information
'toolkit.telemetry.enabled' : False,
# Disable periodic updates of service workers
'dom.serviceWorkers.periodic-updates.enabled': False,
}
class ThunderbirdProfile(Profile):
+12
View File
@@ -299,3 +299,15 @@ user_pref("browser.readinglist.introShown", true);
// Don't block old libavcodec libraries when testing.
user_pref("media.libavcodec.allow-obsolete", true);
// Don't let PAC generator to set PAC, as mochitest framework has its own PAC
// rules during testing.
user_pref("network.proxy.pac_generator", false);
// Make tests run consistently on DevEdition (which has a lightweight theme
// selected by default).
user_pref("lightweightThemes.selectedThemeID", "");
user_pref("browser.devedition.theme.enabled", false);
// Disable periodic updates of service workers.
user_pref("dom.serviceWorkers.periodic-updates.enabled", false);
@@ -86,6 +86,7 @@ SpecialPowersObserver.prototype = new SpecialPowersObserverAPI();
this._messageManager.addMessageListener("SPChromeScriptMessage", this);
this._messageManager.addMessageListener("SPQuotaManager", this);
this._messageManager.addMessageListener("SPSetTestPluginEnabledState", this);
this._messageManager.addMessageListener("SPPeriodicServiceWorkerUpdates", this);
this._messageManager.loadFrameScript(CHILD_LOGGER_SCRIPT, true);
this._messageManager.loadFrameScript(CHILD_SCRIPT_API, true);
@@ -128,7 +129,33 @@ SpecialPowersObserver.prototype = new SpecialPowersObserverAPI();
var obs = Services.obs;
obs.removeObserver(this, "chrome-document-global-created");
obs.removeObserver(this, "http-on-modify-request");
obs.removeObserver(this, "xpcom-shutdown");
this._removeProcessCrashObservers();
if (this._isFrameScriptLoaded) {
this._messageManager.removeMessageListener("SPPrefService", this);
this._messageManager.removeMessageListener("SPProcessCrashService", this);
this._messageManager.removeMessageListener("SPPingService", this);
this._messageManager.removeMessageListener("SpecialPowers.Quit", this);
this._messageManager.removeMessageListener("SpecialPowers.Focus", this);
this._messageManager.removeMessageListener("SPPermissionManager", this);
this._messageManager.removeMessageListener("SPWebAppService", this);
this._messageManager.removeMessageListener("SPObserverService", this);
this._messageManager.removeMessageListener("SPLoadChromeScript", this);
this._messageManager.removeMessageListener("SPChromeScriptMessage", this);
this._messageManager.removeMessageListener("SPQuotaManager", this);
this._messageManager.removeMessageListener("SPSetTestPluginEnabledState", this);
this._messageManager.removeMessageListener("SPPeriodicServiceWorkerUpdates", this);
this._messageManager.removeDelayedFrameScript(CHILD_LOGGER_SCRIPT);
this._messageManager.removeDelayedFrameScript(CHILD_SCRIPT_API);
this._messageManager.removeDelayedFrameScript(CHILD_SCRIPT);
this._isFrameScriptLoaded = false;
}
this._mmIsGlobal = true;
this._messageManager = Cc["@mozilla.org/globalmessagemanager;1"].
getService(Ci.nsIMessageBroadcaster);
};
SpecialPowersObserver.prototype._addProcessCrashObservers = function() {
@@ -509,6 +509,17 @@ SpecialPowersObserverAPI.prototype = {
return undefined; // See comment at the beginning of this function.
}
case "SPPeriodicServiceWorkerUpdates": {
// We could just dispatch a generic idle-daily notification here, but
// this is better since it avoids invoking other idle daily observers
// at the cost of hard-coding the usage of PeriodicServiceWorkerUpdater.
Cc["@mozilla.org/service-worker-periodic-updater;1"].
getService(Ci.nsIObserver).
observe(null, "idle-daily", "");
return undefined; // See comment at the beginning of this function.
}
default:
throw new SpecialPowersException("Unrecognized Special Powers API");
}
@@ -31,7 +31,8 @@ function SpecialPowers(window) {
"SPPrefService",
"SPProcessCrashService",
"SPSetTestPluginEnabledState",
"SPWebAppService"];
"SPWebAppService",
"SPPeriodicServiceWorkerUpdates"];
this.SP_ASYNC_MESSAGES = ["SpecialPowers.Focus",
"SpecialPowers.Quit",
@@ -1922,6 +1922,10 @@ SpecialPowersAPI.prototype = {
createDOMFile: function(path, options) {
return new File(path, options);
},
startPeriodicServiceWorkerUpdates: function() {
return this._sendSyncMessage('SPPeriodicServiceWorkerUpdates', {});
},
};
this.SpecialPowersAPI = SpecialPowersAPI;
+2
View File
@@ -72,6 +72,8 @@ class TPSTestRunner(object):
'services.sync.firstSync': 'notReady',
'services.sync.lastversion': '1.0',
'toolkit.startup.max_resumed_crashes': -1,
# Disable periodic updates of service workers
'dom.serviceWorkers.periodic-updates.enabled': False,
}
debug_preferences = {
+12
View File
@@ -1403,3 +1403,15 @@ try {
prefs.setCharPref("browser.selfsupport.url", "https://%(server)s/selfsupport-dummy/");
}
} catch (e) { }
// Make tests run consistently on DevEdition (which has a lightweight theme
// selected by default).
try {
if (runningInParent) {
let prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
prefs.deleteBranch("lightweightThemes.selectedThemeID");
prefs.deleteBranch("browser.devedition.theme.enabled");
}
} catch (e) { }