Пример #1
0
     }, (stream, status, req) => {
      if (!components.isSuccessCode(status)) {
        reject(new Error("Request failed with status code = "
                         + status
                         + " after NetUtil.asyncFetch for url = "
                         + uri));
        return;
      }

      let source = NetUtil.readInputStreamToString(stream, stream.available());
      stream.close();
      resolve(source);
    });
Пример #2
0
    onStopRequest: function(aRequest, aContext, aStatus) {
        let response = Response(this.target.channel, this.mData, this.mStatus);
        this.target.channel = null;
        this.mData = null;

        observerService.removeObserver(this, "http-on-modify-request");
        observerService.removeObserver(this, "http-on-examine-response");

        if (components.isSuccessCode(aStatus)) {
            emit(this.target, 'complete', response);
        } else {
            emit(this.target, 'complete', null);
        }
    },
Пример #3
0
      function(aResult) {
        FileUtils.closeSafeFileOutputStream(oStream);
        saving = false;

        if (!components.isSuccessCode(aResult)) {
          reject();
        }
        else {
          resolve({
            data: data,
            charset: charset
          });
        }
      }
Пример #4
0
 onStartRequest: function (req /*, ctx*/) {
   var channel = req.QueryInterface(Ci.nsIChannel);
   if (!((channel instanceof Ci.nsIHttpChannel)
     && components.isSuccessCode(channel.status)
     && channel.responseStatus === 200))
   {
     throw new Error("cancel"); //req.cancel(NS_BINDING_ABORTED);
   }
   stream_ctx.contentLength = channel.contentLength || -1;
   fg.log("SWF content length: " + stream_ctx.contentLength);
   stream_ctx.bstream = Cc["@mozilla.org/binaryinputstream;1"]
     .createInstance(Ci.nsIBinaryInputStream);
   st = Date.now();
 },
Пример #5
0
      (inputStream, statusCode, request) => {
        if (!components.isSuccessCode(statusCode)) {
          callback(null);
          return;
        }

        // Try to get the encoding from the channel. If there is none, then use
        // the passed assumed charset.
        let requestChannel = request.QueryInterface(Ci.nsIChannel);
        let contentCharset = requestChannel.contentCharset || charset;

        // Read the content of the stream using contentCharset as encoding.
        callback(this.readAndConvertFromStream(inputStream, contentCharset));
      });
Пример #6
0
    NetUtil.asyncFetch(channel, (aInputStream, aStatusCode, aRequest) => {
      if (!components.isSuccessCode(aStatusCode)) {
        aCallback(null);
        return;
      }

      // Try to get the encoding from the channel. If there is none, then use
      // the passed assumed aCharset.
      let aChannel = aRequest.QueryInterface(Ci.nsIChannel);
      let contentCharset = aChannel.contentCharset || aCharset;

      // Read the content of the stream using contentCharset as encoding.
      aCallback(this.readAndConvertFromStream(aInputStream, contentCharset));
    });
Пример #7
0
function Magnet_ProtocolWrapper(cb)
{
        var myHandler = function() {};

        myHandler.prototype = {
                QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]),

                _xpcom_factory: {
                        singleton: null,
                        createInstance: function (aOuter, aIID) {
                                if (aOuter) throw components.results.NS_ERROR_NO_AGGREGATION;

                                if (!this.singleton) this.singleton = new myHandler();
                                return this.singleton.QueryInterface(aIID);
                        }
                  },

                // nsIProtocolHandler implementation:

                // default attributes
                protocolFlags : Ci.nsIProtocolHandler.URI_LOADABLE_BY_ANYONE,
                defaultPort : -1,

                newURI : function(aSpec, aCharset, aBaseURI)
                {
                        var uri = Cc["@mozilla.org/network/simple-uri;1"].createInstance(Ci.nsIURI);
                        uri.spec = aSpec;
                        return uri;
                },

                newChannel : function(aURI)
                {
                        cb(aURI);

                        // create dummy nsIURI and nsIChannel instances
                        var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
                        return ios.newChannel("javascript:void()", null, null);
                },
                scheme : "magnet",
                classDescription : "Torrent Magnet Handler",
                classID : components.ID( "{cf027d00-ffe4-11e3-9191-0800200c9a66}" ),
                contractID : "@mozilla.org/network/protocol;1?name=magnet"
        }

        return myHandler;
}
        NetUtil.asyncCopy(istream, ostream, function(status) {
        	
        	if (!components.isSuccessCode(status)) {
        		
        		if (Preference.get('showNotifications')){
        			
        			Notification.sendMsg("saveError_id", file.path);        			
        		}

        	}else{
        		
        		if (Preference.get('showNotifications')){
        			
        			Notification.sendMsg("saveComplete_id", file.path);
        		}
        	}
        });
 var fetchCallback = function (inputStream, status) {
     if (components.isSuccessCode(status)) {
         try {
             var data = NetUtil.readInputStreamToString(inputStream, inputStream.available());
             data = converter.ConvertToUnicode(data);
             var lines = data.split(/[\r\n]+/);
             if (!data) {
                 callback(null, []);
                 return;
             }
             callback(null, lines);
         } catch (ex) {
             callback(ex);
         }
     } else {
         callback(status);
     }
 };
