bug 1543679: remote: remove unused server files; r=ochameau,yulia
authorAndreas Tolfsen <ato@sny.no>
Mon, 15 Apr 2019 14:06:25 +0000
changeset 469495 04185cfeb1ae
parent 469494 b4a7ea516329
child 469496 b7402a73e252
push id35873
push userccoroiu@mozilla.com
push dateMon, 15 Apr 2019 21:36:26 +0000
treeherdermozilla-central@b8f49a14c458 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersochameau, yulia
bugs1543679
milestone68.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
bug 1543679: remote: remove unused server files; r=ochameau,yulia These files became redundant after we started serving WebSocket connections from the HTTPD. This fixes the test browser/base/content/test/static/browser_all_files_referenced.js, which checks for unreferenced JSMs. Differential Revision: https://phabricator.services.mozilla.com/D27247
remote/jar.mn
remote/server/Packet.jsm
remote/server/Socket.jsm
remote/server/Transport.jsm
--- a/remote/jar.mn
+++ b/remote/jar.mn
@@ -41,14 +41,11 @@ remote.jar:
   content/domains/content/Performance.jsm (domains/content/Performance.jsm)
   content/domains/content/Runtime.jsm (domains/content/Runtime.jsm)
   content/domains/content/Security.jsm (domains/content/Security.jsm)
   content/domains/parent/Browser.jsm (domains/parent/Browser.jsm)
   content/domains/parent/Target.jsm (domains/parent/Target.jsm)
 
   # transport layer
   content/server/HTTPD.jsm (../netwerk/test/httpserver/httpd.js)
-  content/server/Packet.jsm (server/Packet.jsm)
-  content/server/Socket.jsm (server/Socket.jsm)
   content/server/Stream.jsm (server/Stream.jsm)
-  content/server/Transport.jsm (server/Transport.jsm)
   content/server/WebSocket.jsm (server/WebSocket.jsm)
   content/server/WebSocketTransport.jsm (server/WebSocketTransport.jsm)
