Bug 1576768 - Automatically format .sjs files using prettier. r=Standard8,agi,zombie,extension-reviewers

# ignore-this-changeset

Differential Revision: https://phabricator.services.mozilla.com/D128482
This commit is contained in:
Evgenia Kotovich 2021-10-18 09:26:33 +00:00
Родитель e377953c3c
Коммит 0d0980ee0d
421 изменённых файлов: 7235 добавлений и 4987 удалений

Просмотреть файл

@ -12,7 +12,10 @@ const IMG_BYTES = atob(
// stolen from file_blocked_script.sjs
function setGlobalState(data, key) {
x = { data: data, QueryInterface: function(iid) { return this } };
x = {
data,
QueryInterface: ChromeUtils.generateQI([]),
};
x.wrappedJSObject = x;
setObjectState(key, x);
}

Просмотреть файл

@ -3,7 +3,11 @@
function handleRequest(request, response) {
// let's enjoy the amazing CSP setting
response.setHeader("Content-Security-Policy", "frame-ancestors 'self'", false);
response.setHeader(
"Content-Security-Policy",
"frame-ancestors 'self'",
false
);
// let's avoid caching issues
response.setHeader("Pragma", "no-cache");
@ -18,8 +22,8 @@ function handleRequest(request, response) {
let cookie = request.hasHeader("Cookie")
? request.getHeader("Cookie")
: "<html><body>" +
"<h2 id='strictCookie'>No same site strict cookie header</h2>" +
"</body></html>";
"<h2 id='strictCookie'>No same site strict cookie header</h2>" +
"</body></html>";
response.write(cookie);
if (!request.hasHeader("Cookie")) {

Просмотреть файл

@ -1,7 +1,9 @@
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream"
);
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain", false);
@ -13,8 +15,9 @@ function handleRequest(request, response) {
var avail;
var bytes = [];
while ((avail = body.available()) > 0)
while ((avail = body.available()) > 0) {
Array.prototype.push.apply(bytes, body.readByteArray(avail));
}
var data = String.fromCharCode.apply(null, bytes);
response.bodyOutputStream.write(data, data.length);

Просмотреть файл

@ -13,7 +13,8 @@ function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 200);
response.setHeader("Content-Type", "text/html", false);
let txt = "<html><head><title>XFO page</title></head>" +
let txt =
"<html><head><title>XFO page</title></head>" +
"<body><h1>" +
"XFO blocked page opened in new window!" +
"</h1></body></html>";
@ -22,8 +23,8 @@ function handleRequest(request, response) {
let cookie = request.hasHeader("Cookie")
? request.getHeader("Cookie")
: "<html><body>" +
"<h2 id='strictCookie'>No same site strict cookie header</h2></body>" +
"</html>";
"<h2 id='strictCookie'>No same site strict cookie header</h2></body>" +
"</html>";
response.write(cookie);
if (!request.hasHeader("Cookie")) {

Просмотреть файл

@ -17,6 +17,9 @@ function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 302, "Moved Temporarily");
response.setHeader("Set-Cookie", `faviconCookie=${++state}`);
response.setHeader("Location", "http://example.com/browser/browser/base/content/test/favicons/moz.png");
response.setHeader(
"Location",
"http://example.com/browser/browser/base/content/test/favicons/moz.png"
);
setState("cache_cookie", `${state}`);
}

Просмотреть файл

@ -2,8 +2,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/. */
function handleRequest(request, response)
{
function handleRequest(request, response) {
let page = "<!DOCTYPE html><html><body><p>HSTS page</p></body></html>";
response.setStatusLine(request.httpVersion, "200", "OK");
response.setHeader("Strict-Transport-Security", "max-age=60");

Просмотреть файл

@ -3,11 +3,11 @@
*/
function handleRequest(aRequest, aResponse) {
aResponse.setStatusLine(aRequest.httpVersion, 200);
if (aRequest.hasHeader('Cookie')) {
aResponse.write("cookie-present");
} else {
aResponse.setHeader("Set-Cookie", "foopy=1");
aResponse.write("cookie-not-present");
}
aResponse.setStatusLine(aRequest.httpVersion, 200);
if (aRequest.hasHeader("Cookie")) {
aResponse.write("cookie-present");
} else {
aResponse.setHeader("Set-Cookie", "foopy=1");
aResponse.write("cookie-not-present");
}
}

Просмотреть файл

@ -2,20 +2,17 @@
* 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/. */
function handleRequest(request, response)
{
function handleRequest(request, response) {
let page = "download";
response.setStatusLine(request.httpVersion, "200", "OK");
let [first, second] = request.queryString.split('=');
let [first, second] = request.queryString.split("=");
let headerStr = first;
if (second !== "none") {
headerStr += "; filename=" + second;
}
response.setHeader(
"Content-Disposition",
headerStr);
response.setHeader("Content-Disposition", headerStr);
response.setHeader("Content-Type", "text/plain", false);
response.setHeader("Content-Length", page.length + "", false);
response.write(page);

Просмотреть файл

@ -1,7 +1,9 @@
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream"
);
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain", false);
@ -13,8 +15,9 @@ function handleRequest(request, response) {
var avail;
var bytes = [];
while ((avail = body.available()) > 0)
while ((avail = body.available()) > 0) {
Array.prototype.push.apply(bytes, body.readByteArray(avail));
}
var data = String.fromCharCode.apply(null, bytes);
response.bodyOutputStream.write(data, data.length);

Просмотреть файл

@ -5,5 +5,7 @@ function handleRequest(request, response) {
response.setStatusLine("1.1", 302, "Found");
response.setHeader(
"Location",
`download_with_content_disposition_header.sjs?${queryStr}`, false);
`download_with_content_disposition_header.sjs?${queryStr}`,
false
);
}

Просмотреть файл

@ -21,4 +21,4 @@ function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, "200", "Found");
response.setHeader("refresh", `${delay}; url=${page}`);
response.write("OK");
}
}

Просмотреть файл

@ -33,4 +33,4 @@ function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, "200", "Found");
response.setHeader("Cache-Control", "no-cache", false);
response.write(html);
}
}

Просмотреть файл

@ -25,8 +25,12 @@ function handleRequest(req, resp) {
let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
resp.write(AUTOPLAY_HTML);
timer.init(() => {
resp.write("");
resp.finish();
}, DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT);
timer.init(
() => {
resp.write("");
resp.finish();
},
DELAY_MS,
Ci.nsITimer.TYPE_ONE_SHOT
);
}

Просмотреть файл

