1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// This file is an XPCOM service-ified copy of ../devtools/server/socket/websocket-server.js.
const CC = Components.Constructor;
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
executeSoon: "chrome://remote/content/shared/Sync.sys.mjs",
Log: "chrome://remote/content/shared/Log.sys.mjs",
RemoteAgent: "chrome://remote/content/components/RemoteAgent.sys.mjs",
});
ChromeUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get());
ChromeUtils.defineLazyGetter(lazy, "CryptoHash", () => {
return CC("@mozilla.org/security/hash;1", "nsICryptoHash", "initWithString");
});
ChromeUtils.defineLazyGetter(lazy, "threadManager", () => {
return Cc["@mozilla.org/thread-manager;1"].getService();
});
/**
* Allowed origins are exposed through 2 separate getters because while most
* of the values should be valid URIs, `null` is also a valid origin and cannot
* be converted to a URI. Call sites interested in checking for null should use
* `allowedOrigins`, those interested in URIs should use `allowedOriginURIs`.
*/
ChromeUtils.defineLazyGetter(lazy, "allowedOrigins", () =>
lazy.RemoteAgent.allowOrigins !== null ? lazy.RemoteAgent.allowOrigins : []
);
ChromeUtils.defineLazyGetter(lazy, "allowedOriginURIs", () => {
return lazy.allowedOrigins
.map(origin => {
try {
const originURI = Services.io.newURI(origin);
// Make sure to read host/port/scheme as those getters could throw for
// invalid URIs.
return {
host: originURI.host,
port: originURI.port,
scheme: originURI.scheme,
};
} catch (e) {
return null;
}
})
.filter(uri => uri !== null);
});
/**
* Write a string of bytes to async output stream
* and return promise that resolves once all data has been written.
* Doesn't do any UTF-16/UTF-8 conversion.
* The string is treated as an array of bytes.
*/
function writeString(output, data) {
return new Promise((resolve, reject) => {
const wait = () => {
if (data.length === 0) {
resolve();
return;
}
output.asyncWait(
() => {
try {
const written = output.write(data, data.length);
data = data.slice(written);
wait();
} catch (ex) {
reject(ex);
}
},
0,
0,
lazy.threadManager.currentThread
);
};
wait();
});
}
/**
* Write HTTP response with headers (array of strings) and body
* to async output stream.
*/
function writeHttpResponse(output, headers, body = "") {
headers.push(`Content-Length: ${body.length}`);
const s = headers.join("\r\n") + `\r\n\r\n${body}`;
return writeString(output, s);
}
/**
* Check if the provided URI's host is an IP address.
*
* @param {nsIURI} uri
* The URI to check.
* @returns {boolean}
*/
function isIPAddress(uri) {
try {
// getBaseDomain throws an explicit error if the uri host is an IP address.
Services.eTLD.getBaseDomain(uri);
} catch (e) {
return e.result == Cr.NS_ERROR_HOST_IS_IP_ADDRESS;
}
return false;
}
function isHostValid(hostHeader) {
try {
// Might throw both when calling newURI or when accessing the host/port.
const hostUri = Services.io.newURI(`https://${hostHeader}`);
const { host, port } = hostUri;
const isHostnameValid =
isIPAddress(hostUri) || lazy.RemoteAgent.allowHosts.includes(host);
// For nsIURI a port value of -1 corresponds to the protocol's default port.
const isPortValid = [-1, lazy.RemoteAgent.port].includes(port);
return isHostnameValid && isPortValid;
} catch (e) {
return false;
}
}
function isOriginValid(originHeader) {
if (originHeader === undefined) {
// Always accept no origin header.
return true;
}
// Special case "null" origins, used for privacy sensitive or opaque origins.
if (originHeader === "null") {
return lazy.allowedOrigins.includes("null");
}
try {
// Extract the host, port and scheme from the provided origin header.
const { host, port, scheme } = Services.io.newURI(originHeader);
// Check if any allowed origin matches the provided host, port and scheme.
return lazy.allowedOriginURIs.some(
uri => uri.host === host && uri.port === port && uri.scheme === scheme
);
} catch (e) {
// Reject invalid origin headers
return false;
}
}
/**
* Process the WebSocket handshake headers and return the key to be sent in
* Sec-WebSocket-Accept response header.
*/
function processRequest({ requestLine, headers }) {
if (!isOriginValid(headers.get("origin"))) {
lazy.logger.debug(
`Incorrect Origin header, allowed origins: [${lazy.allowedOrigins}]`
);
throw new Error(
`The handshake request has incorrect Origin header ${headers.get(
"origin"
)}`
);
}
if (!isHostValid(headers.get("host"))) {
lazy.logger.debug(
`Incorrect Host header, allowed hosts: [${lazy.RemoteAgent.allowHosts}]`
);
throw new Error(
`The handshake request has incorrect Host header ${headers.get("host")}`
);
}
const method = requestLine.split(" ")[0];
if (method !== "GET") {
throw new Error("The handshake request must use GET method");
}
const upgrade = headers.get("upgrade");
if (!upgrade || upgrade.toLowerCase() !== "websocket") {
throw new Error(
`The handshake request has incorrect Upgrade header: ${upgrade}`
);
}
const connection = headers.get("connection");
if (
!connection ||
!connection
.split(",")
.map(t => t.trim().toLowerCase())
.includes("upgrade")
) {
throw new Error("The handshake request has incorrect Connection header");
}
const version = headers.get("sec-websocket-version");
if (!version || version !== "13") {
throw new Error(
"The handshake request must have Sec-WebSocket-Version: 13"
);
}
// Compute the accept key
const key = headers.get("sec-websocket-key");
if (!key) {
throw new Error(
"The handshake request must have a Sec-WebSocket-Key header"
);
}
return { acceptKey: computeKey(key) };
}
function computeKey(key) {
const str = `${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`;
const data = Array.from(str, ch => ch.charCodeAt(0));
const hash = new lazy.CryptoHash("sha1");
hash.update(data, data.length);
return hash.finish(true);
}
/**
* Perform the server part of a WebSocket opening handshake
* on an incoming connection.
*/
async function serverHandshake(request, output) {
try {
// Check and extract info from the request
const { acceptKey } = processRequest(request);
// Send response headers
await writeHttpResponse(output, [
"HTTP/1.1 101 Switching Protocols",
"Server: httpd.js",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${acceptKey}`,
]);
} catch (error) {
// Send error response in case of error
await writeHttpResponse(
output,
[
"HTTP/1.1 400 Bad Request",
"Server: httpd.js",
"Content-Type: text/plain",
],
error.message
);
throw error;
}
}
async function createWebSocket(transport, input, output) {
const transportProvider = {
setListener(upgradeListener) {
// onTransportAvailable callback shouldn't be called synchronously
lazy.executeSoon(() => {
upgradeListener.onTransportAvailable(transport, input, output);
});
},
};
return new Promise((resolve, reject) => {
const socket = WebSocket.createServerWebSocket(
null,
[],
transportProvider,
""
);
socket.addEventListener("close", () => {
input.close();
output.close();
});
socket.onopen = () => resolve(socket);
socket.onerror = err => reject(err);
});
}
/** Upgrade an existing HTTP request from httpd.js to WebSocket. */
async function upgrade(request, response) {
// handle response manually, allowing us to send arbitrary data
response._powerSeized = true;
const { transport, input, output } = response._connection;
lazy.logger.info(
`Perform WebSocket upgrade for incoming connection from ${transport.host}:${transport.port}`
);
const headers = new Map();
for (let [key, values] of Object.entries(request._headers._headers)) {
headers.set(key, values.join("\n"));
}
const convertedRequest = {
requestLine: `${request.method} ${request.path}`,
headers,
};
await serverHandshake(convertedRequest, output);
return createWebSocket(transport, input, output);
}
export const WebSocketHandshake = { upgrade };
|