deleted file mode 100644
--- a/remote/server/Packet.jsm
+++ /dev/null
@@ -1,413 +0,0 @@
-/* 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 is an XPCOM service-ified copy of ../devtools/shared/transport/packets.js.
-
-"use strict",
-
-var EXPORTED_SYMBOLS = [
-  "RawPacket",
-  "Packet",
-  "JSONPacket",
-  "BulkPacket",
-];
-
-/**
- * Packets contain read / write functionality for the different packet types
- * supported by the debugging protocol, so that a transport can focus on
- * delivery and queue management without worrying too much about the specific
- * packet types.
- *
- * They are intended to be "one use only", so a new packet should be
- * instantiated for each incoming or outgoing packet.
- *
- * A complete Packet type should expose at least the following:
- *   * read(stream, scriptableStream)
- *     Called when the input stream has data to read
- *   * write(stream)
- *     Called when the output stream is ready to write
- *   * get done()
- *     Returns true once the packet is done being read / written
- *   * destroy()
- *     Called to clean up at the end of use
- */
-
-const {Stream} = ChromeUtils.import("chrome://remote/content/server/Stream.jsm");
-
-const unicodeConverter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
-    .createInstance(Ci.nsIScriptableUnicodeConverter);
-unicodeConverter.charset = "UTF-8";
-
-const defer = function() {
-  let deferred = {
-    promise: new Promise((resolve, reject) => {
-      deferred.resolve = resolve;
-      deferred.reject = reject;
-    }),
-  };
-  return deferred;
-};
-
-// The transport's previous check ensured the header length did not
-// exceed 20 characters.  Here, we opt for the somewhat smaller, but still
-// large limit of 1 TiB.
-const PACKET_LENGTH_MAX = Math.pow(2, 40);
-
-/**
- * A generic Packet processing object (extended by two subtypes below).
- *
- * @class
- */
-function Packet(transport) {
-  this._transport = transport;
-  this._length = 0;
-}
-
-/**
- * Attempt to initialize a new Packet based on the incoming packet header
- * we've received so far.  We try each of the types in succession, trying
- * JSON packets first since they are much more common.
- *
- * @param {string} header
- *     Packet header string to attempt parsing.
- * @param {DebuggerTransport} transport
- *     Transport instance that will own the packet.
- *
- * @return {Packet}
- *     Parsed packet of the matching type, or null if no types matched.
- */
-Packet.fromHeader = function(header, transport) {
-  return JSONPacket.fromHeader(header, transport) ||
-         BulkPacket.fromHeader(header, transport);
-};
-
-Packet.prototype = {
-
-  get length() {
-    return this._length;
-  },
-
-  set length(length) {
-    if (length > PACKET_LENGTH_MAX) {
-      throw new Error("Packet length " + length +
-                      " exceeds the max length of " + PACKET_LENGTH_MAX);
-    }
-    this._length = length;
-  },
-
-  destroy() {
-    this._transport = null;
-  },
-};
-
-/**
- * With a JSON packet (the typical packet type sent via the transport),
- * data is transferred as a JSON packet serialized into a string,
- * with the string length prepended to the packet, followed by a colon
- * ([length]:[packet]). The contents of the JSON packet are specified in
- * the Remote Debugging Protocol specification.
- *
- * @param {DebuggerTransport} transport
- *     Transport instance that will own the packet.
- */
-function JSONPacket(transport) {
-  Packet.call(this, transport);
-  this._data = "";
-  this._done = false;
-}
-
-/**
- * Attempt to initialize a new JSONPacket based on the incoming packet
- * header we've received so far.
- *
- * @param {string} header
- *     Packet header string to attempt parsing.
- * @param {DebuggerTransport} transport
- *     Transport instance that will own the packet.
- *
- * @return {JSONPacket}
- *     Parsed packet, or null if it's not a match.
- */
-JSONPacket.fromHeader = function(header, transport) {
-  let match = this.HEADER_PATTERN.exec(header);
-
-  if (!match) {
-    return null;
-  }
-
-  let packet = new JSONPacket(transport);
-  packet.length = +match[1];
-  return packet;
-};
-
-JSONPacket.HEADER_PATTERN = /^(\d+):$/;
-
-JSONPacket.prototype = Object.create(Packet.prototype);
-
-Object.defineProperty(JSONPacket.prototype, "object", {
-  /**
-   * Gets the object (not the serialized string) being read or written.
-   */
-  get() {
-    return this._object;
-  },
-
-  /**
-   * Sets the object to be sent when write() is called.
-   */
-  set(object) {
-    this._object = object;
-    let data = JSON.stringify(object);
-    this._data = unicodeConverter.ConvertFromUnicode(data);
-    this.length = this._data.length;
-  },
-});
-
-JSONPacket.prototype.read = function(stream, scriptableStream) {
-
-  // Read in more packet data.
-  this._readData(stream, scriptableStream);
-
-  if (!this.done) {
-    // Don't have a complete packet yet.
-    return;
-  }
-
-  let json = this._data;
-  try {
-    json = unicodeConverter.ConvertToUnicode(json);
-    this._object = JSON.parse(json);
-  } catch (e) {
-    let msg = "Error parsing incoming packet: " + json + " (" + e +
-              " - " + e.stack + ")";
-    console.error(msg);
-    dump(msg + "\n");
-    return;
-  }
-
-  this._transport._onJSONObjectReady(this._object);
-};
-
-JSONPacket.prototype._readData = function(stream, scriptableStream) {
-  let bytesToRead = Math.min(
-      this.length - this._data.length,
-      stream.available());
-  this._data += scriptableStream.readBytes(bytesToRead);
-  this._done = this._data.length === this.length;
-};
-
-JSONPacket.prototype.write = function(stream) {
-
-  if (this._outgoing === undefined) {
-    // Format the serialized packet to a buffer
-    this._outgoing = this.length + ":" + this._data;
-  }
-
-  let written = stream.write(this._outgoing, this._outgoing.length);
-  this._outgoing = this._outgoing.slice(written);
-  this._done = !this._outgoing.length;
-};
-
-Object.defineProperty(JSONPacket.prototype, "done", {
-  get() {
-    return this._done;
-  },
-});
-
-JSONPacket.prototype.toString = function() {
-  return JSON.stringify(this._object, null, 2);
-};
-
-/**
- * With a bulk packet, data is transferred by temporarily handing over
- * the transport's input or output stream to the application layer for
- * writing data directly.  This can be much faster for large data sets,
- * and avoids various stages of copies and data duplication inherent in
- * the JSON packet type.  The bulk packet looks like:
- *
- *     bulk [actor] [type] [length]:[data]
- *
- * The interpretation of the data portion depends on the kind of actor and
- * the packet's type.  See the Remote Debugging Protocol Stream Transport
- * spec for more details.
- *
- * @param {DebuggerTransport} transport
- *     Transport instance that will own the packet.
- */
-function BulkPacket(transport) {
-  Packet.call(this, transport);
-  this._done = false;
-  this._readyForWriting = defer();
-}
-
-/**
- * Attempt to initialize a new BulkPacket based on the incoming packet
- * header we've received so far.
- *
- * @param {string} header
- *     Packet header string to attempt parsing.
- * @param {DebuggerTransport} transport
- *     Transport instance that will own the packet.
- *
- * @return {BulkPacket}
- *     Parsed packet, or null if it's not a match.
- */
-BulkPacket.fromHeader = function(header, transport) {
-  let match = this.HEADER_PATTERN.exec(header);
-
-  if (!match) {
-    return null;
-  }
-
-  let packet = new BulkPacket(transport);
-  packet.header = {
-    actor: match[1],
-    type: match[2],
-    length: +match[3],
-  };
-  return packet;
-};
-
-BulkPacket.HEADER_PATTERN = /^bulk ([^: ]+) ([^: ]+) (\d+):$/;
-
-BulkPacket.prototype = Object.create(Packet.prototype);
-
-BulkPacket.prototype.read = function(stream) {
-  // Temporarily pause monitoring of the input stream
-  this._transport.pauseIncoming();
-
-  let deferred = defer();
-
-  this._transport._onBulkReadReady({
-    actor: this.actor,
-    type: this.type,
-    length: this.length,
-    copyTo: (output) => {
-      let copying = StreamUtils.copyStream(stream, output, this.length);
-      deferred.resolve(copying);
-      return copying;
-    },
-    stream,
-    done: deferred,
-  });
-
-  // Await the result of reading from the stream
-  deferred.promise.then(() => {
-    this._done = true;
-    this._transport.resumeIncoming();
-  }, this._transport.close);
-
-  // Ensure this is only done once
-  this.read = () => {
-    throw new Error("Tried to read() a BulkPacket's stream multiple times.");
-  };
-};
-
-BulkPacket.prototype.write = function(stream) {
-  if (this._outgoingHeader === undefined) {
-    // Format the serialized packet header to a buffer
-    this._outgoingHeader = "bulk " + this.actor + " " + this.type + " " +
-                           this.length + ":";
-  }
-
-  // Write the header, or whatever's left of it to write.
-  if (this._outgoingHeader.length) {
-    let written = stream.write(this._outgoingHeader,
-        this._outgoingHeader.length);
-    this._outgoingHeader = this._outgoingHeader.slice(written);
-    return;
-  }
-
-  // Temporarily pause the monitoring of the output stream
-  this._transport.pauseOutgoing();
-
-  let deferred = defer();
-
-  this._readyForWriting.resolve({
-    copyFrom: (input) => {
-      let copying = StreamUtils.copyStream(input, stream, this.length);
-      deferred.resolve(copying);
-      return copying;
-    },
-    stream,
-    done: deferred,
-  });
-
-  // Await the result of writing to the stream
-  deferred.promise.then(() => {
-    this._done = true;
-    this._transport.resumeOutgoing();
-  }, this._transport.close);
-
-  // Ensure this is only done once
-  this.write = () => {
-    throw new Error("Tried to write() a BulkPacket's stream multiple times.");
-  };
-};
-
-Object.defineProperty(BulkPacket.prototype, "streamReadyForWriting", {
-  get() {
-    return this._readyForWriting.promise;
-  },
-});
-
-Object.defineProperty(BulkPacket.prototype, "header", {
-  get() {
-    return {
-      actor: this.actor,
-      type: this.type,
-      length: this.length,
-    };
-  },
-
-  set(header) {
-    this.actor = header.actor;
-    this.type = header.type;
-    this.length = header.length;
-  },
-});
-
-Object.defineProperty(BulkPacket.prototype, "done", {
-  get() {
-    return this._done;
-  },
-});
-
-BulkPacket.prototype.toString = function() {
-  return "Bulk: " + JSON.stringify(this.header, null, 2);
-};
-
-/**
- * RawPacket is used to test the transport's error handling of malformed
- * packets, by writing data directly onto the stream.
- * @param transport DebuggerTransport
- *        The transport instance that will own the packet.
- * @param data string
- *        The raw string to send out onto the stream.
- */
-function RawPacket(transport, data) {
-  Packet.call(this, transport);
-  this._data = data;
-  this.length = data.length;
-  this._done = false;
-}
-
-RawPacket.prototype = Object.create(Packet.prototype);
-
-RawPacket.prototype.read = function() {
-  // this has not yet been needed for testing
-  throw new Error("Not implemented");
-};
-
-RawPacket.prototype.write = function(stream) {
-  let written = stream.write(this._data, this._data.length);
-  this._data = this._data.slice(written);
-  this._done = !this._data.length;
-};
-
-Object.defineProperty(RawPacket.prototype, "done", {
-  get() {
-    return this._done;
-  },
-});
deleted file mode 100644
--- a/remote/server/Socket.jsm
+++ /dev/null
@@ -1,270 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-var EXPORTED_SYMBOLS = [
-  "ConnectionHandshake",
-  "SocketListener",
-];
-
-// This is an XPCOM-service-ified copy of ../devtools/shared/security/socket.js.
-
-const {EventEmitter} = ChromeUtils.import("resource://gre/modules/EventEmitter.jsm");
-const {Log} = ChromeUtils.import("chrome://remote/content/Log.jsm");
-const {Preferences} = ChromeUtils.import("resource://gre/modules/Preferences.jsm");
-const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetters(this, {
-  DebuggerTransport: "chrome://remote/content/server/Transport.jsm",
-  WebSocketDebuggerTransport: "chrome://remote/content/server/WebSocketTransport.jsm",
-  WebSocketServer: "chrome://remote/content/server/WebSocket.jsm",
-});
-
-XPCOMUtils.defineLazyGetter(this, "log", Log.get);
-XPCOMUtils.defineLazyGetter(this, "nsFile", () => CC("@mozilla.org/file/local;1", "nsIFile", "initWithPath"));
-
-const LOOPBACKS = ["localhost", "127.0.0.1"];
-
-const {KeepWhenOffline, LoopbackOnly} = Ci.nsIServerSocket;
-
-this.SocketListener = class SocketListener {
-  constructor() {
-    this.socket = null;
-    this.network = null;
-
-    this.nextConnID = 0;
-
-    this.onConnectionCreated = null;
-    this.onConnectionClose = null;
-
-    EventEmitter.decorate(this);
-  }
-
-  get listening() {
-    return !!this.socket;
-  }
-
-  /**
-   * @param {String} addr
-   *     [<network>][:<host>][:<port>]
-   *     networks: ws, unix, tcp
-   */
-  listen(addr) {
-    const [network, host, port] = addr.split(":");
-    try {
-      this._listen(network, host, port);
-    } catch (e) {
-      this.close();
-      throw new Error(`Unable to start socket server on ${addr}: ${e.message}`, e);
-    }
-  }
-
-  _listen(network = "tcp", host = "localhost", port = 0) {
-    if (typeof network != "string" ||
-        typeof host != "string" ||
-        (network != "unix" && typeof port != "number")) {
-      throw new TypeError();
-    }
-    if (network != "unix" && (!Number.isInteger(port) || port < 0)) {
-      throw new RangeError();
-    }
-    if (!SocketListener.Networks.includes(network)) {
-      throw new Error("Unexpected network: " + network);
-    }
-    if (!LOOPBACKS.includes(host)) {
-      throw new Error("Restricted to listening on loopback devices");
-    }
-
-    const flags = KeepWhenOffline | LoopbackOnly;
-
-    const backlog = 4;
-    this.socket = createSocket();
-    this.network = network;
-
-    switch (this.network) {
-      case "tcp":
-      case "ws":
-        // -1 means kernel-assigned port in Gecko
-        if (port == 0) {
-          port = -1;
-        }
-        
-        this.socket.initSpecialConnection(port, flags, backlog);
-        break;
-
-      case "unix":
-        // concrete Unix socket
-        if (host.startsWith("/")) {
-          const file = nsFile(host);
-          if (file.exists()) {
-            file.remove(false);
-          }
-          this.socket.initWithFilename(file, Number.parseInt("666", 8), backlog);
-        // abstract Unix socket
-        } else {
-          this.socket.initWithAbstractAddress(host, backlog);
-        }
-        break;
-    }
-
-    this.socket.asyncListen(this);
-  }
-
-  close() {
-    if (this.socket) {
-      this.socket.close();
-      this.socket = null;
-    }
-    // TODO(ato): removeSocketListener?
-  }
-
-  get host() {
-    if (this.socket) {
-      // TODO(ato): Don't hardcode:
-      return "localhost";
-    }
-    return null;
-  }
-
-  get port() {
-    if (this.socket) {
-      return this.socket.port;
-    }
-    return null;
-  }
-
-  onAllowedConnection(eventName, transport) {
-    this.emit("accepted", transport, this);
-  }
-
-  // nsIServerSocketListener implementation
-
-  onSocketAccepted(socket, socketTransport) {
-    const conn = new ConnectionHandshake(this, socketTransport);
-    conn.once("allowed", this.onAllowedConnection.bind(this));
-    conn.handle();
-  }
-
-  onStopListening(socket, status) {
-    dump("onStopListening: " + status + "\n");
-  }
-};
-
-SocketListener.Networks = ["tcp", "unix", "ws"];
-
-/**
- * Created by SocketListener for each accepted incoming socket.
- * This is a short-lived object used to implement a handshake,
- * before the socket transport is handed back to RemoteAgent.
- */
-this.ConnectionHandshake = class ConnectionHandshake {
-  constructor(listener, socketTransport) {
-    this.listener = listener;
-    this.socket = socketTransport;
-    this.transport = null;
-    this.destroyed = false;
-
-    EventEmitter.decorate(this);
-  }
-
-  destructor() {
-    this.listener = null;
-    this.socket = null;
-    this.transport = null;
-    this.destroyed = true;
-  }
-
-  get address() {
-    return `${this.host}:${this.port}`;
-  }
-
-  get host() {
-    return this.socket.host;
-  }
-
-  get port() {
-    return this.socket.port;
-  }
-
-  async handle() {
-    try {
-      await this.createTransport();
-      this.allow();
-    } catch (e) {
-      this.deny(e);
-    }
-  }
-
-  async createTransport() {
-    const rx = this.socket.openInputStream(0, 0, 0);
-    const tx = this.socket.openOutputStream(0, 0, 0);
-
-    if (this.listener.network == "ws") {
-      const so = await WebSocketServer.accept(this.socket, rx, tx);
-      this.transport = new WebSocketDebuggerTransport(so);
-    } else {
-      this.transport = new DebuggerTransport(rx, tx);
-    }
-
-    // This handles early disconnects from clients, primarily for failed TLS negotiation.
-    // We don't support TLS connections in RDP, but might be useful for future blocklist.
-    this.transport.hooks = {
-      onClosed: reason => this.deny(reason),
-    };
-    // TODO(ato): Review if this is correct:
-    this.transport.ready();
-  }
-
-  allow() {
-    if (this.destroyed) {
-      return;
-    }
-    log.debug(`Accepted connection from ${this.address}`);
-    this.emit("allowed", this.transport);
-    this.destructor();
-  }
-
-  deny(result) {
-    if (this.destroyed) {
-      return;
-    }
-
-    let err = legibleError(result);
-    log.warn(`Connection from ${this.address} denied: ${err.message}`, err.stack);
-
-    if (this.transport) {
-      this.transport.hooks = null;
-      this.transport.close(result); 
-    }
-    this.socket.close(result);
-    this.destructor();
-  }
-};
-
-function createSocket() {
-  return Cc["@mozilla.org/network/server-socket;1"]
-      .createInstance(Ci.nsIServerSocket);
-}
-
-// TODO(ato): Move to separate module
-function legibleError(obj) {
-  if (obj instanceof Ci.nsIException) {
-    for (const result in Cr) {
-      if (obj.result == Cr[result]) {
-        return {
-          message: result,
-          stack: obj.location.formattedStack,
-        };
-      }
-    }
-
-    return {
-      message: "nsIException",
-      stack: obj,
-    };
-  } else {
-    return obj;
-  }
-}
deleted file mode 100644
--- a/remote/server/Transport.jsm
+++ /dev/null
@@ -1,527 +0,0 @@
-/* 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 is an XPCOM service-ified copy of ../devtools/shared/transport/transport.js.
-
-/* global Pipe, ScriptableInputStream */
-
-"use strict";
-
-var EXPORTED_SYMBOLS = ["DebuggerTransport"];
-
-const CC = Components.Constructor;
-
-const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
-const {EventEmitter} = ChromeUtils.import("resource://gre/modules/EventEmitter.jsm");
-const {Stream} = ChromeUtils.import("chrome://remote/content/server/Stream.jsm");
-const {
-  Packet,
-  JSONPacket,
-  BulkPacket,
-} = ChromeUtils.import("chrome://remote/content/server/Packet.jsm");
-
-const executeSoon = function(func) {
-  Services.tm.dispatchToMainThread(func);
-};
-
-const flags = {wantVerbose: true, wantLogging: true};
-
-const dumpv =
-  flags.wantVerbose ?
-  function(msg) {
-    dump(msg + "\n");
-  } :
-  function() {};
-
-const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1",
-    "nsIScriptableInputStream", "init");
-
-const PACKET_HEADER_MAX = 200;
-
-/**
- * An adapter that handles data transfers between the debugger client
- * and server. It can work with both nsIPipe and nsIServerSocket
- * transports so long as the properly created input and output streams
- * are specified.  (However, for intra-process connections,
- * LocalDebuggerTransport, below, is more efficient than using an nsIPipe
- * pair with DebuggerTransport.)
- *
- * @param {nsIAsyncInputStream} input
- *     The input stream.
- * @param {nsIAsyncOutputStream} output
- *     The output stream.
- *
- * Given a DebuggerTransport instance dt:
- * 1) Set dt.hooks to a packet handler object (described below).
- * 2) Call dt.ready() to begin watching for input packets.
- * 3) Call dt.send() / dt.startBulkSend() to send packets.
- * 4) Call dt.close() to close the connection, and disengage from
- *    the event loop.
- *
- * A packet handler is an object with the following methods:
- *
- * - onPacket(packet) - called when we have received a complete packet.
- *   |packet| is the parsed form of the packet --- a JavaScript value, not
- *   a JSON-syntax string.
- *
- * - onBulkPacket(packet) - called when we have switched to bulk packet
- *   receiving mode. |packet| is an object containing:
- *   * actor:  Name of actor that will receive the packet
- *   * type:   Name of actor's method that should be called on receipt
- *   * length: Size of the data to be read
- *   * stream: This input stream should only be used directly if you
- *             can ensure that you will read exactly |length| bytes and
- *             will not close the stream when reading is complete
- *   * done:   If you use the stream directly (instead of |copyTo|
- *             below), you must signal completion by resolving/rejecting
- *             this deferred.  If it's rejected, the transport will
- *             be closed.  If an Error is supplied as a rejection value,
- *             it will be logged via |dump|.  If you do use |copyTo|,
- *             resolving is taken care of for you when copying completes.
- *   * copyTo: A helper function for getting your data out of the
- *             stream that meets the stream handling requirements above,
- *             and has the following signature:
- *
- *             @param nsIAsyncOutputStream {output}
- *                 The stream to copy to.
- *
- *             @return {Promise}
- *                 The promise is resolved when copying completes or
- *                 rejected if any (unexpected) errors occur.  This object
- *                 also emits "progress" events for each chunk that is
- *                 copied.  See stream-utils.js.
- *
- * - onClosed(reason) - called when the connection is closed. |reason|
- *   is an optional nsresult or object, typically passed when the
- *   transport is closed due to some error in a underlying stream.
- *
- * See ./packets.js and the Remote Debugging Protocol specification for
- * more details on the format of these packets.
- *
- * @class
- */
-function DebuggerTransport(input, output) {
-  EventEmitter.decorate(this);
-
-  this._input = input;
-  this._scriptableInput = new ScriptableInputStream(input);
-  this._output = output;
-
-  // The current incoming (possibly partial) header, which will determine
-  // which type of Packet |_incoming| below will become.
-  this._incomingHeader = "";
-  // The current incoming Packet object
-  this._incoming = null;
-  // A queue of outgoing Packet objects
-  this._outgoing = [];
-
-  this.hooks = null;
-  this.active = false;
-
-  this._incomingEnabled = true;
-  this._outgoingEnabled = true;
-
-  this.close = this.close.bind(this);
-}
-
-DebuggerTransport.prototype = {
-  /**
-   * Transmit an object as a JSON packet.
-   *
-   * This method returns immediately, without waiting for the entire
-   * packet to be transmitted, registering event handlers as needed to
-   * transmit the entire packet. Packets are transmitted in the order they
-   * are passed to this method.
-   */
-  send(object) {
-    this.emit("send", object);
-
-    const packet = new JSONPacket(this);
-    packet.object = object;
-    this._outgoing.push(packet);
-    this._flushOutgoing();
-  },
-
-  /**
-   * Transmit streaming data via a bulk packet.
-   *
-   * This method initiates the bulk send process by queuing up the header
-   * data.  The caller receives eventual access to a stream for writing.
-   *
-   * N.B.: Do *not* attempt to close the stream handed to you, as it
-   * will continue to be used by this transport afterwards.  Most users
-   * should instead use the provided |copyFrom| function instead.
-   *
-   * @param {Object} header
-   *     This is modeled after the format of JSON packets above, but does
-   *     not actually contain the data, but is instead just a routing
-   *     header:
-   *
-   *       - actor:  Name of actor that will receive the packet
-   *       - type:   Name of actor's method that should be called on receipt
-   *       - length: Size of the data to be sent
-   *
-   * @return {Promise}
-   *     The promise will be resolved when you are allowed to write to
-   *     the stream with an object containing:
-   *
-   *       - stream:   This output stream should only be used directly
-   *                   if you can ensure that you will write exactly
-   *                   |length| bytes and will not close the stream when
-   *                    writing is complete.
-   *       - done:     If you use the stream directly (instead of
-   *                   |copyFrom| below), you must signal completion by
-   *                   resolving/rejecting this deferred.  If it's
-   *                   rejected, the transport will be closed.  If an
-   *                   Error is supplied as a rejection value, it will
-   *                   be logged via |dump|.  If you do use |copyFrom|,
-   *                   resolving is taken care of for you when copying
-   *                   completes.
-   *       - copyFrom: A helper function for getting your data onto the
-   *                   stream that meets the stream handling requirements
-   *                   above, and has the following signature:
-   *
-   *                   @param {nsIAsyncInputStream} input
-   *                       The stream to copy from.
-   *
-   *                   @return {Promise}
-   *                       The promise is resolved when copying completes
-   *                       or rejected if any (unexpected) errors occur.
-   *                       This object also emits "progress" events for
-   *                       each chunkthat is copied.  See stream-utils.js.
-   */
-  startBulkSend(header) {
-    this.emit("startbulksend", header);
-
-    const packet = new BulkPacket(this);
-    packet.header = header;
-    this._outgoing.push(packet);
-    this._flushOutgoing();
-    return packet.streamReadyForWriting;
-  },
-
-  /**
-   * Close the transport.
-   *
-   * @param {(nsresult|object)=} reason
-   *     The status code or error message that corresponds to the reason
-   *     for closing the transport (likely because a stream closed
-   *     or failed).
-   */
-  close(reason) {
-    this.emit("close", reason);
-
-    this.active = false;
-    this._input.close();
-    this._scriptableInput.close();
-    this._output.close();
-    this._destroyIncoming();
-    this._destroyAllOutgoing();
-    if (this.hooks) {
-      this.hooks.onClosed(reason);
-      this.hooks = null;
-    }
-    if (reason) {
-      dumpv("Transport closed: " + reason);
-    } else {
-      dumpv("Transport closed.");
-    }
-  },
-
-  /**
-   * The currently outgoing packet (at the top of the queue).
-   */
-  get _currentOutgoing() {
-    return this._outgoing[0];
-  },
-
-  /**
-   * Flush data to the outgoing stream.  Waits until the output
-   * stream notifies us that it is ready to be written to (via
-   * onOutputStreamReady).
-   */
-  _flushOutgoing() {
-    if (!this._outgoingEnabled || this._outgoing.length === 0) {
-      return;
-    }
-
-    // If the top of the packet queue has nothing more to send, remove it.
-    if (this._currentOutgoing.done) {
-      this._finishCurrentOutgoing();
-    }
-
-    if (this._outgoing.length > 0) {
-      const threadManager = Cc["@mozilla.org/thread-manager;1"].getService();
-      this._output.asyncWait(this, 0, 0, threadManager.currentThread);
-    }
-  },
-
-  /**
-   * Pause this transport's attempts to write to the output stream.
-   * This is used when we've temporarily handed off our output stream for
-   * writing bulk data.
-   */
-  pauseOutgoing() {
-    this._outgoingEnabled = false;
-  },
-
-  /**
-   * Resume this transport's attempts to write to the output stream.
-   */
-  resumeOutgoing() {
-    this._outgoingEnabled = true;
-    this._flushOutgoing();
-  },
-
-  // nsIOutputStreamCallback
-  /**
-   * This is called when the output stream is ready for more data to
-   * be written.  The current outgoing packet will attempt to write some
-   * amount of data, but may not complete.
-   */
-  onOutputStreamReady(stream) {
-    if (!this._outgoingEnabled || this._outgoing.length === 0) {
-      return;
-    }
-
-    try {
-      this._currentOutgoing.write(stream);
-    } catch (e) {
-      if (e.result != Cr.NS_BASE_STREAM_WOULD_BLOCK) {
-        this.close(e.result);
-        return;
-      }
-      throw e;
-    }
-
-    this._flushOutgoing();
-  },
-
-  /**
-   * Remove the current outgoing packet from the queue upon completion.
-   */
-  _finishCurrentOutgoing() {
-    if (this._currentOutgoing) {
-      this._currentOutgoing.destroy();
-      this._outgoing.shift();
-    }
-  },
-
-  /**
-   * Clear the entire outgoing queue.
-   */
-  _destroyAllOutgoing() {
-    for (const packet of this._outgoing) {
-      packet.destroy();
-    }
-    this._outgoing = [];
-  },
-
-  /**
-   * Initialize the input stream for reading. Once this method has been
-   * called, we watch for packets on the input stream, and pass them to
-   * the appropriate handlers via this.hooks.
-   */
-  ready() {
-    this.active = true;
-    this._waitForIncoming();
-  },
-
-  /**
-   * Asks the input stream to notify us (via onInputStreamReady) when it is
-   * ready for reading.
-   */
-  _waitForIncoming() {
-    if (this._incomingEnabled) {
-      const threadManager = Cc["@mozilla.org/thread-manager;1"].getService();
-      this._input.asyncWait(this, 0, 0, threadManager.currentThread);
-    }
-  },
-
-  /**
-   * Pause this transport's attempts to read from the input stream.
-   * This is used when we've temporarily handed off our input stream for
-   * reading bulk data.
-   */
-  pauseIncoming() {
-    this._incomingEnabled = false;
-  },
-
-  /**
-   * Resume this transport's attempts to read from the input stream.
-   */
-  resumeIncoming() {
-    this._incomingEnabled = true;
-    this._flushIncoming();
-    this._waitForIncoming();
-  },
-
-  // nsIInputStreamCallback
-  /**
-   * Called when the stream is either readable or closed.
-   */
-  onInputStreamReady(stream) {
-    try {
-      while (stream.available() && this._incomingEnabled &&
-             this._processIncoming(stream, stream.available())) {
-         // Loop until there is nothing more to process
-      }
-      this._waitForIncoming();
-    } catch (e) {
-      if (e.result != Cr.NS_BASE_STREAM_WOULD_BLOCK) {
-        this.close(e.result);
-      } else {
-        throw e;
-      }
-    }
-  },
-
-  /**
-   * Process the incoming data.  Will create a new currently incoming
-   * Packet if needed.  Tells the incoming Packet to read as much data
-   * as it can, but reading may not complete.  The Packet signals that
-   * its data is ready for delivery by calling one of this transport's
-   * _on*Ready methods (see ./packets.js and the _on*Ready methods below).
-   *
-   * @return {boolean}
-   *     Whether incoming stream processing should continue for any
-   *     remaining data.
-   */
-  _processIncoming(stream, count) {
-    dumpv("Data available: " + count);
-
-    if (!count) {
-      dumpv("Nothing to read, skipping");
-      return false;
-    }
-
-    try {
-      if (!this._incoming) {
-        dumpv("Creating a new packet from incoming");
-
-        if (!this._readHeader(stream)) {
-          // Not enough data to read packet type
-          return false;
-        }
-
-        // Attempt to create a new Packet by trying to parse each possible
-        // header pattern.
-        this._incoming = Packet.fromHeader(this._incomingHeader, this);
-        if (!this._incoming) {
-          throw new Error("No packet types for header: " +
-                        this._incomingHeader);
-        }
-      }
-
-      if (!this._incoming.done) {
-        // We have an incomplete packet, keep reading it.
-        dumpv("Existing packet incomplete, keep reading");
-        this._incoming.read(stream, this._scriptableInput);
-      }
-    } catch (e) {
-      dump(`Error reading incoming packet: (${e} - ${e.stack})\n`);
-
-      // Now in an invalid state, shut down the transport.
-      this.close();
-      return false;
-    }
-
-    if (!this._incoming.done) {
-      // Still not complete, we'll wait for more data.
-      dumpv("Packet not done, wait for more");
-      return true;
-    }
-
-    // Ready for next packet
-    this._flushIncoming();
-    return true;
-  },
-
-  /**
-   * Read as far as we can into the incoming data, attempting to build
-   * up a complete packet header (which terminates with ":").  We'll only
-   * read up to PACKET_HEADER_MAX characters.
-   *
-   * @return {boolean}
-   *     True if we now have a complete header.
-   */
-  _readHeader() {
-    const amountToRead = PACKET_HEADER_MAX - this._incomingHeader.length;
-    this._incomingHeader +=
-    Stream.delimitedRead(this._scriptableInput, ":", amountToRead);
-    if (flags.wantVerbose) {
-      dumpv("Header read: " + this._incomingHeader);
-    }
-
-    if (this._incomingHeader.endsWith(":")) {
-      if (flags.wantVerbose) {
-        dumpv("Found packet header successfully: " + this._incomingHeader);
-      }
-      return true;
-    }
-
-    if (this._incomingHeader.length >= PACKET_HEADER_MAX) {
-      throw new Error("Failed to parse packet header!");
-    }
-
-    // Not enough data yet.
-    return false;
-  },
-
-  /**
-   * If the incoming packet is done, log it as needed and clear the buffer.
-   */
-  _flushIncoming() {
-    if (!this._incoming.done) {
-      return;
-    }
-    if (flags.wantLogging) {
-      dumpv("Got: " + this._incoming);
-    }
-    this._destroyIncoming();
-  },
-
-  /**
-   * Handler triggered by an incoming JSONPacket completing it's |read|
-   * method.  Delivers the packet to this.hooks.onPacket.
-   */
-  _onJSONObjectReady(object) {
-    executeSoon(() => {
-    // Ensure the transport is still alive by the time this runs.
-      if (this.active) {
-        this.emit("packet", object);
-        this.hooks.onPacket(object);
-      }
-    });
-  },
-
-  /**
-   * Handler triggered by an incoming BulkPacket entering the |read|
-   * phase for the stream portion of the packet.  Delivers info about the
-   * incoming streaming data to this.hooks.onBulkPacket.  See the main
-   * comment on the transport at the top of this file for more details.
-   */
-  _onBulkReadReady(...args) {
-    executeSoon(() => {
-    // Ensure the transport is still alive by the time this runs.
-      if (this.active) {
-        this.emit("bulkpacket", ...args);
-        this.hooks.onBulkPacket(...args);
-      }
-    });
-  },
-
-  /**
-   * Remove all handlers and references related to the current incoming
-   * packet, either because it is now complete or because the transport
-   * is closing.
-   */
-  _destroyIncoming() {
-    if (this._incoming) {
-      this._incoming.destroy();
-    }
-    this._incomingHeader = "";
-    this._incoming = null;
-  },
-};