@ -4,13 +4,17 @@
// A 1x1 PNG image.
// Source: https://commons.wikimedia.org/wiki/File:1x1.png (Public Domain)
const IMAGE = atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" +
"ACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=");
const IMAGE = atob(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" +
"ACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII="
);
function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 200);
if (request.queryString &&
request.queryString.includes("type=image-no-cookie")) {
if (
request.queryString &&
request.queryString.includes("type=image-no-cookie")
) {
response.setHeader("Content-Type", "image/png", false);
response.write(IMAGE);
} else {

Просмотреть файл

@ -3,8 +3,7 @@
* Used in browser_referrer_*.js, bug 1113431.
* Arguments: ?scheme=http://&policy=origin&rel=noreferrer
*/
function handleRequest(request, response)
{
function handleRequest(request, response) {
Components.utils.importGlobalProperties(["URLSearchParams"]);
let query = new URLSearchParams(request.queryString);
@ -14,11 +13,14 @@ function handleRequest(request, response)
let cross = query.get("cross");
let host = cross ? "example.com" : "test1.example.com";
let linkUrl = scheme + host +
"/browser/browser/base/content/test/referrer/" +
"file_referrer_testserver.sjs";
let metaReferrerTag =
policy ? `<meta name='referrer' content='${policy}'>` : "";
let linkUrl =
scheme +
host +
"/browser/browser/base/content/test/referrer/" +
"file_referrer_testserver.sjs";
let metaReferrerTag = policy
? `<meta name='referrer' content='${policy}'>`
: "";
let html = `<!DOCTYPE HTML>
<html>

Просмотреть файл

@ -3,8 +3,7 @@
* Used in browser_referrer_*.js, bug 1113431.
* Arguments: ?scheme=http://&policy=origin&rel=noreferrer
*/
function handleRequest(request, response)
{
function handleRequest(request, response) {
Components.utils.importGlobalProperties(["URLSearchParams"]);
let query = new URLSearchParams(request.queryString);
@ -14,12 +13,13 @@ function handleRequest(request, response)
let cross = query.get("cross");
let host = cross ? "example.com" : "test1.example.com";
let linkUrl = scheme + host +
"/browser/browser/base/content/test/referrer/" +
"file_referrer_testserver.sjs";
let linkUrl =
scheme +
host +
"/browser/browser/base/content/test/referrer/" +
"file_referrer_testserver.sjs";
let referrerPolicy =
policy ? `referrerpolicy="${policy}"` : "";
let referrerPolicy = policy ? `referrerpolicy="${policy}"` : "";
let html = `<!DOCTYPE HTML>
<html>
@ -28,7 +28,9 @@ function handleRequest(request, response)
<title>Test referrer</title>
</head>
<body>
<a id='testlink' href='${linkUrl}' ${referrerPolicy} ${rel ? ` rel='${rel}'` : ""}>
<a id='testlink' href='${linkUrl}' ${referrerPolicy} ${
rel ? ` rel='${rel}'` : ""
}>
referrer test link</a>
</body>
</html>`;

Просмотреть файл

@ -2,8 +2,7 @@
* Renders the HTTP Referer header up to the second path slash.
* Used in browser_referrer_*.js, bug 1113431.
*/
function handleRequest(request, response)
{
function handleRequest(request, response) {
let referrer = "";
try {
referrer = request.getHeader("referer");
@ -12,7 +11,10 @@ function handleRequest(request, response)
}
// Strip it past the first path slash. Makes tests easier to read.
referrer = referrer.split("/").slice(0, 4).join("/");
referrer = referrer
.split("/")
.slice(0, 4)
.join("/");
let html = `<!DOCTYPE HTML>
<html>

Просмотреть файл

@ -1,9 +1,10 @@
function handleRequest(request, response) {
var page = "<!DOCTYPE html><html><body>bug 906190</body></html>";
var path = "https://test1.example.com/browser/browser/base/content/test/siteIdentity/";
var path =
"https://test1.example.com/browser/browser/base/content/test/siteIdentity/";
var url;
if (request.queryString.includes('bad-redirection=1')) {
if (request.queryString.includes("bad-redirection=1")) {
url = path + "this_page_does_not_exist.html";
} else {
url = path + "file_bug906190_redirected.html";

Просмотреть файл

@ -1,14 +1,17 @@
function handleRequest(request, response) {
var page = "<!DOCTYPE html><html><body>bug 418354 and bug 1082837</body></html>";
var page =
"<!DOCTYPE html><html><body>bug 418354 and bug 1082837</body></html>";
if (request.queryString === "script") {
var redirect = "http://example.com/browser/browser/base/content/test/siteIdentity/test_mcb_redirect.js";
if (request.queryString === "script") {
var redirect =
"http://example.com/browser/browser/base/content/test/siteIdentity/test_mcb_redirect.js";
response.setHeader("Cache-Control", "no-cache", false);
} else if (request.queryString === "image_http") {
var redirect = "http://example.com/tests/image/test/mochitest/blue.png";
response.setHeader("Cache-Control", "max-age=3600", false);
} else if (request.queryString === "image_redirect_http_sjs") {
var redirect = "http://example.com/browser/browser/base/content/test/siteIdentity/test_mcb_redirect.sjs?image_redirect_https";
var redirect =
"http://example.com/browser/browser/base/content/test/siteIdentity/test_mcb_redirect.sjs?image_redirect_https";
response.setHeader("Cache-Control", "max-age=3600", false);
} else if (request.queryString === "image_redirect_https") {
var redirect = "https://example.com/tests/image/test/mochitest/blue.png";

Просмотреть файл

@ -1,6 +1,7 @@
const HTTP_ORIGIN = "http://example.com";
const HTTPS_ORIGIN = "https://example.com";
const URI_PATH = "/browser/browser/components/contextualidentity/test/browser/saveLink.sjs";
const URI_PATH =
"/browser/browser/components/contextualidentity/test/browser/saveLink.sjs";
Components.utils.importGlobalProperties(["URLSearchParams"]);
@ -11,7 +12,12 @@ function handleRequest(aRequest, aResponse) {
if (params.has("UCI")) {
aResponse.setStatusLine(aRequest.httpVersion, 200);
aResponse.setHeader("Set-Cookie", "UCI=" + params.get("UCI"));
aResponse.write("<html><body><a href='" + HTTPS_ORIGIN + URI_PATH + "?redirect=1' id='fff'>this is a link</a></body></html>");
aResponse.write(
"<html><body><a href='" +
HTTPS_ORIGIN +
URI_PATH +
"?redirect=1' id='fff'>this is a link</a></body></html>"
);
return;
}
@ -19,7 +25,11 @@ function handleRequest(aRequest, aResponse) {
// if we are able to follow it.
if (params.has("redirect")) {
aResponse.setStatusLine(aRequest.httpVersion, 302, "Found");
aResponse.setHeader("Location", HTTP_ORIGIN + URI_PATH + "?download=1", false);
aResponse.setHeader(
"Location",
HTTP_ORIGIN + URI_PATH + "?download=1",
false
);
aResponse.write("Redirect!");
return;
}

Просмотреть файл

@ -1,3 +1,3 @@
function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 404, "Not Found");
}
function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 404, "Not Found");
}

Просмотреть файл

@ -1,5 +1,4 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
var match;
var requestAuth = true;
@ -9,23 +8,27 @@ function handleRequest(request, response)
// at the beginning of the query string.
var query = "?" + request.queryString;
var expected_user = "test", expected_pass = "testpass", realm = "mochitest";
var expected_user = "test",
expected_pass = "testpass",
realm = "mochitest";
// user=xxx
match = /[^_]user=([^&]*)/.exec(query);
if (match)
if (match) {
expected_user = match[1];
}
// pass=xxx
match = /[^_]pass=([^&]*)/.exec(query);
if (match)
if (match) {
expected_pass = match[1];
}
// realm=xxx
match = /[^_]realm=([^&]*)/.exec(query);
if (match)
if (match) {
realm = match[1];
}
// Look for an authentication header, if any, in the request.
//
@ -34,51 +37,59 @@ function handleRequest(request, response)
// This test only supports Basic auth. The value sent by the client is
// "username:password", obscured with base64 encoding.
var actual_user = "", actual_pass = "", authHeader, authPresent = false;
var actual_user = "",
actual_pass = "",
authHeader,
authPresent = false;
if (request.hasHeader("Authorization")) {
authPresent = true;
authHeader = request.getHeader("Authorization");
match = /Basic (.+)/.exec(authHeader);
if (match.length != 2)
throw new Error("Couldn't parse auth header: " + authHeader);
if (match.length != 2) {
throw new Error("Couldn't parse auth header: " + authHeader);
}
var userpass = base64ToString(match[1]); // no atob() :-(
match = /(.*):(.*)/.exec(userpass);
if (match.length != 3)
throw new Error("Couldn't decode auth header: " + userpass);
if (match.length != 3) {
throw new Error("Couldn't decode auth header: " + userpass);
}
actual_user = match[1];
actual_pass = match[2];
}
// Don't request authentication if the credentials we got were what we
// expected.
if (expected_user == actual_user &&
expected_pass == actual_pass) {
if (expected_user == actual_user && expected_pass == actual_pass) {
requestAuth = false;
}
if (requestAuth) {
response.setStatusLine("1.0", 401, "Authentication required");
response.setHeader("WWW-Authenticate", "basic realm=\"" + realm + "\"", true);
response.setHeader("WWW-Authenticate", 'basic realm="' + realm + '"', true);
} else {
response.setStatusLine("1.0", 200, "OK");
}
response.setHeader("Content-Type", "application/xhtml+xml", false);
response.write("<html xmlns='http://www.w3.org/1999/xhtml'>");
response.write("<p>Login: <span id='ok'>" + (requestAuth ? "FAIL" : "PASS") + "</span></p>\n");
response.write(
"<p>Login: <span id='ok'>" +
(requestAuth ? "FAIL" : "PASS") +
"</span></p>\n"
);
response.write("<p>Auth: <span id='auth'>" + authHeader + "</span></p>\n");
response.write("<p>User: <span id='user'>" + actual_user + "</span></p>\n");
response.write("<p>Pass: <span id='pass'>" + actual_pass + "</span></p>\n");
response.write("</html>");
}
// base64 decoder
//
// Yoinked from extensions/xml-rpc/src/nsXmlRpcClient.js because btoa()
// doesn't seem to exist. :-(
/* Convert Base64 data to a string */
/* eslint-disable prettier/prettier */
const toBinaryTable = [
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
@ -89,38 +100,42 @@ const toBinaryTable = [
-1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
];
const base64Pad = '=';
/* eslint-enable prettier/prettier */
const base64Pad = "=";
function base64ToString(data) {
var result = "";
var leftbits = 0; // number of bits decoded, but yet to be appended
var leftdata = 0; // bits decoded, but yet to be appended
var result = '';
var leftbits = 0; // number of bits decoded, but yet to be appended
var leftdata = 0; // bits decoded, but yet to be appended
// Convert one by one.
for (var i = 0; i < data.length; i++) {
var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
var padding = (data[i] == base64Pad);
// Skip illegal characters and whitespace
if (c == -1) continue;
// Collect data into leftdata, update bitcount
leftdata = (leftdata << 6) | c;
leftbits += 6;
// If we have 8 or more bits, append 8 bits to the result
if (leftbits >= 8) {
leftbits -= 8;
// Append if not padding.
if (!padding)
result += String.fromCharCode((leftdata >> leftbits) & 0xff);
leftdata &= (1 << leftbits) - 1;
}
// Convert one by one.
for (var i = 0; i < data.length; i++) {
var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
var padding = data[i] == base64Pad;
// Skip illegal characters and whitespace
if (c == -1) {
continue;
}
// If there are any bits left, the base64 string was corrupted
if (leftbits)
throw Components.Exception('Corrupted base64 string');
// Collect data into leftdata, update bitcount
leftdata = (leftdata << 6) | c;
leftbits += 6;
return result;
// If we have 8 or more bits, append 8 bits to the result
if (leftbits >= 8) {
leftbits -= 8;
// Append if not padding.
if (!padding) {
result += String.fromCharCode((leftdata >> leftbits) & 0xff);
}
leftdata &= (1 << leftbits) - 1;
}
}
// If there are any bits left, the base64 string was corrupted
if (leftbits) {
throw Components.Exception("Corrupted base64 string");
}
return result;
}

Просмотреть файл

@ -6,6 +6,8 @@ function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain; charset=UTF-8", false);
if (request.hasHeader("pragma") && request.hasHeader("cache-control")) {
response.write(`${request.getHeader("pragma")}:${request.getHeader("cache-control")}`);
response.write(
`${request.getHeader("pragma")}:${request.getHeader("cache-control")}`
);
}
}
}

Просмотреть файл

@ -11,7 +11,11 @@ const URL = "file_slowed_document.sjs";
const DELAY = 2 * 1000; // Delay two seconds before completing the request.
let nsTimer = Components.Constructor("@mozilla.org/timer;1", "nsITimer", "initWithCallback");
let nsTimer = Components.Constructor(
"@mozilla.org/timer;1",
"nsITimer",
"initWithCallback"
);
let timer;
@ -31,11 +35,15 @@ function handleRequest(request, response) {
// Note: We need to store a reference to the timer to prevent it from being
// canceled when it's GCed.
timer = new nsTimer(() => {
if (request.queryString.includes("with-iframe")) {
response.write(`<iframe src="${URL}?r=${Math.random()}"></iframe>`);
}
response.write(`</body></html>`);
response.finish();
}, DELAY, Ci.nsITimer.TYPE_ONE_SHOT);
timer = new nsTimer(
() => {
if (request.queryString.includes("with-iframe")) {
response.write(`<iframe src="${URL}?r=${Math.random()}"></iframe>`);
}
response.write(`</body></html>`);
response.finish();
},
DELAY,
Ci.nsITimer.TYPE_ONE_SHOT
);
}

Просмотреть файл

@ -6,7 +6,7 @@ const LINK_PATH = `${URI_PATH}file_saveAs.sjs`;
const VIDEO_PATH = `${URI_PATH}file_thirdPartyChild.video.ogv`;
// Reusing existing png file for testing.
const IMAGE_PATH = `${URI_PATH}file_favicon.png`;
const FRAME_PATH = `${SECOND_ORIGIN}${URI_PATH}file_saveAs.sjs?image=1`
const FRAME_PATH = `${SECOND_ORIGIN}${URI_PATH}file_saveAs.sjs?image=1`;
Components.utils.importGlobalProperties(["URLSearchParams"]);

Просмотреть файл

@ -11,10 +11,11 @@ function handleRequest(request, response) {
var cookie = "name=value";
var title = "No Cookie";
if (request.hasHeader("Cookie") && request.getHeader("Cookie") == cookie)
if (request.hasHeader("Cookie") && request.getHeader("Cookie") == cookie) {
title = "Cookie";
else
} else {
response.setHeader("Set-Cookie", cookie, false);
}
response.write("<html><head><title>");
response.write(title);

Просмотреть файл

@ -8,4 +8,4 @@ function handleRequest(request, response) {
} else {
response.write("no user agent header");
}
}
}

Просмотреть файл

@ -55,8 +55,7 @@ const WORKER = `
};
`;
function handleRequest(request, response)
{
function handleRequest(request, response) {
Components.utils.importGlobalProperties(["URLSearchParams"]);
let query = new URLSearchParams(request.queryString);

Просмотреть файл

@ -11,8 +11,12 @@ function handleRequest(req, resp) {
resp.setHeader("Content-Type", "text/html;charset=utf-8", false);
timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.init(() => {
resp.write("hi");
resp.finish();
}, DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT);
timer.init(
() => {
resp.write("hi");
resp.finish();
},
DELAY_MS,
Ci.nsITimer.TYPE_ONE_SHOT
);
}

Просмотреть файл

@ -11,8 +11,12 @@ function handleRequest(req, resp) {
resp.setHeader("Content-Type", "text/html;charset=utf-8", false);
timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.init(() => {
resp.write("hi");
resp.finish();
}, DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT);
timer.init(
() => {
resp.write("hi");
resp.finish();
},
DELAY_MS,
Ci.nsITimer.TYPE_ONE_SHOT
);
}

Просмотреть файл

@ -1,6 +1,6 @@
function handleRequest(request, response) {
Components.utils.importGlobalProperties(["URLSearchParams"]);
Components.utils.import("resource://gre/modules/NetUtil.jsm");
let { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
let query = new URLSearchParams(request.queryString);
response.setHeader("Cross-Origin-Opener-Policy", "same-origin", false);
@ -15,8 +15,9 @@ function handleRequest(request, response) {
});
// Set up the file streams to read in the file as UTF-8
let fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
let fstream = Components.classes[
"@mozilla.org/network/file-input-stream;1"
].createInstance(Components.interfaces.nsIFileInputStream);
fstream.init(file, -1, 0, 0);

Просмотреть файл

@ -5,9 +5,11 @@
"use strict";
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream"
);
Cu.importGlobalProperties(["DOMParser"]);
function handleRequest(req, res) {
@ -33,7 +35,7 @@ const statusCodes = {
405: "Method Not Allowed",
500: "Internal Server Error",
501: "Not Implemented",
503: "Service Unavailable"
503: "Service Unavailable",
};
function HTTPError(code = 500, message) {
@ -46,8 +48,10 @@ HTTPError.prototype.constructor = HTTPError;
function sendError(res, err) {
if (!(err instanceof HTTPError)) {
err = new HTTPError(typeof err == "number" ? err : 500,
err.message || typeof err == "string" ? err : "");
err = new HTTPError(
typeof err == "number" ? err : 500,
err.message || typeof err == "string" ? err : ""
);
}
res.setStatusLine("1.1", err.code, err.name);
res.write(err.message);
@ -57,8 +61,9 @@ function parseQuery(query) {
let ret = {};
for (let param of query.replace(/^[?&]/, "").split("&")) {
param = param.split("=");
if (!param[0])
if (!param[0]) {
continue;
}
ret[unescape(param[0])] = unescape(param[1]);
}
return ret;
@ -69,22 +74,23 @@ function getRequestBody(req) {
let bytes = [];
let body = new BinaryInputStream(req.bodyInputStream);
while ((avail = body.available()) > 0)
while ((avail = body.available()) > 0) {
Array.prototype.push.apply(bytes, body.readByteArray(avail));
}
return String.fromCharCode.apply(null, bytes);
}
function sha1(str) {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
let converter = Cc[
"@mozilla.org/intl/scriptableunicodeconverter"
].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
// `result` is an out parameter, `result.value` will contain the array length.
let result = {};
// `data` is an array of bytes.
let data = converter.convertToByteArray(str, result);
let ch = Cc["@mozilla.org/security/hash;1"]
.createInstance(Ci.nsICryptoHash);
let ch = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
ch.init(ch.SHA1);
ch.update(data, data.length);
let hash = ch.finish(false);
@ -101,19 +107,22 @@ function sha1(str) {
function parseXml(body) {
let parser = new DOMParser();
let xml = parser.parseFromString(body, "text/xml");
if (xml.documentElement.localName == "parsererror")
if (xml.documentElement.localName == "parsererror") {
throw new Error("Invalid XML");
}
return xml;
}
function getInputStream(path) {
let file = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties)
.get("CurWorkD", Ci.nsIFile);
for (let part of path.split("/"))
.getService(Ci.nsIProperties)
.get("CurWorkD", Ci.nsIFile);
for (let part of path.split("/")) {
file.append(part);
let fileStream = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
}
let fileStream = Cc[
"@mozilla.org/network/file-input-stream;1"
].createInstance(Ci.nsIFileInputStream);
fileStream.init(file, 1, 0, false);
return fileStream;
}
@ -122,25 +131,33 @@ function checkAuth(req) {
let err = new Error("Authorization failed");
err.code = 401;
if (!req.hasHeader("Authorization"))
if (!req.hasHeader("Authorization")) {
throw new HTTPError(401, "No Authorization header provided.");
}
let auth = req.getHeader("Authorization");
if (!auth.startsWith("Bearer "))
throw new HTTPError(401, "Invalid Authorization header content: '" + auth + "'");
if (!auth.startsWith("Bearer ")) {
throw new HTTPError(
401,
"Invalid Authorization header content: '" + auth + "'"
);
}
// Rejecting inactive subscriptions.
if (auth.includes("inactive")) {
const INACTIVE_STATE_RESPONSE = "<html><body><h1>TranslateApiException</h1><p>Method: TranslateArray()</p><p>Message: The Azure Market Place Translator Subscription associated with the request credentials is not in an active state.</p><code></code><p>message id=5641.V2_Rest.TranslateArray.48CC6470</p></body></html>";
const INACTIVE_STATE_RESPONSE =
"<html><body><h1>TranslateApiException</h1><p>Method: TranslateArray()</p><p>Message: The Azure Market Place Translator Subscription associated with the request credentials is not in an active state.</p><code></code><p>message id=5641.V2_Rest.TranslateArray.48CC6470</p></body></html>";
throw new HTTPError(401, INACTIVE_STATE_RESPONSE);
}
}
function reallyHandleRequest(req, res) {
log("method: " + req.method);
if (req.method != "POST") {
sendError(res, "Bing only deals with POST requests, not '" + req.method + "'.");
sendError(
res,
"Bing only deals with POST requests, not '" + req.method + "'."
);
return;
}
@ -148,7 +165,9 @@ function reallyHandleRequest(req, res) {
log("body: " + body);
// First, we'll see if we're dealing with an XML body:
let contentType = req.hasHeader("Content-Type") ? req.getHeader("Content-Type") : null;
let contentType = req.hasHeader("Content-Type")
? req.getHeader("Content-Type")
: null;
log("contentType: " + contentType);
if (contentType.startsWith("text/xml")) {
@ -161,10 +180,11 @@ function reallyHandleRequest(req, res) {
let method = xml.documentElement.localName;
log("invoking method: " + method);
// If the requested method is supported, delegate it to its handler.
if (methodHandlers[method])
if (methodHandlers[method]) {
methodHandlers[method](res, xml);
else
} else {
throw new HTTPError(501);
}
} catch (ex) {
sendError(res, ex, ex.code);
}
@ -173,15 +193,16 @@ function reallyHandleRequest(req, res) {
let params = parseQuery(body);
// Delegate an authentication request to the correct handler.
if ("grant_type" in params && params.grant_type == "client_credentials")
if ("grant_type" in params && params.grant_type == "client_credentials") {
methodHandlers.authenticate(res, params);
else
} else {
sendError(res, 501);
}
}
}
const methodHandlers = {
authenticate: function(res, params) {
authenticate(res, params) {
// Validate a few required parameters.
if (params.scope != "http://api.microsofttranslator.com") {
sendError(res, "Invalid scope.");
@ -198,16 +219,16 @@ const methodHandlers = {
// Defines the tokens for certain client ids.
const TOKEN_MAP = {
'testInactive' : 'inactive',
'testClient' : 'test'
testInactive: "inactive",
testClient: "test",
};
let token = 'test'; // Default token.
if((params.client_id in TOKEN_MAP)){
let token = "test"; // Default token.
if (params.client_id in TOKEN_MAP) {
token = TOKEN_MAP[params.client_id];
}
let content = JSON.stringify({
access_token: token,
expires_in: 600
expires_in: 600,
});
res.setStatusLine("1.1", 200, "OK");
@ -216,9 +237,9 @@ const methodHandlers = {
res.write(content);
},
TranslateArrayRequest: function(res, xml, body) {
TranslateArrayRequest(res, xml, body) {
let from = xml.querySelector("From").firstChild.nodeValue;
let to = xml.querySelector("To").firstChild.nodeValue
let to = xml.querySelector("To").firstChild.nodeValue;
log("translating from '" + from + "' to '" + to + "'");
res.setStatusLine("1.1", 200, "OK");
@ -227,8 +248,11 @@ const methodHandlers = {
let hash = sha1(body).substr(0, 10);
log("SHA1 hash of content: " + hash);
let inputStream = getInputStream(
"browser/browser/components/translation/test/fixtures/result-" + hash + ".txt");
"browser/browser/components/translation/test/fixtures/result-" +
hash +
".txt"
);
res.bodyOutputStream.writeFrom(inputStream, inputStream.available());
inputStream.close();
}
},
};

Просмотреть файл

@ -5,9 +5,11 @@
"use strict";
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream"
);
function handleRequest(req, res) {
try {
@ -34,7 +36,7 @@ const statusCodes = {
422: "The text could not be translated",
500: "Internal Server Error",
501: "The specified translation direction is not supported",
503: "Service Unavailable"
503: "Service Unavailable",
};
function HTTPError(code = 500, message) {
@ -47,8 +49,10 @@ HTTPError.prototype.constructor = HTTPError;
function sendError(res, err) {
if (!(err instanceof HTTPError)) {
err = new HTTPError(typeof err == "number" ? err : 500,
err.message || typeof err == "string" ? err : "");
err = new HTTPError(
typeof err == "number" ? err : 500,
err.message || typeof err == "string" ? err : ""
);
}
res.setStatusLine("1.1", err.code, err.name);
res.write(err.message);
@ -58,19 +62,22 @@ function sendError(res, err) {
// http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
function parseQuery(query) {
let match,
params = {},
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); };
params = {},
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function(s) {
return decodeURIComponent(s.replace(pl, " "));
};
while (match = search.exec(query)) {
while ((match = search.exec(query))) {
let k = decode(match[1]),
v = decode(match[2]);
v = decode(match[2]);
if (k in params) {
if(params[k] instanceof Array)
if (params[k] instanceof Array) {
params[k].push(v);
else
} else {
params[k] = [params[k], v];
}
} else {
params[k] = v;
}
@ -80,15 +87,15 @@ function parseQuery(query) {
}
function sha1(str) {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
let converter = Cc[
"@mozilla.org/intl/scriptableunicodeconverter"
].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
// `result` is an out parameter, `result.value` will contain the array length.
let result = {};
// `data` is an array of bytes.
let data = converter.convertToByteArray(str, result);
let ch = Cc["@mozilla.org/security/hash;1"]
.createInstance(Ci.nsICryptoHash);
let ch = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
ch.init(ch.SHA1);
ch.update(data, data.length);
let hash = ch.finish(false);
@ -107,20 +114,23 @@ function getRequestBody(req) {
let bytes = [];
let body = new BinaryInputStream(req.bodyInputStream);
while ((avail = body.available()) > 0)
while ((avail = body.available()) > 0) {
Array.prototype.push.apply(bytes, body.readByteArray(avail));
}
return String.fromCharCode.apply(null, bytes);
}
function getInputStream(path) {
let file = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties)
.get("CurWorkD", Ci.nsIFile);
for (let part of path.split("/"))
.getService(Ci.nsIProperties)
.get("CurWorkD", Ci.nsIFile);
for (let part of path.split("/")) {
file.append(part);
let fileStream = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
}
let fileStream = Cc[
"@mozilla.org/network/file-input-stream;1"
].createInstance(Ci.nsIFileInputStream);
fileStream.init(file, 1, 0, false);
return fileStream;
}
@ -138,33 +148,34 @@ function getInputStream(path) {
* If any other key is used the server reponds with 401 error code.
*/
function checkAuth(params) {
if(!("key" in params))
if (!("key" in params)) {
throw new HTTPError(400);
}
let key = params.key;
if(key === "yandexValidKey")
if (key === "yandexValidKey") {
return true;
}
let invalidKeys = {
"yandexInvalidKey" : 401,
"yandexBlockedKey" : 402,
"yandexOutOfRequestsKey" : 403,
"yandexOutOfCharsKey" : 404,
yandexInvalidKey: 401,
yandexBlockedKey: 402,
yandexOutOfRequestsKey: 403,
yandexOutOfCharsKey: 404,
};
if(key in invalidKeys)
if (key in invalidKeys) {
throw new HTTPError(invalidKeys[key]);
}
throw new HTTPError(401);
}
function reallyHandleRequest(req, res) {
try {
// Preparing the query parameters.
let params = {};
if(req.method == 'POST') {
if (req.method == "POST") {
params = parseQuery(getRequestBody(req));
}
@ -172,28 +183,28 @@ function reallyHandleRequest(req, res) {
log(JSON.stringify(params));
checkAuth(params);
methodHandlers['translate'](res, params);
methodHandlers.translate(res, params);
} catch (ex) {
sendError(res, ex, ex.code);
}
}
const methodHandlers = {
translate: function(res, params) {
translate(res, params) {
res.setStatusLine("1.1", 200, "OK");
res.setHeader("Content-Type", "application/json");
let hash = sha1(JSON.stringify(params)).substr(0, 10);
log("SHA1 hash of content: " + hash);
let fixture = "browser/browser/components/translation/test/fixtures/result-yandex-" + hash + ".json";
let fixture =
"browser/browser/components/translation/test/fixtures/result-yandex-" +
hash +
".json";
log("PATH: " + fixture);
let inputStream = getInputStream(fixture);
res.bodyOutputStream.writeFrom(inputStream, inputStream.available());
inputStream.close();
}
},
};

Просмотреть файл

@ -1,5 +1,4 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
try {
reallyHandleRequest(request, response);
} catch (e) {
@ -8,10 +7,10 @@ function handleRequest(request, response)
}
}
function reallyHandleRequest(request, response) {
var match;
var requestAuth = true, requestProxyAuth = true;
var requestAuth = true,
requestProxyAuth = true;
// Allow the caller to drive how authentication is processed via the query.
// Eg, http://localhost:8888/authenticate.sjs?user=foo&realm=bar
@ -19,133 +18,178 @@ function reallyHandleRequest(request, response) {
// at the beginning of the query string.
var query = "?" + request.queryString;
var expected_user = "", expected_pass = "", realm = "mochitest";
var proxy_expected_user = "", proxy_expected_pass = "", proxy_realm = "mochi-proxy";
var huge = false, plugin = false, anonymous = false;
var expected_user = "",
expected_pass = "",
realm = "mochitest";
var proxy_expected_user = "",
proxy_expected_pass = "",
proxy_realm = "mochi-proxy";
var huge = false,
plugin = false,
anonymous = false;
var authHeaderCount = 1;
// user=xxx
match = /[^_]user=([^&]*)/.exec(query);
if (match)
if (match) {
expected_user = match[1];
}
// pass=xxx
match = /[^_]pass=([^&]*)/.exec(query);
if (match)
if (match) {
expected_pass = match[1];
}
// realm=xxx
match = /[^_]realm=([^&]*)/.exec(query);
if (match)
if (match) {
realm = match[1];
}
// proxy_user=xxx
match = /proxy_user=([^&]*)/.exec(query);
if (match)
if (match) {
proxy_expected_user = match[1];
}
// proxy_pass=xxx
match = /proxy_pass=([^&]*)/.exec(query);
if (match)
if (match) {
proxy_expected_pass = match[1];
}
// proxy_realm=xxx
match = /proxy_realm=([^&]*)/.exec(query);
if (match)
if (match) {
proxy_realm = match[1];
}
// huge=1
match = /huge=1/.exec(query);
if (match)
if (match) {
huge = true;
}
// plugin=1
match = /plugin=1/.exec(query);
if (match)
if (match) {
plugin = true;
}
// multiple=1
match = /multiple=([^&]*)/.exec(query);
if (match)
authHeaderCount = match[1]+0;
if (match) {
authHeaderCount = match[1] + 0;
}
// anonymous=1
match = /anonymous=1/.exec(query);
if (match)
if (match) {
anonymous = true;
}
// Look for an authentication header, if any, in the request.
//
// EG: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
//
//
// This test only supports Basic auth. The value sent by the client is
// "username:password", obscured with base64 encoding.
var actual_user = "", actual_pass = "", authHeader, authPresent = false;
var actual_user = "",
actual_pass = "",
authHeader,
authPresent = false;
if (request.hasHeader("Authorization")) {
authPresent = true;
authHeader = request.getHeader("Authorization");
match = /Basic (.+)/.exec(authHeader);
if (match.length != 2)
throw "Couldn't parse auth header: " + authHeader;
if (match.length != 2) {
throw "Couldn't parse auth header: " + authHeader;
}
var userpass = base64ToString(match[1]); // no atob() :-(
match = /(.*):(.*)/.exec(userpass);
if (match.length != 3)
throw "Couldn't decode auth header: " + userpass;
if (match.length != 3) {
throw "Couldn't decode auth header: " + userpass;
}
actual_user = match[1];
actual_pass = match[2];
}
}
var proxy_actual_user = "", proxy_actual_pass = "";
var proxy_actual_user = "",
proxy_actual_pass = "";
if (request.hasHeader("Proxy-Authorization")) {
authHeader = request.getHeader("Proxy-Authorization");
match = /Basic (.+)/.exec(authHeader);
if (match.length != 2)
throw "Couldn't parse auth header: " + authHeader;
if (match.length != 2) {
throw "Couldn't parse auth header: " + authHeader;
}
var userpass = base64ToString(match[1]); // no atob() :-(
match = /(.*):(.*)/.exec(userpass);
if (match.length != 3)
throw "Couldn't decode auth header: " + userpass;
if (match.length != 3) {
throw "Couldn't decode auth header: " + userpass;
}
proxy_actual_user = match[1];
proxy_actual_pass = match[2];
}
// Don't request authentication if the credentials we got were what we
// expected.
if (expected_user == actual_user &&
expected_pass == actual_pass) {
if (expected_user == actual_user && expected_pass == actual_pass) {
requestAuth = false;
}
if (proxy_expected_user == proxy_actual_user &&
proxy_expected_pass == proxy_actual_pass) {
if (
proxy_expected_user == proxy_actual_user &&
proxy_expected_pass == proxy_actual_pass
) {
requestProxyAuth = false;
}
if (anonymous) {
if (authPresent) {
response.setStatusLine("1.0", 400, "Unexpected authorization header found");
response.setStatusLine(
"1.0",
400,
"Unexpected authorization header found"
);
} else {
response.setStatusLine("1.0", 200, "Authorization header not found");
}
} else {
if (requestProxyAuth) {
response.setStatusLine("1.0", 407, "Proxy authentication required");
for (i = 0; i < authHeaderCount; ++i)
response.setHeader("Proxy-Authenticate", "basic realm=\"" + proxy_realm + "\"", true);
} else if (requestAuth) {
response.setStatusLine("1.0", 401, "Authentication required");
for (i = 0; i < authHeaderCount; ++i)
response.setHeader("WWW-Authenticate", "basic realm=\"" + realm + "\"", true);
} else {
response.setStatusLine("1.0", 200, "OK");
} else if (requestProxyAuth) {
response.setStatusLine("1.0", 407, "Proxy authentication required");
for (i = 0; i < authHeaderCount; ++i) {
response.setHeader(
"Proxy-Authenticate",
'basic realm="' + proxy_realm + '"',
true
);
}
} else if (requestAuth) {
response.setStatusLine("1.0", 401, "Authentication required");
for (i = 0; i < authHeaderCount; ++i) {
response.setHeader(
"WWW-Authenticate",
'basic realm="' + realm + '"',
true
);
}
} else {
response.setStatusLine("1.0", 200, "OK");
}
response.setHeader("Content-Type", "application/xhtml+xml", false);
response.write("<html xmlns='http://www.w3.org/1999/xhtml'>");
response.write("<p>Login: <span id='ok'>" + (requestAuth ? "FAIL" : "PASS") + "</span></p>\n");
response.write("<p>Proxy: <span id='proxy'>" + (requestProxyAuth ? "FAIL" : "PASS") + "</span></p>\n");
response.write(
"<p>Login: <span id='ok'>" +
(requestAuth ? "FAIL" : "PASS") +
"</span></p>\n"
);
response.write(
"<p>Proxy: <span id='proxy'>" +
(requestProxyAuth ? "FAIL" : "PASS") +
"</span></p>\n"
);
response.write("<p>Auth: <span id='auth'>" + authHeader + "</span></p>\n");
response.write("<p>User: <span id='user'>" + actual_user + "</span></p>\n");
response.write("<p>Pass: <span id='pass'>" + actual_pass + "</span></p>\n");
@ -156,23 +200,27 @@ function reallyHandleRequest(request, response) {
response.write("123456789\n");
}
response.write("</div>");
response.write("<span id='footnote'>This is a footnote after the huge content fill</span>");
response.write(
"<span id='footnote'>This is a footnote after the huge content fill</span>"
);
}
if (plugin) {
response.write("<embed id='embedtest' style='width: 400px; height: 100px;' " +
"type='application/x-test'></embed>\n");
response.write(
"<embed id='embedtest' style='width: 400px; height: 100px;' " +
"type='application/x-test'></embed>\n"
);
}
response.write("</html>");
}
// base64 decoder
//
// Yoinked from extensions/xml-rpc/src/nsXmlRpcClient.js because btoa()
// doesn't seem to exist. :-(
/* Convert Base64 data to a string */
/* eslint-disable prettier/prettier */
const toBinaryTable = [
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
@ -183,38 +231,42 @@ const toBinaryTable = [
-1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
];
const base64Pad = '=';
/* eslint-enable prettier/prettier */
const base64Pad = "=";
function base64ToString(data) {
var result = "";
var leftbits = 0; // number of bits decoded, but yet to be appended
var leftdata = 0; // bits decoded, but yet to be appended
var result = '';
var leftbits = 0; // number of bits decoded, but yet to be appended
var leftdata = 0; // bits decoded, but yet to be appended
// Convert one by one.
for (var i = 0; i < data.length; i++) {
var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
var padding = (data[i] == base64Pad);
// Skip illegal characters and whitespace
if (c == -1) continue;
// Collect data into leftdata, update bitcount
leftdata = (leftdata << 6) | c;
leftbits += 6;
// If we have 8 or more bits, append 8 bits to the result
if (leftbits >= 8) {
leftbits -= 8;
// Append if not padding.
if (!padding)
result += String.fromCharCode((leftdata >> leftbits) & 0xff);
leftdata &= (1 << leftbits) - 1;
}
// Convert one by one.
for (var i = 0; i < data.length; i++) {
var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
var padding = data[i] == base64Pad;
// Skip illegal characters and whitespace
if (c == -1) {
continue;
}
// If there are any bits left, the base64 string was corrupted
if (leftbits)
throw Components.Exception('Corrupted base64 string');
// Collect data into leftdata, update bitcount
leftdata = (leftdata << 6) | c;
leftbits += 6;
return result;
// If we have 8 or more bits, append 8 bits to the result
if (leftbits >= 8) {
leftbits -= 8;
// Append if not padding.
if (!padding) {
result += String.fromCharCode((leftdata >> leftbits) & 0xff);
}
leftdata &= (1 << leftbits) - 1;
}
}
// If there are any bits left, the base64 string was corrupted
if (leftbits) {
throw Components.Exception("Corrupted base64 string");
}
return result;
}

Просмотреть файл

@ -1,7 +1,9 @@
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream"
);
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain", false);
@ -13,8 +15,9 @@ function handleRequest(request, response) {
var avail;
var bytes = [];
while ((avail = body.available()) > 0)
while ((avail = body.available()) > 0) {
Array.prototype.push.apply(bytes, body.readByteArray(avail));
}
var data = String.fromCharCode.apply(null, bytes);
response.bodyOutputStream.write(data, data.length);

Просмотреть файл

@ -5,12 +5,12 @@
const REDIRECT_TO = "https://www.bank1.com/"; // Bad-cert host.
function handleRequest(aRequest, aResponse) {
// Set HTTP Status
aResponse.setStatusLine(aRequest.httpVersion, 301, "Moved Permanently");
// Set HTTP Status
aResponse.setStatusLine(aRequest.httpVersion, 301, "Moved Permanently");
// Set redirect URI, mirroring the hash value.
let hash = (/\#.+/.test(aRequest.path))?
"#" + aRequest.path.split("#")[1]:
"";
aResponse.setHeader("Location", REDIRECT_TO + hash);
// Set redirect URI, mirroring the hash value.
let hash = /\#.+/.test(aRequest.path)
? "#" + aRequest.path.split("#")[1]
: "";
aResponse.setHeader("Location", REDIRECT_TO + hash);
}

Просмотреть файл

@ -18,15 +18,19 @@ function handleRequest(req, resp) {
return memo;
}, {});
let timeout = parseInt(params["timeout"]);
let timeout = parseInt(params.timeout);
if (timeout) {
// Write the response after a timeout.
resp.processAsync();
gTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
gTimer.init(() => {
writeResponse(params, resp);
resp.finish();
}, timeout, Ci.nsITimer.TYPE_ONE_SHOT);
gTimer.init(
() => {
writeResponse(params, resp);
resp.finish();
},
timeout,
Ci.nsITimer.TYPE_ONE_SHOT
);
return;
}
@ -36,14 +40,14 @@ function handleRequest(req, resp) {
function writeResponse(params, resp) {
// Echo back the search string with "foo" and "bar" appended.
let suffixes = ["foo", "bar"];
if (params["count"]) {
if (params.count) {
// Add more suffixes.
let serial = 0;
while (suffixes.length < params["count"]) {
while (suffixes.length < params.count) {
suffixes.push(++serial);
}
}
let data = [params["query"], suffixes.map(s => params["query"] + s)];
let data = [params.query, suffixes.map(s => params.query + s)];
resp.setHeader("Content-Type", "application/json", false);
resp.write(JSON.stringify(data));
}

Просмотреть файл

@ -1,5 +1,8 @@
function handleRequest(aRequest, aResponse) {
aResponse.setStatusLine(aRequest.httpVersion, 302, "Moved");
aResponse.setHeader("Location", "http://mochi.test:8888/tests/caps/tests/mochitest/file_bug1367586-target.html");
aResponse.write("To be redirected to target");
aResponse.setStatusLine(aRequest.httpVersion, 302, "Moved");
aResponse.setHeader(
"Location",
"http://mochi.test:8888/tests/caps/tests/mochitest/file_bug1367586-target.html"
);
aResponse.write("To be redirected to target");
}

Просмотреть файл

@ -1,9 +1,9 @@
/* Any copyright is dedicated to the Public Domain.
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function handleRequest(request, response) {
// This returns always new and different CSS content.
const page = `body::before { content: "${ Date.now() }"; }`;
const page = `body::before { content: "${Date.now()}"; }`;
response.setHeader("Content-Type", "text/css; charset=utf-8", false);
response.setHeader("Content-Length", page.length + "", false);
response.write(page);

Просмотреть файл

@ -1,20 +1,22 @@
/* Any copyright is dedicated to the Public Domain.
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function handleRequest(request, response) {
let Etag = '"4d881ab-b03-435f0a0f9ef00"';
let IfNoneMatch = request.hasHeader("If-None-Match")
? request.getHeader("If-None-Match")
: "";
const Etag = '"4d881ab-b03-435f0a0f9ef00"';
const IfNoneMatch = request.hasHeader("If-None-Match")
? request.getHeader("If-None-Match")
: "";
let guid = 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
let r = Math.random() * 16 | 0;
let v = c === "x" ? r : (r & 0x3 | 0x8);
const guid = "xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(
c
) {
const r = (Math.random() * 16) | 0;
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
let page = "<!DOCTYPE html><html><body><h1>" + guid + "</h1></body></html>";
const page = "<!DOCTYPE html><html><body><h1>" + guid + "</h1></body></html>";
response.setHeader("Etag", Etag, false);

Просмотреть файл

@ -13,12 +13,15 @@ function handleRequest(request, response) {
response.setHeader("Access-Control-Allow-Origin", "*", false);
// Redirect to a different file each time.
let counter = 1 + (+getState("counter") % 2);
const counter = 1 + (+getState("counter") % 2);
let index = request.path.lastIndexOf("/");
let newPath = request.path.substr(0, index + 1) +
"code_bundle_reload_" + counter + ".js.map";
let newUrl = request.scheme + "://" + request.host + newPath;
const index = request.path.lastIndexOf("/");
const newPath =
request.path.substr(0, index + 1) +
"code_bundle_reload_" +
counter +
".js.map";
const newUrl = request.scheme + "://" + request.host + newPath;
response.setStatusLine(request.httpVersion, 302, "Found");
response.setHeader("Location", newUrl);

Просмотреть файл

@ -13,12 +13,12 @@ function handleRequest(request, response) {
response.setHeader("Access-Control-Allow-Origin", "*", false);
// Redirect to a different file each time.
let counter = 1 + (+getState("counter") % 2);
const counter = 1 + (+getState("counter") % 2);
let index = request.path.lastIndexOf("/");
let newPath = request.path.substr(0, index + 1) +
"code_bundle_reload_" + counter + ".js";
let newUrl = request.scheme + "://" + request.host + newPath;
const index = request.path.lastIndexOf("/");
const newPath =
request.path.substr(0, index + 1) + "code_bundle_reload_" + counter + ".js";
const newUrl = request.scheme + "://" + request.host + newPath;
response.setStatusLine(request.httpVersion, 302, "Found");
response.setHeader("Location", newUrl);

Просмотреть файл

@ -7,12 +7,14 @@ function setResponse(response) {
}
function getResponse() {
let response;
getObjectState(key, v => { response = v });
getObjectState(key, v => {
response = v;
});
return response;
}
function handleRequest(request, response) {
let {queryString} = request;
const { queryString } = request;
if (!queryString) {
response.processAsync();
setResponse(response);
@ -21,7 +23,7 @@ function handleRequest(request, response) {
response.write(" ");
return;
}
let [command, value] = queryString.split('=');
const [command, value] = queryString.split("=");
switch (command) {
case "write":
getResponse().write(value);

Просмотреть файл

@ -3,7 +3,10 @@
function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 304, "Not Modified");
response.setHeader("Cache-Control", "no-transform,public,max-age=300,s-maxage=900");
response.setHeader(
"Cache-Control",
"no-transform,public,max-age=300,s-maxage=900"
);
response.setHeader("Expires", "Thu, 01 Dec 2100 20:00:00 GMT");
response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
response.write("Hello from cache!");

Просмотреть файл

@ -4,16 +4,22 @@
Cu.importGlobalProperties(["TextEncoder"]);
function gzipCompressString(string, obs) {
let scs = Cc["@mozilla.org/streamConverters;1"]
.getService(Ci.nsIStreamConverterService);
let listener = Cc["@mozilla.org/network/stream-loader;1"]
.createInstance(Ci.nsIStreamLoader);
const scs = Cc["@mozilla.org/streamConverters;1"].getService(
Ci.nsIStreamConverterService
);
const listener = Cc["@mozilla.org/network/stream-loader;1"].createInstance(
Ci.nsIStreamLoader
);
listener.init(obs);
let converter = scs.asyncConvertData("uncompressed", "gzip",
listener, null);
let stringStream = Cc["@mozilla.org/io/string-input-stream;1"]
.createInstance(Ci.nsIStringInputStream);
const converter = scs.asyncConvertData(
"uncompressed",
"gzip",
listener,
null
);
const stringStream = Cc[
"@mozilla.org/io/string-input-stream;1"
].createInstance(Ci.nsIStringInputStream);
stringStream.data = string;
converter.onStartRequest(null);
converter.onDataAvailable(null, stringStream, 0, string.length);
@ -21,11 +27,11 @@ function gzipCompressString(string, obs) {
}
function doubleGzipCompressString(string, observer) {
let observer2 = {
const observer2 = {
onStreamComplete: function(loader, context, status, length, result) {
let buffer = String.fromCharCode.apply(this, result);
const buffer = String.fromCharCode.apply(this, result);
gzipCompressString(buffer, observer);
}
},
};
gzipCompressString(string, observer2);
}
@ -33,18 +39,25 @@ function doubleGzipCompressString(string, observer) {
function handleRequest(request, response) {
response.processAsync();
let params = request.queryString.split("&");
let format = (params.filter((s) => s.includes("fmt="))[0] || "").split("=")[1];
let status = (params.filter((s) => s.includes("sts="))[0] || "").split("=")[1] || 200;
let cookies = (params.filter((s) => s.includes("cookies="))[0] || "").split("=")[1] || 0;
let cors = request.queryString.includes("cors=1");
const params = request.queryString.split("&");
const format = (params.filter(s => s.includes("fmt="))[0] || "").split(
"="
)[1];
const status =
(params.filter(s => s.includes("sts="))[0] || "").split("=")[1] || 200;
const cookies =
(params.filter(s => s.includes("cookies="))[0] || "").split("=")[1] || 0;
const cors = request.queryString.includes("cors=1");
let cachedCount = 0;
let cacheExpire = 60; // seconds
const cacheExpire = 60; // seconds
function setCacheHeaders() {
if (status != 304) {
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader(
"Cache-Control",
"no-cache, no-store, must-revalidate"
);
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
return;
@ -53,15 +66,27 @@ function handleRequest(request, response) {
if (cachedCount % 2) {
response.setHeader("Cache-Control", "max-age=" + cacheExpire, false);
} else {
response.setHeader("Expires", Date(Date.now() + cacheExpire * 1000), false);
response.setHeader(
"Expires",
Date(Date.now() + cacheExpire * 1000),
false
);
}
cachedCount++;
}
function setCookieHeaders() {
if (cookies) {
response.setHeader("Set-Cookie", "name1=value1; Domain=.foo.example.com", true);
response.setHeader("Set-Cookie", "name2=value2; Domain=.example.com", true);
response.setHeader(
"Set-Cookie",
"name1=value1; Domain=.foo.example.com",
true
);
response.setHeader(
"Set-Cookie",
"name2=value2; Domain=.example.com",
true
);
}
}
@ -72,248 +97,296 @@ function handleRequest(request, response) {
}
let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.initWithCallback(() => {
// to avoid garbage collection
timer = null;
switch (format) {
case "txt": {
response.setStatusLine(request.httpVersion, status, "DA DA DA");
response.setHeader("Content-Type", "text/plain", false);
setCacheHeaders();
timer.initWithCallback(
() => {
// to avoid garbage collection
timer = null;
switch (format) {
case "txt": {
response.setStatusLine(request.httpVersion, status, "DA DA DA");
response.setHeader("Content-Type", "text/plain", false);
setCacheHeaders();
function convertToUtf8(str) {
return String.fromCharCode(...new TextEncoder().encode(str));
}
// This script must be evaluated as UTF-8 for this to write out the
// bytes of the string in UTF-8. If it's evaluated as Latin-1, the
// written bytes will be the result of UTF-8-encoding this string
// *twice*.
let data = "Братан, ты вообще качаешься?";
let stringOfUtf8Bytes = convertToUtf8(data);
response.write(stringOfUtf8Bytes);
response.finish();
break;
}
case "xml": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/xml; charset=utf-8", false);
setCacheHeaders();
response.write("<label value='greeting'>Hello XML!</label>");
response.finish();
break;
}
case "html": {
let content = (params.filter((s) => s.includes("res="))[0] || "").split("=")[1];
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/html; charset=utf-8", false);
setAllowOriginHeaders();
setCacheHeaders();
setCookieHeaders();
response.write(content || "<p>Hello HTML!</p>");
response.finish();
break;
}
case "html-long": {
let str = new Array(102400 /* 100 KB in bytes */).join(".");
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/html; charset=utf-8", false);
setCacheHeaders();
response.write("<p>" + str + "</p>");
response.finish();
break;
}
case "css": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/css; charset=utf-8", false);
setCacheHeaders();
response.write("body:pre { content: 'Hello CSS!' }");
response.finish();
break;
}
case "js": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "application/javascript; charset=utf-8", false);
setCacheHeaders();
response.write("function() { return 'Hello JS!'; }");
response.finish();
break;
}
case "json": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "application/json; charset=utf-8", false);
setCacheHeaders();
response.write("{ \"greeting\": \"Hello JSON!\" }");
response.finish();
break;
}
case "jsonp": {
let fun = (params.filter((s) => s.includes("jsonp="))[0] || "").split("=")[1];
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/json; charset=utf-8", false);
setCacheHeaders();
response.write(fun + "({ \"greeting\": \"Hello JSONP!\" })");
response.finish();
break;
}
case "jsonp2": {
let fun = (params.filter((s) => s.includes("jsonp="))[0] || "").split("=")[1];
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/json; charset=utf-8", false);
setCacheHeaders();
response.write(" " + fun + " ( { \"greeting\": \"Hello weird JSONP!\" } ) ; ");
response.finish();
break;
}
case "json-b64": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/json; charset=utf-8", false);
setCacheHeaders();
response.write(btoa("{ \"greeting\": \"This is a base 64 string.\" }"));
response.finish();
break;
}
case "json-long": {
let str = "{ \"greeting\": \"Hello long string JSON!\" },";
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/json; charset=utf-8", false);
setCacheHeaders();
response.write("[" + new Array(2048).join(str).slice(0, -1) + "]");
response.finish();
break;
}
case "json-malformed": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/json; charset=utf-8", false);
setCacheHeaders();
response.write("{ \"greeting\": \"Hello malformed JSON!\" },");
response.finish();
break;
}
case "json-text-mime": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
setCacheHeaders();
response.write("{ \"greeting\": \"Hello third-party JSON!\" }");
response.finish();
break;
}
case "json-custom-mime": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/x-bigcorp-json; charset=utf-8", false);
setCacheHeaders();
response.write("{ \"greeting\": \"Hello oddly-named JSON!\" }");
response.finish();
break;
}
case "font": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "font/woff", false);
setAllowOriginHeaders();
setCacheHeaders();
response.finish();
break;
}
case "image": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "image/png", false);
setCacheHeaders();
response.finish();
break;
}
case "audio": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "audio/ogg", false);
setCacheHeaders();
response.finish();
break;
}
case "video": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "video/webm", false);
setCacheHeaders();
response.finish();
break;
}
case "flash": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "application/x-shockwave-flash", false);
setCacheHeaders();
response.finish();
break;
}
case "ws": {
response.setStatusLine(request.httpVersion, 101, "Switching Protocols");
response.setHeader("Connection", "upgrade", false);
response.setHeader("Upgrade", "websocket", false);
setCacheHeaders();
response.finish();
break;
}
case "gzip": {
// Note: we're doing a double gzip encoding to test multiple
// converters in network monitor.
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/plain", false);
response.setHeader("Content-Encoding", "gzip\t ,gzip", false);
setCacheHeaders();
let observer = {
onStreamComplete: function(loader, context, status, length, result) {
let buffer = String.fromCharCode.apply(this, result);
response.setHeader("Content-Length", "" + buffer.length, false);
response.write(buffer);
response.finish();
function convertToUtf8(str) {
return String.fromCharCode(...new TextEncoder().encode(str));
}
};
let data = new Array(1000).join("Hello gzip!");
doubleGzipCompressString(data, observer);
break;
// This script must be evaluated as UTF-8 for this to write out the
// bytes of the string in UTF-8. If it's evaluated as Latin-1, the
// written bytes will be the result of UTF-8-encoding this string
// *twice*.
const data = "Братан, ты вообще качаешься?";
const stringOfUtf8Bytes = convertToUtf8(data);
response.write(stringOfUtf8Bytes);
response.finish();
break;
}
case "xml": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/xml; charset=utf-8", false);
setCacheHeaders();
response.write("<label value='greeting'>Hello XML!</label>");
response.finish();
break;
}
case "html": {
const content = (
params.filter(s => s.includes("res="))[0] || ""
).split("=")[1];
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/html; charset=utf-8", false);
setAllowOriginHeaders();
setCacheHeaders();
setCookieHeaders();
response.write(content || "<p>Hello HTML!</p>");
response.finish();
break;
}
case "html-long": {
const str = new Array(102400 /* 100 KB in bytes */).join(".");
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/html; charset=utf-8", false);
setCacheHeaders();
response.write("<p>" + str + "</p>");
response.finish();
break;
}
case "css": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/css; charset=utf-8", false);
setCacheHeaders();
response.write("body:pre { content: 'Hello CSS!' }");
response.finish();
break;
}
case "js": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader(
"Content-Type",
"application/javascript; charset=utf-8",
false
);
setCacheHeaders();
response.write("function() { return 'Hello JS!'; }");
response.finish();
break;
}
case "json": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader(
"Content-Type",
"application/json; charset=utf-8",
false
);
setCacheHeaders();
response.write('{ "greeting": "Hello JSON!" }');
response.finish();
break;
}
case "jsonp": {
const fun = (params.filter(s => s.includes("jsonp="))[0] || "").split(
"="
)[1];
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/json; charset=utf-8", false);
setCacheHeaders();
response.write(fun + '({ "greeting": "Hello JSONP!" })');
response.finish();
break;
}
case "jsonp2": {
const fun = (params.filter(s => s.includes("jsonp="))[0] || "").split(
"="
)[1];
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/json; charset=utf-8", false);
setCacheHeaders();
response.write(
" " + fun + ' ( { "greeting": "Hello weird JSONP!" } ) ; '
);
response.finish();
break;
}
case "json-b64": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/json; charset=utf-8", false);
setCacheHeaders();
response.write(btoa('{ "greeting": "This is a base 64 string." }'));
response.finish();
break;
}
case "json-long": {
const str = '{ "greeting": "Hello long string JSON!" },';
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/json; charset=utf-8", false);
setCacheHeaders();
response.write("[" + new Array(2048).join(str).slice(0, -1) + "]");
response.finish();
break;
}
case "json-malformed": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/json; charset=utf-8", false);
setCacheHeaders();
response.write('{ "greeting": "Hello malformed JSON!" },');
response.finish();
break;
}
case "json-text-mime": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader(
"Content-Type",
"text/plain; charset=utf-8",
false
);
setCacheHeaders();
response.write('{ "greeting": "Hello third-party JSON!" }');
response.finish();
break;
}
case "json-custom-mime": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader(
"Content-Type",
"text/x-bigcorp-json; charset=utf-8",
false
);
setCacheHeaders();
response.write('{ "greeting": "Hello oddly-named JSON!" }');
response.finish();
break;
}
case "font": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "font/woff", false);
setAllowOriginHeaders();
setCacheHeaders();
response.finish();
break;
}
case "image": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "image/png", false);
setCacheHeaders();
response.finish();
break;
}
case "audio": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "audio/ogg", false);
setCacheHeaders();
response.finish();
break;
}
case "video": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "video/webm", false);
setCacheHeaders();
response.finish();
break;
}
case "flash": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader(
"Content-Type",
"application/x-shockwave-flash",
false
);
setCacheHeaders();
response.finish();
break;
}
case "ws": {
response.setStatusLine(
request.httpVersion,
101,
"Switching Protocols"
);
response.setHeader("Connection", "upgrade", false);
response.setHeader("Upgrade", "websocket", false);
setCacheHeaders();
response.finish();
break;
}
case "gzip": {
// Note: we're doing a double gzip encoding to test multiple
// converters in network monitor.
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "text/plain", false);
response.setHeader("Content-Encoding", "gzip\t ,gzip", false);
setCacheHeaders();
const observer = {
onStreamComplete: function(
loader,
context,
status,
length,
result
) {
const buffer = String.fromCharCode.apply(this, result);
response.setHeader("Content-Length", "" + buffer.length, false);
response.write(buffer);
response.finish();
},
};
const data = new Array(1000).join("Hello gzip!");
doubleGzipCompressString(data, observer);
break;
}
case "br": {
response.setStatusLine(request.httpVersion, status, "Connected");
response.setHeader("Content-Type", "text/plain", false);
response.setHeader("Content-Encoding", "br", false);
setCacheHeaders();
response.setHeader("Content-Length", "10", false);
// Use static data since we cannot encode brotli.
response.write("\x1b\x3f\x00\x00\x24\xb0\xe2\x99\x80\x12");
response.finish();
break;
}
case "hls-m3u8": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "application/x-mpegurl", false);
setCacheHeaders();
response.write("#EXTM3U\n");
response.finish();
break;
}
case "hls-m3u8-alt-mime-type": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader(
"Content-Type",
"application/vnd.apple.mpegurl",
false
);
setCacheHeaders();
response.write("#EXTM3U\n");
response.finish();
break;
}
case "mpeg-dash": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "video/vnd.mpeg.dash.mpd", false);
setCacheHeaders();
response.write('<?xml version="1.0" encoding="UTF-8"?>\n');
response.write(
'<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></MPD>\n'
);
response.finish();
break;
}
default: {
response.setStatusLine(request.httpVersion, 404, "Not Found");
response.setHeader("Content-Type", "text/html; charset=utf-8", false);
setCacheHeaders();
response.write("<blink>Not Found</blink>");
response.finish();
break;
}
}
case "br": {
response.setStatusLine(request.httpVersion, status, "Connected");
response.setHeader("Content-Type", "text/plain", false);
response.setHeader("Content-Encoding", "br", false);
setCacheHeaders();
response.setHeader("Content-Length", "10", false);
// Use static data since we cannot encode brotli.
response.write("\x1b\x3f\x00\x00\x24\xb0\xe2\x99\x80\x12");
response.finish();
break;
}
case "hls-m3u8": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "application/x-mpegurl", false);
setCacheHeaders();
response.write("#EXTM3U\n");
response.finish();
break;
}
case "hls-m3u8-alt-mime-type": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "application/vnd.apple.mpegurl", false);
setCacheHeaders();
response.write("#EXTM3U\n");
response.finish();
break;
}
case "mpeg-dash": {
response.setStatusLine(request.httpVersion, status, "OK");
response.setHeader("Content-Type", "video/vnd.mpeg.dash.mpd", false);
setCacheHeaders();
response.write('<?xml version="1.0" encoding="UTF-8"?>\n');
response.write('<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></MPD>\n');
response.finish();
break;
}
default: {
response.setStatusLine(request.httpVersion, 404, "Not Found");
response.setHeader("Content-Type", "text/html; charset=utf-8", false);
setCacheHeaders();
response.write("<blink>Not Found</blink>");
response.finish();
break;
}
}
}, 10, Ci.nsITimer.TYPE_ONE_SHOT); // Make sure this request takes a few ms.
},
10,
Ci.nsITimer.TYPE_ONE_SHOT
); // Make sure this request takes a few ms.
}