Пример #10
0
    NetUtil.asyncCopy(istream, stream, function (result) {
        let err = components.isSuccessCode(result) ? undefined :
        new Error("An error occured while writing to the stream: " + result);
      if (err)
        console.error(err);

      // asyncCopy() closes its output (and input) stream.
      manager.opened = false;

      if (typeof(callback) === "function") {
        try {
          callback.call(self, err);
        }
        catch (exc) {
          console.exception(exc);
        }
      }
    });
Пример #11
0
  NetUtil.asyncFetch(certfile, function(inputStream, status) {
    if (!components.isSuccessCode(status)) {
      var msg = "Error reading file: " +
                "status=" + status + " " +
                "baseDirId=" + baseDirId + " " +
                "certPathComponents=" + certPathComponents;
      throw new Error(msg);
    }

    var cert = NetUtil.readInputStreamToString(inputStream, inputStream.available());
    cert = cert.replace(/[\r\n]/g, "");
    var BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
    var END_CERT = "-----END CERTIFICATE-----";
    var begin = cert.indexOf(BEGIN_CERT);
    var end = cert.indexOf(END_CERT);
    cert = cert.substring(begin + BEGIN_CERT.length, end);
    certDB.addCertFromBase64(cert, certTrust, "");
  });
Пример #12
0
    NetUtil.asyncFetch(channel, function(iStream, aResult) {
      if (!components.isSuccessCode(aResult)) {
        reject();
      }
      else {
        let text = NetUtil.readInputStreamToString(iStream, iStream.available());

        let conv = Instances.suc;
        conv.charset = charset;

        text = conv.ConvertToUnicode(text);

        resolve({
          data: text,
          charset: charset
        });
      }
    });
Пример #13
0
function onIconDownloaded(nativeShell, mimeType, aStatusCode, icon) {
  if(nativeShell.isInstallAborted) {
    nativeShell.removeInstallation();
    return;
  }
  if (!components.isSuccessCode(aStatusCode)) {
    console.log("Attempt to retrieve icon returned result code "
              + aStatusCode);
    nativeShell.postIconProcessing();
    return;
  }
  try {
    nativeShell.processIcon(mimeType, icon);
  } catch(e) {
    console.log("Failure processing icon (" + e + ")");
    nativeShell.postIconProcessing();
  }
}
Пример #14
0
    onStopRequest: function (req, context, status) {
        try {
            var resp = {
                status: context.responseStatus
            };
            if (components.isSuccessCode(status)) {
                resp.body = this.body.join(" ");
            } else {
                var err = DatawakeHTTPHelper.lookupStatus(status);
                if (err !== null)
                    resp.error = err;
                else
                    resp.error = "error " + String(status);
            }
            this.callback(resp);

        } catch(e){
            console.error("Context Closed");
        }
    },
Пример #15
0
 NetUtil.asyncFetch(imageFile, (imageStream,result)=>{
   if (!components.isSuccessCode(result)) {
     console.warn("NetUtil.asyncFetch error! result:", result);
     return;
   }
   // Create temporary local file
   // (Required since I don't want to manually
   //  populate a GdkPixbuf...)
   tempIconFile.createUnique(
     Ci.nsIFile.NORMAL_FILE_TYPE,
     FileUtils.PERMS_FILE
   );
   let iconStream = FileUtils.openSafeFileOutputStream(tempIconFile);
   NetUtil.asyncCopy(imageStream, iconStream, function(result) {
     if (!components.isSuccessCode(result)) {
       console.log("NetUtil.asyncCopy error! result:", result);
       return;
     }
     GNotifier_AlertsService_showAlertNotification_cb(tempIconFile.path);
     iconStream.close();
     imageStream.close();
   });
 });
Пример #16
0
 onStopRequest: function (req, ctx, status) {
   ft = Date.now();
   stream_ctx.bstream = null;
   // SDASniffer::sniff0 is async, so we can't simply do if (SDASniffer.working) {clean up}.
   var cleanup = true;
   if (components.isSuccessCode(status)) {
     fg.log("SWF downloaded in " + (ft - st) + " ms, size: " + stream_ctx.bytes.length);
     if (stream_ctx.contentLength === -1 || stream_ctx.bytes.length === stream_ctx.contentLength) {
       SDASniffer.sniff0(stream_ctx, callback);
       cleanup = false;
     }
     else {
       fg.log("SWF content length mismatch: expected " + stream_ctx.contentLength + ", got " + stream_ctx.bytes.length);
     }
   }
   else {
     fg.log("Failed to download the SWF: status=" + status);
   }
   stream_ctx = null;
   if (cleanup) {
     SDASniffer.working = false;
     SDASniffer.callbacks = [];
   }
 }
Пример #17
0
exports.main = function() {
  // Initialize persistent data and defaults
  if (storage.autoBlockThreshold == null) {
    storage.autoBlockThreshold = DEFAULT_AUTO_BLOCK_THRESHOLD;
  }
  if (storage.blocked == null) {
    storage.blocked = {};
  }
  if (storage.trackers == null) {
    storage.trackers = {};
  }

  // Do some cleaning of single-site trackers to save some space
  unload.when(function() {
    Object.keys(storage.trackers).forEach(function(tracker) {
      if (Object.keys(storage.trackers[tracker]).length == 1) {
        delete storage.trackers[tracker];
      }
    });
  });

  // Initialize the tracked trackers with existing data
  Object.keys(storage.trackers).forEach(function(tracker) {
    Object.keys(storage.trackers[tracker]).forEach(function(tracked) {
      allTracked[tracked] = true;
    });
  });

  // Detect and block trackers with a content policy
  ({
    classDescription: "about:trackers content policy",
    classID: components.ID("d27de1fd-f2cc-4f84-be48-65d2510123b5"),
    contractID: "@mozilla.org/about-trackers/content-policy;1",
    QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPolicy, Ci.nsIFactory]),

    init: function() {
      let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
      registrar.registerFactory(this.classID, this.classDescription, this.contractID, this);

      let catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
      catMan.addCategoryEntry("content-policy", this.contractID, this.contractID, false, true);

      unload.when(function() {
        catMan.deleteCategoryEntry("content-policy", this.contractID, false);

        // This needs to run asynchronously, see bug 753687
        Services.tm.currentThread.dispatch(function() {
          registrar.unregisterFactory(this.classID, this);
        }.bind(this), Ci.nsIEventTarget.DISPATCH_NORMAL);
      }.bind(this));
    },

    shouldLoad: function(contentType, contentLocation, requestOrigin, context, mimeTypeGuess, extra) {
      // Allow everything temporarily when the user reloads
      if (acceptForReload) {
        return Ci.nsIContentPolicy.ACCEPT;
      }

      try {
        // Ignore top level browser document loads
        if (contentType == Ci.nsIContentPolicy.TYPE_DOCUMENT) {
          return Ci.nsIContentPolicy.ACCEPT;
        }

        // Return to normal behavior (not blocking) for private browsing windows
        let topWindow = (context.ownerDocument || context).defaultView.top;
        if (privateBrowsing.isPrivate(topWindow)) {
          return Ci.nsIContentPolicy.ACCEPT;
        }

        // Ignore requests that share a base domain
        let trackerDomain = Services.eTLD.getBaseDomain(contentLocation);
        let topLevel = topWindow.location.host;
        let contextDomain = Services.eTLD.getBaseDomainFromHost(topLevel);
        if (trackerDomain == contextDomain) {
          return Ci.nsIContentPolicy.ACCEPT;
        }

        // Always allow known not-tracking domains
        if (domainPrefs.knownNotTrackers[trackerDomain]) {
          return Ci.nsIContentPolicy.ACCEPT;
        }

        // We have a 3rd-party tracker, so initialize if it's new
        if (storage.trackers[trackerDomain] == null) {
           storage.trackers[trackerDomain] = {};
        }

        // Include this site as tracked and check for auto-block
        if (storage.trackers[trackerDomain][contextDomain] == null) {
          storage.trackers[trackerDomain][contextDomain] = 1;
          allTracked[contextDomain] = true;
          updateAutoBlock(trackerDomain);
        }

        // Check if this tracker should get cookies blocked
        if (storage.blocked[trackerDomain] == AUTO_BLOCK_COOKIE ||
            domainPrefs.potentialTrackers[trackerDomain]) {
          unCookieNext = contentLocation.spec;
          return Ci.nsIContentPolicy.ACCEPT;
        }
        // Block the connection for automatic and manual blocking
        else if (storage.blocked[trackerDomain]) {
          return Ci.nsIContentPolicy.REJECT_REQUEST;
        }
      }
      catch(ex) {}
      return Ci.nsIContentPolicy.ACCEPT;
    },

    shouldProcess: function(contentType, contentLocation, requestOrigin, context, mimeType, extra) {
      return Ci.nsIContentPolicy.ACCEPT;
    },

    createInstance: function(outer, iid) {
      if (outer) {
        throw Cr.NS_ERROR_NO_AGGREGATION;
      }
      return this.QueryInterface(iid);
    }
  }).init();

  // Keep track of the next url that should have cookies removed
  let unCookieNext = null;

  // Watch for requests that happen immediately after accepting from shouldLoad
  on("http-on-modify-request", unCookier = function({subject}) {
    // Nothing to do if there's no url to uncookie
    if (unCookieNext == null) {
      return;
    }

    // Remove the cookie header for the url that matches
    let httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
    if (httpChannel.originalURI.spec == unCookieNext) {
      httpChannel.setRequestHeader("cookie", "", false);
    }

    // Always clear if we got the request or not (cache hit = no request)
    unCookieNext = null;
  });

  // Handle about:trackers requests
  Factory({
    contract: "@mozilla.org/network/protocol/about;1?what=trackers",

    Component: Class({
      extends: Unknown,
      interfaces: ["nsIAboutModule"],

      getURIFlags: function(uri) {
        return 0;
      },

      newChannel: function(uri) {
        let chan = Services.io.newChannel(data.url("trackers.html"), null, null);
        chan.originalURI = uri;
        return chan;
      }
    })
  });

  // Add functionality into about:trackers page loads
  PageMod({
    contentScriptFile: [data.url("trackers.js")],
    include: ["about:trackers"],

    onAttach: function(worker) {
      // Build a mapping of which trackers have cookies
      let cookied = {};
      Object.keys(storage.trackers).forEach(function(tracker) {
        cookied[tracker] = isCookied(tracker);
      });

      // Update the page with stored values
      worker.port.emit("show_threshold", storage.autoBlockThreshold, CONNECTION_MULTIPLIER);
      worker.port.emit("show_trackers", storage.trackers, storage.blocked, cookied);

      // Allow clearing all custom settings and blockings
      worker.port.on("reset", function() {
        storage.autoBlockThreshold = DEFAULT_AUTO_BLOCK_THRESHOLD;
        storage.blocked = {};
        updateAllAutoBlocked(false);
      });

      // Save changes to the threshold
      worker.port.on("set_threshold", function(threshold) {
        storage.autoBlockThreshold = threshold;
        updateAllAutoBlocked(true);
      });

      // Save changes to the block status for a tracker
      worker.port.on("toggle_block", function(tracker) {
        storage.blocked[tracker] = +!storage.blocked[tracker];
        worker.port.emit("update_block", tracker, storage.blocked[tracker]);
      });

      // Update the auto-blocked state for all trackers and notify updates
      function updateAllAutoBlocked(notify) {
        Object.keys(storage.trackers).forEach(function(tracker) {
          // Update the UI for trackers if changed
          if (updateAutoBlock(tracker) && notify) {
            worker.port.emit("update_block", tracker, storage.blocked[tracker]);
          }
        });
      }
    }
  });

  // Detect if the user hits reload to temporarily disable blocking
  let acceptForReload = false;
  new WindowTracker({
    onReload: function(event) {
      acceptForReload = true;
      setTimeout(function() {
        acceptForReload = false;
      }, RELOAD_AUTO_ACCEPT_DURATION);
    },

    onTrack: function(window) {
      let reload = window.document.getElementById("Browser:Reload");
      if (reload != null) {
        reload.addEventListener("command", this.onReload);
      }
    },

    onUntrack: function(window) {
      let reload = window.document.getElementById("Browser:Reload");
      if (reload != null) {
        reload.removeEventListener("command", this.onReload);
      }
    }
  });

  // Watch for preference changes to list of domains
  let domainPrefs = {};
  const ALLOWED_API_PREF = "allowedAPIDomains";
  ["knownNotTrackers", "potentialTrackers"].forEach(function(pref) {
    Preferences.on(pref, updateDomains);
    function updateDomains() {
      domainPrefs[pref] = {};

      // Short circuit if there's nothing to do
      let userValue = Preferences.prefs[pref].trim();
      if (userValue == "") {
        return;
      }

      // Convert the array of domains to an object
      userValue.split(/\s*,\s*/).forEach(function(domain) {
        domainPrefs[pref][domain] = true;
      });
    }
    updateDomains();
  });
};
Пример #18
0
  let onResponse = (stream, status, request) => {
    if (!components.isSuccessCode(status)) {
      deferred.reject(new Error(`Failed to fetch ${url}. Code ${status}.`));
      return;
    }

    try {
      // We cannot use NetUtil to do the charset conversion as if charset
      // information is not available and our default guess is wrong the method
      // might fail and we lose the stream data. This means we can't fall back
      // to using the locale default encoding (bug 1181345).

      // Read and decode the data according to the locale default encoding.
      let available = stream.available();
      let source = NetUtil.readInputStreamToString(stream, available);
      stream.close();

      // We do our own BOM sniffing here because there's no convenient
      // implementation of the "decode" algorithm
      // (https://encoding.spec.whatwg.org/#decode) exposed to JS.
      let bomCharset = null;
      if (available >= 3 && source.codePointAt(0) == 0xef &&
          source.codePointAt(1) == 0xbb && source.codePointAt(2) == 0xbf) {
        bomCharset = "UTF-8";
        source = source.slice(3);
      } else if (available >= 2 && source.codePointAt(0) == 0xfe &&
                 source.codePointAt(1) == 0xff) {
        bomCharset = "UTF-16BE";
        source = source.slice(2);
      } else if (available >= 2 && source.codePointAt(0) == 0xff &&
                 source.codePointAt(1) == 0xfe) {
        bomCharset = "UTF-16LE";
        source = source.slice(2);
      }

      // If the channel or the caller has correct charset information, the
      // content will be decoded correctly. If we have to fall back to UTF-8 and
      // the guess is wrong, the conversion fails and convertToUnicode returns
      // the input unmodified. Essentially we try to decode the data as UTF-8
      // and if that fails, we use the locale specific default encoding. This is
      // the best we can do if the source does not provide charset info.
      let charset = bomCharset || channel.contentCharset || aOptions.charset || "UTF-8";
      let unicodeSource = NetworkHelper.convertToUnicode(source, charset);

      deferred.resolve({
        content: unicodeSource,
        contentType: request.contentType
      });
    } catch (ex) {
      let uri = request.originalURI;
      if (ex.name === "NS_BASE_STREAM_CLOSED" && uri instanceof Ci.nsIFileURL) {
        // Empty files cause NS_BASE_STREAM_CLOSED exception. Use OS.File to
        // differentiate between empty files and other errors (bug 1170864).
        // This can be removed when bug 982654 is fixed.

        uri.QueryInterface(Ci.nsIFileURL);
        let result = OS.File.read(uri.file.path).then(bytes => {
          // Convert the bytearray to a String.
          let decoder = new TextDecoder();
          let content = decoder.decode(bytes);

          // We can't detect the contentType without opening a channel
          // and that failed already. This is the best we can do here.
          return {
            content,
            contentType: "text/plain"
          };
        });

        deferred.resolve(result);
      } else {
        deferred.reject(ex);
      }
    }
  };
Пример #19
0
var factory;
const aboutDualViewDescription = 'About Dual View';
const aboutDualViewUUID = '7ad46da0-15c9-11e5-b939-0800200c9a66';
const aboutDualView_word = 'dualview';
const aboutDualView_page = "resource://FileSearch-at-tenneco-dot-com/data/viewer.html";

const aboutEPFViewerDescription = 'About EPF Viewer';
const aboutEPFViewerUUID = '7ad46da1-15c9-11e5-b939-0800200c9a66';
const aboutEPFViewer_word = 'epfviewer';
const aboutEPFViewer_page = "resource://FileSearch-at-tenneco-dot-com/data/EPFViewer.html";

function AboutDualView() {}
AboutDualView.prototype = Object.freeze({
    classDescription: aboutDualViewDescription,
    contractID: '@mozilla.org/network/protocol/about;1?what=' + aboutDualView_word,
    classID: components.ID('{' + aboutDualViewUUID + '}'),
    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),

    getURIFlags: function(aURI) {
        return Ci.nsIAboutModule.ALLOW_SCRIPT, Ci.nsIAboutModule.HIDE_FROM_ABOUTABOUT;
    },

    newChannel: function(aURI) {
        if (aURI.spec != "about:" + aboutDualView_word)
            return;

        let uri = Services.io.newURI(aboutDualView_page, null, null);
        return Services.io.newChannelFromURI(uri);
    }
});
 */

if (typeof chrome == "undefined") {
  var {Cm,Cc,Ci,Cr,Cu,components} = require("chrome");
  Cu.import("resource://gre/modules/XPCOMUtils.jsm");
}

let {Utils, onShutdown} = require("./utils");

/**
 * about: URL module used to count hits.
 * @class
 */
let AboutHandler = exports.AboutHandler =
{
  classID: components.ID("{55fb7be0-1dd2-11b2-98e6-9e97caf8ba67}"),
  classDescription: "Element hiding hit registration protocol handler",
  aboutPrefix: "abc-elemhidehit",

  /**
   * Registers handler on startup.
   */
  init: function()
  {
    let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
    registrar.registerFactory(this.classID, this.classDescription,
        "@mozilla.org/network/protocol/about;1?what=" + this.aboutPrefix, this);
    onShutdown.add(function()
    {
      registrar.unregisterFactory(this.classID, this);
    }.bind(this));
Пример #21
0
		NetUtil.asyncFetch(tmpFile, function(inputStream, status) {
			if (components.isSuccessCode(status)) {
				callback(NetUtil.readInputStreamToString(inputStream, inputStream.available()));
			}
			tmpFile.remove(false);
		});
Пример #22
0
let DNS_SERVICE = Cc['@mozilla.org/network/dns-service;1'].createInstance(Ci.nsIDNSService);

let SCHEME = 'd2';
let DOUBLE_SLASH = '//';

function get_fabric_url(fabric) {
  return url.d2_proxy_url[fabric];
}

let current_d2_proxy_url = get_fabric_url(fabrics.default_fabric);

function D2Protocol() {}
D2Protocol.prototype = {
  classDescription: 'D2 Protocol Handler',
  contractID: '@mozilla.org/network/protocol;1?name=' + SCHEME,
  classID: components.ID('{c2bd92c0-309d-11e4-8c21-0800200c9a66}'),
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]),

  defaultPort: -1,
  protocolFlags: Ci.nsIProtocolHandler.URI_NORELATIVE |
                 Ci.nsIProtocolHandler.URI_NOAUTH |
                 Ci.nsIProtocolHandler.URI_LOADABLE_BY_ANYONE,
  scheme: SCHEME,

  allowPort: function(port, scheme) {
    return false;
  },

  newChannel: function(aURI) {
    let path;
    if (aURI.path.startsWith(DOUBLE_SLASH)) {
Пример #23
0
    value += eol;

    var requestHeaders = headers.request;
    for (var i=0; i<requestHeaders.length; i++) {
      var header = requestHeaders[i];
      value += header.name + ": " + header.value + eol;
    }

    Clipboard.set(value, "text");
  }
});

// Stream converter component definition
var service = xpcom.Service({
  id: components.ID(CLASS_ID),
  contract: CONTRACT_ID,
  Component: Converter,
  register: false,
  unregister: false
});

function register() {
  if (!xpcom.isRegistered(service)) {
    xpcom.register(service);
    return true;
  }
  return false;
}

function unregister() {
Пример #24
0
var {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm");
var {Unknown, Factory} = require('sdk/platform/xpcom');
var {Class} = require('sdk/core/heritage');
var Request = require("sdk/request").Request;

var page_focus = false;
var get_user_id = function() { return localStorage['search_user_id'] };

var C_ADDRESSBAR_SEARCH = 100;
var C_FIREFOX_SEARCH    = 200;
var CURRENT_SEARCH      = C_ADDRESSBAR_SEARCH;

var contractId = "@disconnect.me/HttpRequest-Policy";
var disconnectSearch = Class({
  classDescription:   "Deferred To HTTP Requests Interceptor",
  classID:            components.ID("{CC9486AA-1E4E-4759-A976-B497268A6180}"),
  contractID:         contractId,
  _xpcom_categories:  [{category: "content-policy"}],
  QueryInterface:     XPCOMUtils.generateQI([Ci.nsIContentPolicy]),
  shouldLoad: shouldLoadFunction,
  shouldProcess: function(aContentType, aContentLocation, aRequestOrigin, aContext, aMimeType, aExtra, aRequestPrincipal) {
    return Ci.nsIContentPolicy.ACCEPT;
  }
});
var factory = Factory({ contract: contractId, Component: disconnectSearch });

var httpRequestObserver = { 
  observe: function(subject, topic, data) {
    var channel = subject;
    //console.log("Got observer topic:", topic, channel);
        return requestProperties;
    }
};

/**
 * This objects manages HTTP requests filtering.
 *
 * It implements nsIContentPolicy and so it can block requests.
 * It also subscribes to the following events:
 * http-on-examine-response, http-on-examine-cached-response, http-on-examine-merged-response, http-on-opening-request
 */
var WebRequestImpl = exports.WebRequestImpl = {

    classDescription: "Adguard content policy",
    classID: components.ID("f5d18a88-c4b8-40ed-85cc-6cb3fd02268e"),
    contractID: "@adguard.com/adg/policy;1",
    xpcom_categories: ["content-policy", "net-channel-event-sinks"],

    antiBannerService: null,
    adguardApplication: null,
    ElemHide: null,
    framesMap: null,
    filteringLog: null,
    webRequestService: null,

    /**
     * Initialize WebRequest filtering, register is as events listener
     *
     * @param antiBannerService     AntiBannerService object (implements the filtering)
     * @param adguardApplication    AdguardApplication (used for integration with Adguard for Windows/Mac/Android)
Пример #26
0
// https://github.com/lidel/ipfs-firefox-addon/issues/36
function createWebVariant (target, base, uuid) {
  target.prototype = Object.create(base.prototype)
  target.prototype.constructor = target
  target.prototype.scheme = WEB_SCHEME_PREFIX + base.prototype.scheme
  target.prototype.classDescription = WEB_SCHEME_PREFIX + base.prototype.classDescription
  target.prototype.classID = components.ID(uuid)
  target.prototype.contractID = '@mozilla.org/network/protocol;1?name=' + target.prototype.scheme
  target.prototype.QueryInterface = XPCOMUtils.generateQI([Ci.nsIProtocolHandler])
}

IpfsProtocolHandler.prototype = Object.create(CommonProtocolHandler.prototype)
IpfsProtocolHandler.prototype.constructor = IpfsProtocolHandler
IpfsProtocolHandler.prototype.classDescription = 'ipfs Protocol Handler'
IpfsProtocolHandler.prototype.contractID = '@mozilla.org/network/protocol;1?name=' + IPFS_SCHEME
IpfsProtocolHandler.prototype.classID = components.ID('{34023afe-f3aa-4b3d-b546-cb66f6e14c4b}')
IpfsProtocolHandler.prototype.QueryInterface = XPCOMUtils.generateQI([Ci.nsIProtocolHandler])
IpfsProtocolHandler.prototype.scheme = IPFS_SCHEME
IpfsProtocolHandler.prototype.pathPrefix = IPFS_SCHEME + '/'
createWebVariant(WebIpfsProtocolHandler, IpfsProtocolHandler, '{713a4fe5-c5b8-43fa-a0c3-2742b3eea368}')

IpnsProtocolHandler.prototype = Object.create(CommonProtocolHandler.prototype)
IpnsProtocolHandler.prototype.constructor = IpnsProtocolHandler
IpnsProtocolHandler.prototype.classDescription = 'ipns Protocol Handler'
IpnsProtocolHandler.prototype.contractID = '@mozilla.org/network/protocol;1?name=' + IPNS_SCHEME
IpnsProtocolHandler.prototype.classID = components.ID('{33920c2c-dd6b-11e4-b9d6-1681e6b88ec1}')
IpnsProtocolHandler.prototype.QueryInterface = XPCOMUtils.generateQI([Ci.nsIProtocolHandler])
IpnsProtocolHandler.prototype.scheme = IPNS_SCHEME
IpnsProtocolHandler.prototype.pathPrefix = IPNS_SCHEME + '/'
createWebVariant(WebIpnsProtocolHandler, IpnsProtocolHandler, '{0f612fe4-5aa5-41ce-9fec-d827b702f5da}')
Пример #27
0
// Register about:devtools-toolbox which allows to open a devtools toolbox
// in a Firefox tab or a custom html iframe in browser.html

const { Ci, Cu, Cm, components } = require("chrome");
const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
const Services = require("Services");
const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
const { nsIAboutModule } = Ci;

function AboutURL() {}

AboutURL.prototype = {
  uri: Services.io.newURI("chrome://devtools/content/framework/toolbox.xul",
                          null, null),
  classDescription: "about:devtools-toolbox",
  classID: components.ID("11342911-3135-45a8-8d71-737a2b0ad469"),
  contractID: "@mozilla.org/network/protocol/about;1?what=devtools-toolbox",

  QueryInterface: XPCOMUtils.generateQI([nsIAboutModule]),

  newChannel: function(aURI, aLoadInfo) {
    let chan = Services.io.newChannelFromURIWithLoadInfo(this.uri, aLoadInfo);
    chan.owner = Services.scriptSecurityManager.getSystemPrincipal();
    return chan;
  },

  getURIFlags: function(aURI) {
    return nsIAboutModule.ALLOW_SCRIPT || nsIAboutModule.ENABLE_INDEXED_DB;
  }
};
Пример #28
0
"use strict";
let {components, Cc, Ci, Cm, Cr} = require("chrome");

//reference: https://developer.mozilla.org/en-US/docs/Custom_about:_URLs

Cm.QueryInterface(Ci.nsIComponentRegistrar);

function AboutCustom() {}
AboutCustom.prototype = Object.freeze({
    classDescription: 'BBSFox Preferences',
    contractID: '@mozilla.org/network/protocol/about;1?what=bbsfox',
    classID: components.ID('{be8771f0-2dbb-11e5-a2cb-0800200c9a66}'),
    QueryInterface: function QueryInterface(iid){
      if (iid.equals(Ci.nsIAboutModule))
        return this;
      else
        throw Cr.NS_ERROR_NO_INTERFACE;
    },

    getURIFlags: function(aURI) {
        return Ci.nsIAboutModule.ALLOW_SCRIPT;
    },

    newChannel: function(aURI, aSecurity_or_aLoadInfo) {
      if (! (aURI.spec === 'about:bbsfox') )
        return;

      let ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
      let uri = ios.newURI("chrome://bbsfox/content/options.xul", null, null);
      let channel = ios.newChannelFromURIWithLoadInfo(uri, aSecurity_or_aLoadInfo);
      channel.originalURI = aURI;
 function (status) {
   if (!components.isSuccessCode(status)) {
     d.reject(Error('Segment write error.'));
   }
   d.resolve(true);
 }
Пример #30
0
            console.log("unable to parse date");
          }
          //console.log("scanner got data "+JSON.stringify(data));
          scanner.args.data = data;
          scanner.worker.port.emit("account-refresh", scanner.args);
          worker.port.emit('signout');
          page.destroy();
          thePage.destroy();
        });
      }
    });
  }

}

const AboutAwardsUUID = components.ID("{03e7c639-aa1f-f040-b6d2-910c9adaa297}");
const AboutAwardsContract = "@mozilla.org/network/protocol/about;1?what=awards";
let AboutAwardsFactory = {
  createInstance: function(outer, iid) {
    if (outer != null) throw Cr.NS_ERROR_NO_AGGREGATION;
    return AboutAwards.QueryInterface(iid);
  }
};
let AboutAwards = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),

  getURIFlags: function(aURI) {
    return Ci.nsIAboutModule.ALLOW_SCRIPT;
  },

  newChannel: function(aURI) {