Просмотреть файл

@ -15,5 +15,4 @@ function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 200, "OK");
response.write("Page was accessed over HTTPS!");
}
}

Просмотреть файл

@ -2,7 +2,6 @@
http://creativecommons.org/publicdomain/zero/1.0/ */
function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 200, "OK");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
@ -12,14 +11,14 @@ function handleRequest(request, response) {
// This server checks the name parameter from the request to decide which JSON object to
// return.
let params = request.queryString.split("&");
let name = (params.filter((s) => s.includes("name="))[0] || "").split("=")[1];
const params = request.queryString.split("&");
const name = (params.filter(s => s.includes("name="))[0] || "").split("=")[1];
switch (name) {
case "null":
response.write("{ \"greeting\": null }");
response.write('{ "greeting": null }');
break;
case "nogrip":
response.write("{\"obj\": {\"type\": \"string\" }}");
response.write('{"obj": {"type": "string" }}');
break;
case "empty":
response.write("{}");

Просмотреть файл

@ -3,9 +3,11 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
"setInputStream"
);
function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 200, "Och Aye");
@ -14,12 +16,18 @@ function handleRequest(request, response) {
var body = "";
if (request.method == "POST") {
var bodyStream = new BinaryInputStream(request.bodyInputStream);
var bytes = [], avail = 0;
var bytes = [],
avail = 0;
while ((avail = bodyStream.available()) > 0) {
body += String.fromCharCode.apply(String, bodyStream.readByteArray(avail));
body += String.fromCharCode.apply(
String,
bodyStream.readByteArray(avail)
);
}
}
var contentType = request.hasHeader("content-type") ? request.getHeader("content-type") : ""
var contentType = request.hasHeader("content-type")
? request.getHeader("content-type")
: "";
var bodyOutput = [request.method, contentType, body].join("\n");
response.bodyOutputStream.write(bodyOutput, bodyOutput.length);

Просмотреть файл

@ -9,9 +9,13 @@ const DELAY_MS = 2000;
function handleRequest(request, response) {
response.processAsync();
timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.init(() => {
response.setHeader("Content-Type", "text/javascript", false);
response.write("console.log('script loaded')\n");
response.finish();
}, DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT);
timer.init(
() => {
response.setHeader("Content-Type", "text/javascript", false);
response.write("console.log('script loaded')\n");
response.finish();
},
DELAY_MS,
Ci.nsITimer.TYPE_ONE_SHOT
);
}

Просмотреть файл

@ -9,9 +9,15 @@ const DELAY_MS = 10000;
function handleRequest(request, response) {
response.processAsync();
timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.init(() => {
response.setHeader("Content-Type", "text/html", false);
response.write("<body>Slow loading page for netmonitor test. You should never see this.</body>");
response.finish();
}, DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT);
timer.init(
() => {
response.setHeader("Content-Type", "text/html", false);
response.write(
"<body>Slow loading page for netmonitor test. You should never see this.</body>"
);
response.finish();
},
DELAY_MS,
Ci.nsITimer.TYPE_ONE_SHOT
);
}

Просмотреть файл

@ -4,21 +4,32 @@
function handleRequest(request, response) {
response.processAsync();
let params = request.queryString.split("&");
let index = params.filter((s) => s.includes("index="))[0].split("=")[1];
const params = request.queryString.split("&");
const index = params.filter(s => s.includes("index="))[0].split("=")[1];
let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.initWithCallback(() => {
// to avoid garbage collection
timer = null;
response.setStatusLine(request.httpVersion, index == 1 ? 101 : index * 100, "Meh");
timer.initWithCallback(
() => {
// to avoid garbage collection
timer = null;
response.setStatusLine(
request.httpVersion,
index == 1 ? 101 : index * 100,
"Meh"
);
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
response.setHeader(
"Cache-Control",
"no-cache, no-store, must-revalidate"
);
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
response.setHeader("Content-Type", "text/" + index, false);
response.write(new Array(index * 10).join(index)); // + 0.01 KB
response.finish();
}, 10, Ci.nsITimer.TYPE_ONE_SHOT); // Make sure this request takes a few ms.
response.setHeader("Content-Type", "text/" + index, false);
response.write(new Array(index * 10).join(index)); // + 0.01 KB
response.finish();
},
10,
Ci.nsITimer.TYPE_ONE_SHOT
); // Make sure this request takes a few ms.
}

Просмотреть файл

@ -1,6 +1,6 @@
function handleRequest(request, response) {
response.processAsync();
response.setHeader("Content-Type", "text/event-stream");
response.write("data: Why so serious?\n\n");
response.finish();
}
function handleRequest(request, response) {
response.processAsync();
response.setHeader("Content-Type", "text/event-stream");
response.write("data: Why so serious?\n\n");
response.finish();
}

Просмотреть файл

@ -4,54 +4,67 @@
function handleRequest(request, response) {
response.processAsync();
let params = request.queryString.split("&");
let status = params.filter(s => s.includes("sts="))[0].split("=")[1];
let cached = params.filter(s => s === 'cached').length !== 0;
const params = request.queryString.split("&");
const status = params.filter(s => s.includes("sts="))[0].split("=")[1];
const cached = params.filter(s => s === "cached").length !== 0;
let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.initWithCallback(() => {
// to avoid garbage collection
timer = null;
switch (status) {
case "100":
response.setStatusLine(request.httpVersion, 101, "Switching Protocols");
break;
case "200":
response.setStatusLine(request.httpVersion, 202, "Created");
break;
case "300":
response.setStatusLine(request.httpVersion, 303, "See Other");
break;
case "304":
response.setStatusLine(request.httpVersion, 304, "Not Modified");
break;
case "400":
response.setStatusLine(request.httpVersion, 404, "Not Found");
break;
case "500":
response.setStatusLine(request.httpVersion, 501, "Not Implemented");
break;
case "ok":
response.setStatusLine(request.httpVersion, 200, "OK");
break;
case "redirect":
response.setStatusLine(request.httpVersion, 301, "Moved Permanently");
response.setHeader("Location", "http://example.com/redirected");
break;
}
timer.initWithCallback(
() => {
// to avoid garbage collection
timer = null;
switch (status) {
case "100":
response.setStatusLine(
request.httpVersion,
101,
"Switching Protocols"
);
break;
case "200":
response.setStatusLine(request.httpVersion, 202, "Created");
break;
case "300":
response.setStatusLine(request.httpVersion, 303, "See Other");
break;
case "304":
response.setStatusLine(request.httpVersion, 304, "Not Modified");
break;
case "400":
response.setStatusLine(request.httpVersion, 404, "Not Found");
break;
case "500":
response.setStatusLine(request.httpVersion, 501, "Not Implemented");
break;
case "ok":
response.setStatusLine(request.httpVersion, 200, "OK");
break;
case "redirect":
response.setStatusLine(request.httpVersion, 301, "Moved Permanently");
response.setHeader("Location", "http://example.com/redirected");
break;
}
if(!cached) {
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
}
else {
response.setHeader("Cache-Control", "no-transform,public,max-age=300,s-maxage=900");
response.setHeader("Expires", "Thu, 01 Dec 2100 20:00:00 GMT");
}
if (!cached) {
response.setHeader(
"Cache-Control",
"no-cache, no-store, must-revalidate"
);
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
} else {
response.setHeader(
"Cache-Control",
"no-transform,public,max-age=300,s-maxage=900"
);
response.setHeader("Expires", "Thu, 01 Dec 2100 20:00:00 GMT");
}
response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
response.write("Hello status code " + status + "!");
response.finish();
}, 10, Ci.nsITimer.TYPE_ONE_SHOT); // Make sure this request takes a few ms.
response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
response.write("Hello status code " + status + "!");
response.finish();
},
10,
Ci.nsITimer.TYPE_ONE_SHOT
); // Make sure this request takes a few ms.
}

Просмотреть файл

@ -2,13 +2,13 @@
http://creativecommons.org/publicdomain/zero/1.0/ */
var trailerServerTiming = [
{metric:"metric3", duration:"99789.11", description:"time3"},
{metric:"metric4", duration:"1112.13", description:"time4"}
{ metric: "metric3", duration: "99789.11", description: "time3" },
{ metric: "metric4", duration: "1112.13", description: "time4" },
];
var responseServerTiming = [
{metric:"metric1", duration:"123.4", description:"time1"},
{metric:"metric2", duration:"0", description:"time2"}
{ metric: "metric1", duration: "123.4", description: "time1" },
{ metric: "metric2", duration: "0", description: "time2" },
];
function handleRequest(request, response) {
@ -29,9 +29,16 @@ function handleRequest(request, response) {
function createServerTimingHeader(headerData) {
var header = "";
for (var i = 0; i < headerData.length; i++) {
header += "Server-Timing: " + headerData[i].metric + ";" +
"dur=" + headerData[i].duration + ";" +
"desc=" + headerData[i].description + "\r\n";
header +=
"Server-Timing: " +
headerData[i].metric +
";" +
"dur=" +
headerData[i].duration +
";" +
"desc=" +
headerData[i].description +
"\r\n";
}
return header;
}

Просмотреть файл

@ -2,8 +2,10 @@
http://creativecommons.org/publicdomain/zero/1.0/ */
function handleRequest(request, response) {
let params = request.queryString.split("&");
let limit = (params.filter((s) => s.includes("limit="))[0] || "").split("=")[1];
const params = request.queryString.split("&");
const limit = (params.filter(s => s.includes("limit="))[0] || "").split(
"="
)[1];
response.setStatusLine(request.httpVersion, 200, "Och Aye");

Просмотреть файл

@ -1,14 +1,13 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
let issue;
switch (request.queryString) {
case "badSyntax":
response.setHeader("Strict-Transport-Security", "\"");
response.setHeader("Strict-Transport-Security", '"');
issue = "is not syntactically correct.";
break;
case "noMaxAge":
@ -24,13 +23,17 @@ function handleRequest(request, response)
issue = "includes an invalid max-age directive.";
break;
case "multipleIncludeSubDomains":
response.setHeader("Strict-Transport-Security",
"includeSubDomains; includeSubDomains");
response.setHeader(
"Strict-Transport-Security",
"includeSubDomains; includeSubDomains"
);
issue = "includes multiple includeSubDomains directives.";
break;
case "multipleMaxAge":
response.setHeader("Strict-Transport-Security",
"max-age=444; max-age=999");
response.setHeader(
"Strict-Transport-Security",
"max-age=444; max-age=999"
);
issue = "includes multiple max-age directives.";
break;
}

Просмотреть файл

@ -5,16 +5,18 @@
// A 1x1 PNG image.
// Source: https://commons.wikimedia.org/wiki/File:1x1.png (Public Domain)
const IMAGE = atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" +
"ACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=");
const IMAGE = atob(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" +
"ACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII="
);
// To avoid GC.
let timer = null;
function handleRequest(request, response) {
let query = {};
const query = {};
request.queryString.split("&").forEach(function(val) {
let [name, value] = val.split("=");
const [name, value] = val.split("=");
query[name] = unescape(value);
});
@ -33,8 +35,12 @@ function handleRequest(request, response) {
const nsITimer = Components.interfaces.nsITimer;
timer = Components.classes["@mozilla.org/timer;1"].createInstance(nsITimer);
timer.initWithCallback(function() {
response.write(IMAGE);
response.finish();
}, query.delay, nsITimer.TYPE_ONE_SHOT);
timer.initWithCallback(
function() {
response.write(IMAGE);
response.finish();
},
query.delay,
nsITimer.TYPE_ONE_SHOT
);
}

Просмотреть файл

@ -1,9 +1,9 @@
Components.utils.importGlobalProperties(["URLSearchParams"]);
function handleRequest(request, response) {
let params = new URLSearchParams(request.queryString);
const params = new URLSearchParams(request.queryString);
switch(params.get("test")) {
switch (params.get("test")) {
case "cache":
handleCacheTestRequest(request, response);
break;
@ -22,7 +22,9 @@ function handleCacheTestRequest(request, response) {
response.setHeader("Content-Type", "text/plain; charset=UTF-8", false);
if (request.hasHeader("pragma") && request.hasHeader("cache-control")) {
response.write(`${request.getHeader("pragma")}:${request.getHeader("cache-control")}`);
response.write(
`${request.getHeader("pragma")}:${request.getHeader("cache-control")}`
);
} else {
response.write("empty cache headers");
}
@ -47,11 +49,12 @@ function handleInjectedScriptTestRequest(request, response, params) {
if (frames > 0) {
// Output an iframe in seamless mode, so that there is an higher chance that in case
// of test failures we get a screenshot where the nested iframes are all visible.
content = `<iframe seamless src="?test=injected-script&frames=${frames - 1}"></iframe>`;
content = `<iframe seamless src="?test=injected-script&frames=${frames -
1}"></iframe>`;
} else {
// Output an about:srcdoc frame to be sure that inspectedWindow.eval is able to
// evaluate js code into it.
let srcdoc = `
const srcdoc = `
<pre>injected script NOT executed</pre>
<script>window.pageScriptExecutedFirst = true</script>
`;
@ -80,4 +83,4 @@ function handleInjectedScriptTestRequest(request, response, params) {
</body>
</html>
`);
}
}

Просмотреть файл

@ -1,6 +1,6 @@
function handleRequest(request, response) {
response.processAsync();
response.setHeader("Content-Type", "text/event-stream");
response.write("data: Why so serious?\n\n");
response.finish();
}
function handleRequest(request, response) {
response.processAsync();
response.setHeader("Content-Type", "text/event-stream");
response.write("data: Why so serious?\n\n");
response.finish();
}

Просмотреть файл

@ -1,11 +1,11 @@
function handleRequest(request, response) {
let Etag = '"4d881ab-b03-435f0a0f9ef00"';
let IfNoneMatch = request.hasHeader("If-None-Match")
? request.getHeader("If-None-Match")
: "";
const Etag = '"4d881ab-b03-435f0a0f9ef00"';
const IfNoneMatch = request.hasHeader("If-None-Match")
? request.getHeader("If-None-Match")
: "";
var counter = getState("cache-counter") || 1;
let page = "<script>var jsValue = '" + counter + "';</script>" + counter;
const page = "<script>var jsValue = '" + counter + "';</script>" + counter;
setState("cache-counter", "" + (parseInt(counter) + 1));

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Просмотреть файл

@ -1,7 +1,10 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
if (getState("reloaded") == "reloaded") {
response.setHeader("Content-Type", "text/html; charset=windows-1254", false);
response.setHeader(
"Content-Type",
"text/html; charset=windows-1254",
false
);
response.write("\u00E4");
} else {
response.setHeader("Content-Type", "text/html; charset=Shift_JIS", false);

Просмотреть файл

@ -1,5 +1,4 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
if (getState("reloaded") == "reloaded") {
response.setHeader("Content-Type", "text/html", false);
response.write("<meta charset=iso-2022-kr>\u00E4");

Просмотреть файл

@ -1,5 +1,4 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
if (getState("reloaded") == "reloaded") {
response.setHeader("Content-Type", "text/html; charset=iso-2022-kr", false);
response.write("\u00E4");

Просмотреть файл

@ -1,5 +1,4 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
if (getState("reloaded") == "reloaded") {
response.setHeader("Content-Type", "text/html", false);
response.write("\u00FE\u00FF\u00E4");

Просмотреть файл

@ -1,7 +1,9 @@
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream"
);
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain", false);
@ -13,8 +15,9 @@ function handleRequest(request, response) {
var avail;
var bytes = [];
while ((avail = body.available()) > 0)
while ((avail = body.available()) > 0) {
Array.prototype.push.apply(bytes, body.readByteArray(avail));
}
var data = String.fromCharCode.apply(null, bytes);
response.bodyOutputStream.write(data, data.length);

Просмотреть файл

@ -1,5 +1,4 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
var redirectstate = "/docshell/test/chrome/bug89419.sjs";
response.setStatusLine("1.1", 302, "Found");
if (getState(redirectstate) == "") {

Просмотреть файл

@ -1,7 +1,10 @@
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/html");
response.write("<body onload='window.parent.onloadCount++'>" +
request.method + " " +
Date.now() +
"</body>");
response.write(
"<body onload='window.parent.onloadCount++'>" +
request.method +
" " +
Date.now() +
"</body>"
);
}

Просмотреть файл

@ -3,14 +3,16 @@ function handleRequest(request, response) {
response.setHeader("Cache-Control", "no-cache");
response.write("<body onload='");
if (!request.hasHeader('Referer')) {
if (!request.hasHeader("Referer")) {
response.write("window.parent.onloadCount++;");
}
if (request.queryString == "newwindow") {
response.write("if (window.opener) { window.opener.parent.onloadCount++; window.opener.parent.doNextStep(); }");
response.write("if (!window.opener) window.close();");
response.write("'>");
response.write(
"if (window.opener) { window.opener.parent.onloadCount++; window.opener.parent.doNextStep(); }"
);
response.write("if (!window.opener) window.close();");
response.write("'>");
} else {
response.write("window.parent.doNextStep();'>");
}

Просмотреть файл

@ -2,7 +2,8 @@
let self = this;
Cu.import("resource://gre/modules/Timer.jsm");
// eslint-disable-next-line mozilla/use-chromeutils-import
let { setTimeout } = Cu.import("resource://gre/modules/Timer.jsm");
const CC = Components.Constructor;
const BinaryInputStream = CC(
@ -18,7 +19,7 @@ const BinaryOutputStream = CC(
);
function log(str) {
// dump(`LOG: ${str}\n`);
// dump(`LOG: ${str}\n`);
}
function* generateBody(fragments, size) {
@ -26,7 +27,7 @@ function* generateBody(fragments, size) {
let chunkSize = (size / fragments) | 0;
let remaining = size;
log(`Chunk size ${chunkSize}`)
log(`Chunk size ${chunkSize}`);
while (remaining > 0) {
let data = new Uint8Array(Math.min(remaining, chunkSize));
for (let i = 0; i < data.length; ++i) {
@ -35,7 +36,7 @@ function* generateBody(fragments, size) {
}
yield data;
log(`Remaining to chunk ${remaining}`)
log(`Remaining to chunk ${remaining}`);
remaining -= data.length;
}
}
@ -47,7 +48,7 @@ function readStream(inputStream) {
result.push(inputStream.readBytes(available));
}
return result.join('');
return result.join("");
}
function now() {
@ -68,7 +69,9 @@ async function handleRequest(request, response) {
message = "bad";
} else {
log("Read POST body");
let body = new URLSearchParams(readStream(new BinaryInputStream(request.bodyInputStream)));
let body = new URLSearchParams(
readStream(new BinaryInputStream(request.bodyInputStream))
);
message = body.get("token") || "bad";
log(`The result was ${message}`);
}
@ -81,17 +84,21 @@ async function handleRequest(request, response) {
let header = "<!doctype html><!-- ";
let footer = ` --><script>"use strict"; let target = (opener || parent); target.postMessage('${message}', '*');</script>`;
log("Set headers")
log("Set headers");
response.setHeader("Content-Type", "text/html", false);
response.setHeader("Content-Length", `${size + header.length + footer.length}`, false);
response.setHeader(
"Content-Length",
`${size + header.length + footer.length}`,
false
);
response.setStatusLine(request.httpVersion, "200", "OK");
response.processAsync();
log("Write header");
response.write(header);
log("Write body")
log("Write body");
for (let data of generateBody(fragments, size)) {
delay = Math.max(0, delayUntil - now())
delay = Math.max(0, delayUntil - now());
log(`Delay sending fragment for ${delay / fragments}`);
let failed = false;
await new Promise(resolve => {
@ -112,10 +119,10 @@ async function handleRequest(request, response) {
}
fragments = Math.max(--fragments, 1);
log(`Fragments left ${fragments}`)
log(`Fragments left ${fragments}`);
}
log("Write footer")
log("Write footer");
response.write(footer);
response.finish();

Просмотреть файл

@ -1,10 +1,17 @@
jsURL = "javascript:" + escape('window.parent.postMessage("JS uri ran", "*");\
jsURL =
"javascript:" +
escape(
'window.parent.postMessage("JS uri ran", "*");\
return \'\
<script>\
window.parent.postMessage("Able to access private: " +\
window.parent.private, "*");\
</script>\'');
dataURL = "data:text/html," + escape('<!DOCTYPE HTML>\
</script>\''
);
dataURL =
"data:text/html," +
escape(
'<!DOCTYPE HTML>\
<script>\
try {\
window.parent.postMessage("Able to access private: " +\
@ -13,11 +20,12 @@ try {\
catch (e) {\
window.parent.postMessage("pass", "*");\
}\
</script>');
</script>'
);
tests = [
// Plain document should work as normal
'<!DOCTYPE HTML>\
// Plain document should work as normal
'<!DOCTYPE HTML>\
<script>\
try {\
window.parent.private;\
@ -28,62 +36,62 @@ catch (e) {\
}\
</script>',
// refresh to plain doc
{ refresh: "file_bug475636.sjs?1",
doc: '<!DOCTYPE HTML>' },
// refresh to plain doc
{ refresh: "file_bug475636.sjs?1", doc: "<!DOCTYPE HTML>" },
// meta-refresh to plain doc
'<!DOCTYPE HTML>\
// meta-refresh to plain doc
'<!DOCTYPE HTML>\
<head>\
<meta http-equiv="refresh" content="0; url=file_bug475636.sjs?1">\
</head>',
// refresh to data url
{ refresh: dataURL,
doc: '<!DOCTYPE HTML>' },
// refresh to data url
{ refresh: dataURL, doc: "<!DOCTYPE HTML>" },
// meta-refresh to data url
'<!DOCTYPE HTML>\
// meta-refresh to data url
'<!DOCTYPE HTML>\
<head>\
<meta http-equiv="refresh" content="0; url=' + dataURL + '">\
<meta http-equiv="refresh" content="0; url=' +
dataURL +
'">\
</head>',
// refresh to js url should not be followed
{ refresh: jsURL,
doc:
'<!DOCTYPE HTML>\
// refresh to js url should not be followed
{
refresh: jsURL,
doc:
'<!DOCTYPE HTML>\
<script>\
setTimeout(function() {\
window.parent.postMessage("pass", "*");\
}, 2000);\
</script>' },
</script>',
},
// meta refresh to js url should not be followed
'<!DOCTYPE HTML>\
// meta refresh to js url should not be followed
'<!DOCTYPE HTML>\
<head>\
<meta http-equiv="refresh" content="0; url=' + jsURL + '">\
<meta http-equiv="refresh" content="0; url=' +
jsURL +
'">\
</head>\
<script>\
setTimeout(function() {\
window.parent.postMessage("pass", "*");\
}, 2000);\
</script>'
</script>',
];
function handleRequest(request, response)
{
function handleRequest(request, response) {
dump("@@@@@@@@@hi there: " + request.queryString + "\n");
test = tests[parseInt(request.queryString, 10) - 1];
response.setHeader("Content-Type", "text/html");
if (!test) {
response.write('<script>parent.postMessage("done", "*");</script>');
}
else if (typeof test == "string") {
} else if (typeof test == "string") {
response.write(test);
}
else if (test.refresh) {
} else if (test.refresh) {
response.setHeader("Refresh", "0; url=" + test.refresh);
response.write(test.doc);
}

Просмотреть файл

@ -1,5 +1,8 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/html", false);
response.write('<html><body onload=\'parent.page2Load("' + request.method + '")\'>file_bug580069_2.sjs</body></html>');
response.write(
"<html><body onload='parent.page2Load(\"" +
request.method +
"\")'>file_bug580069_2.sjs</body></html>"
);
}

Просмотреть файл

@ -1,14 +1,17 @@
function handleRequest(request, response)
{
var count = parseInt(getState('count'));
if (!count || request.queryString == 'countreset')
function handleRequest(request, response) {
var count = parseInt(getState("count"));
if (!count || request.queryString == "countreset") {
count = 0;
}
setState('count', count + 1 + '');
setState("count", count + 1 + "");
response.setHeader('Content-Type', 'text/html', false);
response.setHeader('Cache-Control', 'max-age=0');
response.write('<html><body onload="opener.onChildLoad()" ' +
'onunload="parseInt(\'0\')">' +
count + '</body></html>');
response.setHeader("Content-Type", "text/html", false);
response.setHeader("Cache-Control", "max-age=0");
response.write(
'<html><body onload="opener.onChildLoad()" ' +
"onunload=\"parseInt('0')\">" +
count +
"</body></html>"
);
}

Просмотреть файл

@ -1,7 +1,5 @@
"use strict";
Cu.import("resource://gre/modules/Timer.jsm");
const CC = Components.Constructor;
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
@ -23,7 +21,7 @@ async function handleRequest(request, response) {
if (request.method !== "POST") {
message = "bad";
} else {
log("Reading request")
log("Reading request");
let available = 0;
let inputStream = new BinaryInputStream(request.bodyInputStream);
while ((available = inputStream.available()) > 0) {
@ -31,10 +29,12 @@ async function handleRequest(request, response) {
}
}
log("Setting Headers")
log("Setting Headers");
response.setHeader("Content-Type", "text/html", false);
response.setStatusLine(request.httpVersion, "200", "OK");
log("Writing body");
response.write('<script>"use strict"; let target = opener ? opener : parent; target.postMessage("done", "*");</script>');
log("Done")
response.write(
'<script>"use strict"; let target = opener ? opener : parent; target.postMessage("done", "*");</script>'
);
log("Done");
}

Просмотреть файл

@ -7,7 +7,7 @@ function handleRequest(request, response) {
response.setHeader("Cache-Control", "no-cache", false);
// Wait a bit.
var s = Date.now();
while (Date.now() - s < 1000);
while (Date.now() - s < 1000) {}
response.write(`<!DOCTYPE HTML>
<html>
@ -16,4 +16,4 @@ function handleRequest(request, response) {
</body>
</html>
`);
}
}

Просмотреть файл

@ -20,7 +20,10 @@ function handleRequest(request, response) {
setState("sessionhistory_do_redirect", "");
response.setStatusLine("1.1", 302, "Found");
response.setHeader("Location",
"file_session_history_on_redirect_2.html", false);
response.setHeader(
"Location",
"file_session_history_on_redirect_2.html",
false
);
}
}

Просмотреть файл

@ -1,12 +1,16 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.processAsync();
timer = Components.classes["@mozilla.org/timer;1"].
createInstance(Components.interfaces.nsITimer);
timer.init(function() {
response.finish();
}, 5000, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
timer = Components.classes["@mozilla.org/timer;1"].createInstance(
Components.interfaces.nsITimer
);
timer.init(
function() {
response.finish();
},
5000,
Components.interfaces.nsITimer.TYPE_ONE_SHOT
);
response.setStatusLine(null, 200, "OK");
response.setHeader("Content-Type", "text/plain", false);

Просмотреть файл

@ -1,11 +1,15 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.processAsync();
timer = Components.classes["@mozilla.org/timer;1"].
createInstance(Components.interfaces.nsITimer);
timer.init(function() {
response.write("Here the content. But slowly.");
response.finish();
}, 1000, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
timer = Components.classes["@mozilla.org/timer;1"].createInstance(
Components.interfaces.nsITimer
);
timer.init(
function() {
response.write("Here the content. But slowly.");
response.finish();
},
1000,
Components.interfaces.nsITimer.TYPE_ONE_SHOT
);
}

Просмотреть файл

@ -1,8 +1,8 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.setStatusLine("1.1", 500, "Internal Server Error");
response.setHeader("Content-Type", "image/svg+xml", false);
let body = "<svg xmlns='http://www.w3.org/2000/svg' width='70' height='0'></svg>";
let body =
"<svg xmlns='http://www.w3.org/2000/svg' width='70' height='0'></svg>";
response.bodyOutputStream.write(body, body.length);
}

Просмотреть файл

@ -1,8 +1,7 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.setStatusLine(null, 401, "Unauthorized");
response.setHeader("WWW-Authenticate", "basic realm=\"restricted\"", false);
response.setHeader("WWW-Authenticate", 'basic realm="restricted"', false);
response.setHeader("Access-Control-Allow-Origin", "*", false);
response.setHeader("Access-Control-Allow-Credentials", "true", false);

Просмотреть файл

@ -1,10 +1,11 @@
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream"
);
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain", false);
if (request.method == "GET") {
response.write(request.queryString);
@ -14,11 +15,11 @@ function handleRequest(request, response)
var avail;
var bytes = [];
while ((avail = body.available()) > 0)
while ((avail = body.available()) > 0) {
Array.prototype.push.apply(bytes, body.readByteArray(avail));
}
var data = String.fromCharCode.apply(null, bytes);
response.bodyOutputStream.write(data, data.length);
}
}

Просмотреть файл

@ -1,6 +1,4 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.setStatusLine(null, 302, "Moved");
response.setHeader("Location", "http://nosuchdomain.localhost", false);
}

Просмотреть файл

@ -1,20 +1,21 @@
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream"
);
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain", false);
var body = new BinaryInputStream(request.bodyInputStream);
var avail;
var bytes = [];
while ((avail = body.available()) > 0)
while ((avail = body.available()) > 0) {
Array.prototype.push.apply(bytes, body.readByteArray(avail));
}
var data = String.fromCharCode.apply(null, bytes);
response.bodyOutputStream.write(data, data.length);
}

Просмотреть файл

@ -1,11 +1,10 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain; charset=ISO-8859-1", false);
const body = [0xC1];
var bos = Components.classes["@mozilla.org/binaryoutputstream;1"]
.createInstance(Components.interfaces.nsIBinaryOutputStream);
const body = [0xc1];
var bos = Components.classes[
"@mozilla.org/binaryoutputstream;1"
].createInstance(Components.interfaces.nsIBinaryOutputStream);
bos.setOutputStream(response.bodyOutputStream);
bos.writeByteArray(body);
}

Просмотреть файл

@ -1,4 +1,8 @@
function handleRequest(request, response) {
response.setStatusLine(null, 302, "Found");
response.setHeader("Location", "http://example.com/tests/dom/base/test/bug461735-post-redirect.js", false);
response.setHeader(
"Location",
"http://example.com/tests/dom/base/test/bug461735-post-redirect.js",
false
);
}

Просмотреть файл

@ -1,4 +1,8 @@
function handleRequest(request, response) {
response.setStatusLine(null, 302, "Found");
response.setHeader("Location", "http://mochi.test:8888/tests/dom/base/test/bug461735-post-redirect.js", false);
response.setHeader(
"Location",
"http://mochi.test:8888/tests/dom/base/test/bug461735-post-redirect.js",
false
);
}

Просмотреть файл

@ -1,18 +1,14 @@
function handleRequest(request, response) {
var body = "loaded";
var origin = "localhost";
try {
var origin = request.getHeader("Origin");
} catch (e) {}
function handleRequest(request, response)
{
var body = "loaded";
var origin = "localhost";
try {
var origin = request.getHeader("Origin");
} catch(e) {}
response.setHeader("Access-Control-Allow-Origin",
origin,
false);
response.setHeader("Access-Control-Allow-Credentials", "true", false);
response.setHeader("Access-Control-Allow-Methods", "XMETHOD", false);
response.setHeader("Connection", "Keep-alive", false);
response.setHeader("Access-Control-Allow-Origin", origin, false);
response.setHeader("Access-Control-Allow-Credentials", "true", false);
response.setHeader("Access-Control-Allow-Methods", "XMETHOD", false);
response.setHeader("Connection", "Keep-alive", false);
response.bodyOutputStream.write(body, body.length);
response.bodyOutputStream.write(body, body.length);
}

Просмотреть файл

@ -1,27 +1,23 @@
function handleRequest(request, response)
{
if (request.queryString == "")
{
var etag = request.hasHeader("If-Match") ? request.getHeader("If-Match") : null;
if (!etag || etag == getState("etag"))
{
function handleRequest(request, response) {
if (request.queryString == "") {
var etag = request.hasHeader("If-Match")
? request.getHeader("If-Match")
: null;
if (!etag || etag == getState("etag")) {
response.setStatusLine(request.httpVersion, 200, "Ok");
response.setHeader("Content-Type", "text/html");
response.setHeader("ETag", getState("etag"));
response.setHeader("Cache-control", "max-age=36000");
response.write(getState("etag"));
} else if (etag) {
response.setStatusLine(request.httpVersion, 412, "Precondition Failed");
}
else if (etag)
{
response.setStatusLine(request.httpVersion, 412, "Precondition Failed");
}
}
else
{
} else {
var etag = request.queryString.match(/^etag=(.*)$/);
if (etag)
if (etag) {
setState("etag", etag[1]);
}
response.setStatusLine(request.httpVersion, 204, "No content");
}
}

Просмотреть файл

@ -3,7 +3,7 @@ function handleRequest(request, response) {
try {
body = request.getHeader("X-Request");
} catch(e) {
} catch (e) {
body = "request.getHeader() failed! Exception: " + e;
}

Просмотреть файл

@ -1,18 +1,20 @@
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream"
);
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain", false);
var body = new BinaryInputStream(request.bodyInputStream);
var avail;
var bytes = [];
while ((avail = body.available()) > 0)
while ((avail = body.available()) > 0) {
Array.prototype.push.apply(bytes, body.readByteArray(avail));
}
var data = String.fromCharCode.apply(null, bytes);
response.bodyOutputStream.write(data, data.length);

Просмотреть файл

@ -1,26 +1,24 @@
function getInputStream(path)
{
var file = Components.classes["@mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("CurWorkD", Components.interfaces.nsIFile);
var fis = Components.classes['@mozilla.org/network/file-input-stream;1'].
createInstance(Components.interfaces.nsIFileInputStream);
function getInputStream(path) {
var file = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("CurWorkD", Components.interfaces.nsIFile);
var fis = Components.classes[
"@mozilla.org/network/file-input-stream;1"
].createInstance(Components.interfaces.nsIFileInputStream);
var split = path.split("/");
for(var i = 0; i < split.length; ++i) {
for (var i = 0; i < split.length; ++i) {
file.append(split[i]);
}
fis.init(file, -1, -1, false);
return fis;
}
function handleRequest(request, response)
{
var inputStream = getInputStream("tests/dom/base/test/bug638112-response.txt")
function handleRequest(request, response) {
var inputStream = getInputStream(
"tests/dom/base/test/bug638112-response.txt"
);
response.seizePower();
response.bodyOutputStream.writeFrom(inputStream,
inputStream.available());
response.bodyOutputStream.writeFrom(inputStream, inputStream.available());
response.finish();
inputStream.close();
}

Просмотреть файл

@ -1,20 +1,46 @@
var BASE_URL = 'example.com/tests/dom/base/test/bug704320.sjs';
var BASE_URL = "example.com/tests/dom/base/test/bug704320.sjs";
function createTestUrl(schemeFrom, schemeTo, policy, action, type) {
return schemeTo + '://' + BASE_URL + '?' +
'action=' + action + '&' +
'scheme=' + schemeFrom + '-to-' + schemeTo + '&' +
'policy=' + policy + '&' +
'type=' + type;
return (
schemeTo +
"://" +
BASE_URL +
"?" +
"action=" +
action +
"&" +
"scheme=" +
schemeFrom +
"-to-" +
schemeTo +
"&" +
"policy=" +
policy +
"&" +
"type=" +
type
);
}
function create2ndLevelIframeUrl(schemeFrom, schemeTo, policy, type) {
return schemeFrom + '://' + BASE_URL + '?' +
'action=create-2nd-level-iframe&' +
'scheme-from=' + schemeFrom + '&' +
'scheme-to=' + schemeTo + '&' +
'policy=' + policy + '&' +
'type=' + type;
return (
schemeFrom +
"://" +
BASE_URL +
"?" +
"action=create-2nd-level-iframe&" +
"scheme-from=" +
schemeFrom +
"&" +
"scheme-to=" +
schemeTo +
"&" +
"policy=" +
policy +
"&" +
"type=" +
type
);
}
// Creates the following test cases for the specified scheme and referrer
@ -46,68 +72,113 @@ function create2ndLevelIframeUrl(schemeFrom, schemeTo, policy, type) {
// results.
function createTest(schemeFrom, schemeTo, policy, optionalEarlierPolicy) {
var _createTestUrl = createTestUrl.bind(
null, schemeFrom, schemeTo, policy, 'test');
null,
schemeFrom,
schemeTo,
policy,
"test"
);
var _create2ndLevelIframeUrl = create2ndLevelIframeUrl.bind(
null, schemeFrom, schemeTo, policy);
null,
schemeFrom,
schemeTo,
policy
);
var metaReferrerPolicyString = '';
if (optionalEarlierPolicy && optionalEarlierPolicy != '') {
metaReferrerPolicyString += '<meta name="referrer" content="' + optionalEarlierPolicy + '">\n';
var metaReferrerPolicyString = "";
if (optionalEarlierPolicy && optionalEarlierPolicy != "") {
metaReferrerPolicyString +=
'<meta name="referrer" content="' + optionalEarlierPolicy + '">\n';
}
metaReferrerPolicyString += '<meta name="referrer" content="' + policy + '">';
return '<!DOCTYPE HTML>\n\
return (
"<!DOCTYPE HTML>\n\
<html>\n\
<head>\n\
'+metaReferrerPolicyString+'\n\
<link rel="stylesheet" type="text/css" href="' + _createTestUrl('stylesheet') + '">\n\
" +
metaReferrerPolicyString +
'\n\
<link rel="stylesheet" type="text/css" href="' +
_createTestUrl("stylesheet") +
'">\n\
<style type="text/css">\n\
@import "' + _createTestUrl('import-css') + '";\n\
@import "' +
_createTestUrl("import-css") +
'";\n\
@font-face {\n\
font-family: "Fake Serif Bold";\n\
src: url("' + _createTestUrl('font-face') + '");\n\
src: url("' +
_createTestUrl("font-face") +
'");\n\
}\n\
body {\n\
font-family: "Fake Serif Bold", serif;\n\
background: url("' + _createTestUrl('bg-url') + '");\n\
background: url("' +
_createTestUrl("bg-url") +
'");\n\
}\n\
</style>\n\
</head>\n\
<body>\n\
<script src="' + _createTestUrl('script') + '"></script>\n\
<img src="' + _createTestUrl('img') + '"></img>\n\
<iframe src="' + _createTestUrl('iframe') + '"></iframe>\n\
<audio src="' + _createTestUrl('audio') + '"></audio>\n\
<video src="' + _createTestUrl('video') + '"></video>\n\
<object type="bogus" data="' + _createTestUrl('object') + '"></object>\n\
<object type="image/svg+xml" data="' + _createTestUrl('object-svg') + '"></object>\n\
<a id="link" href="' + _createTestUrl('link') + '" ping="' + _createTestUrl('link-ping') + '"></a>\n\
<iframe src="' + _create2ndLevelIframeUrl('form') + '"></iframe>\n\
<iframe src="' + _create2ndLevelIframeUrl('window.location') + '"></iframe>\n\
<script src="' +
_createTestUrl("script") +
'"></script>\n\
<img src="' +
_createTestUrl("img") +
'"></img>\n\
<iframe src="' +
_createTestUrl("iframe") +
'"></iframe>\n\
<audio src="' +
_createTestUrl("audio") +
'"></audio>\n\
<video src="' +
_createTestUrl("video") +
'"></video>\n\
<object type="bogus" data="' +
_createTestUrl("object") +
'"></object>\n\
<object type="image/svg+xml" data="' +
_createTestUrl("object-svg") +
'"></object>\n\
<a id="link" href="' +
_createTestUrl("link") +
'" ping="' +
_createTestUrl("link-ping") +
'"></a>\n\
<iframe src="' +
_create2ndLevelIframeUrl("form") +
'"></iframe>\n\
<iframe src="' +
_create2ndLevelIframeUrl("window.location") +
'"></iframe>\n\
<script>\n\
var _testFinished = 0\n\
(function() {\n\
var x = new XMLHttpRequest();\n\
x.open("GET", "' + _createTestUrl('xmlhttprequest') + '");\n\
x.open("GET", "' +
_createTestUrl("xmlhttprequest") +
'");\n\
x.send();\n\
})();\n\
(function() {\n\
var eventSource = new EventSource("' + _createTestUrl('eventsource') + '");\n\
var eventSource = new EventSource("' +
_createTestUrl("eventsource") +
'");\n\
})();' +
// LOAD EVENT (most of the tests)
// fires when the resources for the page are loaded
'var _isLoaded = false;\n\
// LOAD EVENT (most of the tests)
// fires when the resources for the page are loaded
'var _isLoaded = false;\n\
window.addEventListener("load", function() {\n\
this._isLoaded = true;\n\
this.checkForFinish();\n\
}.bind(window), false);' +
// WINDOW.OPEN test
// listen for incoming status from window.open, close the window
// and check if we're done.
'var _openedWindowLoaded = false;\n\
// WINDOW.OPEN test
// listen for incoming status from window.open, close the window
// and check if we're done.
'var _openedWindowLoaded = false;\n\
window.addEventListener("message", function(message) {\n\
if (message.data == "window.open") {\n\
this._openedWindowLoaded = true;\n\
@ -115,13 +186,14 @@ function createTest(schemeFrom, schemeTo, policy, optionalEarlierPolicy) {
this.checkForFinish();\n\
}\n\
}.bind(window), false);\n\
var win = window.open("' + _createTestUrl('window.open') + '", "");' +
// called by the two things that must complete: window.open page
// and the window load event. When both are complete, this
// "finishes" the iframe subtest by clicking the link.
// _testFinished avoids calling this function twice (which may happen)
'function checkForFinish() {\n\
var win = window.open("' +
_createTestUrl("window.open") +
'", "");' +
// called by the two things that must complete: window.open page
// and the window load event. When both are complete, this
// "finishes" the iframe subtest by clicking the link.
// _testFinished avoids calling this function twice (which may happen)
'function checkForFinish() {\n\
if (window._isLoaded && window._openedWindowLoaded && !window._testFinished) {\n\
window._testFinished = 1;\n\
document.getElementById("link").click();\n\
@ -129,59 +201,87 @@ function createTest(schemeFrom, schemeTo, policy, optionalEarlierPolicy) {
}\n\
</script>\n\
</body>\n\
</html>';
</html>'
);
}
function createIframedFormTest(schemeFrom, schemeTo, policy) {
var actionUrl = schemeTo + '://' + BASE_URL;
var actionUrl = schemeTo + "://" + BASE_URL;
return '<!DOCTYPE HTML>\n\
return (
'<!DOCTYPE HTML>\n\
<html>\n\
<head>\n\
<meta name="referrer" content="' + policy + '">\n\
<meta name="referrer" content="' +
policy +
'">\n\
</head>\n\
<body>\n\
<form id="form" action="' + actionUrl + '">\n\
<form id="form" action="' +
actionUrl +
'">\n\
<input type="hidden" name="action" value="test">\n\
<input type="hidden" name="scheme" value="' + schemeFrom + '-to-' + schemeTo + '">\n\
<input type="hidden" name="policy" value="' + policy + '">\n\
<input type="hidden" name="scheme" value="' +
schemeFrom +
"-to-" +
schemeTo +
'">\n\
<input type="hidden" name="policy" value="' +
policy +
'">\n\
<input type="hidden" name="type" value="form">\n\
</form>\n\
<script>\n\
document.getElementById("form").submit();\n\
</script>\n\
</body>\n\
</html>';
</html>'
);
}
function createIframedWindowLocationTest(schemeFrom, schemeTo, policy) {
var url = createTestUrl(
schemeFrom, schemeTo, policy, 'test', 'window.location');
schemeFrom,
schemeTo,
policy,
"test",
"window.location"
);
return '<!DOCTYPE HTML>\n\
return (
'<!DOCTYPE HTML>\n\
<html>\n\
<head>\n\
<meta name="referrer" content="' + policy + '">\n\
<meta name="referrer" content="' +
policy +
'">\n\
</head>\n\
<body>\n\
<script>\n\
window.location = "' + url + '";\n\
window.location = "' +
url +
'";\n\
</script>\n\
</body>\n\
</html>';
</html>'
);
}
function createPolicyTest(policy, optionalEarlierPolicy) {
var metaReferrerPolicyString = '';
if (optionalEarlierPolicy && optionalEarlierPolicy != '') {
metaReferrerPolicyString += '<meta name="referrer" content="' + optionalEarlierPolicy + '">\n';
var metaReferrerPolicyString = "";
if (optionalEarlierPolicy && optionalEarlierPolicy != "") {
metaReferrerPolicyString +=
'<meta name="referrer" content="' + optionalEarlierPolicy + '">\n';
}
metaReferrerPolicyString += '<meta name="referrer" content="' + policy + '">';
return '<!DOCTYPE HTML>\n\
return (
"<!DOCTYPE HTML>\n\
<html>\n\
<head>\n\
'+metaReferrerPolicyString+'\n\
" +
metaReferrerPolicyString +
'\n\
<script type="text/javascript" src="/tests/dom/base/test/file_bug704320_preload_common.js"></script>\n\
</head>\n\
<body>\n\
@ -190,53 +290,55 @@ function createPolicyTest(policy, optionalEarlierPolicy) {
<img src="http://example.com/tests/dom/base/test/bug704320_counter.sjs?type=img"\n\
onload="incrementLoad2(\'img\', 2);">\n\
</body>\n\
</html>';
</html>'
);
}
function handleRequest(request, response) {
var sharedKey = 'bug704320.sjs';
var params = request.queryString.split('&');
var action = params[0].split('=')[1];
var sharedKey = "bug704320.sjs";
var params = request.queryString.split("&");
var action = params[0].split("=")[1];
if (action === 'create-1st-level-iframe') {
if (action === "create-1st-level-iframe") {
// ?action=create-1st-level-iframe&scheme-from=http&scheme-to=https&policy=origin
var schemeFrom = params[1].split('=')[1];
var schemeTo = params[2].split('=')[1];
var policy = params[3].split('=')[1];
var optionalEarlierPolicy = '';
var schemeFrom = params[1].split("=")[1];
var schemeTo = params[2].split("=")[1];
var policy = params[3].split("=")[1];
var optionalEarlierPolicy = "";
if (params[4]) {
optionalEarlierPolicy = params[4].split('=')[1];
optionalEarlierPolicy = params[4].split("=")[1];
}
response.setHeader('Content-Type', 'text/html; charset=utf-8', false);
response.setHeader('Cache-Control', 'no-cache', false);
response.write(createTest(schemeFrom, schemeTo, policy, optionalEarlierPolicy));
}
else if (action === 'create-2nd-level-iframe') {
response.setHeader("Content-Type", "text/html; charset=utf-8", false);
response.setHeader("Cache-Control", "no-cache", false);
response.write(
createTest(schemeFrom, schemeTo, policy, optionalEarlierPolicy)
);
} else if (action === "create-2nd-level-iframe") {
// ?action=create-2nd-level-iframe&scheme-from=http&scheme-to=https&policy=origin&type=form"
var schemeFrom = params[1].split('=')[1];
var schemeTo = params[2].split('=')[1];
var policy = params[3].split('=')[1];
var type = params[4].split('=')[1];
var schemeFrom = params[1].split("=")[1];
var schemeTo = params[2].split("=")[1];
var policy = params[3].split("=")[1];
var type = params[4].split("=")[1];
response.setHeader('Content-Type', 'text/html; charset=utf-8', false);
response.setHeader('Cache-Control', 'no-cache', false);
response.setHeader("Content-Type", "text/html; charset=utf-8", false);
response.setHeader("Cache-Control", "no-cache", false);
if (type === 'form') {
if (type === "form") {
response.write(createIframedFormTest(schemeFrom, schemeTo, policy));
} else if (type === 'window.location') {
response.write(createIframedWindowLocationTest(
schemeFrom, schemeTo, policy));
} else if (type === "window.location") {
response.write(
createIframedWindowLocationTest(schemeFrom, schemeTo, policy)
);
}
}
else if (action === 'test') {
} else if (action === "test") {
// ?action=test&scheme=http-to-https&policy=origin&type=img
var scheme = params[1].split('=')[1];
var policy = params[2].split('=')[1];
var type = params[3].split('=')[1];
var scheme = params[1].split("=")[1];
var policy = params[2].split("=")[1];
var type = params[3].split("=")[1];
var result = getSharedState(sharedKey);
if (result === '') {
if (result === "") {
result = {};
} else {
result = JSON.parse(result);
@ -250,42 +352,43 @@ function handleRequest(request, response) {
result[type][scheme] = {};
}
if (request.hasHeader('Referer')) {
result[type][scheme][policy] = request.getHeader('Referer');
if (request.hasHeader("Referer")) {
result[type][scheme][policy] = request.getHeader("Referer");
} else {
result[type][scheme][policy] = '';
result[type][scheme][policy] = "";
}
setSharedState(sharedKey, JSON.stringify(result));
if (type === 'link') {
var loc = 'https://example.com/tests/dom/base/test/file_bug704320_redirect.html';
response.setStatusLine('1.1', 302, 'Found');
response.setHeader('Location', loc, false);
if (type === "link") {
var loc =
"https://example.com/tests/dom/base/test/file_bug704320_redirect.html";
response.setStatusLine("1.1", 302, "Found");
response.setHeader("Location", loc, false);
}
if (type === 'window.open') {
response.setHeader('Cache-Control', 'no-cache', false);
response.setHeader('Content-Type', 'text/html', false);
response.write('<html><body><script>'
+ 'window.opener.postMessage("window.open", "*");'
+ '</script></body></html>');
if (type === "window.open") {
response.setHeader("Cache-Control", "no-cache", false);
response.setHeader("Content-Type", "text/html", false);
response.write(
"<html><body><script>" +
'window.opener.postMessage("window.open", "*");' +
"</script></body></html>"
);
}
}
else if (action === 'get-test-results') {
} else if (action === "get-test-results") {
// ?action=get-result
response.setHeader('Cache-Control', 'no-cache', false);
response.setHeader('Content-Type', 'text/plain', false);
response.setHeader("Cache-Control", "no-cache", false);
response.setHeader("Content-Type", "text/plain", false);
response.write(getSharedState(sharedKey));
}
else if (action === 'generate-policy-test') {
} else if (action === "generate-policy-test") {
// ?action=generate-policy-test&policy=b64-encoded-string
response.setHeader('Cache-Control', 'no-cache', false);
response.setHeader('Content-Type', 'text/html', false);
var policy = unescape(params[1].split('=')[1]);
var optionalEarlierPolicy = '';
response.setHeader("Cache-Control", "no-cache", false);
response.setHeader("Content-Type", "text/html", false);
var policy = unescape(params[1].split("=")[1]);
var optionalEarlierPolicy = "";
if (params[2]) {
optionalEarlierPolicy = params[2].split('=')[1];
optionalEarlierPolicy = params[2].split("=")[1];
}
response.write(createPolicyTest(policy, optionalEarlierPolicy));

Просмотреть файл

@ -1,44 +1,47 @@
// Handle counting loads for bug 704320.
const SHARED_KEY="bug704320_counter";
const DEFAULT_STATE = {'css': {'count': 0, 'referrers': []},
'img': {'count': 0, 'referrers': []},
'js': {'count': 0, 'referrers': []}};
const TYPE_MAP = {'css': 'text/css',
'js': 'application/javascript',
'img': 'image/png',
'html': 'text/html'};
const SHARED_KEY = "bug704320_counter";
const DEFAULT_STATE = {
css: { count: 0, referrers: [] },
img: { count: 0, referrers: [] },
js: { count: 0, referrers: [] },
};
const TYPE_MAP = {
css: "text/css",
js: "application/javascript",
img: "image/png",
html: "text/html",
};
// Writes an image to the response
function WriteOutImage(response)
{
function WriteOutImage(response) {
var file = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("CurWorkD", Components.interfaces.nsIFile);
.getService(Components.interfaces.nsIProperties)
.get("CurWorkD", Components.interfaces.nsIFile);
file.append("tests");
file.append("image");
file.append("test");
file.append("mochitest");
file.append('blue.png');
file.append("blue.png");
var fileStream = Components.classes['@mozilla.org/network/file-input-stream;1']
.createInstance(Components.interfaces.nsIFileInputStream);
var fileStream = Components.classes[
"@mozilla.org/network/file-input-stream;1"
].createInstance(Components.interfaces.nsIFileInputStream);
fileStream.init(file, 1, 0, false);
response.bodyOutputStream.writeFrom(fileStream, fileStream.available());
}
function handleRequest(request, response)
{
function handleRequest(request, response) {
var query = {};
request.queryString.split('&').forEach(function (val) {
var [name, value] = val.split('=');
request.queryString.split("&").forEach(function(val) {
var [name, value] = val.split("=");
query[name] = unescape(value);
});
var referrerLevel = "none";
if (request.hasHeader('Referer')) {
let referrer = request.getHeader('Referer');
if (request.hasHeader("Referer")) {
let referrer = request.getHeader("Referer");
if (referrer.indexOf("bug704320") > 0) {
referrerLevel = "full";
} else if (referrer == "http://mochi.test:8888/") {
@ -47,7 +50,7 @@ function handleRequest(request, response)
}
var state = getSharedState(SHARED_KEY);
if (state === '') {
if (state === "") {
state = DEFAULT_STATE;
} else {
state = JSON.parse(state);
@ -55,7 +58,6 @@ function handleRequest(request, response)
response.setStatusLine(request.httpVersion, 200, "OK");
//avoid confusing cache behaviors
response.setHeader("Cache-Control", "no-cache", false);
@ -73,20 +75,20 @@ function handleRequest(request, response)
return;
}
if ('type' in query) {
if ("type" in query) {
state[query.type].count++;
response.setHeader("Content-Type", TYPE_MAP[query.type], false);
if (state[query.type].referrers.indexOf(referrerLevel) < 0) {
state[query.type].referrers.push(referrerLevel);
}
if (query.type == 'img') {
if (query.type == "img") {
WriteOutImage(response);
}
}
if ('content' in query) {
response.write(unescape(query['content']));
if ("content" in query) {
response.write(unescape(query.content));
}
setSharedState(SHARED_KEY, JSON.stringify(state));

Просмотреть файл

@ -1,7 +1,9 @@
function handleRequest(request, response)
{
response.setStatusLine(request.httpVersion, 200, "Ok");
response.setHeader("X-appended-result", request.getHeader("X-appended-to-this"));
response.setHeader("X-Accept-Result", request.getHeader("Accept"));
response.write("");
function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 200, "Ok");
response.setHeader(
"X-appended-result",
request.getHeader("X-appended-to-this")
);
response.setHeader("X-Accept-Result", request.getHeader("Accept"));
response.write("");
}

Просмотреть файл

@ -2,7 +2,8 @@ function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain", false);
response.setHeader("Cache-Control", "no-cache", false);
var referer = request.hasHeader("Referer") ? request.getHeader("Referer")
: "";
var referer = request.hasHeader("Referer")
? request.getHeader("Referer")
: "";
response.write("Referer: " + referer);
}

Просмотреть файл

@ -1,5 +1,4 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
let [status, statusText, encodedBody] = request.queryString.split("&");
let body = decodeURIComponent(encodedBody);
response.setStatusLine(request.httpVersion, status, statusText);

Просмотреть файл

@ -1,10 +1,18 @@
// this will take strings_to_send.length*500 ms = 5 sec
var timer = null;
var strings_to_send = ["retry:999999999\ndata\r\n\nda", "ta", ":", "de", "layed1\n\n",
"",
"",
"data:delayed2\n\n", "", ""];
var strings_to_send = [
"retry:999999999\ndata\r\n\nda",
"ta",
":",
"de",
"layed1\n\n",
"",
"",
"data:delayed2\n\n",
"",
"",
];
var resp = null;
function sendNextString() {
@ -29,7 +37,7 @@ function handleRequest(request, response) {
var bytes = strings_to_send.reduce((len, s) => len + s.length, 0);
response.seizePower();
response.write("HTTP/1.1 200 OK\r\n")
response.write("HTTP/1.1 200 OK\r\n");
response.write(`Content-Length: ${bytes}\r\n`);
response.write("Content-Type: text/event-stream; charset=utf-8\r\n");
response.write("Cache-Control: no-cache, must-revalidate\r\n");
@ -37,6 +45,12 @@ function handleRequest(request, response) {
resp = response;
timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
timer.initWithCallback(sendNextString, 500, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);
timer = Components.classes["@mozilla.org/timer;1"].createInstance(
Components.interfaces.nsITimer
);
timer.initWithCallback(
sendNextString,
500,
Components.interfaces.nsITimer.TYPE_REPEATING_SLACK
);
}

Просмотреть файл

@ -1,7 +1,9 @@
const CC = Components.Constructor;
const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream");
const BinaryInputStream = CC(
"@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream",
"setInputStream"
);
function utf8decode(s) {
return decodeURIComponent(escape(s));
@ -23,35 +25,46 @@ function handleRequest(request, response) {
if (request.method == "POST") {
var contentTypeParams = {};
request.getHeader("Content-Type").split(/\s*\;\s*/).forEach(function(s) {
if (s.indexOf('=') >= 0) {
let [name, value] = s.split('=');
contentTypeParams[name] = value;
}
else {
contentTypeParams[''] = s;
}
});
if (contentTypeParams[''] == "multipart/form-data" &&
request.queryString == "") {
requestBody.split("--" + contentTypeParams.boundary).slice(1, -1).forEach(function (s) {
let headers = {};
let headerEnd = s.indexOf("\r\n\r\n");
s.substr(2, headerEnd-2).split("\r\n").forEach(function(s) {
// We're assuming UTF8 for now
let [name, value] = s.split(': ');
headers[name] = utf8decode(value);
});
let body = s.substring(headerEnd + 4, s.length - 2);
if (!headers["Content-Type"] || headers["Content-Type"] == "text/plain") {
// We're assuming UTF8 for now
body = utf8decode(body);
request
.getHeader("Content-Type")
.split(/\s*\;\s*/)
.forEach(function(s) {
if (s.indexOf("=") >= 0) {
let [name, value] = s.split("=");
contentTypeParams[name] = value;
} else {
contentTypeParams[""] = s;
}
result.push({ headers: headers, body: body});
});
if (
contentTypeParams[""] == "multipart/form-data" &&
request.queryString == ""
) {
requestBody
.split("--" + contentTypeParams.boundary)
.slice(1, -1)
.forEach(function(s) {
let headers = {};
let headerEnd = s.indexOf("\r\n\r\n");
s.substr(2, headerEnd - 2)
.split("\r\n")
.forEach(function(s) {
// We're assuming UTF8 for now
let [name, value] = s.split(": ");
headers[name] = utf8decode(value);
});
let body = s.substring(headerEnd + 4, s.length - 2);
if (
!headers["Content-Type"] ||
headers["Content-Type"] == "text/plain"
) {
// We're assuming UTF8 for now
body = utf8decode(body);
}
result.push({ headers, body });
});
}
}

Просмотреть файл

@ -1,90 +1,92 @@
// Test server for bug 1268962
'use strict';
"use strict";
Components.utils.importGlobalProperties(["URLSearchParams"]);
const HTTPStatus = new Map([
[100, 'Continue'],
[101, 'Switching Protocol'],
[200, 'OK'],
[201, 'Created'],
[202, 'Accepted'],
[203, 'Non-Authoritative Information'],
[204, 'No Content'],
[205, 'Reset Content'],
[206, 'Partial Content'],
[300, 'Multiple Choice'],
[301, 'Moved Permanently'],
[302, 'Found'],
[303, 'See Other'],
[304, 'Not Modified'],
[305, 'Use Proxy'],
[306, 'unused'],
[307, 'Temporary Redirect'],
[308, 'Permanent Redirect'],
[400, 'Bad Request'],
[401, 'Unauthorized'],
[402, 'Payment Required'],
[403, 'Forbidden'],
[404, 'Not Found'],
[405, 'Method Not Allowed'],
[406, 'Not Acceptable'],
[407, 'Proxy Authentication Required'],
[408, 'Request Timeout'],
[409, 'Conflict'],
[410, 'Gone'],
[411, 'Length Required'],
[412, 'Precondition Failed'],
[413, 'Request Entity Too Large'],
[414, 'Request-URI Too Long'],
[415, 'Unsupported Media Type'],
[416, 'Requested Range Not Satisfiable'],
[417, 'Expectation Failed'],
[500, 'Internal Server Error'],
[501, 'Not Implemented'],
[502, 'Bad Gateway'],
[503, 'Service Unavailable'],
[504, 'Gateway Timeout'],
[505, 'HTTP Version Not Supported']
[100, "Continue"],
[101, "Switching Protocol"],
[200, "OK"],
[201, "Created"],
[202, "Accepted"],
[203, "Non-Authoritative Information"],
[204, "No Content"],
[205, "Reset Content"],
[206, "Partial Content"],
[300, "Multiple Choice"],
[301, "Moved Permanently"],
[302, "Found"],
[303, "See Other"],
[304, "Not Modified"],
[305, "Use Proxy"],
[306, "unused"],
[307, "Temporary Redirect"],
[308, "Permanent Redirect"],
[400, "Bad Request"],
[401, "Unauthorized"],
[402, "Payment Required"],
[403, "Forbidden"],
[404, "Not Found"],
[405, "Method Not Allowed"],
[406, "Not Acceptable"],
[407, "Proxy Authentication Required"],
[408, "Request Timeout"],
[409, "Conflict"],
[410, "Gone"],
[411, "Length Required"],
[412, "Precondition Failed"],
[413, "Request Entity Too Large"],
[414, "Request-URI Too Long"],
[415, "Unsupported Media Type"],
[416, "Requested Range Not Satisfiable"],
[417, "Expectation Failed"],
[500, "Internal Server Error"],
[501, "Not Implemented"],
[502, "Bad Gateway"],
[503, "Service Unavailable"],
[504, "Gateway Timeout"],
[505, "HTTP Version Not Supported"],
]);
const SAME_ORIGIN = 'http://mochi.test:8888/tests/dom/base/test/file_bug1268962.sjs';
const CROSS_ORIGIN = 'http://example.com/tests/dom/base/test/file_bug1268962.sjs';
const SAME_ORIGIN =
"http://mochi.test:8888/tests/dom/base/test/file_bug1268962.sjs";
const CROSS_ORIGIN =
"http://example.com/tests/dom/base/test/file_bug1268962.sjs";
function handleRequest(request, response) {
const queryMap = new URLSearchParams(request.queryString);
// Check redirection before everything else.
if (queryMap.has('redirect')) {
let redirect = queryMap.get('redirect');
if (queryMap.has("redirect")) {
let redirect = queryMap.get("redirect");
let location;
if (redirect == 'sameorigin') {
if (redirect == "sameorigin") {
location = SAME_ORIGIN;
} else if (redirect == 'crossorigin') {
} else if (redirect == "crossorigin") {
location = CROSS_ORIGIN;
}
if (location) {
// Use HTTP 302 redirection.
response.setStatusLine('1.1', 302, HTTPStatus.get(302));
response.setStatusLine("1.1", 302, HTTPStatus.get(302));
// Forward query strings except the redirect option.
queryMap.delete('redirect');
response.setHeader('Location', location + '?' + queryMap.toString());
queryMap.delete("redirect");
response.setHeader("Location", location + "?" + queryMap.toString());
return;
}
}
if (queryMap.has('statusCode')) {
let statusCode = parseInt(queryMap.get('statusCode'));
if (queryMap.has("statusCode")) {
let statusCode = parseInt(queryMap.get("statusCode"));
let statusText = HTTPStatus.get(statusCode);
response.setStatusLine('1.1', statusCode, statusText);
response.setStatusLine("1.1", statusCode, statusText);
}
if (queryMap.has('cacheControl')) {
let cacheControl = queryMap.get('cacheControl');
response.setHeader('Cache-Control', cacheControl);
if (queryMap.has("cacheControl")) {
let cacheControl = queryMap.get("cacheControl");
response.setHeader("Cache-Control", cacheControl);
}
if (queryMap.has('allowOrigin')) {
let allowOrigin = queryMap.get('allowOrigin');
response.setHeader('Access-Control-Allow-Origin', allowOrigin);
if (queryMap.has("allowOrigin")) {
let allowOrigin = queryMap.get("allowOrigin");
response.setHeader("Access-Control-Allow-Origin", allowOrigin);
}
}

Просмотреть файл

@ -1,5 +1,4 @@
function handleRequest(request, response)
{
function handleRequest(request, response) {
response.setHeader("Content-Type", "text/plain", false);
response.write(decodeURIComponent(request.queryString));
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше