summaryrefslogtreecommitdiffstats
path: root/toolkit/components/search
diff options
context:
space:
mode:
Diffstat (limited to 'toolkit/components/search')
-rw-r--r--toolkit/components/search/SearchStaticData.jsm43
-rw-r--r--toolkit/components/search/SearchSuggestionController.jsm398
-rw-r--r--toolkit/components/search/moz.build33
-rw-r--r--toolkit/components/search/nsSearchService.js4789
-rw-r--r--toolkit/components/search/nsSearchSuggestions.js197
-rw-r--r--toolkit/components/search/nsSidebar.js66
-rw-r--r--toolkit/components/search/tests/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/search/tests/xpcshell/data/chrome.manifest3
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-addon.xml8
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-app.xml9
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-chromeicon.xml9
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-fr.xml12
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-override.xml8
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-pref.xml9
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-rel-searchform-post.xml6
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-rel-searchform-purpose.xml11
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-rel-searchform.xml5
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-resourceicon.xml9
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-system-purpose.xml10
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine-update.xml10
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine.xml25
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engine2.xml9
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engineImages.xml22
-rw-r--r--toolkit/components/search/tests/xpcshell/data/engineMaker.sjs54
-rw-r--r--toolkit/components/search/tests/xpcshell/data/ico-size-16x16-png.icobin0 -> 901 bytes
-rw-r--r--toolkit/components/search/tests/xpcshell/data/install.rdf23
-rw-r--r--toolkit/components/search/tests/xpcshell/data/invalid-engine.xml1
-rw-r--r--toolkit/components/search/tests/xpcshell/data/langpack-metadata.json5
-rw-r--r--toolkit/components/search/tests/xpcshell/data/list.json7
-rw-r--r--toolkit/components/search/tests/xpcshell/data/metadata.json30
-rw-r--r--toolkit/components/search/tests/xpcshell/data/search.json86
-rw-r--r--toolkit/components/search/tests/xpcshell/data/search.sqlitebin0 -> 65536 bytes
-rw-r--r--toolkit/components/search/tests/xpcshell/data/searchSuggestions.sjs78
-rw-r--r--toolkit/components/search/tests/xpcshell/data/searchTest.jarbin0 -> 1249 bytes
-rw-r--r--toolkit/components/search/tests/xpcshell/head_search.js544
-rw-r--r--toolkit/components/search/tests/xpcshell/test_645970.js22
-rw-r--r--toolkit/components/search/tests/xpcshell/test_SearchStaticData.js27
-rw-r--r--toolkit/components/search/tests/xpcshell/test_addEngineWithDetails.js34
-rw-r--r--toolkit/components/search/tests/xpcshell/test_addEngine_callback.js95
-rw-r--r--toolkit/components/search/tests/xpcshell/test_async.js34
-rw-r--r--toolkit/components/search/tests/xpcshell/test_async_addon.js33
-rw-r--r--toolkit/components/search/tests/xpcshell/test_async_addon_no_override.js33
-rw-r--r--toolkit/components/search/tests/xpcshell/test_async_distribution.js33
-rw-r--r--toolkit/components/search/tests/xpcshell/test_async_migration.js27
-rw-r--r--toolkit/components/search/tests/xpcshell/test_async_profile_engine.js42
-rw-r--r--toolkit/components/search/tests/xpcshell/test_bug930456.js11
-rw-r--r--toolkit/components/search/tests/xpcshell/test_bug930456_child.js3
-rw-r--r--toolkit/components/search/tests/xpcshell/test_chromeresource_icon1.js31
-rw-r--r--toolkit/components/search/tests/xpcshell/test_chromeresource_icon2.js23
-rw-r--r--toolkit/components/search/tests/xpcshell/test_currentEngine_fallback.js25
-rw-r--r--toolkit/components/search/tests/xpcshell/test_defaultEngine.js51
-rw-r--r--toolkit/components/search/tests/xpcshell/test_engineUpdate.js50
-rw-r--r--toolkit/components/search/tests/xpcshell/test_engine_set_alias.js80
-rw-r--r--toolkit/components/search/tests/xpcshell/test_geodefaults.js253
-rw-r--r--toolkit/components/search/tests/xpcshell/test_hasEngineWithURL.js135
-rw-r--r--toolkit/components/search/tests/xpcshell/test_hidden.js93
-rw-r--r--toolkit/components/search/tests/xpcshell/test_identifiers.js56
-rw-r--r--toolkit/components/search/tests/xpcshell/test_init_async_multiple.js55
-rw-r--r--toolkit/components/search/tests/xpcshell/test_init_async_multiple_then_sync.js68
-rw-r--r--toolkit/components/search/tests/xpcshell/test_invalid_engine_from_dir.js35
-rw-r--r--toolkit/components/search/tests/xpcshell/test_json_cache.js227
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location.js66
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location_error.js30
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location_funnelcake.js17
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location_malformed_json.js57
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location_migrate_countrycode_isUS.js24
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location_migrate_no_countrycode_isUS.js30
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location_migrate_no_countrycode_notUS.js30
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location_partner.js16
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location_sync.js101
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location_timeout.js78
-rw-r--r--toolkit/components/search/tests/xpcshell/test_location_timeout_xhr.js85
-rw-r--r--toolkit/components/search/tests/xpcshell/test_migration_langpack.js37
-rw-r--r--toolkit/components/search/tests/xpcshell/test_multipleIcons.js61
-rw-r--r--toolkit/components/search/tests/xpcshell/test_nocache.js60
-rw-r--r--toolkit/components/search/tests/xpcshell/test_nodb.js37
-rw-r--r--toolkit/components/search/tests/xpcshell/test_nodb_pluschanges.js57
-rw-r--r--toolkit/components/search/tests/xpcshell/test_notifications.js72
-rw-r--r--toolkit/components/search/tests/xpcshell/test_parseSubmissionURL.js148
-rw-r--r--toolkit/components/search/tests/xpcshell/test_pref.js36
-rw-r--r--toolkit/components/search/tests/xpcshell/test_purpose.js70
-rw-r--r--toolkit/components/search/tests/xpcshell/test_rel_searchform.js33
-rw-r--r--toolkit/components/search/tests/xpcshell/test_remove_profile_engine.js35
-rw-r--r--toolkit/components/search/tests/xpcshell/test_require_engines_in_cache.js74
-rw-r--r--toolkit/components/search/tests/xpcshell/test_resultDomain.js33
-rw-r--r--toolkit/components/search/tests/xpcshell/test_save_sorted_engines.js67
-rw-r--r--toolkit/components/search/tests/xpcshell/test_searchReset.js137
-rw-r--r--toolkit/components/search/tests/xpcshell/test_searchSuggest.js572
-rw-r--r--toolkit/components/search/tests/xpcshell/test_selectedEngine.js165
-rw-r--r--toolkit/components/search/tests/xpcshell/test_svg_icon.js52
-rw-r--r--toolkit/components/search/tests/xpcshell/test_sync.js27
-rw-r--r--toolkit/components/search/tests/xpcshell/test_sync_addon.js26
-rw-r--r--toolkit/components/search/tests/xpcshell/test_sync_addon_no_override.js26
-rw-r--r--toolkit/components/search/tests/xpcshell/test_sync_delay_fallback.js52
-rw-r--r--toolkit/components/search/tests/xpcshell/test_sync_distribution.js26
-rw-r--r--toolkit/components/search/tests/xpcshell/test_sync_fallback.js42
-rw-r--r--toolkit/components/search/tests/xpcshell/test_sync_migration.js29
-rw-r--r--toolkit/components/search/tests/xpcshell/test_sync_profile_engine.js35
-rw-r--r--toolkit/components/search/tests/xpcshell/test_update_telemetry.js36
-rw-r--r--toolkit/components/search/tests/xpcshell/xpcshell.ini102
-rw-r--r--toolkit/components/search/toolkitsearch.manifest10
101 files changed, 10793 insertions, 0 deletions
diff --git a/toolkit/components/search/SearchStaticData.jsm b/toolkit/components/search/SearchStaticData.jsm
new file mode 100644
index 000000000..de2be695c
--- /dev/null
+++ b/toolkit/components/search/SearchStaticData.jsm
@@ -0,0 +1,43 @@
+/* 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 module contains additional data about default search engines that is the
+ * same across all languages. This information is defined outside of the actual
+ * search engine definition files, so that localizers don't need to update them
+ * when a change is made.
+ *
+ * This separate module is also easily overridable, in case a hotfix is needed.
+ * No high-level processing logic is applied here.
+ */
+
+"use strict";
+
+this.EXPORTED_SYMBOLS = [
+ "SearchStaticData",
+];
+
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
+
+// To update this list of known alternate domains, just cut-and-paste from
+// https://www.google.com/supported_domains
+const gGoogleDomainsSource = ".google.com .google.ad .google.ae .google.com.af .google.com.ag .google.com.ai .google.al .google.am .google.co.ao .google.com.ar .google.as .google.at .google.com.au .google.az .google.ba .google.com.bd .google.be .google.bf .google.bg .google.com.bh .google.bi .google.bj .google.com.bn .google.com.bo .google.com.br .google.bs .google.bt .google.co.bw .google.by .google.com.bz .google.ca .google.cd .google.cf .google.cg .google.ch .google.ci .google.co.ck .google.cl .google.cm .google.cn .google.com.co .google.co.cr .google.com.cu .google.cv .google.com.cy .google.cz .google.de .google.dj .google.dk .google.dm .google.com.do .google.dz .google.com.ec .google.ee .google.com.eg .google.es .google.com.et .google.fi .google.com.fj .google.fm .google.fr .google.ga .google.ge .google.gg .google.com.gh .google.com.gi .google.gl .google.gm .google.gp .google.gr .google.com.gt .google.gy .google.com.hk .google.hn .google.hr .google.ht .google.hu .google.co.id .google.ie .google.co.il .google.im .google.co.in .google.iq .google.is .google.it .google.je .google.com.jm .google.jo .google.co.jp .google.co.ke .google.com.kh .google.ki .google.kg .google.co.kr .google.com.kw .google.kz .google.la .google.com.lb .google.li .google.lk .google.co.ls .google.lt .google.lu .google.lv .google.com.ly .google.co.ma .google.md .google.me .google.mg .google.mk .google.ml .google.com.mm .google.mn .google.ms .google.com.mt .google.mu .google.mv .google.mw .google.com.mx .google.com.my .google.co.mz .google.com.na .google.com.nf .google.com.ng .google.com.ni .google.ne .google.nl .google.no .google.com.np .google.nr .google.nu .google.co.nz .google.com.om .google.com.pa .google.com.pe .google.com.pg .google.com.ph .google.com.pk .google.pl .google.pn .google.com.pr .google.ps .google.pt .google.com.py .google.com.qa .google.ro .google.ru .google.rw .google.com.sa .google.com.sb .google.sc .google.se .google.com.sg .google.sh .google.si .google.sk .google.com.sl .google.sn .google.so .google.sm .google.sr .google.st .google.com.sv .google.td .google.tg .google.co.th .google.com.tj .google.tk .google.tl .google.tm .google.tn .google.to .google.com.tr .google.tt .google.com.tw .google.co.tz .google.com.ua .google.co.ug .google.co.uk .google.com.uy .google.co.uz .google.com.vc .google.co.ve .google.vg .google.co.vi .google.com.vn .google.vu .google.ws .google.rs .google.co.za .google.co.zm .google.co.zw .google.cat";
+const gGoogleDomains = gGoogleDomainsSource.split(" ").map(d => "www" + d);
+
+this.SearchStaticData = {
+ /**
+ * Returns a list of alternate domains for a given search engine domain.
+ *
+ * @param aDomain
+ * Lowercase host name to look up. For example, if this argument is
+ * "www.google.com" or "www.google.co.uk", the function returns the
+ * full list of supported Google domains.
+ *
+ * @return Array containing one entry for each alternate host name, or empty
+ * array if none is known. The returned array should not be modified.
+ */
+ getAlternateDomains: function (aDomain) {
+ return gGoogleDomains.indexOf(aDomain) == -1 ? [] : gGoogleDomains;
+ },
+};
diff --git a/toolkit/components/search/SearchSuggestionController.jsm b/toolkit/components/search/SearchSuggestionController.jsm
new file mode 100644
index 000000000..952838c0c
--- /dev/null
+++ b/toolkit/components/search/SearchSuggestionController.jsm
@@ -0,0 +1,398 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["SearchSuggestionController"];
+
+const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/Promise.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NS_ASSERT", "resource://gre/modules/debug.js");
+
+const SEARCH_RESPONSE_SUGGESTION_JSON = "application/x-suggestions+json";
+const DEFAULT_FORM_HISTORY_PARAM = "searchbar-history";
+const HTTP_OK = 200;
+const REMOTE_TIMEOUT = 500; // maximum time (ms) to wait before giving up on a remote suggestions
+const BROWSER_SUGGEST_PREF = "browser.search.suggest.enabled";
+
+/**
+ * Remote search suggestions will be shown if gRemoteSuggestionsEnabled
+ * is true. Global because only one pref observer is needed for all instances.
+ */
+var gRemoteSuggestionsEnabled = Services.prefs.getBoolPref(BROWSER_SUGGEST_PREF);
+Services.prefs.addObserver(BROWSER_SUGGEST_PREF, function(aSubject, aTopic, aData) {
+ gRemoteSuggestionsEnabled = Services.prefs.getBoolPref(BROWSER_SUGGEST_PREF);
+}, false);
+
+/**
+ * SearchSuggestionController.jsm exists as a helper module to allow multiple consumers to request and display
+ * search suggestions from a given engine, regardless of the base implementation. Much of this
+ * code was originally in nsSearchSuggestions.js until it was refactored to separate it from the
+ * nsIAutoCompleteSearch dependency.
+ * One instance of SearchSuggestionController should be used per field since form history results are cached.
+ */
+
+/**
+ * @param {function} [callback] - Callback for search suggestion results. You can use the promise
+ * returned by the search method instead if you prefer.
+ * @constructor
+ */
+this.SearchSuggestionController = function SearchSuggestionController(callback = null) {
+ this._callback = callback;
+};
+
+this.SearchSuggestionController.prototype = {
+ /**
+ * The maximum number of local form history results to return. This limit is
+ * only enforced if remote results are also returned.
+ */
+ maxLocalResults: 5,
+
+ /**
+ * The maximum number of remote search engine results to return.
+ * We'll actually only display at most
+ * maxRemoteResults - <displayed local results count> remote results.
+ */
+ maxRemoteResults: 10,
+
+ /**
+ * The maximum time (ms) to wait before giving up on a remote suggestions.
+ */
+ remoteTimeout: REMOTE_TIMEOUT,
+
+ /**
+ * The additional parameter used when searching form history.
+ */
+ formHistoryParam: DEFAULT_FORM_HISTORY_PARAM,
+
+ // Private properties
+ /**
+ * The last form history result used to improve the performance of subsequent searches.
+ * This shouldn't be used for any other purpose as it is never cleared and therefore could be stale.
+ */
+ _formHistoryResult: null,
+
+ /**
+ * The remote server timeout timer, if applicable. The timer starts when form history
+ * search is completed.
+ */
+ _remoteResultTimer: null,
+
+ /**
+ * The deferred for the remote results before its promise is resolved.
+ */
+ _deferredRemoteResult: null,
+
+ /**
+ * The optional result callback registered from the constructor.
+ */
+ _callback: null,
+
+ /**
+ * The XMLHttpRequest object for remote results.
+ */
+ _request: null,
+
+ // Public methods
+
+ /**
+ * Fetch search suggestions from all of the providers. Fetches in progress will be stopped and
+ * results from them will not be provided.
+ *
+ * @param {string} searchTerm - the term to provide suggestions for
+ * @param {bool} privateMode - whether the request is being made in the context of private browsing
+ * @param {nsISearchEngine} engine - search engine for the suggestions.
+ * @param {int} userContextId - the userContextId of the selected tab.
+ *
+ * @return {Promise} resolving to an object containing results or null.
+ */
+ fetch: function(searchTerm, privateMode, engine, userContextId) {
+ // There is no smart filtering from previous results here (as there is when looking through
+ // history/form data) because the result set returned by the server is different for every typed
+ // value - e.g. "ocean breathes" does not return a subset of the results returned for "ocean".
+
+ this.stop();
+
+ if (!Services.search.isInitialized) {
+ throw new Error("Search not initialized yet (how did you get here?)");
+ }
+ if (typeof privateMode === "undefined") {
+ throw new Error("The privateMode argument is required to avoid unintentional privacy leaks");
+ }
+ if (!(engine instanceof Ci.nsISearchEngine)) {
+ throw new Error("Invalid search engine");
+ }
+ if (!this.maxLocalResults && !this.maxRemoteResults) {
+ throw new Error("Zero results expected, what are you trying to do?");
+ }
+ if (this.maxLocalResults < 0 || this.maxRemoteResults < 0) {
+ throw new Error("Number of requested results must be positive");
+ }
+
+ // Array of promises to resolve before returning results.
+ let promises = [];
+ this._searchString = searchTerm;
+
+ // Remote results
+ if (searchTerm && gRemoteSuggestionsEnabled && this.maxRemoteResults &&
+ engine.supportsResponseType(SEARCH_RESPONSE_SUGGESTION_JSON)) {
+ this._deferredRemoteResult = this._fetchRemote(searchTerm, engine, privateMode, userContextId);
+ promises.push(this._deferredRemoteResult.promise);
+ }
+
+ // Local results from form history
+ if (this.maxLocalResults) {
+ let deferredHistoryResult = this._fetchFormHistory(searchTerm);
+ promises.push(deferredHistoryResult.promise);
+ }
+
+ function handleRejection(reason) {
+ if (reason == "HTTP request aborted") {
+ // Do nothing since this is normal.
+ return null;
+ }
+ Cu.reportError("SearchSuggestionController rejection: " + reason);
+ return null;
+ }
+ return Promise.all(promises).then(this._dedupeAndReturnResults.bind(this), handleRejection);
+ },
+
+ /**
+ * Stop pending fetches so no results are returned from them.
+ *
+ * Note: If there was no remote results fetched, the fetching cannot be stopped and local results
+ * will still be returned because stopping relies on aborting the XMLHTTPRequest to reject the
+ * promise for Promise.all.
+ */
+ stop: function() {
+ if (this._request) {
+ this._request.abort();
+ } else if (!this.maxRemoteResults) {
+ Cu.reportError("SearchSuggestionController: Cannot stop fetching if remote results were not "+
+ "requested");
+ }
+ this._reset();
+ },
+
+ // Private methods
+
+ _fetchFormHistory: function(searchTerm) {
+ let deferredFormHistory = Promise.defer();
+
+ let acSearchObserver = {
+ // Implements nsIAutoCompleteSearch
+ onSearchResult: (search, result) => {
+ this._formHistoryResult = result;
+
+ if (this._request) {
+ this._remoteResultTimer = Cc["@mozilla.org/timer;1"].
+ createInstance(Ci.nsITimer);
+ this._remoteResultTimer.initWithCallback(this._onRemoteTimeout.bind(this),
+ this.remoteTimeout || REMOTE_TIMEOUT,
+ Ci.nsITimer.TYPE_ONE_SHOT);
+ }
+
+ switch (result.searchResult) {
+ case Ci.nsIAutoCompleteResult.RESULT_SUCCESS:
+ case Ci.nsIAutoCompleteResult.RESULT_NOMATCH:
+ if (result.searchString !== this._searchString) {
+ deferredFormHistory.resolve("Unexpected response, this._searchString does not match form history response");
+ return;
+ }
+ let fhEntries = [];
+ for (let i = 0; i < result.matchCount; ++i) {
+ fhEntries.push(result.getValueAt(i));
+ }
+ deferredFormHistory.resolve({
+ result: fhEntries,
+ formHistoryResult: result,
+ });
+ break;
+ case Ci.nsIAutoCompleteResult.RESULT_FAILURE:
+ case Ci.nsIAutoCompleteResult.RESULT_IGNORED:
+ deferredFormHistory.resolve("Form History returned RESULT_FAILURE or RESULT_IGNORED");
+ break;
+ }
+ },
+ };
+
+ let formHistory = Cc["@mozilla.org/autocomplete/search;1?name=form-history"].
+ createInstance(Ci.nsIAutoCompleteSearch);
+ formHistory.startSearch(searchTerm, this.formHistoryParam || DEFAULT_FORM_HISTORY_PARAM,
+ this._formHistoryResult,
+ acSearchObserver);
+ return deferredFormHistory;
+ },
+
+ /**
+ * Fetch suggestions from the search engine over the network.
+ */
+ _fetchRemote: function(searchTerm, engine, privateMode, userContextId) {
+ let deferredResponse = Promise.defer();
+ this._request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
+ createInstance(Ci.nsIXMLHttpRequest);
+ let submission = engine.getSubmission(searchTerm,
+ SEARCH_RESPONSE_SUGGESTION_JSON);
+ let method = (submission.postData ? "POST" : "GET");
+ this._request.open(method, submission.uri.spec, true);
+
+ this._request.setOriginAttributes({userContextId,
+ privateBrowsingId: privateMode ? 1 : 0});
+
+ this._request.mozBackgroundRequest = true; // suppress dialogs and fail silently
+
+ this._request.addEventListener("load", this._onRemoteLoaded.bind(this, deferredResponse));
+ this._request.addEventListener("error", (evt) => deferredResponse.resolve("HTTP error"));
+ // Reject for an abort assuming it's always from .stop() in which case we shouldn't return local
+ // or remote results for existing searches.
+ this._request.addEventListener("abort", (evt) => deferredResponse.reject("HTTP request aborted"));
+
+ this._request.send(submission.postData);
+
+ return deferredResponse;
+ },
+
+ /**
+ * Called when the request completed successfully (thought the HTTP status could be anything)
+ * so we can handle the response data.
+ * @private
+ */
+ _onRemoteLoaded: function(deferredResponse) {
+ if (!this._request) {
+ deferredResponse.resolve("Got HTTP response after the request was cancelled");
+ return;
+ }
+
+ let status, serverResults;
+ try {
+ status = this._request.status;
+ } catch (e) {
+ // The XMLHttpRequest can throw NS_ERROR_NOT_AVAILABLE.
+ deferredResponse.resolve("Unknown HTTP status: " + e);
+ return;
+ }
+
+ if (status != HTTP_OK || this._request.responseText == "") {
+ deferredResponse.resolve("Non-200 status or empty HTTP response: " + status);
+ return;
+ }
+
+ try {
+ serverResults = JSON.parse(this._request.responseText);
+ } catch (ex) {
+ deferredResponse.resolve("Failed to parse suggestion JSON: " + ex);
+ return;
+ }
+
+ if (!serverResults[0] ||
+ this._searchString.localeCompare(serverResults[0], undefined,
+ { sensitivity: "base" })) {
+ // something is wrong here so drop remote results
+ deferredResponse.resolve("Unexpected response, this._searchString does not match remote response");
+ return;
+ }
+ let results = serverResults[1] || [];
+ deferredResponse.resolve({ result: results });
+ },
+
+ /**
+ * Called when this._remoteResultTimer fires indicating the remote request took too long.
+ */
+ _onRemoteTimeout: function () {
+ this._request = null;
+
+ // FIXME: bug 387341
+ // Need to break the cycle between us and the timer.
+ this._remoteResultTimer = null;
+
+ // The XMLHTTPRequest for suggest results is taking too long
+ // so send out the form history results and cancel the request.
+ if (this._deferredRemoteResult) {
+ this._deferredRemoteResult.resolve("HTTP Timeout");
+ this._deferredRemoteResult = null;
+ }
+ },
+
+ /**
+ * @param {Array} suggestResults - an array of result objects from different sources (local or remote)
+ * @return {Object}
+ */
+ _dedupeAndReturnResults: function(suggestResults) {
+ if (this._searchString === null) {
+ // _searchString can be null if stop() was called and remote suggestions
+ // were disabled (stopping if we are fetching remote suggestions will
+ // cause a promise rejection before we reach _dedupeAndReturnResults).
+ return null;
+ }
+
+ let results = {
+ term: this._searchString,
+ remote: [],
+ local: [],
+ formHistoryResult: null,
+ };
+
+ for (let result of suggestResults) {
+ if (typeof result === "string") { // Failure message
+ Cu.reportError("SearchSuggestionController: " + result);
+ } else if (result.formHistoryResult) { // Local results have a formHistoryResult property.
+ results.formHistoryResult = result.formHistoryResult;
+ results.local = result.result || [];
+ } else { // Remote result
+ results.remote = result.result || [];
+ }
+ }
+
+ // If we have remote results, cap the number of local results
+ if (results.remote.length) {
+ results.local = results.local.slice(0, this.maxLocalResults);
+ }
+
+ // We don't want things to appear in both history and suggestions so remove entries from
+ // remote results that are already in local.
+ if (results.remote.length && results.local.length) {
+ for (let i = 0; i < results.local.length; ++i) {
+ let term = results.local[i];
+ let dupIndex = results.remote.indexOf(term);
+ if (dupIndex != -1) {
+ results.remote.splice(dupIndex, 1);
+ }
+ }
+ }
+
+ // Trim the number of results to the maximum requested (now that we've pruned dupes).
+ results.remote =
+ results.remote.slice(0, this.maxRemoteResults - results.local.length);
+
+ if (this._callback) {
+ this._callback(results);
+ }
+ this._reset();
+
+ return results;
+ },
+
+ _reset: function() {
+ this._request = null;
+ if (this._remoteResultTimer) {
+ this._remoteResultTimer.cancel();
+ this._remoteResultTimer = null;
+ }
+ this._deferredRemoteResult = null;
+ this._searchString = null;
+ },
+};
+
+/**
+ * Determines whether the given engine offers search suggestions.
+ *
+ * @param {nsISearchEngine} engine - The search engine
+ * @return {boolean} True if the engine offers suggestions and false otherwise.
+ */
+this.SearchSuggestionController.engineOffersSuggestions = function(engine) {
+ return engine.supportsResponseType(SEARCH_RESPONSE_SUGGESTION_JSON);
+};
diff --git a/toolkit/components/search/moz.build b/toolkit/components/search/moz.build
new file mode 100644
index 000000000..98ccf2b8d
--- /dev/null
+++ b/toolkit/components/search/moz.build
@@ -0,0 +1,33 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
+
+EXTRA_COMPONENTS += [
+ 'nsSearchService.js',
+ 'nsSearchSuggestions.js',
+]
+
+if CONFIG['MOZ_BUILD_APP'] in ['browser', 'mobile/android', 'xulrunner']:
+ DEFINES['HAVE_SIDEBAR'] = True
+ EXTRA_COMPONENTS += [
+ 'nsSidebar.js',
+ ]
+
+EXTRA_JS_MODULES += [
+ 'SearchSuggestionController.jsm',
+]
+
+EXTRA_PP_COMPONENTS += [
+ 'toolkitsearch.manifest',
+]
+
+EXTRA_JS_MODULES += [
+ 'SearchStaticData.jsm',
+]
+
+with Files('**'):
+ BUG_COMPONENT = ('Firefox', 'Search')
diff --git a/toolkit/components/search/nsSearchService.js b/toolkit/components/search/nsSearchService.js
new file mode 100644
index 000000000..bbe66ba7e
--- /dev/null
+++ b/toolkit/components/search/nsSearchService.js
@@ -0,0 +1,4789 @@
+/* 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/. */
+
+const Ci = Components.interfaces;
+const Cc = Components.classes;
+const Cr = Components.results;
+const Cu = Components.utils;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/Promise.jsm");
+Cu.import("resource://gre/modules/debug.js");
+Cu.import("resource://gre/modules/AppConstants.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown",
+ "resource://gre/modules/AsyncShutdown.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "DeferredTask",
+ "resource://gre/modules/DeferredTask.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "OS",
+ "resource://gre/modules/osfile.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Task",
+ "resource://gre/modules/Task.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "TelemetryStopwatch",
+ "resource://gre/modules/TelemetryStopwatch.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Deprecated",
+ "resource://gre/modules/Deprecated.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "SearchStaticData",
+ "resource://gre/modules/SearchStaticData.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "setTimeout",
+ "resource://gre/modules/Timer.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "clearTimeout",
+ "resource://gre/modules/Timer.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Lz4",
+ "resource://gre/modules/lz4.js");
+
+XPCOMUtils.defineLazyServiceGetter(this, "gTextToSubURI",
+ "@mozilla.org/intl/texttosuburi;1",
+ "nsITextToSubURI");
+XPCOMUtils.defineLazyServiceGetter(this, "gEnvironment",
+ "@mozilla.org/process/environment;1",
+ "nsIEnvironment");
+
+Cu.importGlobalProperties(["XMLHttpRequest"]);
+
+// A text encoder to UTF8, used whenever we commit the cache to disk.
+XPCOMUtils.defineLazyGetter(this, "gEncoder",
+ function() {
+ return new TextEncoder();
+ });
+
+const MODE_RDONLY = 0x01;
+const MODE_WRONLY = 0x02;
+const MODE_CREATE = 0x08;
+const MODE_APPEND = 0x10;
+const MODE_TRUNCATE = 0x20;
+
+// Directory service keys
+const NS_APP_SEARCH_DIR_LIST = "SrchPluginsDL";
+const NS_APP_DISTRIBUTION_SEARCH_DIR_LIST = "SrchPluginsDistDL";
+const NS_APP_USER_SEARCH_DIR = "UsrSrchPlugns";
+const NS_APP_SEARCH_DIR = "SrchPlugns";
+const NS_APP_USER_PROFILE_50_DIR = "ProfD";
+
+// Loading plugins from NS_APP_SEARCH_DIR is no longer supported.
+// Instead, we now load plugins from APP_SEARCH_PREFIX, where a
+// list.txt file needs to exist to list available engines.
+const APP_SEARCH_PREFIX = "resource://search-plugins/";
+
+// See documentation in nsIBrowserSearchService.idl.
+const SEARCH_ENGINE_TOPIC = "browser-search-engine-modified";
+const QUIT_APPLICATION_TOPIC = "quit-application";
+
+const SEARCH_ENGINE_REMOVED = "engine-removed";
+const SEARCH_ENGINE_ADDED = "engine-added";
+const SEARCH_ENGINE_CHANGED = "engine-changed";
+const SEARCH_ENGINE_LOADED = "engine-loaded";
+const SEARCH_ENGINE_CURRENT = "engine-current";
+const SEARCH_ENGINE_DEFAULT = "engine-default";
+
+// The following constants are left undocumented in nsIBrowserSearchService.idl
+// For the moment, they are meant for testing/debugging purposes only.
+
+/**
+ * Topic used for events involving the service itself.
+ */
+const SEARCH_SERVICE_TOPIC = "browser-search-service";
+
+/**
+ * Sent whenever the cache is fully written to disk.
+ */
+const SEARCH_SERVICE_CACHE_WRITTEN = "write-cache-to-disk-complete";
+
+// Delay for lazy serialization (ms)
+const LAZY_SERIALIZE_DELAY = 100;
+
+// Delay for batching invalidation of the JSON cache (ms)
+const CACHE_INVALIDATION_DELAY = 1000;
+
+// Current cache version. This should be incremented if the format of the cache
+// file is modified.
+const CACHE_VERSION = 1;
+
+const CACHE_FILENAME = "search.json.mozlz4";
+
+const NEW_LINES = /(\r\n|\r|\n)/;
+
+// Set an arbitrary cap on the maximum icon size. Without this, large icons can
+// cause big delays when loading them at startup.
+const MAX_ICON_SIZE = 10000;
+
+// Default charset to use for sending search parameters. ISO-8859-1 is used to
+// match previous nsInternetSearchService behavior.
+const DEFAULT_QUERY_CHARSET = "ISO-8859-1";
+
+const SEARCH_BUNDLE = "chrome://global/locale/search/search.properties";
+const BRAND_BUNDLE = "chrome://branding/locale/brand.properties";
+
+const OPENSEARCH_NS_10 = "http://a9.com/-/spec/opensearch/1.0/";
+const OPENSEARCH_NS_11 = "http://a9.com/-/spec/opensearch/1.1/";
+
+// Although the specification at http://opensearch.a9.com/spec/1.1/description/
+// gives the namespace names defined above, many existing OpenSearch engines
+// are using the following versions. We therefore allow either.
+const OPENSEARCH_NAMESPACES = [
+ OPENSEARCH_NS_11, OPENSEARCH_NS_10,
+ "http://a9.com/-/spec/opensearchdescription/1.1/",
+ "http://a9.com/-/spec/opensearchdescription/1.0/"
+];
+
+const OPENSEARCH_LOCALNAME = "OpenSearchDescription";
+
+const MOZSEARCH_NS_10 = "http://www.mozilla.org/2006/browser/search/";
+const MOZSEARCH_LOCALNAME = "SearchPlugin";
+
+const URLTYPE_SUGGEST_JSON = "application/x-suggestions+json";
+const URLTYPE_SEARCH_HTML = "text/html";
+const URLTYPE_OPENSEARCH = "application/opensearchdescription+xml";
+
+const BROWSER_SEARCH_PREF = "browser.search.";
+const LOCALE_PREF = "general.useragent.locale";
+
+const USER_DEFINED = "{searchTerms}";
+
+// Custom search parameters
+const MOZ_OFFICIAL = AppConstants.MOZ_OFFICIAL_BRANDING ? "official" : "unofficial";
+
+const MOZ_PARAM_LOCALE = /\{moz:locale\}/g;
+const MOZ_PARAM_DIST_ID = /\{moz:distributionID\}/g;
+const MOZ_PARAM_OFFICIAL = /\{moz:official\}/g;
+
+// Supported OpenSearch parameters
+// See http://opensearch.a9.com/spec/1.1/querysyntax/#core
+const OS_PARAM_USER_DEFINED = /\{searchTerms\??\}/g;
+const OS_PARAM_INPUT_ENCODING = /\{inputEncoding\??\}/g;
+const OS_PARAM_LANGUAGE = /\{language\??\}/g;
+const OS_PARAM_OUTPUT_ENCODING = /\{outputEncoding\??\}/g;
+
+// Default values
+const OS_PARAM_LANGUAGE_DEF = "*";
+const OS_PARAM_OUTPUT_ENCODING_DEF = "UTF-8";
+const OS_PARAM_INPUT_ENCODING_DEF = "UTF-8";
+
+// "Unsupported" OpenSearch parameters. For example, we don't support
+// page-based results, so if the engine requires that we send the "page index"
+// parameter, we'll always send "1".
+const OS_PARAM_COUNT = /\{count\??\}/g;
+const OS_PARAM_START_INDEX = /\{startIndex\??\}/g;
+const OS_PARAM_START_PAGE = /\{startPage\??\}/g;
+
+// Default values
+const OS_PARAM_COUNT_DEF = "20"; // 20 results
+const OS_PARAM_START_INDEX_DEF = "1"; // start at 1st result
+const OS_PARAM_START_PAGE_DEF = "1"; // 1st page
+
+// Optional parameter
+const OS_PARAM_OPTIONAL = /\{(?:\w+:)?\w+\?\}/g;
+
+// A array of arrays containing parameters that we don't fully support, and
+// their default values. We will only send values for these parameters if
+// required, since our values are just really arbitrary "guesses" that should
+// give us the output we want.
+var OS_UNSUPPORTED_PARAMS = [
+ [OS_PARAM_COUNT, OS_PARAM_COUNT_DEF],
+ [OS_PARAM_START_INDEX, OS_PARAM_START_INDEX_DEF],
+ [OS_PARAM_START_PAGE, OS_PARAM_START_PAGE_DEF],
+];
+
+// The default engine update interval, in days. This is only used if an engine
+// specifies an updateURL, but not an updateInterval.
+const SEARCH_DEFAULT_UPDATE_INTERVAL = 7;
+
+// The default interval before checking again for the name of the
+// default engine for the region, in seconds. Only used if the response
+// from the server doesn't specify an interval.
+const SEARCH_GEO_DEFAULT_UPDATE_INTERVAL = 2592000; // 30 days.
+
+this.__defineGetter__("FileUtils", function() {
+ delete this.FileUtils;
+ Components.utils.import("resource://gre/modules/FileUtils.jsm");
+ return FileUtils;
+});
+
+this.__defineGetter__("NetUtil", function() {
+ delete this.NetUtil;
+ Components.utils.import("resource://gre/modules/NetUtil.jsm");
+ return NetUtil;
+});
+
+this.__defineGetter__("gChromeReg", function() {
+ delete this.gChromeReg;
+ return this.gChromeReg = Cc["@mozilla.org/chrome/chrome-registry;1"].
+ getService(Ci.nsIChromeRegistry);
+});
+
+/**
+ * Prefixed to all search debug output.
+ */
+const SEARCH_LOG_PREFIX = "*** Search: ";
+
+/**
+ * Outputs aText to the JavaScript console as well as to stdout.
+ */
+function DO_LOG(aText) {
+ dump(SEARCH_LOG_PREFIX + aText + "\n");
+ Services.console.logStringMessage(aText);
+}
+
+/**
+ * In debug builds, use a live, pref-based (browser.search.log) LOG function
+ * to allow enabling/disabling without a restart. Otherwise, don't log at all by
+ * default. This can be overridden at startup by the pref, see SearchService's
+ * _init method.
+ */
+var LOG = function() {};
+
+if (AppConstants.DEBUG) {
+ LOG = function (aText) {
+ if (getBoolPref(BROWSER_SEARCH_PREF + "log", false)) {
+ DO_LOG(aText);
+ }
+ };
+}
+
+/**
+ * Presents an assertion dialog in non-release builds and throws.
+ * @param message
+ * A message to display
+ * @param resultCode
+ * The NS_ERROR_* value to throw.
+ * @throws resultCode
+ */
+function ERROR(message, resultCode) {
+ NS_ASSERT(false, SEARCH_LOG_PREFIX + message);
+ throw Components.Exception(message, resultCode);
+}
+
+/**
+ * Logs the failure message (if browser.search.log is enabled) and throws.
+ * @param message
+ * A message to display
+ * @param resultCode
+ * The NS_ERROR_* value to throw.
+ * @throws resultCode or NS_ERROR_INVALID_ARG if resultCode isn't specified.
+ */
+function FAIL(message, resultCode) {
+ LOG(message);
+ throw Components.Exception(message, resultCode || Cr.NS_ERROR_INVALID_ARG);
+}
+
+/**
+ * Truncates big blobs of (data-)URIs to console-friendly sizes
+ * @param str
+ * String to tone down
+ * @param len
+ * Maximum length of the string to return. Defaults to the length of a tweet.
+ */
+function limitURILength(str, len) {
+ len = len || 140;
+ if (str.length > len)
+ return str.slice(0, len) + "...";
+ return str;
+}
+
+/**
+ * Ensures an assertion is met before continuing. Should be used to indicate
+ * fatal errors.
+ * @param assertion
+ * An assertion that must be met
+ * @param message
+ * A message to display if the assertion is not met
+ * @param resultCode
+ * The NS_ERROR_* value to throw if the assertion is not met
+ * @throws resultCode
+ */
+function ENSURE_WARN(assertion, message, resultCode) {
+ NS_ASSERT(assertion, SEARCH_LOG_PREFIX + message);
+ if (!assertion)
+ throw Components.Exception(message, resultCode);
+}
+
+function loadListener(aChannel, aEngine, aCallback) {
+ this._channel = aChannel;
+ this._bytes = [];
+ this._engine = aEngine;
+ this._callback = aCallback;
+}
+loadListener.prototype = {
+ _callback: null,
+ _channel: null,
+ _countRead: 0,
+ _engine: null,
+ _stream: null,
+
+ QueryInterface: XPCOMUtils.generateQI([
+ Ci.nsIRequestObserver,
+ Ci.nsIStreamListener,
+ Ci.nsIChannelEventSink,
+ Ci.nsIInterfaceRequestor,
+ // See FIXME comment below.
+ Ci.nsIHttpEventSink,
+ Ci.nsIProgressEventSink
+ ]),
+
+ // nsIRequestObserver
+ onStartRequest: function SRCH_loadStartR(aRequest, aContext) {
+ LOG("loadListener: Starting request: " + aRequest.name);
+ this._stream = Cc["@mozilla.org/binaryinputstream;1"].
+ createInstance(Ci.nsIBinaryInputStream);
+ },
+
+ onStopRequest: function SRCH_loadStopR(aRequest, aContext, aStatusCode) {
+ LOG("loadListener: Stopping request: " + aRequest.name);
+
+ var requestFailed = !Components.isSuccessCode(aStatusCode);
+ if (!requestFailed && (aRequest instanceof Ci.nsIHttpChannel))
+ requestFailed = !aRequest.requestSucceeded;
+
+ if (requestFailed || this._countRead == 0) {
+ LOG("loadListener: request failed!");
+ // send null so the callback can deal with the failure
+ this._callback(null, this._engine);
+ } else
+ this._callback(this._bytes, this._engine);
+ this._channel = null;
+ this._engine = null;
+ },
+
+ // nsIStreamListener
+ onDataAvailable: function SRCH_loadDAvailable(aRequest, aContext,
+ aInputStream, aOffset,
+ aCount) {
+ this._stream.setInputStream(aInputStream);
+
+ // Get a byte array of the data
+ this._bytes = this._bytes.concat(this._stream.readByteArray(aCount));
+ this._countRead += aCount;
+ },
+
+ // nsIChannelEventSink
+ asyncOnChannelRedirect: function SRCH_loadCRedirect(aOldChannel, aNewChannel,
+ aFlags, callback) {
+ this._channel = aNewChannel;
+ callback.onRedirectVerifyCallback(Components.results.NS_OK);
+ },
+
+ // nsIInterfaceRequestor
+ getInterface: function SRCH_load_GI(aIID) {
+ return this.QueryInterface(aIID);
+ },
+
+ // FIXME: bug 253127
+ // nsIHttpEventSink
+ onRedirect: function (aChannel, aNewChannel) {},
+ // nsIProgressEventSink
+ onProgress: function (aRequest, aContext, aProgress, aProgressMax) {},
+ onStatus: function (aRequest, aContext, aStatus, aStatusArg) {}
+}
+
+function isPartnerBuild() {
+ try {
+ let distroID = Services.prefs.getCharPref("distribution.id");
+
+ // Mozilla-provided builds (i.e. funnelcake) are not partner builds
+ if (distroID && !distroID.startsWith("mozilla")) {
+ return true;
+ }
+ } catch (e) {}
+
+ return false;
+}
+
+// Method to determine if we should be using geo-specific defaults
+function geoSpecificDefaultsEnabled() {
+ let geoSpecificDefaults = false;
+ try {
+ geoSpecificDefaults = Services.prefs.getBoolPref("browser.search.geoSpecificDefaults");
+ } catch (e) {}
+
+ return geoSpecificDefaults;
+}
+
+// Some notes on countryCode and region prefs:
+// * A "countryCode" pref is set via a geoip lookup. It always reflects the
+// result of that geoip request.
+// * A "region" pref, once set, is the region actually used for search. In
+// most cases it will be identical to the countryCode pref.
+// * The value of "region" and "countryCode" will only not agree in one edge
+// case - 34/35 users who have previously been configured to use US defaults
+// based purely on a timezone check will have "region" forced to US,
+// regardless of what countryCode geoip returns.
+// * We may want to know if we are in the US before we have *either*
+// countryCode or region - in which case we fallback to a timezone check,
+// but we don't persist that value anywhere in the expectation we will
+// eventually get a countryCode/region.
+
+// A method that "migrates" prefs if necessary.
+function migrateRegionPrefs() {
+ // If we already have a "region" pref there's nothing to do.
+ if (Services.prefs.prefHasUserValue("browser.search.region")) {
+ return;
+ }
+
+ // If we have 'isUS' but no 'countryCode' then we are almost certainly
+ // a profile from Fx 34/35 that set 'isUS' based purely on a timezone
+ // check. If this said they were US, we force region to be US.
+ // (But if isUS was false, we leave region alone - we will do a geoip request
+ // and set the region accordingly)
+ try {
+ if (Services.prefs.getBoolPref("browser.search.isUS") &&
+ !Services.prefs.prefHasUserValue("browser.search.countryCode")) {
+ Services.prefs.setCharPref("browser.search.region", "US");
+ }
+ } catch (ex) {
+ // no isUS pref, nothing to do.
+ }
+ // If we have a countryCode pref but no region pref, just force region
+ // to be the countryCode.
+ try {
+ let countryCode = Services.prefs.getCharPref("browser.search.countryCode");
+ if (!Services.prefs.prefHasUserValue("browser.search.region")) {
+ Services.prefs.setCharPref("browser.search.region", countryCode);
+ }
+ } catch (ex) {
+ // no countryCode pref, nothing to do.
+ }
+}
+
+// A method to determine if we are in the United States (US) for the search
+// service.
+// It uses a browser.search.region pref (which typically comes from a geoip
+// request) or if that doesn't exist, falls back to a hacky timezone check.
+function getIsUS() {
+ // Regardless of the region or countryCode, non en-US builds are not
+ // considered to be in the US from the POV of the search service.
+ if (getLocale() != "en-US") {
+ return false;
+ }
+
+ // If we've got a region pref, trust it.
+ try {
+ return Services.prefs.getCharPref("browser.search.region") == "US";
+ } catch (e) {}
+
+ // So we are en-US but have no region pref - fallback to hacky timezone check.
+ let isNA = isUSTimezone();
+ LOG("getIsUS() fell back to a timezone check with the result=" + isNA);
+ return isNA;
+}
+
+// Helper method to modify preference keys with geo-specific modifiers, if needed.
+function getGeoSpecificPrefName(basepref) {
+ if (!geoSpecificDefaultsEnabled() || isPartnerBuild())
+ return basepref;
+ if (getIsUS())
+ return basepref + ".US";
+ return basepref;
+}
+
+// A method that tries to determine if this user is in a US geography.
+function isUSTimezone() {
+ // Timezone assumptions! We assume that if the system clock's timezone is
+ // between Newfoundland and Hawaii, that the user is in North America.
+
+ // This includes all of South America as well, but we have relatively few
+ // en-US users there, so that's OK.
+
+ // 150 minutes = 2.5 hours (UTC-2.5), which is
+ // Newfoundland Daylight Time (http://www.timeanddate.com/time/zones/ndt)
+
+ // 600 minutes = 10 hours (UTC-10), which is
+ // Hawaii-Aleutian Standard Time (http://www.timeanddate.com/time/zones/hast)
+
+ let UTCOffset = (new Date()).getTimezoneOffset();
+ return UTCOffset >= 150 && UTCOffset <= 600;
+}
+
+// A less hacky method that tries to determine our country-code via an XHR
+// geoip lookup.
+// If this succeeds and we are using an en-US locale, we set the pref used by
+// the hacky method above, so isUS() can avoid the hacky timezone method.
+// If it fails we don't touch that pref so isUS() does its normal thing.
+var ensureKnownCountryCode = Task.async(function* (ss) {
+ // If we have a country-code already stored in our prefs we trust it.
+ let countryCode;
+ try {
+ countryCode = Services.prefs.getCharPref("browser.search.countryCode");
+ } catch (e) {}
+
+ if (!countryCode) {
+ // We don't have it cached, so fetch it. fetchCountryCode() will call
+ // storeCountryCode if it gets a result (even if that happens after the
+ // promise resolves) and fetchRegionDefault.
+ yield fetchCountryCode(ss);
+ } else {
+ // if nothing to do, return early.
+ if (!geoSpecificDefaultsEnabled())
+ return;
+
+ let expir = ss.getGlobalAttr("searchDefaultExpir") || 0;
+ if (expir > Date.now()) {
+ // The territory default we have already fetched hasn't expired yet.
+ // If we have a default engine or a list of visible default engines
+ // saved, the hashes should be valid, verify them now so that we can
+ // refetch if they have been tampered with.
+ let defaultEngine = ss.getVerifiedGlobalAttr("searchDefault");
+ let visibleDefaultEngines = ss.getVerifiedGlobalAttr("visibleDefaultEngines");
+ if ((defaultEngine || defaultEngine === undefined) &&
+ (visibleDefaultEngines || visibleDefaultEngines === undefined)) {
+ // No geo defaults, or valid hashes; nothing to do.
+ return;
+ }
+ }
+
+ yield new Promise(resolve => {
+ let timeoutMS = Services.prefs.getIntPref("browser.search.geoip.timeout");
+ let timerId = setTimeout(() => {
+ timerId = null;
+ resolve();
+ }, timeoutMS);
+
+ let callback = () => {
+ clearTimeout(timerId);
+ resolve();
+ };
+ fetchRegionDefault(ss).then(callback).catch(err => {
+ Components.utils.reportError(err);
+ callback();
+ });
+ });
+ }
+
+ // If gInitialized is true then the search service was forced to perform
+ // a sync initialization during our XHRs - capture this via telemetry.
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT").add(gInitialized);
+});
+
+// Store the result of the geoip request as well as any other values and
+// telemetry which depend on it.
+function storeCountryCode(cc) {
+ // Set the country-code itself.
+ Services.prefs.setCharPref("browser.search.countryCode", cc);
+ // And set the region pref if we don't already have a value.
+ if (!Services.prefs.prefHasUserValue("browser.search.region")) {
+ Services.prefs.setCharPref("browser.search.region", cc);
+ }
+ // and telemetry...
+ let isTimezoneUS = isUSTimezone();
+ if (cc == "US" && !isTimezoneUS) {
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_US_COUNTRY_MISMATCHED_TIMEZONE").add(1);
+ }
+ if (cc != "US" && isTimezoneUS) {
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_US_TIMEZONE_MISMATCHED_COUNTRY").add(1);
+ }
+ // telemetry to compare our geoip response with platform-specific country data.
+ // On Mac and Windows, we can get a country code via sysinfo
+ let platformCC = Services.sysinfo.get("countryCode");
+ if (platformCC) {
+ let probeUSMismatched, probeNonUSMismatched;
+ switch (Services.appinfo.OS) {
+ case "Darwin":
+ probeUSMismatched = "SEARCH_SERVICE_US_COUNTRY_MISMATCHED_PLATFORM_OSX";
+ probeNonUSMismatched = "SEARCH_SERVICE_NONUS_COUNTRY_MISMATCHED_PLATFORM_OSX";
+ break;
+ case "WINNT":
+ probeUSMismatched = "SEARCH_SERVICE_US_COUNTRY_MISMATCHED_PLATFORM_WIN";
+ probeNonUSMismatched = "SEARCH_SERVICE_NONUS_COUNTRY_MISMATCHED_PLATFORM_WIN";
+ break;
+ default:
+ Cu.reportError("Platform " + Services.appinfo.OS + " has system country code but no search service telemetry probes");
+ break;
+ }
+ if (probeUSMismatched && probeNonUSMismatched) {
+ if (cc == "US" || platformCC == "US") {
+ // one of the 2 said US, so record if they are the same.
+ Services.telemetry.getHistogramById(probeUSMismatched).add(cc != platformCC);
+ } else {
+ // different country - record if they are the same
+ Services.telemetry.getHistogramById(probeNonUSMismatched).add(cc != platformCC);
+ }
+ }
+ }
+}
+
+// Get the country we are in via a XHR geoip request.
+function fetchCountryCode(ss) {
+ // values for the SEARCH_SERVICE_COUNTRY_FETCH_RESULT 'enum' telemetry probe.
+ const TELEMETRY_RESULT_ENUM = {
+ SUCCESS: 0,
+ SUCCESS_WITHOUT_DATA: 1,
+ XHRTIMEOUT: 2,
+ ERROR: 3,
+ // Note that we expect to add finer-grained error types here later (eg,
+ // dns error, network error, ssl error, etc) with .ERROR remaining as the
+ // generic catch-all that doesn't fit into other categories.
+ };
+ let endpoint = Services.urlFormatter.formatURLPref("browser.search.geoip.url");
+ LOG("_fetchCountryCode starting with endpoint " + endpoint);
+ // As an escape hatch, no endpoint means no geoip.
+ if (!endpoint) {
+ return Promise.resolve();
+ }
+ let startTime = Date.now();
+ return new Promise(resolve => {
+ // Instead of using a timeout on the xhr object itself, we simulate one
+ // using a timer and let the XHR request complete. This allows us to
+ // capture reliable telemetry on what timeout value should actually be
+ // used to ensure most users don't see one while not making it so large
+ // that many users end up doing a sync init of the search service and thus
+ // would see the jank that implies.
+ // (Note we do actually use a timeout on the XHR, but that's set to be a
+ // large value just incase the request never completes - we don't want the
+ // XHR object to live forever)
+ let timeoutMS = Services.prefs.getIntPref("browser.search.geoip.timeout");
+ let geoipTimeoutPossible = true;
+ let timerId = setTimeout(() => {
+ LOG("_fetchCountryCode: timeout fetching country information");
+ if (geoipTimeoutPossible)
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_TIMEOUT").add(1);
+ timerId = null;
+ resolve();
+ }, timeoutMS);
+
+ let resolveAndReportSuccess = (result, reason) => {
+ // Even if we timed out, we want to save the country code and everything
+ // related so next startup sees the value and doesn't retry this dance.
+ if (result) {
+ storeCountryCode(result);
+ }
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_FETCH_RESULT").add(reason);
+
+ // This notification is just for tests...
+ Services.obs.notifyObservers(null, SEARCH_SERVICE_TOPIC, "geoip-lookup-xhr-complete");
+
+ if (timerId) {
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_TIMEOUT").add(0);
+ geoipTimeoutPossible = false;
+ }
+
+ let callback = () => {
+ // If we've already timed out then we've already resolved the promise,
+ // so there's nothing else to do.
+ if (timerId == null) {
+ return;
+ }
+ clearTimeout(timerId);
+ resolve();
+ };
+
+ if (result && geoSpecificDefaultsEnabled()) {
+ fetchRegionDefault(ss).then(callback).catch(err => {
+ Components.utils.reportError(err);
+ callback();
+ });
+ } else {
+ callback();
+ }
+ };
+
+ let request = new XMLHttpRequest();
+ // This notification is just for tests...
+ Services.obs.notifyObservers(request, SEARCH_SERVICE_TOPIC, "geoip-lookup-xhr-starting");
+ request.timeout = 100000; // 100 seconds as the last-chance fallback
+ request.onload = function(event) {
+ let took = Date.now() - startTime;
+ let cc = event.target.response && event.target.response.country_code;
+ LOG("_fetchCountryCode got success response in " + took + "ms: " + cc);
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS").add(took);
+ let reason = cc ? TELEMETRY_RESULT_ENUM.SUCCESS : TELEMETRY_RESULT_ENUM.SUCCESS_WITHOUT_DATA;
+ resolveAndReportSuccess(cc, reason);
+ };
+ request.ontimeout = function(event) {
+ LOG("_fetchCountryCode: XHR finally timed-out fetching country information");
+ resolveAndReportSuccess(null, TELEMETRY_RESULT_ENUM.XHRTIMEOUT);
+ };
+ request.onerror = function(event) {
+ LOG("_fetchCountryCode: failed to retrieve country information");
+ resolveAndReportSuccess(null, TELEMETRY_RESULT_ENUM.ERROR);
+ };
+ request.open("POST", endpoint, true);
+ request.setRequestHeader("Content-Type", "application/json");
+ request.responseType = "json";
+ request.send("{}");
+ });
+}
+
+// This will make an HTTP request to a Mozilla server that will return
+// JSON data telling us what engine should be set as the default for
+// the current region, and how soon we should check again.
+//
+// The optional cohort value returned by the server is to be kept locally
+// and sent to the server the next time we ping it. It lets the server
+// identify profiles that have been part of a specific experiment.
+//
+// This promise may take up to 100s to resolve, it's the caller's
+// responsibility to ensure with a timer that we are not going to
+// block the async init for too long.
+var fetchRegionDefault = (ss) => new Promise(resolve => {
+ let urlTemplate = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF)
+ .getCharPref("geoSpecificDefaults.url");
+ let endpoint = Services.urlFormatter.formatURL(urlTemplate);
+
+ // As an escape hatch, no endpoint means no region specific defaults.
+ if (!endpoint) {
+ resolve();
+ return;
+ }
+
+ // Append the optional cohort value.
+ const cohortPref = "browser.search.cohort";
+ let cohort;
+ try {
+ cohort = Services.prefs.getCharPref(cohortPref);
+ } catch (e) {}
+ if (cohort)
+ endpoint += "/" + cohort;
+
+ LOG("fetchRegionDefault starting with endpoint " + endpoint);
+
+ let startTime = Date.now();
+ let request = new XMLHttpRequest();
+ request.timeout = 100000; // 100 seconds as the last-chance fallback
+ request.onload = function(event) {
+ let took = Date.now() - startTime;
+
+ let status = event.target.status;
+ if (status != 200) {
+ LOG("fetchRegionDefault failed with HTTP code " + status);
+ let retryAfter = request.getResponseHeader("retry-after");
+ if (retryAfter) {
+ ss.setGlobalAttr("searchDefaultExpir", Date.now() + retryAfter * 1000);
+ }
+ resolve();
+ return;
+ }
+
+ let response = event.target.response || {};
+ LOG("received " + response.toSource());
+
+ if (response.cohort) {
+ Services.prefs.setCharPref(cohortPref, response.cohort);
+ } else {
+ Services.prefs.clearUserPref(cohortPref);
+ }
+
+ if (response.settings && response.settings.searchDefault) {
+ let defaultEngine = response.settings.searchDefault;
+ ss.setVerifiedGlobalAttr("searchDefault", defaultEngine);
+ LOG("fetchRegionDefault saved searchDefault: " + defaultEngine);
+ }
+
+ if (response.settings && response.settings.visibleDefaultEngines) {
+ let visibleDefaultEngines = response.settings.visibleDefaultEngines;
+ let string = visibleDefaultEngines.join(",");
+ ss.setVerifiedGlobalAttr("visibleDefaultEngines", string);
+ LOG("fetchRegionDefault saved visibleDefaultEngines: " + string);
+ }
+
+ let interval = response.interval || SEARCH_GEO_DEFAULT_UPDATE_INTERVAL;
+ let milliseconds = interval * 1000; // |interval| is in seconds.
+ ss.setGlobalAttr("searchDefaultExpir", Date.now() + milliseconds);
+
+ LOG("fetchRegionDefault got success response in " + took + "ms");
+ resolve();
+ };
+ request.ontimeout = function(event) {
+ LOG("fetchRegionDefault: XHR finally timed-out");
+ resolve();
+ };
+ request.onerror = function(event) {
+ LOG("fetchRegionDefault: failed to retrieve territory default information");
+ resolve();
+ };
+ request.open("GET", endpoint, true);
+ request.setRequestHeader("Content-Type", "application/json");
+ request.responseType = "json";
+ request.send();
+});
+
+function getVerificationHash(aName) {
+ let disclaimer = "By modifying this file, I agree that I am doing so " +
+ "only within $appName itself, using official, user-driven search " +
+ "engine selection processes, and in a way which does not circumvent " +
+ "user consent. I acknowledge that any attempt to change this file " +
+ "from outside of $appName is a malicious act, and will be responded " +
+ "to accordingly."
+
+ let salt = OS.Path.basename(OS.Constants.Path.profileDir) + aName +
+ disclaimer.replace(/\$appName/g, Services.appinfo.name);
+
+ let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
+ .createInstance(Ci.nsIScriptableUnicodeConverter);
+ converter.charset = "UTF-8";
+
+ // Data is an array of bytes.
+ let data = converter.convertToByteArray(salt, {});
+ let hasher = Cc["@mozilla.org/security/hash;1"]
+ .createInstance(Ci.nsICryptoHash);
+ hasher.init(hasher.SHA256);
+ hasher.update(data, data.length);
+
+ return hasher.finish(true);
+}
+
+/**
+ * Safely close a nsISafeOutputStream.
+ * @param aFOS
+ * The file output stream to close.
+ */
+function closeSafeOutputStream(aFOS) {
+ if (aFOS instanceof Ci.nsISafeOutputStream) {
+ try {
+ aFOS.finish();
+ return;
+ } catch (e) { }
+ }
+ aFOS.close();
+}
+
+/**
+ * Wrapper function for nsIIOService::newURI.
+ * @param aURLSpec
+ * The URL string from which to create an nsIURI.
+ * @returns an nsIURI object, or null if the creation of the URI failed.
+ */
+function makeURI(aURLSpec, aCharset) {
+ try {
+ return NetUtil.newURI(aURLSpec, aCharset);
+ } catch (ex) { }
+
+ return null;
+}
+
+/**
+ * Wrapper function for nsIIOService::newChannel2.
+ * @param url
+ * The URL string from which to create an nsIChannel.
+ * @returns an nsIChannel object, or null if the url is invalid.
+ */
+function makeChannel(url) {
+ try {
+ return NetUtil.newChannel({
+ uri: url,
+ loadUsingSystemPrincipal: true
+ });
+ } catch (ex) { }
+
+ return null;
+}
+
+/**
+ * Gets a directory from the directory service.
+ * @param aKey
+ * The directory service key indicating the directory to get.
+ */
+function getDir(aKey, aIFace) {
+ if (!aKey)
+ FAIL("getDir requires a directory key!");
+
+ return Services.dirsvc.get(aKey, aIFace || Ci.nsIFile);
+}
+
+/**
+ * Gets the current value of the locale. It's possible for this preference to
+ * be localized, so we have to do a little extra work here. Similar code
+ * exists in nsHttpHandler.cpp when building the UA string.
+ */
+function getLocale() {
+ let locale = getLocalizedPref(LOCALE_PREF);
+ if (locale)
+ return locale;
+
+ // Not localized.
+ return Services.prefs.getCharPref(LOCALE_PREF);
+}
+
+/**
+ * Wrapper for nsIPrefBranch::getComplexValue.
+ * @param aPrefName
+ * The name of the pref to get.
+ * @returns aDefault if the requested pref doesn't exist.
+ */
+function getLocalizedPref(aPrefName, aDefault) {
+ const nsIPLS = Ci.nsIPrefLocalizedString;
+ try {
+ return Services.prefs.getComplexValue(aPrefName, nsIPLS).data;
+ } catch (ex) {}
+
+ return aDefault;
+}
+
+/**
+ * Wrapper for nsIPrefBranch::getBoolPref.
+ * @param aPrefName
+ * The name of the pref to get.
+ * @returns aDefault if the requested pref doesn't exist.
+ */
+function getBoolPref(aName, aDefault) {
+ if (Services.prefs.getPrefType(aName) != Ci.nsIPrefBranch.PREF_BOOL)
+ return aDefault;
+ return Services.prefs.getBoolPref(aName);
+}
+
+/**
+ * @return a sanitized name to be used as a filename, or a random name
+ * if a sanitized name cannot be obtained (if aName contains
+ * no valid characters).
+ */
+function sanitizeName(aName) {
+ const maxLength = 60;
+ const minLength = 1;
+ var name = aName.toLowerCase();
+ name = name.replace(/\s+/g, "-");
+ name = name.replace(/[^-a-z0-9]/g, "");
+
+ // Use a random name if our input had no valid characters.
+ if (name.length < minLength)
+ name = Math.random().toString(36).replace(/^.*\./, '');
+
+ // Force max length.
+ return name.substring(0, maxLength);
+}
+
+/**
+ * Retrieve a pref from the search param branch.
+ *
+ * @param prefName
+ * The name of the pref.
+ **/
+function getMozParamPref(prefName) {
+ let branch = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF + "param.");
+ return encodeURIComponent(branch.getCharPref(prefName));
+}
+
+/**
+ * Notifies watchers of SEARCH_ENGINE_TOPIC about changes to an engine or to
+ * the state of the search service.
+ *
+ * @param aEngine
+ * The nsISearchEngine object to which the change applies.
+ * @param aVerb
+ * A verb describing the change.
+ *
+ * @see nsIBrowserSearchService.idl
+ */
+var gInitialized = false;
+function notifyAction(aEngine, aVerb) {
+ if (gInitialized) {
+ LOG("NOTIFY: Engine: \"" + aEngine.name + "\"; Verb: \"" + aVerb + "\"");
+ Services.obs.notifyObservers(aEngine, SEARCH_ENGINE_TOPIC, aVerb);
+ }
+}
+
+function parseJsonFromStream(aInputStream) {
+ const json = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
+ const data = json.decodeFromStream(aInputStream, aInputStream.available());
+ return data;
+}
+
+/**
+ * Simple object representing a name/value pair.
+ */
+function QueryParameter(aName, aValue, aPurpose) {
+ if (!aName || (aValue == null))
+ FAIL("missing name or value for QueryParameter!");
+
+ this.name = aName;
+ this.value = aValue;
+ this.purpose = aPurpose;
+}
+
+/**
+ * Perform OpenSearch parameter substitution on aParamValue.
+ *
+ * @param aParamValue
+ * A string containing OpenSearch search parameters.
+ * @param aSearchTerms
+ * The user-provided search terms. This string will inserted into
+ * aParamValue as the value of the OS_PARAM_USER_DEFINED parameter.
+ * This value must already be escaped appropriately - it is inserted
+ * as-is.
+ * @param aEngine
+ * The engine which owns the string being acted on.
+ *
+ * @see http://opensearch.a9.com/spec/1.1/querysyntax/#core
+ */
+function ParamSubstitution(aParamValue, aSearchTerms, aEngine) {
+ var value = aParamValue;
+
+ var distributionID = Services.appinfo.distributionID;
+ try {
+ distributionID = Services.prefs.getCharPref(BROWSER_SEARCH_PREF + "distributionID");
+ }
+ catch (ex) { }
+ var official = MOZ_OFFICIAL;
+ try {
+ if (Services.prefs.getBoolPref(BROWSER_SEARCH_PREF + "official"))
+ official = "official";
+ else
+ official = "unofficial";
+ }
+ catch (ex) { }
+
+ // Custom search parameters. These are only available to default search
+ // engines.
+ if (aEngine._isDefault) {
+ value = value.replace(MOZ_PARAM_LOCALE, getLocale());
+ value = value.replace(MOZ_PARAM_DIST_ID, distributionID);
+ value = value.replace(MOZ_PARAM_OFFICIAL, official);
+ }
+
+ // Insert the OpenSearch parameters we're confident about
+ value = value.replace(OS_PARAM_USER_DEFINED, aSearchTerms);
+ value = value.replace(OS_PARAM_INPUT_ENCODING, aEngine.queryCharset);
+ value = value.replace(OS_PARAM_LANGUAGE,
+ getLocale() || OS_PARAM_LANGUAGE_DEF);
+ value = value.replace(OS_PARAM_OUTPUT_ENCODING,
+ OS_PARAM_OUTPUT_ENCODING_DEF);
+
+ // Replace any optional parameters
+ value = value.replace(OS_PARAM_OPTIONAL, "");
+
+ // Insert any remaining required params with our default values
+ for (var i = 0; i < OS_UNSUPPORTED_PARAMS.length; ++i) {
+ value = value.replace(OS_UNSUPPORTED_PARAMS[i][0],
+ OS_UNSUPPORTED_PARAMS[i][1]);
+ }
+
+ return value;
+}
+
+/**
+ * Creates an engineURL object, which holds the query URL and all parameters.
+ *
+ * @param aType
+ * A string containing the name of the MIME type of the search results
+ * returned by this URL.
+ * @param aMethod
+ * The HTTP request method. Must be a case insensitive value of either
+ * "GET" or "POST".
+ * @param aTemplate
+ * The URL to which search queries should be sent. For GET requests,
+ * must contain the string "{searchTerms}", to indicate where the user
+ * entered search terms should be inserted.
+ * @param aResultDomain
+ * The root domain for this URL. Defaults to the template's host.
+ *
+ * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag
+ *
+ * @throws NS_ERROR_NOT_IMPLEMENTED if aType is unsupported.
+ */
+function EngineURL(aType, aMethod, aTemplate, aResultDomain) {
+ if (!aType || !aMethod || !aTemplate)
+ FAIL("missing type, method or template for EngineURL!");
+
+ var method = aMethod.toUpperCase();
+ var type = aType.toLowerCase();
+
+ if (method != "GET" && method != "POST")
+ FAIL("method passed to EngineURL must be \"GET\" or \"POST\"");
+
+ this.type = type;
+ this.method = method;
+ this.params = [];
+ this.rels = [];
+ // Don't serialize expanded mozparams
+ this.mozparams = {};
+
+ var templateURI = makeURI(aTemplate);
+ if (!templateURI)
+ FAIL("new EngineURL: template is not a valid URI!", Cr.NS_ERROR_FAILURE);
+
+ switch (templateURI.scheme) {
+ case "http":
+ case "https":
+ // Disable these for now, see bug 295018
+ // case "file":
+ // case "resource":
+ this.template = aTemplate;
+ break;
+ default:
+ FAIL("new EngineURL: template uses invalid scheme!", Cr.NS_ERROR_FAILURE);
+ }
+
+ // If no resultDomain was specified in the engine definition file, use the
+ // host from the template.
+ this.resultDomain = aResultDomain || templateURI.host;
+ // We never want to return a "www." prefix, so eventually strip it.
+ if (this.resultDomain.startsWith("www.")) {
+ this.resultDomain = this.resultDomain.substr(4);
+ }
+}
+EngineURL.prototype = {
+
+ addParam: function SRCH_EURL_addParam(aName, aValue, aPurpose) {
+ this.params.push(new QueryParameter(aName, aValue, aPurpose));
+ },
+
+ // Note: This method requires that aObj has a unique name or the previous MozParams entry with
+ // that name will be overwritten.
+ _addMozParam: function SRCH_EURL__addMozParam(aObj) {
+ aObj.mozparam = true;
+ this.mozparams[aObj.name] = aObj;
+ },
+
+ getSubmission: function SRCH_EURL_getSubmission(aSearchTerms, aEngine, aPurpose) {
+ var url = ParamSubstitution(this.template, aSearchTerms, aEngine);
+ // Default to searchbar if the purpose is not provided
+ var purpose = aPurpose || "searchbar";
+
+ // If a particular purpose isn't defined in the plugin, fallback to 'searchbar'.
+ if (!this.params.some(p => p.purpose !== undefined && p.purpose == purpose))
+ purpose = "searchbar";
+
+ // Create an application/x-www-form-urlencoded representation of our params
+ // (name=value&name=value&name=value)
+ var dataString = "";
+ for (var i = 0; i < this.params.length; ++i) {
+ var param = this.params[i];
+
+ // If this parameter has a purpose, only add it if the purpose matches
+ if (param.purpose !== undefined && param.purpose != purpose)
+ continue;
+
+ var value = ParamSubstitution(param.value, aSearchTerms, aEngine);
+
+ dataString += (i > 0 ? "&" : "") + param.name + "=" + value;
+ }
+
+ var postData = null;
+ if (this.method == "GET") {
+ // GET method requests have no post data, and append the encoded
+ // query string to the url...
+ if (url.indexOf("?") == -1 && dataString)
+ url += "?";
+ url += dataString;
+ } else if (this.method == "POST") {
+ // POST method requests must wrap the encoded text in a MIME
+ // stream and supply that as POSTDATA.
+ var stringStream = Cc["@mozilla.org/io/string-input-stream;1"].
+ createInstance(Ci.nsIStringInputStream);
+ stringStream.data = dataString;
+
+ postData = Cc["@mozilla.org/network/mime-input-stream;1"].
+ createInstance(Ci.nsIMIMEInputStream);
+ postData.addHeader("Content-Type", "application/x-www-form-urlencoded");
+ postData.addContentLength = true;
+ postData.setData(stringStream);
+ }
+
+ return new Submission(makeURI(url), postData);
+ },
+
+ _getTermsParameterName: function SRCH_EURL__getTermsParameterName() {
+ let queryParam = this.params.find(p => p.value == USER_DEFINED);
+ return queryParam ? queryParam.name : "";
+ },
+
+ _hasRelation: function SRC_EURL__hasRelation(aRel) {
+ return this.rels.some(e => e == aRel.toLowerCase());
+ },
+
+ _initWithJSON: function SRC_EURL__initWithJSON(aJson, aEngine) {
+ if (!aJson.params)
+ return;
+
+ this.rels = aJson.rels;
+
+ for (let i = 0; i < aJson.params.length; ++i) {
+ let param = aJson.params[i];
+ if (param.mozparam) {
+ if (param.condition == "pref") {
+ let value = getMozParamPref(param.pref);
+ this.addParam(param.name, value);
+ }
+ this._addMozParam(param);
+ }
+ else
+ this.addParam(param.name, param.value, param.purpose || undefined);
+ }
+ },
+
+ /**
+ * Creates a JavaScript object that represents this URL.
+ * @returns An object suitable for serialization as JSON.
+ **/
+ toJSON: function SRCH_EURL_toJSON() {
+ var json = {
+ template: this.template,
+ rels: this.rels,
+ resultDomain: this.resultDomain
+ };
+
+ if (this.type != URLTYPE_SEARCH_HTML)
+ json.type = this.type;
+ if (this.method != "GET")
+ json.method = this.method;
+
+ function collapseMozParams(aParam) {
+ return this.mozparams[aParam.name] || aParam;
+ }
+ json.params = this.params.map(collapseMozParams, this);
+
+ return json;
+ }
+};
+
+/**
+ * nsISearchEngine constructor.
+ * @param aLocation
+ * A nsILocalFile or nsIURI object representing the location of the
+ * search engine data file.
+ * @param aIsReadOnly
+ * Boolean indicating whether the engine should be treated as read-only.
+ */
+function Engine(aLocation, aIsReadOnly) {
+ this._readOnly = aIsReadOnly;
+ this._urls = [];
+ this._metaData = {};
+
+ let file, uri;
+ if (typeof aLocation == "string") {
+ this._shortName = aLocation;
+ } else if (aLocation instanceof Ci.nsILocalFile) {
+ if (!aIsReadOnly) {
+ // This is an engine that was installed in NS_APP_USER_SEARCH_DIR by a
+ // previous version. We are converting the file to an engine stored only
+ // in JSON, but we need to keep the reference to the profile file to
+ // remove it if the user ever removes the engine.
+ this._filePath = aLocation.persistentDescriptor;
+ }
+ file = aLocation;
+ } else if (aLocation instanceof Ci.nsIURI) {
+ switch (aLocation.scheme) {
+ case "https":
+ case "http":
+ case "ftp":
+ case "data":
+ case "file":
+ case "resource":
+ case "chrome":
+ uri = aLocation;
+ break;
+ default:
+ ERROR("Invalid URI passed to the nsISearchEngine constructor",
+ Cr.NS_ERROR_INVALID_ARG);
+ }
+ } else
+ ERROR("Engine location is neither a File nor a URI object",
+ Cr.NS_ERROR_INVALID_ARG);
+
+ if (!this._shortName) {
+ // If we don't have a shortName at this point, it's the first time we load
+ // this engine, so let's generate the shortName, id and loadPath values.
+ let shortName;
+ if (file) {
+ shortName = file.leafName;
+ }
+ else if (uri && uri instanceof Ci.nsIURL) {
+ if (aIsReadOnly || (gEnvironment.get("XPCSHELL_TEST_PROFILE_DIR") &&
+ uri.scheme == "resource")) {
+ shortName = uri.fileName;
+ }
+ }
+ if (shortName && shortName.endsWith(".xml")) {
+ this._shortName = shortName.slice(0, -4);
+ }
+ this._loadPath = this.getAnonymizedLoadPath(file, uri);
+
+ if (!shortName && !aIsReadOnly) {
+ // We are in the process of downloading and installing the engine.
+ // We'll have the shortName and id once we are done parsing it.
+ return;
+ }
+
+ // Build the id used for the legacy metadata storage, so that we
+ // can do a one-time import of data from old profiles.
+ if (this._isDefault ||
+ (uri && uri.spec.startsWith(APP_SEARCH_PREFIX))) {
+ // The second part of the check is to catch engines from language packs.
+ // They aren't default engines (because they aren't app-shipped), but we
+ // still need to give their id an [app] prefix for backward compat.
+ this._id = "[app]/" + this._shortName + ".xml";
+ }
+ else if (!aIsReadOnly) {
+ this._id = "[profile]/" + this._shortName + ".xml";
+ }
+ else {
+ // If the engine is neither a default one, nor a user-installed one,
+ // it must be extension-shipped, so use the full path as id.
+ LOG("Setting _id to full path for engine from " + this._loadPath);
+ this._id = file ? file.path : uri.spec;
+ }
+ }
+}
+
+Engine.prototype = {
+ // Data set by the user.
+ _metaData: null,
+ // The data describing the engine, in the form of an XML document element.
+ _data: null,
+ // Whether or not the engine is readonly.
+ _readOnly: true,
+ // Anonymized path of where we initially loaded the engine from.
+ // This will stay null for engines installed in the profile before we moved
+ // to a JSON storage.
+ _loadPath: null,
+ // The engine's description
+ _description: "",
+ // Used to store the engine to replace, if we're an update to an existing
+ // engine.
+ _engineToUpdate: null,
+ // Set to true if the engine has a preferred icon (an icon that should not be
+ // overridden by a non-preferred icon).
+ _hasPreferredIcon: null,
+ // The engine's name.
+ _name: null,
+ // The name of the charset used to submit the search terms.
+ _queryCharset: null,
+ // The engine's raw SearchForm value (URL string pointing to a search form).
+ __searchForm: null,
+ get _searchForm() {
+ return this.__searchForm;
+ },
+ set _searchForm(aValue) {
+ if (/^https?:/i.test(aValue))
+ this.__searchForm = aValue;
+ else
+ LOG("_searchForm: Invalid URL dropped for " + this._name ||
+ "the current engine");
+ },
+ // Whether to obtain user confirmation before adding the engine. This is only
+ // used when the engine is first added to the list.
+ _confirm: false,
+ // Whether to set this as the current engine as soon as it is loaded. This
+ // is only used when the engine is first added to the list.
+ _useNow: false,
+ // A function to be invoked when this engine object's addition completes (or
+ // fails). Only used for installation via addEngine.
+ _installCallback: null,
+ // The number of days between update checks for new versions
+ _updateInterval: null,
+ // The url to check at for a new update
+ _updateURL: null,
+ // The url to check for a new icon
+ _iconUpdateURL: null,
+ /* The extension ID if added by an extension. */
+ _extensionID: null,
+
+ /**
+ * Retrieves the data from the engine's file.
+ * The document element is placed in the engine's data field.
+ */
+ _initFromFile: function SRCH_ENG_initFromFile(file) {
+ if (!file || !file.exists())
+ FAIL("File must exist before calling initFromFile!", Cr.NS_ERROR_UNEXPECTED);
+
+ var fileInStream = Cc["@mozilla.org/network/file-input-stream;1"].
+ createInstance(Ci.nsIFileInputStream);
+
+ fileInStream.init(file, MODE_RDONLY, FileUtils.PERMS_FILE, false);
+
+ var domParser = Cc["@mozilla.org/xmlextras/domparser;1"].
+ createInstance(Ci.nsIDOMParser);
+ var doc = domParser.parseFromStream(fileInStream, "UTF-8",
+ file.fileSize,
+ "text/xml");
+
+ this._data = doc.documentElement;
+ fileInStream.close();
+
+ // Now that the data is loaded, initialize the engine object
+ this._initFromData();
+ },
+
+ /**
+ * Retrieves the data from the engine's file asynchronously.
+ * The document element is placed in the engine's data field.
+ *
+ * @param file The file to load the search plugin from.
+ *
+ * @returns {Promise} A promise, resolved successfully if initializing from
+ * data succeeds, rejected if it fails.
+ */
+ _asyncInitFromFile: Task.async(function* (file) {
+ if (!file || !(yield OS.File.exists(file.path)))
+ FAIL("File must exist before calling initFromFile!", Cr.NS_ERROR_UNEXPECTED);
+
+ let fileURI = NetUtil.ioService.newFileURI(file);
+ yield this._retrieveSearchXMLData(fileURI.spec);
+
+ // Now that the data is loaded, initialize the engine object
+ this._initFromData();
+ }),
+
+ /**
+ * Retrieves the engine data from a URI. Initializes the engine, flushes to
+ * disk, and notifies the search service once initialization is complete.
+ *
+ * @param uri The uri to load the search plugin from.
+ */
+ _initFromURIAndLoad: function SRCH_ENG_initFromURIAndLoad(uri) {
+ ENSURE_WARN(uri instanceof Ci.nsIURI,
+ "Must have URI when calling _initFromURIAndLoad!",
+ Cr.NS_ERROR_UNEXPECTED);
+
+ LOG("_initFromURIAndLoad: Downloading engine from: \"" + uri.spec + "\".");
+
+ var chan = NetUtil.newChannel({
+ uri: uri,
+ loadUsingSystemPrincipal: true
+ });
+
+ if (this._engineToUpdate && (chan instanceof Ci.nsIHttpChannel)) {
+ var lastModified = this._engineToUpdate.getAttr("updatelastmodified");
+ if (lastModified)
+ chan.setRequestHeader("If-Modified-Since", lastModified, false);
+ }
+ this._uri = uri;
+ var listener = new loadListener(chan, this, this._onLoad);
+ chan.notificationCallbacks = listener;
+ chan.asyncOpen2(listener);
+ },
+
+ /**
+ * Retrieves the engine data from a URI asynchronously and initializes it.
+ *
+ * @param uri The uri to load the search plugin from.
+ *
+ * @returns {Promise} A promise, resolved successfully if retrieveing data
+ * succeeds.
+ */
+ _asyncInitFromURI: Task.async(function* (uri) {
+ LOG("_asyncInitFromURI: Loading engine from: \"" + uri.spec + "\".");
+ yield this._retrieveSearchXMLData(uri.spec);
+ // Now that the data is loaded, initialize the engine object
+ this._initFromData();
+ }),
+
+ /**
+ * Retrieves the engine data for a given URI asynchronously.
+ *
+ * @returns {Promise} A promise, resolved successfully if retrieveing data
+ * succeeds.
+ */
+ _retrieveSearchXMLData: function SRCH_ENG__retrieveSearchXMLData(aURL) {
+ let deferred = Promise.defer();
+ let request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
+ createInstance(Ci.nsIXMLHttpRequest);
+ request.overrideMimeType("text/xml");
+ request.onload = (aEvent) => {
+ let responseXML = aEvent.target.responseXML;
+ this._data = responseXML.documentElement;
+ deferred.resolve();
+ };
+ request.onerror = function(aEvent) {
+ deferred.resolve();
+ };
+ request.open("GET", aURL, true);
+ request.send();
+
+ return deferred.promise;
+ },
+
+ _initFromURISync: function SRCH_ENG_initFromURISync(uri) {
+ ENSURE_WARN(uri instanceof Ci.nsIURI,
+ "Must have URI when calling _initFromURISync!",
+ Cr.NS_ERROR_UNEXPECTED);
+
+ ENSURE_WARN(uri.schemeIs("resource"), "_initFromURISync called for non-resource URI",
+ Cr.NS_ERROR_FAILURE);
+
+ LOG("_initFromURISync: Loading engine from: \"" + uri.spec + "\".");
+
+ var chan = NetUtil.newChannel({
+ uri: uri,
+ loadUsingSystemPrincipal: true
+ });
+
+ var stream = chan.open2();
+ var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
+ createInstance(Ci.nsIDOMParser);
+ var doc = parser.parseFromStream(stream, "UTF-8", stream.available(), "text/xml");
+
+ this._data = doc.documentElement;
+
+ // Now that the data is loaded, initialize the engine object
+ this._initFromData();
+ },
+
+ /**
+ * Attempts to find an EngineURL object in the set of EngineURLs for
+ * this Engine that has the given type string. (This corresponds to the
+ * "type" attribute in the "Url" node in the OpenSearch spec.)
+ * This method will return the first matching URL object found, or null
+ * if no matching URL is found.
+ *
+ * @param aType string to match the EngineURL's type attribute
+ * @param aRel [optional] only return URLs that with this rel value
+ */
+ _getURLOfType: function SRCH_ENG__getURLOfType(aType, aRel) {
+ for (var i = 0; i < this._urls.length; ++i) {
+ if (this._urls[i].type == aType && (!aRel || this._urls[i]._hasRelation(aRel)))
+ return this._urls[i];
+ }
+
+ return null;
+ },
+
+ _confirmAddEngine: function SRCH_SVC_confirmAddEngine() {
+ var stringBundle = Services.strings.createBundle(SEARCH_BUNDLE);
+ var titleMessage = stringBundle.GetStringFromName("addEngineConfirmTitle");
+
+ // Display only the hostname portion of the URL.
+ var dialogMessage =
+ stringBundle.formatStringFromName("addEngineConfirmation",
+ [this._name, this._uri.host], 2);
+ var checkboxMessage = null;
+ if (!getBoolPref(BROWSER_SEARCH_PREF + "noCurrentEngine", false))
+ checkboxMessage = stringBundle.GetStringFromName("addEngineAsCurrentText");
+
+ var addButtonLabel =
+ stringBundle.GetStringFromName("addEngineAddButtonLabel");
+
+ var ps = Services.prompt;
+ var buttonFlags = (ps.BUTTON_TITLE_IS_STRING * ps.BUTTON_POS_0) +
+ (ps.BUTTON_TITLE_CANCEL * ps.BUTTON_POS_1) +
+ ps.BUTTON_POS_0_DEFAULT;
+
+ var checked = {value: false};
+ // confirmEx returns the index of the button that was pressed. Since "Add"
+ // is button 0, we want to return the negation of that value.
+ var confirm = !ps.confirmEx(null,
+ titleMessage,
+ dialogMessage,
+ buttonFlags,
+ addButtonLabel,
+ null, null, // button 1 & 2 names not used
+ checkboxMessage,
+ checked);
+
+ return {confirmed: confirm, useNow: checked.value};
+ },
+
+ /**
+ * Handle the successful download of an engine. Initializes the engine and
+ * triggers parsing of the data. The engine is then flushed to disk. Notifies
+ * the search service once initialization is complete.
+ */
+ _onLoad: function SRCH_ENG_onLoad(aBytes, aEngine) {
+ /**
+ * Handle an error during the load of an engine by notifying the engine's
+ * error callback, if any.
+ */
+ function onError(errorCode = Ci.nsISearchInstallCallback.ERROR_UNKNOWN_FAILURE) {
+ // Notify the callback of the failure
+ if (aEngine._installCallback) {
+ aEngine._installCallback(errorCode);
+ }
+ }
+
+ function promptError(strings = {}, error = undefined) {
+ onError(error);
+
+ if (aEngine._engineToUpdate) {
+ // We're in an update, so just fail quietly
+ LOG("updating " + aEngine._engineToUpdate.name + " failed");
+ return;
+ }
+ var brandBundle = Services.strings.createBundle(BRAND_BUNDLE);
+ var brandName = brandBundle.GetStringFromName("brandShortName");
+
+ var searchBundle = Services.strings.createBundle(SEARCH_BUNDLE);
+ var msgStringName = strings.error || "error_loading_engine_msg2";
+ var titleStringName = strings.title || "error_loading_engine_title";
+ var title = searchBundle.GetStringFromName(titleStringName);
+ var text = searchBundle.formatStringFromName(msgStringName,
+ [brandName, aEngine._location],
+ 2);
+
+ Services.ww.getNewPrompter(null).alert(title, text);
+ }
+
+ if (!aBytes) {
+ promptError();
+ return;
+ }
+
+ var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
+ createInstance(Ci.nsIDOMParser);
+ var doc = parser.parseFromBuffer(aBytes, aBytes.length, "text/xml");
+ aEngine._data = doc.documentElement;
+
+ try {
+ // Initialize the engine from the obtained data
+ aEngine._initFromData();
+ } catch (ex) {
+ LOG("_onLoad: Failed to init engine!\n" + ex);
+ // Report an error to the user
+ promptError();
+ return;
+ }
+
+ if (aEngine._engineToUpdate) {
+ let engineToUpdate = aEngine._engineToUpdate.wrappedJSObject;
+
+ // Make this new engine use the old engine's shortName, and preserve
+ // metadata.
+ aEngine._shortName = engineToUpdate._shortName;
+ Object.keys(engineToUpdate._metaData).forEach(key => {
+ aEngine.setAttr(key, engineToUpdate.getAttr(key));
+ });
+ aEngine._loadPath = engineToUpdate._loadPath;
+
+ // Keep track of the last modified date, so that we can make conditional
+ // requests for future updates.
+ aEngine.setAttr("updatelastmodified", (new Date()).toUTCString());
+
+ // Set the new engine's icon, if it doesn't yet have one.
+ if (!aEngine._iconURI && engineToUpdate._iconURI)
+ aEngine._iconURI = engineToUpdate._iconURI;
+ } else {
+ // Check that when adding a new engine (e.g., not updating an
+ // existing one), a duplicate engine does not already exist.
+ if (Services.search.getEngineByName(aEngine.name)) {
+ // If we're confirming the engine load, then display a "this is a
+ // duplicate engine" prompt; otherwise, fail silently.
+ if (aEngine._confirm) {
+ promptError({ error: "error_duplicate_engine_msg",
+ title: "error_invalid_engine_title"
+ }, Ci.nsISearchInstallCallback.ERROR_DUPLICATE_ENGINE);
+ } else {
+ onError(Ci.nsISearchInstallCallback.ERROR_DUPLICATE_ENGINE);
+ }
+ LOG("_onLoad: duplicate engine found, bailing");
+ return;
+ }
+
+ // If requested, confirm the addition now that we have the title.
+ // This property is only ever true for engines added via
+ // nsIBrowserSearchService::addEngine.
+ if (aEngine._confirm) {
+ var confirmation = aEngine._confirmAddEngine();
+ LOG("_onLoad: confirm is " + confirmation.confirmed +
+ "; useNow is " + confirmation.useNow);
+ if (!confirmation.confirmed) {
+ onError();
+ return;
+ }
+ aEngine._useNow = confirmation.useNow;
+ }
+
+ aEngine._shortName = sanitizeName(aEngine.name);
+ aEngine._loadPath = aEngine.getAnonymizedLoadPath(null, aEngine._uri);
+ aEngine.setAttr("loadPathHash", getVerificationHash(aEngine._loadPath));
+ }
+
+ // Notify the search service of the successful load. It will deal with
+ // updates by checking aEngine._engineToUpdate.
+ notifyAction(aEngine, SEARCH_ENGINE_LOADED);
+
+ // Notify the callback if needed
+ if (aEngine._installCallback) {
+ aEngine._installCallback();
+ }
+ },
+
+ /**
+ * Creates a key by serializing an object that contains the icon's width
+ * and height.
+ *
+ * @param aWidth
+ * Width of the icon.
+ * @param aHeight
+ * Height of the icon.
+ * @returns key string
+ */
+ _getIconKey: function SRCH_ENG_getIconKey(aWidth, aHeight) {
+ let keyObj = {
+ width: aWidth,
+ height: aHeight
+ };
+
+ return JSON.stringify(keyObj);
+ },
+
+ /**
+ * Add an icon to the icon map used by getIconURIBySize() and getIcons().
+ *
+ * @param aWidth
+ * Width of the icon.
+ * @param aHeight
+ * Height of the icon.
+ * @param aURISpec
+ * String with the icon's URI.
+ */
+ _addIconToMap: function SRCH_ENG_addIconToMap(aWidth, aHeight, aURISpec) {
+ if (aWidth == 16 && aHeight == 16) {
+ // The 16x16 icon is stored in _iconURL, we don't need to store it twice.
+ return;
+ }
+
+ // Use an object instead of a Map() because it needs to be serializable.
+ this._iconMapObj = this._iconMapObj || {};
+ let key = this._getIconKey(aWidth, aHeight);
+ this._iconMapObj[key] = aURISpec;
+ },
+
+ /**
+ * Sets the .iconURI property of the engine. If both aWidth and aHeight are
+ * provided an entry will be added to _iconMapObj that will enable accessing
+ * icon's data through getIcons() and getIconURIBySize() APIs.
+ *
+ * @param aIconURL
+ * A URI string pointing to the engine's icon. Must have a http[s],
+ * ftp, or data scheme. Icons with HTTP[S] or FTP schemes will be
+ * downloaded and converted to data URIs for storage in the engine
+ * XML files, if the engine is not readonly.
+ * @param aIsPreferred
+ * Whether or not this icon is to be preferred. Preferred icons can
+ * override non-preferred icons.
+ * @param aWidth (optional)
+ * Width of the icon.
+ * @param aHeight (optional)
+ * Height of the icon.
+ */
+ _setIcon: function SRCH_ENG_setIcon(aIconURL, aIsPreferred, aWidth, aHeight) {
+ var uri = makeURI(aIconURL);
+
+ // Ignore bad URIs
+ if (!uri)
+ return;
+
+ LOG("_setIcon: Setting icon url \"" + limitURILength(uri.spec) + "\" for engine \""
+ + this.name + "\".");
+ // Only accept remote icons from http[s] or ftp
+ switch (uri.scheme) {
+ case "resource":
+ case "chrome":
+ // We only allow chrome and resource icon URLs for built-in search engines
+ if (!this._isDefault) {
+ return;
+ }
+ // Fall through to the data case
+ case "data":
+ if (!this._hasPreferredIcon || aIsPreferred) {
+ this._iconURI = uri;
+ notifyAction(this, SEARCH_ENGINE_CHANGED);
+ this._hasPreferredIcon = aIsPreferred;
+ }
+
+ if (aWidth && aHeight) {
+ this._addIconToMap(aWidth, aHeight, aIconURL)
+ }
+ break;
+ case "http":
+ case "https":
+ case "ftp":
+ LOG("_setIcon: Downloading icon: \"" + uri.spec +
+ "\" for engine: \"" + this.name + "\"");
+ var chan = NetUtil.newChannel({
+ uri: uri,
+ loadUsingSystemPrincipal: true
+ });
+
+ let iconLoadCallback = function (aByteArray, aEngine) {
+ // This callback may run after we've already set a preferred icon,
+ // so check again.
+ if (aEngine._hasPreferredIcon && !aIsPreferred)
+ return;
+
+ if (!aByteArray || aByteArray.length > MAX_ICON_SIZE) {
+ LOG("iconLoadCallback: load failed, or the icon was too large!");
+ return;
+ }
+
+ let type = chan.contentType;
+ if (!type.startsWith("image/"))
+ type = "image/x-icon";
+ let dataURL = "data:" + type + ";base64," +
+ btoa(String.fromCharCode.apply(null, aByteArray));
+
+ aEngine._iconURI = makeURI(dataURL);
+
+ if (aWidth && aHeight) {
+ aEngine._addIconToMap(aWidth, aHeight, dataURL)
+ }
+
+ notifyAction(aEngine, SEARCH_ENGINE_CHANGED);
+ aEngine._hasPreferredIcon = aIsPreferred;
+ };
+
+ // If we're currently acting as an "update engine", then the callback
+ // should set the icon on the engine we're updating and not us, since
+ // |this| might be gone by the time the callback runs.
+ var engineToSet = this._engineToUpdate || this;
+
+ var listener = new loadListener(chan, engineToSet, iconLoadCallback);
+ chan.notificationCallbacks = listener;
+ chan.asyncOpen2(listener);
+ break;
+ }
+ },
+
+ /**
+ * Initialize this Engine object from the collected data.
+ */
+ _initFromData: function SRCH_ENG_initFromData() {
+ ENSURE_WARN(this._data, "Can't init an engine with no data!",
+ Cr.NS_ERROR_UNEXPECTED);
+
+ // Ensure we have a supported engine type before attempting to parse it.
+ let element = this._data;
+ if ((element.localName == MOZSEARCH_LOCALNAME &&
+ element.namespaceURI == MOZSEARCH_NS_10) ||
+ (element.localName == OPENSEARCH_LOCALNAME &&
+ OPENSEARCH_NAMESPACES.indexOf(element.namespaceURI) != -1)) {
+ LOG("_init: Initing search plugin from " + this._location);
+
+ this._parse();
+
+ } else
+ FAIL(this._location + " is not a valid search plugin.", Cr.NS_ERROR_FAILURE);
+
+ // No need to keep a ref to our data (which in some cases can be a document
+ // element) past this point
+ this._data = null;
+ },
+
+ /**
+ * Initialize this Engine object from a collection of metadata.
+ */
+ _initFromMetadata: function SRCH_ENG_initMetaData(aName, aIconURL, aAlias,
+ aDescription, aMethod,
+ aTemplate, aExtensionID) {
+ ENSURE_WARN(!this._readOnly,
+ "Can't call _initFromMetaData on a readonly engine!",
+ Cr.NS_ERROR_FAILURE);
+
+ this._urls.push(new EngineURL(URLTYPE_SEARCH_HTML, aMethod, aTemplate));
+
+ this._name = aName;
+ this.alias = aAlias;
+ this._description = aDescription;
+ this._setIcon(aIconURL, true);
+ this._extensionID = aExtensionID;
+ },
+
+ /**
+ * Extracts data from an OpenSearch URL element and creates an EngineURL
+ * object which is then added to the engine's list of URLs.
+ *
+ * @throws NS_ERROR_FAILURE if a URL object could not be created.
+ *
+ * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag.
+ * @see EngineURL()
+ */
+ _parseURL: function SRCH_ENG_parseURL(aElement) {
+ var type = aElement.getAttribute("type");
+ // According to the spec, method is optional, defaulting to "GET" if not
+ // specified
+ var method = aElement.getAttribute("method") || "GET";
+ var template = aElement.getAttribute("template");
+ var resultDomain = aElement.getAttribute("resultdomain");
+
+ try {
+ var url = new EngineURL(type, method, template, resultDomain);
+ } catch (ex) {
+ FAIL("_parseURL: failed to add " + template + " as a URL",
+ Cr.NS_ERROR_FAILURE);
+ }
+
+ if (aElement.hasAttribute("rel"))
+ url.rels = aElement.getAttribute("rel").toLowerCase().split(/\s+/);
+
+ for (var i = 0; i < aElement.childNodes.length; ++i) {
+ var param = aElement.childNodes[i];
+ if (param.localName == "Param") {
+ try {
+ url.addParam(param.getAttribute("name"), param.getAttribute("value"));
+ } catch (ex) {
+ // Ignore failure
+ LOG("_parseURL: Url element has an invalid param");
+ }
+ } else if (param.localName == "MozParam" &&
+ // We only support MozParams for default search engines
+ this._isDefault) {
+ var value;
+ let condition = param.getAttribute("condition");
+
+ // MozParams must have a condition to be valid
+ if (!condition) {
+ let engineLoc = this._location;
+ let paramName = param.getAttribute("name");
+ LOG("_parseURL: MozParam (" + paramName + ") without a condition attribute found parsing engine: " + engineLoc);
+ continue;
+ }
+
+ switch (condition) {
+ case "purpose":
+ url.addParam(param.getAttribute("name"),
+ param.getAttribute("value"),
+ param.getAttribute("purpose"));
+ // _addMozParam is not needed here since it can be serialized fine without. _addMozParam
+ // also requires a unique "name" which is not normally the case when @purpose is used.
+ break;
+ case "pref":
+ try {
+ value = getMozParamPref(param.getAttribute("pref"), value);
+ url.addParam(param.getAttribute("name"), value);
+ url._addMozParam({"pref": param.getAttribute("pref"),
+ "name": param.getAttribute("name"),
+ "condition": "pref"});
+ } catch (e) { }
+ break;
+ default:
+ let engineLoc = this._location;
+ let paramName = param.getAttribute("name");
+ LOG("_parseURL: MozParam (" + paramName + ") has an unknown condition: " + condition + ". Found parsing engine: " + engineLoc);
+ break;
+ }
+ }
+ }
+
+ this._urls.push(url);
+ },
+
+ /**
+ * Get the icon from an OpenSearch Image element.
+ * @see http://opensearch.a9.com/spec/1.1/description/#image
+ */
+ _parseImage: function SRCH_ENG_parseImage(aElement) {
+ LOG("_parseImage: Image textContent: \"" + limitURILength(aElement.textContent) + "\"");
+
+ let width = parseInt(aElement.getAttribute("width"), 10);
+ let height = parseInt(aElement.getAttribute("height"), 10);
+ let isPrefered = width == 16 && height == 16;
+
+ if (isNaN(width) || isNaN(height) || width <= 0 || height <=0) {
+ LOG("OpenSearch image element must have positive width and height.");
+ return;
+ }
+
+ this._setIcon(aElement.textContent, isPrefered, width, height);
+ },
+
+ /**
+ * Extract search engine information from the collected data to initialize
+ * the engine object.
+ */
+ _parse: function SRCH_ENG_parse() {
+ var doc = this._data;
+
+ // The OpenSearch spec sets a default value for the input encoding.
+ this._queryCharset = OS_PARAM_INPUT_ENCODING_DEF;
+
+ for (var i = 0; i < doc.childNodes.length; ++i) {
+ var child = doc.childNodes[i];
+ switch (child.localName) {
+ case "ShortName":
+ this._name = child.textContent;
+ break;
+ case "Description":
+ this._description = child.textContent;
+ break;
+ case "Url":
+ try {
+ this._parseURL(child);
+ } catch (ex) {
+ // Parsing of the element failed, just skip it.
+ LOG("_parse: failed to parse URL child: " + ex);
+ }
+ break;
+ case "Image":
+ this._parseImage(child);
+ break;
+ case "InputEncoding":
+ this._queryCharset = child.textContent.toUpperCase();
+ break;
+
+ // Non-OpenSearch elements
+ case "SearchForm":
+ this._searchForm = child.textContent;
+ break;
+ case "UpdateUrl":
+ this._updateURL = child.textContent;
+ break;
+ case "UpdateInterval":
+ this._updateInterval = parseInt(child.textContent);
+ break;
+ case "IconUpdateUrl":
+ this._iconUpdateURL = child.textContent;
+ break;
+ case "ExtensionID":
+ this._extensionID = child.textContent;
+ break;
+ }
+ }
+ if (!this.name || (this._urls.length == 0))
+ FAIL("_parse: No name, or missing URL!", Cr.NS_ERROR_FAILURE);
+ if (!this.supportsResponseType(URLTYPE_SEARCH_HTML))
+ FAIL("_parse: No text/html result type!", Cr.NS_ERROR_FAILURE);
+ },
+
+ /**
+ * Init from a JSON record.
+ **/
+ _initWithJSON: function SRCH_ENG__initWithJSON(aJson) {
+ this._name = aJson._name;
+ this._shortName = aJson._shortName;
+ this._loadPath = aJson._loadPath;
+ this._description = aJson.description;
+ this._hasPreferredIcon = aJson._hasPreferredIcon == undefined;
+ this._queryCharset = aJson.queryCharset || DEFAULT_QUERY_CHARSET;
+ this.__searchForm = aJson.__searchForm;
+ this._updateInterval = aJson._updateInterval || null;
+ this._updateURL = aJson._updateURL || null;
+ this._iconUpdateURL = aJson._iconUpdateURL || null;
+ this._readOnly = aJson._readOnly == undefined;
+ this._iconURI = makeURI(aJson._iconURL);
+ this._iconMapObj = aJson._iconMapObj;
+ this._metaData = aJson._metaData || {};
+ if (aJson.filePath) {
+ this._filePath = aJson.filePath;
+ }
+ if (aJson.dirPath) {
+ this._dirPath = aJson.dirPath;
+ this._dirLastModifiedTime = aJson.dirLastModifiedTime;
+ }
+ if (aJson.extensionID) {
+ this._extensionID = aJson.extensionID;
+ }
+ for (let i = 0; i < aJson._urls.length; ++i) {
+ let url = aJson._urls[i];
+ let engineURL = new EngineURL(url.type || URLTYPE_SEARCH_HTML,
+ url.method || "GET", url.template,
+ url.resultDomain || undefined);
+ engineURL._initWithJSON(url, this);
+ this._urls.push(engineURL);
+ }
+ },
+
+ /**
+ * Creates a JavaScript object that represents this engine.
+ * @returns An object suitable for serialization as JSON.
+ **/
+ toJSON: function SRCH_ENG_toJSON() {
+ var json = {
+ _name: this._name,
+ _shortName: this._shortName,
+ _loadPath: this._loadPath,
+ description: this.description,
+ __searchForm: this.__searchForm,
+ _iconURL: this._iconURL,
+ _iconMapObj: this._iconMapObj,
+ _metaData: this._metaData,
+ _urls: this._urls
+ };
+
+ if (this._updateInterval)
+ json._updateInterval = this._updateInterval;
+ if (this._updateURL)
+ json._updateURL = this._updateURL;
+ if (this._iconUpdateURL)
+ json._iconUpdateURL = this._iconUpdateURL;
+ if (!this._hasPreferredIcon)
+ json._hasPreferredIcon = this._hasPreferredIcon;
+ if (this.queryCharset != DEFAULT_QUERY_CHARSET)
+ json.queryCharset = this.queryCharset;
+ if (!this._readOnly)
+ json._readOnly = this._readOnly;
+ if (this._filePath) {
+ // File path is stored so that we can remove legacy xml files
+ // from the profile if the user removes the engine.
+ json.filePath = this._filePath;
+ }
+ if (this._dirPath) {
+ // The directory path is only stored for extension-shipped engines,
+ // it's used to invalidate the cache.
+ json.dirPath = this._dirPath;
+ json.dirLastModifiedTime = this._dirLastModifiedTime;
+ }
+ if (this._extensionID) {
+ json.extensionID = this._extensionID;
+ }
+
+ return json;
+ },
+
+ setAttr(name, val) {
+ this._metaData[name] = val;
+ },
+
+ getAttr(name) {
+ return this._metaData[name] || undefined;
+ },
+
+ // nsISearchEngine
+ get alias() {
+ return this.getAttr("alias");
+ },
+ set alias(val) {
+ var value = val ? val.trim() : null;
+ this.setAttr("alias", value);
+ notifyAction(this, SEARCH_ENGINE_CHANGED);
+ },
+
+ /**
+ * Return the built-in identifier of app-provided engines.
+ *
+ * Note that this identifier is substantially similar to _id, with the
+ * following exceptions:
+ *
+ * * There is no trailing file extension.
+ * * There is no [app] prefix.
+ *
+ * @return a string identifier, or null.
+ */
+ get identifier() {
+ // No identifier if If the engine isn't app-provided
+ return this._isDefault ? this._shortName : null;
+ },
+
+ get description() {
+ return this._description;
+ },
+
+ get hidden() {
+ return this.getAttr("hidden") || false;
+ },
+ set hidden(val) {
+ var value = !!val;
+ if (value != this.hidden) {
+ this.setAttr("hidden", value);
+ notifyAction(this, SEARCH_ENGINE_CHANGED);
+ }
+ },
+
+ get iconURI() {
+ if (this._iconURI)
+ return this._iconURI;
+ return null;
+ },
+
+ get _iconURL() {
+ if (!this._iconURI)
+ return "";
+ return this._iconURI.spec;
+ },
+
+ // Where the engine is being loaded from: will return the URI's spec if the
+ // engine is being downloaded and does not yet have a file. This is only used
+ // for logging and error messages.
+ get _location() {
+ if (this._uri)
+ return this._uri.spec;
+
+ return this._loadPath;
+ },
+
+ // This indicates where we found the .xml file to load the engine,
+ // and attempts to hide user-identifiable data (such as username).
+ getAnonymizedLoadPath(file, uri) {
+ /* Examples of expected output:
+ * jar:[app]/omni.ja!browser/engine.xml
+ * 'browser' here is the name of the chrome package, not a folder.
+ * [profile]/searchplugins/engine.xml
+ * [distribution]/searchplugins/common/engine.xml
+ * [other]/engine.xml
+ */
+
+ const NS_XPCOM_CURRENT_PROCESS_DIR = "XCurProcD";
+ const NS_APP_USER_PROFILE_50_DIR = "ProfD";
+ const XRE_APP_DISTRIBUTION_DIR = "XREAppDist";
+
+ const knownDirs = {
+ app: NS_XPCOM_CURRENT_PROCESS_DIR,
+ profile: NS_APP_USER_PROFILE_50_DIR,
+ distribution: XRE_APP_DISTRIBUTION_DIR
+ };
+
+ let leafName = this._shortName;
+ if (!leafName)
+ return "null";
+ leafName += ".xml";
+
+ let prefix = "", suffix = "";
+ if (!file) {
+ if (uri.schemeIs("resource")) {
+ uri = makeURI(Services.io.getProtocolHandler("resource")
+ .QueryInterface(Ci.nsISubstitutingProtocolHandler)
+ .resolveURI(uri));
+ }
+ let scheme = uri.scheme;
+ let packageName = "";
+ if (scheme == "chrome") {
+ packageName = uri.hostPort;
+ uri = gChromeReg.convertChromeURL(uri);
+ }
+
+ if (AppConstants.platform == "android") {
+ // On Android the omni.ja file isn't at the same path as the binary
+ // used to start the process. We tweak the path here so that the code
+ // shared with Desktop will correctly identify files from the omni.ja
+ // file as coming from the [app] folder.
+ let appPath = Services.io.getProtocolHandler("resource")
+ .QueryInterface(Ci.nsIResProtocolHandler)
+ .getSubstitution("android");
+ if (appPath) {
+ appPath = appPath.spec;
+ let spec = uri.spec;
+ if (spec.includes(appPath)) {
+ let appURI = Services.io.newFileURI(getDir(knownDirs["app"]));
+ uri = NetUtil.newURI(spec.replace(appPath, appURI.spec));
+ }
+ }
+ }
+
+ if (uri instanceof Ci.nsINestedURI) {
+ prefix = "jar:";
+ suffix = "!" + packageName + "/" + leafName;
+ uri = uri.innermostURI;
+ }
+ if (uri instanceof Ci.nsIFileURL) {
+ file = uri.file;
+ } else {
+ let path = "[" + scheme + "]";
+ if (/^(?:https?|ftp)$/.test(scheme)) {
+ path += uri.host;
+ }
+ return path + "/" + leafName;
+ }
+ }
+
+ let id;
+ let enginePath = file.path;
+
+ for (let key in knownDirs) {
+ let path;
+ try {
+ path = getDir(knownDirs[key]).path;
+ } catch (e) {
+ // Getting XRE_APP_DISTRIBUTION_DIR throws during unit tests.
+ continue;
+ }
+ if (enginePath.startsWith(path)) {
+ id = "[" + key + "]" + enginePath.slice(path.length).replace(/\\/g, "/");
+ break;
+ }
+ }
+
+ // If the folder doesn't have a known ancestor, don't record its path to
+ // avoid leaking user identifiable data.
+ if (!id)
+ id = "[other]/" + file.leafName;
+
+ return prefix + id + suffix;
+ },
+
+ get _isDefault() {
+ // If we don't have a shortName, the engine is being parsed from a
+ // downloaded file, so this can't be a default engine.
+ if (!this._shortName)
+ return false;
+
+ // An engine is a default one if we initially loaded it from the application
+ // or distribution directory.
+ if (/^(?:jar:)?(?:\[app\]|\[distribution\])/.test(this._loadPath))
+ return true;
+
+ // If we are using a non-default locale or in the xpcshell test case,
+ // we'll accept as a 'default' engine anything that has been registered at
+ // resource://search-plugins/ even if the file doesn't come from the
+ // application folder. If not, skip costly additional checks.
+ if (!Services.prefs.prefHasUserValue(LOCALE_PREF) &&
+ !gEnvironment.get("XPCSHELL_TEST_PROFILE_DIR"))
+ return false;
+
+ // Some xpcshell tests use the search service without registering
+ // resource://search-plugins/.
+ if (!Services.io.getProtocolHandler("resource")
+ .QueryInterface(Ci.nsIResProtocolHandler)
+ .hasSubstitution("search-plugins"))
+ return false;
+
+ let uri = makeURI(APP_SEARCH_PREFIX + this._shortName + ".xml");
+ if (this.getAnonymizedLoadPath(null, uri) == this._loadPath) {
+ // This isn't a real default engine, but it's very close.
+ LOG("_isDefault, pretending " + this._loadPath + " is a default engine");
+ return true;
+ }
+
+ return false;
+ },
+
+ get _hasUpdates() {
+ // Whether or not the engine has an update URL
+ let selfURL = this._getURLOfType(URLTYPE_OPENSEARCH, "self");
+ return !!(this._updateURL || this._iconUpdateURL || selfURL);
+ },
+
+ get name() {
+ return this._name;
+ },
+
+ get searchForm() {
+ return this._getSearchFormWithPurpose();
+ },
+
+ _getSearchFormWithPurpose(aPurpose = "") {
+ // First look for a <Url rel="searchform">
+ var searchFormURL = this._getURLOfType(URLTYPE_SEARCH_HTML, "searchform");
+ if (searchFormURL) {
+ let submission = searchFormURL.getSubmission("", this, aPurpose);
+
+ // If the rel=searchform URL is not type="get" (i.e. has postData),
+ // ignore it, since we can only return a URL.
+ if (!submission.postData)
+ return submission.uri.spec;
+ }
+
+ if (!this._searchForm) {
+ // No SearchForm specified in the engine definition file, use the prePath
+ // (e.g. https://foo.com for https://foo.com/search.php?q=bar).
+ var htmlUrl = this._getURLOfType(URLTYPE_SEARCH_HTML);
+ ENSURE_WARN(htmlUrl, "Engine has no HTML URL!", Cr.NS_ERROR_UNEXPECTED);
+ this._searchForm = makeURI(htmlUrl.template).prePath;
+ }
+
+ return ParamSubstitution(this._searchForm, "", this);
+ },
+
+ get queryCharset() {
+ if (this._queryCharset)
+ return this._queryCharset;
+ return this._queryCharset = "windows-1252"; // the default
+ },
+
+ // from nsISearchEngine
+ addParam: function SRCH_ENG_addParam(aName, aValue, aResponseType) {
+ if (!aName || (aValue == null))
+ FAIL("missing name or value for nsISearchEngine::addParam!");
+ ENSURE_WARN(!this._readOnly,
+ "called nsISearchEngine::addParam on a read-only engine!",
+ Cr.NS_ERROR_FAILURE);
+ if (!aResponseType)
+ aResponseType = URLTYPE_SEARCH_HTML;
+
+ var url = this._getURLOfType(aResponseType);
+ if (!url)
+ FAIL("Engine object has no URL for response type " + aResponseType,
+ Cr.NS_ERROR_FAILURE);
+
+ url.addParam(aName, aValue);
+ },
+
+ get _defaultMobileResponseType() {
+ let type = URLTYPE_SEARCH_HTML;
+
+ let sysInfo = Cc["@mozilla.org/system-info;1"].getService(Ci.nsIPropertyBag2);
+ let isTablet = sysInfo.get("tablet");
+ if (isTablet && this.supportsResponseType("application/x-moz-tabletsearch")) {
+ // Check for a tablet-specific search URL override
+ type = "application/x-moz-tabletsearch";
+ } else if (!isTablet && this.supportsResponseType("application/x-moz-phonesearch")) {
+ // Check for a phone-specific search URL override
+ type = "application/x-moz-phonesearch";
+ }
+
+ delete this._defaultMobileResponseType;
+ return this._defaultMobileResponseType = type;
+ },
+
+ get _isWhiteListed() {
+ let url = this._getURLOfType(URLTYPE_SEARCH_HTML).template;
+ let hostname = makeURI(url).host;
+ let whitelist = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF)
+ .getCharPref("reset.whitelist")
+ .split(",");
+ if (whitelist.includes(hostname)) {
+ LOG("The hostname " + hostname + " is white listed, " +
+ "we won't show the search reset prompt");
+ return true;
+ }
+
+ return false;
+ },
+
+ // from nsISearchEngine
+ getSubmission: function SRCH_ENG_getSubmission(aData, aResponseType, aPurpose) {
+ if (!aResponseType) {
+ aResponseType = AppConstants.platform == "android" ? this._defaultMobileResponseType :
+ URLTYPE_SEARCH_HTML;
+ }
+
+ if (aResponseType == URLTYPE_SEARCH_HTML &&
+ Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).getBoolPref("reset.enabled") &&
+ this.name == Services.search.currentEngine.name &&
+ !this._isDefault &&
+ this.name != Services.search.originalDefaultEngine.name &&
+ (!this.getAttr("loadPathHash") ||
+ this.getAttr("loadPathHash") != getVerificationHash(this._loadPath)) &&
+ !this._isWhiteListed) {
+ let url = "about:searchreset";
+ let data = [];
+ if (aData)
+ data.push("data=" + encodeURIComponent(aData));
+ if (aPurpose)
+ data.push("purpose=" + aPurpose);
+ if (data.length)
+ url += "?" + data.join("&");
+ return new Submission(makeURI(url));
+ }
+
+ var url = this._getURLOfType(aResponseType);
+
+ if (!url)
+ return null;
+
+ if (!aData) {
+ // Return a dummy submission object with our searchForm attribute
+ return new Submission(makeURI(this._getSearchFormWithPurpose(aPurpose)));
+ }
+
+ LOG("getSubmission: In data: \"" + aData + "\"; Purpose: \"" + aPurpose + "\"");
+ var data = "";
+ try {
+ data = gTextToSubURI.ConvertAndEscape(this.queryCharset, aData);
+ } catch (ex) {
+ LOG("getSubmission: Falling back to default queryCharset!");
+ data = gTextToSubURI.ConvertAndEscape(DEFAULT_QUERY_CHARSET, aData);
+ }
+ LOG("getSubmission: Out data: \"" + data + "\"");
+ return url.getSubmission(data, this, aPurpose);
+ },
+
+ // from nsISearchEngine
+ supportsResponseType: function SRCH_ENG_supportsResponseType(type) {
+ return (this._getURLOfType(type) != null);
+ },
+
+ // from nsISearchEngine
+ getResultDomain: function SRCH_ENG_getResultDomain(aResponseType) {
+ if (!aResponseType) {
+ aResponseType = AppConstants.platform == "android" ? this._defaultMobileResponseType :
+ URLTYPE_SEARCH_HTML;
+ }
+
+ LOG("getResultDomain: responseType: \"" + aResponseType + "\"");
+
+ let url = this._getURLOfType(aResponseType);
+ if (url)
+ return url.resultDomain;
+ return "";
+ },
+
+ /**
+ * Returns URL parsing properties used by _buildParseSubmissionMap.
+ */
+ getURLParsingInfo: function () {
+ let responseType = AppConstants.platform == "android" ? this._defaultMobileResponseType :
+ URLTYPE_SEARCH_HTML;
+
+ LOG("getURLParsingInfo: responseType: \"" + responseType + "\"");
+
+ let url = this._getURLOfType(responseType);
+ if (!url || url.method != "GET") {
+ return null;
+ }
+
+ let termsParameterName = url._getTermsParameterName();
+ if (!termsParameterName) {
+ return null;
+ }
+
+ let templateUrl = NetUtil.newURI(url.template).QueryInterface(Ci.nsIURL);
+ return {
+ mainDomain: templateUrl.host,
+ path: templateUrl.filePath.toLowerCase(),
+ termsParameterName: termsParameterName,
+ };
+ },
+
+ // nsISupports
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsISearchEngine]),
+
+ get wrappedJSObject() {
+ return this;
+ },
+
+ /**
+ * Returns a string with the URL to an engine's icon matching both width and
+ * height. Returns null if icon with specified dimensions is not found.
+ *
+ * @param width
+ * Width of the requested icon.
+ * @param height
+ * Height of the requested icon.
+ */
+ getIconURLBySize: function SRCH_ENG_getIconURLBySize(aWidth, aHeight) {
+ if (aWidth == 16 && aHeight == 16)
+ return this._iconURL;
+
+ if (!this._iconMapObj)
+ return null;
+
+ let key = this._getIconKey(aWidth, aHeight);
+ if (key in this._iconMapObj) {
+ return this._iconMapObj[key];
+ }
+ return null;
+ },
+
+ /**
+ * Gets an array of all available icons. Each entry is an object with
+ * width, height and url properties. width and height are numeric and
+ * represent the icon's dimensions. url is a string with the URL for
+ * the icon.
+ */
+ getIcons: function SRCH_ENG_getIcons() {
+ let result = [];
+ if (this._iconURL)
+ result.push({width: 16, height: 16, url: this._iconURL});
+
+ if (!this._iconMapObj)
+ return result;
+
+ for (let key of Object.keys(this._iconMapObj)) {
+ let iconSize = JSON.parse(key);
+ result.push({
+ width: iconSize.width,
+ height: iconSize.height,
+ url: this._iconMapObj[key]
+ });
+ }
+
+ return result;
+ },
+
+ /**
+ * Opens a speculative connection to the engine's search URI
+ * (and suggest URI, if different) to reduce request latency
+ *
+ * @param options
+ * An object that must contain the following fields:
+ * {window} the content window for the window performing the search
+ *
+ * @throws NS_ERROR_INVALID_ARG if options is omitted or lacks required
+ * elemeents
+ */
+ speculativeConnect: function SRCH_ENG_speculativeConnect(options) {
+ if (!options || !options.window) {
+ Cu.reportError("invalid options arg passed to nsISearchEngine.speculativeConnect");
+ throw Cr.NS_ERROR_INVALID_ARG;
+ }
+ let connector =
+ Services.io.QueryInterface(Components.interfaces.nsISpeculativeConnect);
+
+ let searchURI = this.getSubmission("dummy").uri;
+
+ let callbacks = options.window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
+ .getInterface(Components.interfaces.nsIWebNavigation)
+ .QueryInterface(Components.interfaces.nsILoadContext);
+
+ connector.speculativeConnect(searchURI, callbacks);
+
+ if (this.supportsResponseType(URLTYPE_SUGGEST_JSON)) {
+ let suggestURI = this.getSubmission("dummy", URLTYPE_SUGGEST_JSON).uri;
+ if (suggestURI.prePath != searchURI.prePath)
+ connector.speculativeConnect(suggestURI, callbacks);
+ }
+ },
+};
+
+// nsISearchSubmission
+function Submission(aURI, aPostData = null) {
+ this._uri = aURI;
+ this._postData = aPostData;
+}
+Submission.prototype = {
+ get uri() {
+ return this._uri;
+ },
+ get postData() {
+ return this._postData;
+ },
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsISearchSubmission])
+}
+
+// nsISearchParseSubmissionResult
+function ParseSubmissionResult(aEngine, aTerms, aTermsOffset, aTermsLength) {
+ this._engine = aEngine;
+ this._terms = aTerms;
+ this._termsOffset = aTermsOffset;
+ this._termsLength = aTermsLength;
+}
+ParseSubmissionResult.prototype = {
+ get engine() {
+ return this._engine;
+ },
+ get terms() {
+ return this._terms;
+ },
+ get termsOffset() {
+ return this._termsOffset;
+ },
+ get termsLength() {
+ return this._termsLength;
+ },
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsISearchParseSubmissionResult]),
+}
+
+const gEmptyParseSubmissionResult =
+ Object.freeze(new ParseSubmissionResult(null, "", -1, 0));
+
+function executeSoon(func) {
+ Services.tm.mainThread.dispatch(func, Ci.nsIThread.DISPATCH_NORMAL);
+}
+
+/**
+ * Check for sync initialization has completed or not.
+ *
+ * @param {aPromise} A promise.
+ *
+ * @returns the value returned by the invoked method.
+ * @throws NS_ERROR_ALREADY_INITIALIZED if sync initialization has completed.
+ */
+function checkForSyncCompletion(aPromise) {
+ return aPromise.then(function(aValue) {
+ if (gInitialized) {
+ throw Components.Exception("Synchronous fallback was called and has " +
+ "finished so no need to pursue asynchronous " +
+ "initialization",
+ Cr.NS_ERROR_ALREADY_INITIALIZED);
+ }
+ return aValue;
+ });
+}
+
+// nsIBrowserSearchService
+function SearchService() {
+ // Replace empty LOG function with the useful one if the log pref is set.
+ if (getBoolPref(BROWSER_SEARCH_PREF + "log", false))
+ LOG = DO_LOG;
+
+ this._initObservers = Promise.defer();
+}
+
+SearchService.prototype = {
+ classID: Components.ID("{7319788a-fe93-4db3-9f39-818cf08f4256}"),
+
+ // The current status of initialization. Note that it does not determine if
+ // initialization is complete, only if an error has been encountered so far.
+ _initRV: Cr.NS_OK,
+
+ // The boolean indicates that the initialization has started or not.
+ _initStarted: null,
+
+ // Reading the JSON cache file is the first thing done during initialization.
+ // During the async init, we save it in a field so that if we have to do a
+ // sync init before the async init finishes, we can avoid reading the cache
+ // with sync disk I/O and handling lz4 decompression synchronously.
+ // This is set back to null as soon as the initialization is finished.
+ _cacheFileJSON: null,
+
+ // If initialization has not been completed yet, perform synchronous
+ // initialization.
+ // Throws in case of initialization error.
+ _ensureInitialized: function SRCH_SVC__ensureInitialized() {
+ if (gInitialized) {
+ if (!Components.isSuccessCode(this._initRV)) {
+ LOG("_ensureInitialized: failure");
+ throw this._initRV;
+ }
+ return;
+ }
+
+ let warning =
+ "Search service falling back to synchronous initialization. " +
+ "This is generally the consequence of an add-on using a deprecated " +
+ "search service API.";
+ Deprecated.warning(warning, "https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIBrowserSearchService#async_warning");
+ LOG(warning);
+
+ this._syncInit();
+ if (!Components.isSuccessCode(this._initRV)) {
+ throw this._initRV;
+ }
+ },
+
+ // Synchronous implementation of the initializer.
+ // Used by |_ensureInitialized| as a fallback if initialization is not
+ // complete.
+ _syncInit: function SRCH_SVC__syncInit() {
+ LOG("_syncInit start");
+ this._initStarted = true;
+ migrateRegionPrefs();
+
+ let cache = this._readCacheFile();
+ if (cache.metaData)
+ this._metaData = cache.metaData;
+
+ try {
+ this._syncLoadEngines(cache);
+ } catch (ex) {
+ this._initRV = Cr.NS_ERROR_FAILURE;
+ LOG("_syncInit: failure loading engines: " + ex);
+ }
+ this._addObservers();
+
+ gInitialized = true;
+ this._cacheFileJSON = null;
+
+ this._initObservers.resolve(this._initRV);
+
+ Services.obs.notifyObservers(null, SEARCH_SERVICE_TOPIC, "init-complete");
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_INIT_SYNC").add(true);
+ this._recordEngineTelemetry();
+
+ LOG("_syncInit end");
+ },
+
+ /**
+ * Asynchronous implementation of the initializer.
+ *
+ * @returns {Promise} A promise, resolved successfully if the initialization
+ * succeeds.
+ */
+ _asyncInit: Task.async(function* () {
+ LOG("_asyncInit start");
+
+ migrateRegionPrefs();
+
+ // See if we have a cache file so we don't have to parse a bunch of XML.
+ let cache = {};
+ // Not using checkForSyncCompletion here because we want to ensure we
+ // fetch the country code and geo specific defaults asynchronously even
+ // if a sync init has been forced.
+ cache = yield this._asyncReadCacheFile();
+
+ if (!gInitialized && cache.metaData)
+ this._metaData = cache.metaData;
+
+ try {
+ yield checkForSyncCompletion(ensureKnownCountryCode(this));
+ } catch (ex) {
+ if (ex.result == Cr.NS_ERROR_ALREADY_INITIALIZED) {
+ throw ex;
+ }
+ LOG("_asyncInit: failure determining country code: " + ex);
+ }
+ try {
+ yield checkForSyncCompletion(this._asyncLoadEngines(cache));
+ } catch (ex) {
+ if (ex.result == Cr.NS_ERROR_ALREADY_INITIALIZED) {
+ throw ex;
+ }
+ this._initRV = Cr.NS_ERROR_FAILURE;
+ LOG("_asyncInit: failure loading engines: " + ex);
+ }
+ this._addObservers();
+ gInitialized = true;
+ this._cacheFileJSON = null;
+ this._initObservers.resolve(this._initRV);
+ Services.obs.notifyObservers(null, SEARCH_SERVICE_TOPIC, "init-complete");
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_INIT_SYNC").add(false);
+ this._recordEngineTelemetry();
+
+ LOG("_asyncInit: Completed _asyncInit");
+ }),
+
+ _metaData: { },
+ setGlobalAttr(name, val) {
+ this._metaData[name] = val;
+ this.batchTask.disarm();
+ this.batchTask.arm();
+ },
+ setVerifiedGlobalAttr(name, val) {
+ this.setGlobalAttr(name, val);
+ this.setGlobalAttr(name + "Hash", getVerificationHash(val));
+ },
+
+ getGlobalAttr(name) {
+ return this._metaData[name] || undefined;
+ },
+ getVerifiedGlobalAttr(name) {
+ let val = this.getGlobalAttr(name);
+ if (val && this.getGlobalAttr(name + "Hash") != getVerificationHash(val)) {
+ LOG("getVerifiedGlobalAttr, invalid hash for " + name);
+ return "";
+ }
+ return val;
+ },
+
+ _engines: { },
+ __sortedEngines: null,
+ _visibleDefaultEngines: [],
+ get _sortedEngines() {
+ if (!this.__sortedEngines)
+ return this._buildSortedEngineList();
+ return this.__sortedEngines;
+ },
+
+ // Get the original Engine object that is the default for this region,
+ // ignoring changes the user may have subsequently made.
+ get originalDefaultEngine() {
+ let defaultEngine = this.getVerifiedGlobalAttr("searchDefault");
+ if (!defaultEngine) {
+ let defaultPrefB = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF);
+ let nsIPLS = Ci.nsIPrefLocalizedString;
+
+ let defPref = getGeoSpecificPrefName("defaultenginename");
+ try {
+ defaultEngine = defaultPrefB.getComplexValue(defPref, nsIPLS).data;
+ } catch (ex) {
+ // If the default pref is invalid (e.g. an add-on set it to a bogus value)
+ // getEngineByName will just return null, which is the best we can do.
+ }
+ }
+
+ return this.getEngineByName(defaultEngine);
+ },
+
+ resetToOriginalDefaultEngine: function SRCH_SVC__resetToOriginalDefaultEngine() {
+ this.currentEngine = this.originalDefaultEngine;
+ },
+
+ _buildCache: function SRCH_SVC__buildCache() {
+ if (this._batchTask)
+ this._batchTask.disarm();
+
+ let cache = {};
+ let locale = getLocale();
+ let buildID = Services.appinfo.platformBuildID;
+
+ // Allows us to force a cache refresh should the cache format change.
+ cache.version = CACHE_VERSION;
+ // We don't want to incur the costs of stat()ing each plugin on every
+ // startup when the only (supported) time they will change is during
+ // app updates (where the buildID is obviously going to change).
+ // Extension-shipped plugins are the only exception to this, but their
+ // directories are blown away during updates, so we'll detect their changes.
+ cache.buildID = buildID;
+ cache.locale = locale;
+
+ cache.visibleDefaultEngines = this._visibleDefaultEngines;
+ cache.metaData = this._metaData;
+ cache.engines = [];
+
+ for (let name in this._engines) {
+ cache.engines.push(this._engines[name]);
+ }
+
+ try {
+ if (!cache.engines.length)
+ throw "cannot write without any engine.";
+
+ LOG("_buildCache: Writing to cache file.");
+ let path = OS.Path.join(OS.Constants.Path.profileDir, CACHE_FILENAME);
+ let data = gEncoder.encode(JSON.stringify(cache));
+ let promise = OS.File.writeAtomic(path, data, {compression: "lz4",
+ tmpPath: path + ".tmp"});
+
+ promise.then(
+ function onSuccess() {
+ Services.obs.notifyObservers(null, SEARCH_SERVICE_TOPIC, SEARCH_SERVICE_CACHE_WRITTEN);
+ },
+ function onError(e) {
+ LOG("_buildCache: failure during writeAtomic: " + e);
+ }
+ );
+ } catch (ex) {
+ LOG("_buildCache: Could not write to cache file: " + ex);
+ }
+ },
+
+ _syncLoadEngines: function SRCH_SVC__syncLoadEngines(cache) {
+ LOG("_syncLoadEngines: start");
+ // See if we have a cache file so we don't have to parse a bunch of XML.
+ let chromeURIs = this._findJAREngines();
+
+ let distDirs = [];
+ let locations;
+ try {
+ locations = getDir(NS_APP_DISTRIBUTION_SEARCH_DIR_LIST,
+ Ci.nsISimpleEnumerator);
+ } catch (e) {
+ // NS_APP_DISTRIBUTION_SEARCH_DIR_LIST is defined by each app
+ // so this throws during unit tests (but not xpcshell tests).
+ locations = {hasMoreElements: () => false};
+ }
+ while (locations.hasMoreElements()) {
+ let dir = locations.getNext().QueryInterface(Ci.nsIFile);
+ if (dir.directoryEntries.hasMoreElements())
+ distDirs.push(dir);
+ }
+
+ let otherDirs = [];
+ let userSearchDir = getDir(NS_APP_USER_SEARCH_DIR);
+ locations = getDir(NS_APP_SEARCH_DIR_LIST, Ci.nsISimpleEnumerator);
+ while (locations.hasMoreElements()) {
+ let dir = locations.getNext().QueryInterface(Ci.nsIFile);
+ if ((!cache.engines || !dir.equals(userSearchDir)) &&
+ dir.directoryEntries.hasMoreElements())
+ otherDirs.push(dir);
+ }
+
+ function modifiedDir(aDir) {
+ return cacheOtherPaths.get(aDir.path) != aDir.lastModifiedTime;
+ }
+
+ function notInCacheVisibleEngines(aEngineName) {
+ return cache.visibleDefaultEngines.indexOf(aEngineName) == -1;
+ }
+
+ let buildID = Services.appinfo.platformBuildID;
+ let cacheOtherPaths = new Map();
+ if (cache.engines) {
+ for (let engine of cache.engines) {
+ if (engine._dirPath) {
+ cacheOtherPaths.set(engine._dirPath, engine._dirLastModifiedTime);
+ }
+ }
+ }
+
+ let rebuildCache = !cache.engines ||
+ cache.version != CACHE_VERSION ||
+ cache.locale != getLocale() ||
+ cache.buildID != buildID ||
+ cacheOtherPaths.size != otherDirs.length ||
+ otherDirs.some(d => !cacheOtherPaths.has(d.path)) ||
+ cache.visibleDefaultEngines.length != this._visibleDefaultEngines.length ||
+ this._visibleDefaultEngines.some(notInCacheVisibleEngines) ||
+ otherDirs.some(modifiedDir);
+
+ if (rebuildCache) {
+ LOG("_loadEngines: Absent or outdated cache. Loading engines from disk.");
+ distDirs.forEach(this._loadEnginesFromDir, this);
+
+ this._loadFromChromeURLs(chromeURIs);
+
+ LOG("_loadEngines: load user-installed engines from the obsolete cache");
+ this._loadEnginesFromCache(cache, true);
+
+ otherDirs.forEach(this._loadEnginesFromDir, this);
+
+ this._loadEnginesMetadataFromCache(cache);
+ this._buildCache();
+ return;
+ }
+
+ LOG("_loadEngines: loading from cache directories");
+ this._loadEnginesFromCache(cache);
+
+ LOG("_loadEngines: done");
+ },
+
+ /**
+ * Loads engines asynchronously.
+ *
+ * @returns {Promise} A promise, resolved successfully if loading data
+ * succeeds.
+ */
+ _asyncLoadEngines: Task.async(function* (cache) {
+ LOG("_asyncLoadEngines: start");
+ Services.obs.notifyObservers(null, SEARCH_SERVICE_TOPIC, "find-jar-engines");
+ let chromeURIs =
+ yield checkForSyncCompletion(this._asyncFindJAREngines());
+
+ // Get the non-empty distribution directories into distDirs...
+ let distDirs = [];
+ let locations;
+ try {
+ locations = getDir(NS_APP_DISTRIBUTION_SEARCH_DIR_LIST,
+ Ci.nsISimpleEnumerator);
+ } catch (e) {
+ // NS_APP_DISTRIBUTION_SEARCH_DIR_LIST is defined by each app
+ // so this throws during unit tests (but not xpcshell tests).
+ locations = {hasMoreElements: () => false};
+ }
+ while (locations.hasMoreElements()) {
+ let dir = locations.getNext().QueryInterface(Ci.nsIFile);
+ let iterator = new OS.File.DirectoryIterator(dir.path,
+ { winPattern: "*.xml" });
+ try {
+ // Add dir to distDirs if it contains any files.
+ yield checkForSyncCompletion(iterator.next());
+ distDirs.push(dir);
+ } catch (ex) {
+ // Catch for StopIteration exception.
+ if (ex.result == Cr.NS_ERROR_ALREADY_INITIALIZED) {
+ throw ex;
+ }
+ } finally {
+ iterator.close();
+ }
+ }
+
+ // Add the non-empty directories of NS_APP_SEARCH_DIR_LIST to
+ // otherDirs...
+ let otherDirs = [];
+ let userSearchDir = getDir(NS_APP_USER_SEARCH_DIR);
+ locations = getDir(NS_APP_SEARCH_DIR_LIST, Ci.nsISimpleEnumerator);
+ while (locations.hasMoreElements()) {
+ let dir = locations.getNext().QueryInterface(Ci.nsIFile);
+ if (cache.engines && dir.equals(userSearchDir))
+ continue;
+ let iterator = new OS.File.DirectoryIterator(dir.path,
+ { winPattern: "*.xml" });
+ try {
+ // Add dir to otherDirs if it contains any files.
+ yield checkForSyncCompletion(iterator.next());
+ otherDirs.push(dir);
+ } catch (ex) {
+ // Catch for StopIteration exception.
+ if (ex.result == Cr.NS_ERROR_ALREADY_INITIALIZED) {
+ throw ex;
+ }
+ } finally {
+ iterator.close();
+ }
+ }
+
+ let hasModifiedDir = Task.async(function* (aList) {
+ let modifiedDir = false;
+
+ for (let dir of aList) {
+ let lastModifiedTime = cacheOtherPaths.get(dir.path);
+ if (!lastModifiedTime) {
+ continue;
+ }
+
+ let info = yield OS.File.stat(dir.path);
+ if (lastModifiedTime != info.lastModificationDate.getTime()) {
+ modifiedDir = true;
+ break;
+ }
+ }
+ return modifiedDir;
+ });
+
+ function notInCacheVisibleEngines(aEngineName) {
+ return cache.visibleDefaultEngines.indexOf(aEngineName) == -1;
+ }
+
+ let buildID = Services.appinfo.platformBuildID;
+ let cacheOtherPaths = new Map();
+ if (cache.engines) {
+ for (let engine of cache.engines) {
+ if (engine._dirPath) {
+ cacheOtherPaths.set(engine._dirPath, engine._dirLastModifiedTime);
+ }
+ }
+ }
+
+ let rebuildCache = !cache.engines ||
+ cache.version != CACHE_VERSION ||
+ cache.locale != getLocale() ||
+ cache.buildID != buildID ||
+ cacheOtherPaths.size != otherDirs.length ||
+ otherDirs.some(d => !cacheOtherPaths.has(d.path)) ||
+ cache.visibleDefaultEngines.length != this._visibleDefaultEngines.length ||
+ this._visibleDefaultEngines.some(notInCacheVisibleEngines) ||
+ (yield checkForSyncCompletion(hasModifiedDir(otherDirs)));
+
+ if (rebuildCache) {
+ LOG("_asyncLoadEngines: Absent or outdated cache. Loading engines from disk.");
+ for (let loadDir of distDirs) {
+ let enginesFromDir =
+ yield checkForSyncCompletion(this._asyncLoadEnginesFromDir(loadDir));
+ enginesFromDir.forEach(this._addEngineToStore, this);
+ }
+ let enginesFromURLs =
+ yield checkForSyncCompletion(this._asyncLoadFromChromeURLs(chromeURIs));
+ enginesFromURLs.forEach(this._addEngineToStore, this);
+
+ LOG("_asyncLoadEngines: loading user-installed engines from the obsolete cache");
+ this._loadEnginesFromCache(cache, true);
+
+ for (let loadDir of otherDirs) {
+ let enginesFromDir =
+ yield checkForSyncCompletion(this._asyncLoadEnginesFromDir(loadDir));
+ enginesFromDir.forEach(this._addEngineToStore, this);
+ }
+
+ this._loadEnginesMetadataFromCache(cache);
+ this._buildCache();
+ return;
+ }
+
+ LOG("_asyncLoadEngines: loading from cache directories");
+ this._loadEnginesFromCache(cache);
+
+ LOG("_asyncLoadEngines: done");
+ }),
+
+ _asyncReInit: function () {
+ LOG("_asyncReInit");
+ // Start by clearing the initialized state, so we don't abort early.
+ gInitialized = false;
+
+ Task.spawn(function* () {
+ try {
+ if (this._batchTask) {
+ LOG("finalizing batch task");
+ let task = this._batchTask;
+ this._batchTask = null;
+ yield task.finalize();
+ }
+
+ // Clear the engines, too, so we don't stick with the stale ones.
+ this._engines = {};
+ this.__sortedEngines = null;
+ this._currentEngine = null;
+ this._visibleDefaultEngines = [];
+ this._metaData = {};
+ this._cacheFileJSON = null;
+
+ // Tests that want to force a synchronous re-initialization need to
+ // be notified when we are done uninitializing.
+ Services.obs.notifyObservers(null, SEARCH_SERVICE_TOPIC,
+ "uninit-complete");
+
+ let cache = {};
+ cache = yield this._asyncReadCacheFile();
+ if (!gInitialized && cache.metaData)
+ this._metaData = cache.metaData;
+
+ yield ensureKnownCountryCode(this);
+ // Due to the HTTP requests done by ensureKnownCountryCode, it's possible that
+ // at this point a synchronous init has been forced by other code.
+ if (!gInitialized)
+ yield this._asyncLoadEngines(cache);
+
+ // Typically we'll re-init as a result of a pref observer,
+ // so signal to 'callers' that we're done.
+ Services.obs.notifyObservers(null, SEARCH_SERVICE_TOPIC, "init-complete");
+ this._recordEngineTelemetry();
+ gInitialized = true;
+ } catch (err) {
+ LOG("Reinit failed: " + err);
+ Services.obs.notifyObservers(null, SEARCH_SERVICE_TOPIC, "reinit-failed");
+ } finally {
+ Services.obs.notifyObservers(null, SEARCH_SERVICE_TOPIC, "reinit-complete");
+ }
+ }.bind(this));
+ },
+
+ /**
+ * Read the cache file synchronously. This also imports data from the old
+ * search-metadata.json file if needed.
+ *
+ * @returns A JS object containing the cached data.
+ */
+ _readCacheFile: function SRCH_SVC__readCacheFile() {
+ if (this._cacheFileJSON) {
+ return this._cacheFileJSON;
+ }
+
+ let cacheFile = getDir(NS_APP_USER_PROFILE_50_DIR);
+ cacheFile.append(CACHE_FILENAME);
+
+ let stream;
+ try {
+ stream = Cc["@mozilla.org/network/file-input-stream;1"].
+ createInstance(Ci.nsIFileInputStream);
+ stream.init(cacheFile, MODE_RDONLY, FileUtils.PERMS_FILE, 0);
+
+ let bis = Cc["@mozilla.org/binaryinputstream;1"]
+ .createInstance(Ci.nsIBinaryInputStream);
+ bis.setInputStream(stream);
+
+ let count = stream.available();
+ let array = new Uint8Array(count);
+ bis.readArrayBuffer(count, array.buffer);
+
+ let bytes = Lz4.decompressFileContent(array);
+ let json = JSON.parse(new TextDecoder().decode(bytes));
+ if (!json.engines || !json.engines.length)
+ throw "no engine in the file";
+ return json;
+ } catch (ex) {
+ LOG("_readCacheFile: Error reading cache file: " + ex);
+ } finally {
+ stream.close();
+ }
+
+ try {
+ cacheFile.leafName = "search-metadata.json";
+ stream = Cc["@mozilla.org/network/file-input-stream;1"].
+ createInstance(Ci.nsIFileInputStream);
+ stream.init(cacheFile, MODE_RDONLY, FileUtils.PERMS_FILE, 0);
+ let metadata = parseJsonFromStream(stream);
+ let json = {};
+ if ("[global]" in metadata) {
+ LOG("_readCacheFile: migrating metadata from search-metadata.json");
+ let data = metadata["[global]"];
+ json.metaData = {};
+ let fields = ["searchDefault", "searchDefaultHash", "searchDefaultExpir",
+ "current", "hash",
+ "visibleDefaultEngines", "visibleDefaultEnginesHash"];
+ for (let field of fields) {
+ let name = field.toLowerCase();
+ if (name in data)
+ json.metaData[field] = data[name];
+ }
+ }
+ delete metadata["[global]"];
+ json._oldMetadata = metadata;
+
+ return json;
+ } catch (ex) {
+ LOG("_readCacheFile: failed to read old metadata: " + ex);
+ return {};
+ } finally {
+ stream.close();
+ }
+ },
+
+ /**
+ * Read the cache file asynchronously. This also imports data from the old
+ * search-metadata.json file if needed.
+ *
+ * @returns {Promise} A promise, resolved successfully if retrieveing data
+ * succeeds.
+ */
+ _asyncReadCacheFile: Task.async(function* () {
+ let json;
+ try {
+ let cacheFilePath = OS.Path.join(OS.Constants.Path.profileDir, CACHE_FILENAME);
+ let bytes = yield OS.File.read(cacheFilePath, {compression: "lz4"});
+ json = JSON.parse(new TextDecoder().decode(bytes));
+ if (!json.engines || !json.engines.length)
+ throw "no engine in the file";
+ this._cacheFileJSON = json;
+ } catch (ex) {
+ LOG("_asyncReadCacheFile: Error reading cache file: " + ex);
+ json = {};
+
+ let oldMetadata =
+ OS.Path.join(OS.Constants.Path.profileDir, "search-metadata.json");
+ try {
+ let bytes = yield OS.File.read(oldMetadata);
+ let metadata = JSON.parse(new TextDecoder().decode(bytes));
+ if ("[global]" in metadata) {
+ LOG("_asyncReadCacheFile: migrating metadata from search-metadata.json");
+ let data = metadata["[global]"];
+ json.metaData = {};
+ let fields = ["searchDefault", "searchDefaultHash", "searchDefaultExpir",
+ "current", "hash",
+ "visibleDefaultEngines", "visibleDefaultEnginesHash"];
+ for (let field of fields) {
+ let name = field.toLowerCase();
+ if (name in data)
+ json.metaData[field] = data[name];
+ }
+ }
+ delete metadata["[global]"];
+ json._oldMetadata = metadata;
+ } catch (ex) {}
+ }
+ return json;
+ }),
+
+ _batchTask: null,
+ get batchTask() {
+ if (!this._batchTask) {
+ let task = function taskCallback() {
+ LOG("batchTask: Invalidating engine cache");
+ this._buildCache();
+ }.bind(this);
+ this._batchTask = new DeferredTask(task, CACHE_INVALIDATION_DELAY);
+ }
+ return this._batchTask;
+ },
+
+ _addEngineToStore: function SRCH_SVC_addEngineToStore(aEngine) {
+ LOG("_addEngineToStore: Adding engine: \"" + aEngine.name + "\"");
+
+ // See if there is an existing engine with the same name. However, if this
+ // engine is updating another engine, it's allowed to have the same name.
+ var hasSameNameAsUpdate = (aEngine._engineToUpdate &&
+ aEngine.name == aEngine._engineToUpdate.name);
+ if (aEngine.name in this._engines && !hasSameNameAsUpdate) {
+ LOG("_addEngineToStore: Duplicate engine found, aborting!");
+ return;
+ }
+
+ if (aEngine._engineToUpdate) {
+ // We need to replace engineToUpdate with the engine that just loaded.
+ var oldEngine = aEngine._engineToUpdate;
+
+ // Remove the old engine from the hash, since it's keyed by name, and our
+ // name might change (the update might have a new name).
+ delete this._engines[oldEngine.name];
+
+ // Hack: we want to replace the old engine with the new one, but since
+ // people may be holding refs to the nsISearchEngine objects themselves,
+ // we'll just copy over all "private" properties (those without a getter
+ // or setter) from one object to the other.
+ for (var p in aEngine) {
+ if (!(aEngine.__lookupGetter__(p) || aEngine.__lookupSetter__(p)))
+ oldEngine[p] = aEngine[p];
+ }
+ aEngine = oldEngine;
+ aEngine._engineToUpdate = null;
+
+ // Add the engine back
+ this._engines[aEngine.name] = aEngine;
+ notifyAction(aEngine, SEARCH_ENGINE_CHANGED);
+ } else {
+ // Not an update, just add the new engine.
+ this._engines[aEngine.name] = aEngine;
+ // Only add the engine to the list of sorted engines if the initial list
+ // has already been built (i.e. if this.__sortedEngines is non-null). If
+ // it hasn't, we're loading engines from disk and the sorted engine list
+ // will be built once we need it.
+ if (this.__sortedEngines) {
+ this.__sortedEngines.push(aEngine);
+ this._saveSortedEngineList();
+ }
+ notifyAction(aEngine, SEARCH_ENGINE_ADDED);
+ }
+
+ if (aEngine._hasUpdates) {
+ // Schedule the engine's next update, if it isn't already.
+ if (!aEngine.getAttr("updateexpir"))
+ engineUpdateService.scheduleNextUpdate(aEngine);
+ }
+ },
+
+ _loadEnginesMetadataFromCache: function SRCH_SVC__loadEnginesMetadataFromCache(cache) {
+ if (cache._oldMetadata) {
+ // If we have old metadata in the cache, we had no valid cache
+ // file and read data from search-metadata.json.
+ for (let name in this._engines) {
+ let engine = this._engines[name];
+ if (engine._id && cache._oldMetadata[engine._id])
+ engine._metaData = cache._oldMetadata[engine._id];
+ }
+ return;
+ }
+
+ if (!cache.engines)
+ return;
+
+ for (let engine of cache.engines) {
+ let name = engine._name;
+ if (name in this._engines) {
+ LOG("_loadEnginesMetadataFromCache, transfering metadata for " + name);
+ this._engines[name]._metaData = engine._metaData;
+ }
+ }
+ },
+
+ _loadEnginesFromCache: function SRCH_SVC__loadEnginesFromCache(cache,
+ skipReadOnly) {
+ if (!cache.engines)
+ return;
+
+ LOG("_loadEnginesFromCache: Loading " +
+ cache.engines.length + " engines from cache");
+
+ let skippedEngines = 0;
+ for (let engine of cache.engines) {
+ if (skipReadOnly && engine._readOnly == undefined) {
+ ++skippedEngines;
+ continue;
+ }
+
+ this._loadEngineFromCache(engine);
+ }
+
+ if (skippedEngines) {
+ LOG("_loadEnginesFromCache: skipped " + skippedEngines + " read-only engines.");
+ }
+ },
+
+ _loadEngineFromCache: function SRCH_SVC__loadEngineFromCache(json) {
+ try {
+ let engine = new Engine(json._shortName, json._readOnly == undefined);
+ engine._initWithJSON(json);
+ this._addEngineToStore(engine);
+ } catch (ex) {
+ LOG("Failed to load " + json._name + " from cache: " + ex);
+ LOG("Engine JSON: " + json.toSource());
+ }
+ },
+
+ _loadEnginesFromDir: function SRCH_SVC__loadEnginesFromDir(aDir) {
+ LOG("_loadEnginesFromDir: Searching in " + aDir.path + " for search engines.");
+
+ // Check whether aDir is the user profile dir
+ var isInProfile = aDir.equals(getDir(NS_APP_USER_SEARCH_DIR));
+
+ var files = aDir.directoryEntries
+ .QueryInterface(Ci.nsIDirectoryEnumerator);
+
+ while (files.hasMoreElements()) {
+ var file = files.nextFile;
+
+ // Ignore hidden and empty files, and directories
+ if (!file.isFile() || file.fileSize == 0 || file.isHidden())
+ continue;
+
+ var fileURL = NetUtil.ioService.newFileURI(file).QueryInterface(Ci.nsIURL);
+ var fileExtension = fileURL.fileExtension.toLowerCase();
+
+ if (fileExtension != "xml") {
+ // Not an engine
+ continue;
+ }
+
+ var addedEngine = null;
+ try {
+ addedEngine = new Engine(file, !isInProfile);
+ addedEngine._initFromFile(file);
+ if (!isInProfile && !addedEngine._isDefault) {
+ addedEngine._dirPath = aDir.path;
+ addedEngine._dirLastModifiedTime = aDir.lastModifiedTime;
+ }
+ } catch (ex) {
+ LOG("_loadEnginesFromDir: Failed to load " + file.path + "!\n" + ex);
+ continue;
+ }
+
+ this._addEngineToStore(addedEngine);
+ }
+ },
+
+ /**
+ * Loads engines from a given directory asynchronously.
+ *
+ * @param aDir the directory.
+ *
+ * @returns {Promise} A promise, resolved successfully if retrieveing data
+ * succeeds.
+ */
+ _asyncLoadEnginesFromDir: Task.async(function* (aDir) {
+ LOG("_asyncLoadEnginesFromDir: Searching in " + aDir.path + " for search engines.");
+
+ // Check whether aDir is the user profile dir
+ let isInProfile = aDir.equals(getDir(NS_APP_USER_SEARCH_DIR));
+ let dirPath = aDir.path;
+ let iterator = new OS.File.DirectoryIterator(dirPath);
+
+ let osfiles = yield iterator.nextBatch();
+ iterator.close();
+
+ let engines = [];
+ for (let osfile of osfiles) {
+ if (osfile.isDir || osfile.isSymLink)
+ continue;
+
+ let fileInfo = yield OS.File.stat(osfile.path);
+ if (fileInfo.size == 0)
+ continue;
+
+ let parts = osfile.path.split(".");
+ if (parts.length <= 1 || (parts.pop()).toLowerCase() != "xml") {
+ // Not an engine
+ continue;
+ }
+
+ let addedEngine = null;
+ try {
+ let file = new FileUtils.File(osfile.path);
+ addedEngine = new Engine(file, !isInProfile);
+ yield checkForSyncCompletion(addedEngine._asyncInitFromFile(file));
+ if (!isInProfile && !addedEngine._isDefault) {
+ addedEngine._dirPath = dirPath;
+ let info = yield OS.File.stat(dirPath);
+ addedEngine._dirLastModifiedTime =
+ info.lastModificationDate.getTime();
+ }
+ engines.push(addedEngine);
+ } catch (ex) {
+ if (ex.result == Cr.NS_ERROR_ALREADY_INITIALIZED) {
+ throw ex;
+ }
+ LOG("_asyncLoadEnginesFromDir: Failed to load " + osfile.path + "!\n" + ex);
+ }
+ }
+ return engines;
+ }),
+
+ _loadFromChromeURLs: function SRCH_SVC_loadFromChromeURLs(aURLs) {
+ aURLs.forEach(function (url) {
+ try {
+ LOG("_loadFromChromeURLs: loading engine from chrome url: " + url);
+
+ let uri = makeURI(url);
+ let engine = new Engine(uri, true);
+
+ engine._initFromURISync(uri);
+
+ this._addEngineToStore(engine);
+ } catch (ex) {
+ LOG("_loadFromChromeURLs: failed to load engine: " + ex);
+ }
+ }, this);
+ },
+
+ /**
+ * Loads engines from Chrome URLs asynchronously.
+ *
+ * @param aURLs a list of URLs.
+ *
+ * @returns {Promise} A promise, resolved successfully if loading data
+ * succeeds.
+ */
+ _asyncLoadFromChromeURLs: Task.async(function* (aURLs) {
+ let engines = [];
+ for (let url of aURLs) {
+ try {
+ LOG("_asyncLoadFromChromeURLs: loading engine from chrome url: " + url);
+ let uri = NetUtil.newURI(url);
+ let engine = new Engine(uri, true);
+ yield checkForSyncCompletion(engine._asyncInitFromURI(uri));
+ engines.push(engine);
+ } catch (ex) {
+ if (ex.result == Cr.NS_ERROR_ALREADY_INITIALIZED) {
+ throw ex;
+ }
+ LOG("_asyncLoadFromChromeURLs: failed to load engine: " + ex);
+ }
+ }
+ return engines;
+ }),
+
+ _convertChannelToFile: function(chan) {
+ let fileURI = chan.URI;
+ while (fileURI instanceof Ci.nsIJARURI)
+ fileURI = fileURI.JARFile;
+ fileURI.QueryInterface(Ci.nsIFileURL);
+
+ return fileURI.file;
+ },
+
+ _findJAREngines: function SRCH_SVC_findJAREngines() {
+ LOG("_findJAREngines: looking for engines in JARs")
+
+ let chan = makeChannel(APP_SEARCH_PREFIX + "list.json");
+ if (!chan) {
+ LOG("_findJAREngines: " + APP_SEARCH_PREFIX + " isn't registered");
+ return [];
+ }
+
+ let uris = [];
+
+ let sis = Cc["@mozilla.org/scriptableinputstream;1"].
+ createInstance(Ci.nsIScriptableInputStream);
+ try {
+ sis.init(chan.open2());
+ this._parseListJSON(sis.read(sis.available()), uris);
+ // parseListJSON will catch its own errors, so we
+ // should only go into this catch if list.json
+ // doesn't exist
+ } catch (e) {
+ chan = makeChannel(APP_SEARCH_PREFIX + "list.txt");
+ sis.init(chan.open2());
+ this._parseListTxt(sis.read(sis.available()), uris);
+ }
+ return uris;
+ },
+
+ /**
+ * Loads jar engines asynchronously.
+ *
+ * @returns {Promise} A promise, resolved successfully if finding jar engines
+ * succeeds.
+ */
+ _asyncFindJAREngines: Task.async(function* () {
+ LOG("_asyncFindJAREngines: looking for engines in JARs")
+
+ let listURL = APP_SEARCH_PREFIX + "list.json";
+ let chan = makeChannel(listURL);
+ if (!chan) {
+ LOG("_asyncFindJAREngines: " + APP_SEARCH_PREFIX + " isn't registered");
+ return [];
+ }
+
+ let uris = [];
+
+ // Read list.json to find the engines we need to load.
+ let deferred = Promise.defer();
+ let request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
+ createInstance(Ci.nsIXMLHttpRequest);
+ request.overrideMimeType("text/plain");
+ request.onload = function(aEvent) {
+ deferred.resolve(aEvent.target.responseText);
+ };
+ request.onerror = function(aEvent) {
+ LOG("_asyncFindJAREngines: failed to read " + listURL);
+ // Couldn't find list.json, try list.txt
+ request.onerror = function(aEvent) {
+ LOG("_asyncFindJAREngines: failed to read " + APP_SEARCH_PREFIX + "list.txt");
+ deferred.resolve("");
+ }
+ request.open("GET", NetUtil.newURI(APP_SEARCH_PREFIX + "list.txt").spec, true);
+ request.send();
+ };
+ request.open("GET", NetUtil.newURI(listURL).spec, true);
+ request.send();
+ let list = yield deferred.promise;
+
+ if (request.responseURL.endsWith(".txt")) {
+ this._parseListTxt(list, uris);
+ } else {
+ this._parseListJSON(list, uris);
+ }
+ return uris;
+ }),
+
+ _parseListJSON: function SRCH_SVC_parseListJSON(list, uris) {
+ let searchSettings;
+ try {
+ searchSettings = JSON.parse(list);
+ } catch (e) {
+ LOG("failing to parse list.json: " + e);
+ return;
+ }
+
+ let jarNames = new Set();
+ for (let region in searchSettings) {
+ // Artifact builds use the full list.json which parses
+ // slightly differently
+ if (!("visibleDefaultEngines" in searchSettings[region])) {
+ continue;
+ }
+ for (let engine of searchSettings[region]["visibleDefaultEngines"]) {
+ jarNames.add(engine);
+ }
+ }
+
+ // Check if we have a useable country specific list of visible default engines.
+ let engineNames;
+ let visibleDefaultEngines = this.getVerifiedGlobalAttr("visibleDefaultEngines");
+ if (visibleDefaultEngines) {
+ engineNames = visibleDefaultEngines.split(",");
+ for (let engineName of engineNames) {
+ // If all engineName values are part of jarNames,
+ // then we can use the country specific list, otherwise ignore it.
+ // The visibleDefaultEngines string containing the name of an engine we
+ // don't ship indicates the server is misconfigured to answer requests
+ // from the specific Firefox version we are running, so ignoring the
+ // value altogether is safer.
+ if (!jarNames.has(engineName)) {
+ LOG("_parseListJSON: ignoring visibleDefaultEngines value because " +
+ engineName + " is not in the jar engines we have found");
+ engineNames = null;
+ break;
+ }
+ }
+ }
+
+ // Fallback to building a list based on the regions in the JSON
+ if (!engineNames || !engineNames.length) {
+ let region;
+ if (Services.prefs.prefHasUserValue("browser.search.region")) {
+ region = Services.prefs.getCharPref("browser.search.region");
+ }
+ if (!region || !(region in searchSettings)) {
+ region = "default";
+ }
+ engineNames = searchSettings[region]["visibleDefaultEngines"];
+ }
+
+ for (let name of engineNames) {
+ uris.push(APP_SEARCH_PREFIX + name + ".xml");
+ }
+
+ // Store this so that it can be used while writing the cache file.
+ this._visibleDefaultEngines = engineNames;
+ },
+
+ _parseListTxt: function SRCH_SVC_parseListTxt(list, uris) {
+ let names = list.split("\n").filter(n => !!n);
+ // This maps the names of our built-in engines to a boolean
+ // indicating whether it should be hidden by default.
+ let jarNames = new Map();
+ for (let name of names) {
+ if (name.endsWith(":hidden")) {
+ name = name.split(":")[0];
+ jarNames.set(name, true);
+ } else {
+ jarNames.set(name, false);
+ }
+ }
+
+ // Check if we have a useable country specific list of visible default engines.
+ let engineNames;
+ let visibleDefaultEngines = this.getVerifiedGlobalAttr("visibleDefaultEngines");
+ if (visibleDefaultEngines) {
+ engineNames = visibleDefaultEngines.split(",");
+
+ for (let engineName of engineNames) {
+ // If all engineName values are part of jarNames,
+ // then we can use the country specific list, otherwise ignore it.
+ // The visibleDefaultEngines string containing the name of an engine we
+ // don't ship indicates the server is misconfigured to answer requests
+ // from the specific Firefox version we are running, so ignoring the
+ // value altogether is safer.
+ if (!jarNames.has(engineName)) {
+ LOG("_parseListTxt: ignoring visibleDefaultEngines value because " +
+ engineName + " is not in the jar engines we have found");
+ engineNames = null;
+ break;
+ }
+ }
+ }
+
+ // Fallback to building a list based on the :hidden suffixes found in list.txt.
+ if (!engineNames) {
+ engineNames = [];
+ for (let [name, hidden] of jarNames) {
+ if (!hidden)
+ engineNames.push(name);
+ }
+ }
+
+ for (let name of engineNames) {
+ uris.push(APP_SEARCH_PREFIX + name + ".xml");
+ }
+
+ // Store this so that it can be used while writing the cache file.
+ this._visibleDefaultEngines = engineNames;
+ },
+
+
+ _saveSortedEngineList: function SRCH_SVC_saveSortedEngineList() {
+ LOG("SRCH_SVC_saveSortedEngineList: starting");
+
+ // Set the useDB pref to indicate that from now on we should use the order
+ // information stored in the database.
+ Services.prefs.setBoolPref(BROWSER_SEARCH_PREF + "useDBForOrder", true);
+
+ var engines = this._getSortedEngines(true);
+
+ for (var i = 0; i < engines.length; ++i) {
+ engines[i].setAttr("order", i + 1);
+ }
+
+ LOG("SRCH_SVC_saveSortedEngineList: done");
+ },
+
+ _buildSortedEngineList: function SRCH_SVC_buildSortedEngineList() {
+ LOG("_buildSortedEngineList: building list");
+ var addedEngines = { };
+ this.__sortedEngines = [];
+ var engine;
+
+ // If the user has specified a custom engine order, read the order
+ // information from the metadata instead of the default prefs.
+ if (getBoolPref(BROWSER_SEARCH_PREF + "useDBForOrder", false)) {
+ LOG("_buildSortedEngineList: using db for order");
+
+ // Flag to keep track of whether or not we need to call _saveSortedEngineList.
+ let needToSaveEngineList = false;
+
+ for (let name in this._engines) {
+ let engine = this._engines[name];
+ var orderNumber = engine.getAttr("order");
+
+ // Since the DB isn't regularly cleared, and engine files may disappear
+ // without us knowing, we may already have an engine in this slot. If
+ // that happens, we just skip it - it will be added later on as an
+ // unsorted engine.
+ if (orderNumber && !this.__sortedEngines[orderNumber-1]) {
+ this.__sortedEngines[orderNumber-1] = engine;
+ addedEngines[engine.name] = engine;
+ } else {
+ // We need to call _saveSortedEngineList so this gets sorted out.
+ needToSaveEngineList = true;
+ }
+ }
+
+ // Filter out any nulls for engines that may have been removed
+ var filteredEngines = this.__sortedEngines.filter(function(a) { return !!a; });
+ if (this.__sortedEngines.length != filteredEngines.length)
+ needToSaveEngineList = true;
+ this.__sortedEngines = filteredEngines;
+
+ if (needToSaveEngineList)
+ this._saveSortedEngineList();
+ } else {
+ // The DB isn't being used, so just read the engine order from the prefs
+ var i = 0;
+ var engineName;
+ var prefName;
+
+ try {
+ var extras =
+ Services.prefs.getChildList(BROWSER_SEARCH_PREF + "order.extra.");
+
+ for (prefName of extras) {
+ engineName = Services.prefs.getCharPref(prefName);
+
+ engine = this._engines[engineName];
+ if (!engine || engine.name in addedEngines)
+ continue;
+
+ this.__sortedEngines.push(engine);
+ addedEngines[engine.name] = engine;
+ }
+ }
+ catch (e) { }
+
+ let prefNameBase = getGeoSpecificPrefName(BROWSER_SEARCH_PREF + "order");
+ while (true) {
+ prefName = prefNameBase + "." + (++i);
+ engineName = getLocalizedPref(prefName);
+ if (!engineName)
+ break;
+
+ engine = this._engines[engineName];
+ if (!engine || engine.name in addedEngines)
+ continue;
+
+ this.__sortedEngines.push(engine);
+ addedEngines[engine.name] = engine;
+ }
+ }
+
+ // Array for the remaining engines, alphabetically sorted.
+ let alphaEngines = [];
+
+ for (let name in this._engines) {
+ let engine = this._engines[name];
+ if (!(engine.name in addedEngines))
+ alphaEngines.push(this._engines[engine.name]);
+ }
+
+ let locale = Cc["@mozilla.org/intl/nslocaleservice;1"]
+ .getService(Ci.nsILocaleService)
+ .newLocale(getLocale());
+ let collation = Cc["@mozilla.org/intl/collation-factory;1"]
+ .createInstance(Ci.nsICollationFactory)
+ .CreateCollation(locale);
+ const strength = Ci.nsICollation.kCollationCaseInsensitiveAscii;
+ let comparator = (a, b) => collation.compareString(strength, a.name, b.name);
+ alphaEngines.sort(comparator);
+ return this.__sortedEngines = this.__sortedEngines.concat(alphaEngines);
+ },
+
+ /**
+ * Get a sorted array of engines.
+ * @param aWithHidden
+ * True if hidden plugins should be included in the result.
+ */
+ _getSortedEngines: function SRCH_SVC_getSorted(aWithHidden) {
+ if (aWithHidden)
+ return this._sortedEngines;
+
+ return this._sortedEngines.filter(function (engine) {
+ return !engine.hidden;
+ });
+ },
+
+ // nsIBrowserSearchService
+ init: function SRCH_SVC_init(observer) {
+ LOG("SearchService.init");
+ let self = this;
+ if (!this._initStarted) {
+ TelemetryStopwatch.start("SEARCH_SERVICE_INIT_MS");
+ this._initStarted = true;
+ Task.spawn(function* task() {
+ try {
+ // Complete initialization by calling asynchronous initializer.
+ yield self._asyncInit();
+ TelemetryStopwatch.finish("SEARCH_SERVICE_INIT_MS");
+ } catch (ex) {
+ if (ex.result == Cr.NS_ERROR_ALREADY_INITIALIZED) {
+ // No need to pursue asynchronous because synchronous fallback was
+ // called and has finished.
+ TelemetryStopwatch.finish("SEARCH_SERVICE_INIT_MS");
+ } else {
+ self._initObservers.reject(ex);
+ TelemetryStopwatch.cancel("SEARCH_SERVICE_INIT_MS");
+ }
+ }
+ });
+ }
+ if (observer) {
+ this._initObservers.promise.then(
+ function onSuccess() {
+ try {
+ observer.onInitComplete(self._initRV);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ },
+ function onError(aReason) {
+ Cu.reportError("Internal error while initializing SearchService: " + aReason);
+ observer.onInitComplete(Components.results.NS_ERROR_UNEXPECTED);
+ }
+ );
+ }
+ },
+
+ get isInitialized() {
+ return gInitialized;
+ },
+
+ getEngines: function SRCH_SVC_getEngines(aCount) {
+ this._ensureInitialized();
+ LOG("getEngines: getting all engines");
+ var engines = this._getSortedEngines(true);
+ aCount.value = engines.length;
+ return engines;
+ },
+
+ getVisibleEngines: function SRCH_SVC_getVisible(aCount) {
+ this._ensureInitialized();
+ LOG("getVisibleEngines: getting all visible engines");
+ var engines = this._getSortedEngines(false);
+ aCount.value = engines.length;
+ return engines;
+ },
+
+ getDefaultEngines: function SRCH_SVC_getDefault(aCount) {
+ this._ensureInitialized();
+ function isDefault(engine) {
+ return engine._isDefault;
+ }
+ var engines = this._sortedEngines.filter(isDefault);
+ var engineOrder = {};
+ var engineName;
+ var i = 1;
+
+ // Build a list of engines which we have ordering information for.
+ // We're rebuilding the list here because _sortedEngines contain the
+ // current order, but we want the original order.
+
+ // First, look at the "browser.search.order.extra" branch.
+ try {
+ var extras = Services.prefs.getChildList(BROWSER_SEARCH_PREF + "order.extra.");
+
+ for (var prefName of extras) {
+ engineName = Services.prefs.getCharPref(prefName);
+
+ if (!(engineName in engineOrder))
+ engineOrder[engineName] = i++;
+ }
+ } catch (e) {
+ LOG("Getting extra order prefs failed: " + e);
+ }
+
+ // Now look through the "browser.search.order" branch.
+ let prefNameBase = getGeoSpecificPrefName(BROWSER_SEARCH_PREF + "order");
+ for (var j = 1; ; j++) {
+ let prefName = prefNameBase + "." + j;
+ engineName = getLocalizedPref(prefName);
+ if (!engineName)
+ break;
+
+ if (!(engineName in engineOrder))
+ engineOrder[engineName] = i++;
+ }
+
+ LOG("getDefaultEngines: engineOrder: " + engineOrder.toSource());
+
+ function compareEngines (a, b) {
+ var aIdx = engineOrder[a.name];
+ var bIdx = engineOrder[b.name];
+
+ if (aIdx && bIdx)
+ return aIdx - bIdx;
+ if (aIdx)
+ return -1;
+ if (bIdx)
+ return 1;
+
+ return a.name.localeCompare(b.name);
+ }
+ engines.sort(compareEngines);
+
+ aCount.value = engines.length;
+ return engines;
+ },
+
+ getEngineByName: function SRCH_SVC_getEngineByName(aEngineName) {
+ this._ensureInitialized();
+ return this._engines[aEngineName] || null;
+ },
+
+ getEngineByAlias: function SRCH_SVC_getEngineByAlias(aAlias) {
+ this._ensureInitialized();
+ for (var engineName in this._engines) {
+ var engine = this._engines[engineName];
+ if (engine && engine.alias == aAlias)
+ return engine;
+ }
+ return null;
+ },
+
+ addEngineWithDetails: function SRCH_SVC_addEWD(aName, aIconURL, aAlias,
+ aDescription, aMethod,
+ aTemplate, aExtensionID) {
+ this._ensureInitialized();
+ if (!aName)
+ FAIL("Invalid name passed to addEngineWithDetails!");
+ if (!aMethod)
+ FAIL("Invalid method passed to addEngineWithDetails!");
+ if (!aTemplate)
+ FAIL("Invalid template passed to addEngineWithDetails!");
+ if (this._engines[aName])
+ FAIL("An engine with that name already exists!", Cr.NS_ERROR_FILE_ALREADY_EXISTS);
+
+ var engine = new Engine(sanitizeName(aName), false);
+ engine._initFromMetadata(aName, aIconURL, aAlias, aDescription,
+ aMethod, aTemplate, aExtensionID);
+ engine._loadPath = "[other]addEngineWithDetails";
+ this._addEngineToStore(engine);
+ },
+
+ addEngine: function SRCH_SVC_addEngine(aEngineURL, aDataType, aIconURL,
+ aConfirm, aCallback) {
+ LOG("addEngine: Adding \"" + aEngineURL + "\".");
+ this._ensureInitialized();
+ try {
+ var uri = makeURI(aEngineURL);
+ var engine = new Engine(uri, false);
+ if (aCallback) {
+ engine._installCallback = function (errorCode) {
+ try {
+ if (errorCode == null)
+ aCallback.onSuccess(engine);
+ else
+ aCallback.onError(errorCode);
+ } catch (ex) {
+ Cu.reportError("Error invoking addEngine install callback: " + ex);
+ }
+ // Clear the reference to the callback now that it's been invoked.
+ engine._installCallback = null;
+ };
+ }
+ engine._initFromURIAndLoad(uri);
+ } catch (ex) {
+ // Drop the reference to the callback, if set
+ if (engine)
+ engine._installCallback = null;
+ FAIL("addEngine: Error adding engine:\n" + ex, Cr.NS_ERROR_FAILURE);
+ }
+ engine._setIcon(aIconURL, false);
+ engine._confirm = aConfirm;
+ },
+
+ removeEngine: function SRCH_SVC_removeEngine(aEngine) {
+ this._ensureInitialized();
+ if (!aEngine)
+ FAIL("no engine passed to removeEngine!");
+
+ var engineToRemove = null;
+ for (var e in this._engines) {
+ if (aEngine.wrappedJSObject == this._engines[e])
+ engineToRemove = this._engines[e];
+ }
+
+ if (!engineToRemove)
+ FAIL("removeEngine: Can't find engine to remove!", Cr.NS_ERROR_FILE_NOT_FOUND);
+
+ if (engineToRemove == this.currentEngine) {
+ this._currentEngine = null;
+ }
+
+ if (engineToRemove._readOnly) {
+ // Just hide it (the "hidden" setter will notify) and remove its alias to
+ // avoid future conflicts with other engines.
+ engineToRemove.hidden = true;
+ engineToRemove.alias = null;
+ } else {
+ // Remove the engine file from disk if we had a legacy file in the profile.
+ if (engineToRemove._filePath) {
+ let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
+ file.persistentDescriptor = engineToRemove._filePath;
+ if (file.exists()) {
+ file.remove(false);
+ }
+ engineToRemove._filePath = null;
+ }
+
+ // Remove the engine from _sortedEngines
+ var index = this._sortedEngines.indexOf(engineToRemove);
+ if (index == -1)
+ FAIL("Can't find engine to remove in _sortedEngines!", Cr.NS_ERROR_FAILURE);
+ this.__sortedEngines.splice(index, 1);
+
+ // Remove the engine from the internal store
+ delete this._engines[engineToRemove.name];
+
+ // Since we removed an engine, we need to update the preferences.
+ this._saveSortedEngineList();
+ }
+ notifyAction(engineToRemove, SEARCH_ENGINE_REMOVED);
+ },
+
+ moveEngine: function SRCH_SVC_moveEngine(aEngine, aNewIndex) {
+ this._ensureInitialized();
+ if ((aNewIndex > this._sortedEngines.length) || (aNewIndex < 0))
+ FAIL("SRCH_SVC_moveEngine: Index out of bounds!");
+ if (!(aEngine instanceof Ci.nsISearchEngine))
+ FAIL("SRCH_SVC_moveEngine: Invalid engine passed to moveEngine!");
+ if (aEngine.hidden)
+ FAIL("moveEngine: Can't move a hidden engine!", Cr.NS_ERROR_FAILURE);
+
+ var engine = aEngine.wrappedJSObject;
+
+ var currentIndex = this._sortedEngines.indexOf(engine);
+ if (currentIndex == -1)
+ FAIL("moveEngine: Can't find engine to move!", Cr.NS_ERROR_UNEXPECTED);
+
+ // Our callers only take into account non-hidden engines when calculating
+ // aNewIndex, but we need to move it in the array of all engines, so we
+ // need to adjust aNewIndex accordingly. To do this, we count the number
+ // of hidden engines in the list before the engine that we're taking the
+ // place of. We do this by first finding newIndexEngine (the engine that
+ // we were supposed to replace) and then iterating through the complete
+ // engine list until we reach it, increasing aNewIndex for each hidden
+ // engine we find on our way there.
+ //
+ // This could be further simplified by having our caller pass in
+ // newIndexEngine directly instead of aNewIndex.
+ var newIndexEngine = this._getSortedEngines(false)[aNewIndex];
+ if (!newIndexEngine)
+ FAIL("moveEngine: Can't find engine to replace!", Cr.NS_ERROR_UNEXPECTED);
+
+ for (var i = 0; i < this._sortedEngines.length; ++i) {
+ if (newIndexEngine == this._sortedEngines[i])
+ break;
+ if (this._sortedEngines[i].hidden)
+ aNewIndex++;
+ }
+
+ if (currentIndex == aNewIndex)
+ return; // nothing to do!
+
+ // Move the engine
+ var movedEngine = this.__sortedEngines.splice(currentIndex, 1)[0];
+ this.__sortedEngines.splice(aNewIndex, 0, movedEngine);
+
+ notifyAction(engine, SEARCH_ENGINE_CHANGED);
+
+ // Since we moved an engine, we need to update the preferences.
+ this._saveSortedEngineList();
+ },
+
+ restoreDefaultEngines: function SRCH_SVC_resetDefaultEngines() {
+ this._ensureInitialized();
+ for (let name in this._engines) {
+ let e = this._engines[name];
+ // Unhide all default engines
+ if (e.hidden && e._isDefault)
+ e.hidden = false;
+ }
+ },
+
+ get defaultEngine() { return this.currentEngine; },
+
+ set defaultEngine(val) {
+ this.currentEngine = val;
+ },
+
+ get currentEngine() {
+ this._ensureInitialized();
+ if (!this._currentEngine) {
+ let name = this.getGlobalAttr("current");
+ let engine = this.getEngineByName(name);
+ if (engine && (this.getGlobalAttr("hash") == getVerificationHash(name) ||
+ engine._isDefault)) {
+ // If the current engine is a default one, we can relax the
+ // verification hash check to reduce the annoyance for users who
+ // backup/sync their profile in custom ways.
+ this._currentEngine = engine;
+ }
+ if (!name)
+ this._currentEngine = this.originalDefaultEngine;
+ }
+
+ // If the current engine is not set or hidden, we fallback...
+ if (!this._currentEngine || this._currentEngine.hidden) {
+ // first to the original default engine
+ let originalDefault = this.originalDefaultEngine;
+ if (!originalDefault || originalDefault.hidden) {
+ // then to the first visible engine
+ let firstVisible = this._getSortedEngines(false)[0];
+ if (firstVisible && !firstVisible.hidden) {
+ this.currentEngine = firstVisible;
+ return firstVisible;
+ }
+ // and finally as a last resort we unhide the original default engine.
+ if (originalDefault)
+ originalDefault.hidden = false;
+ }
+ if (!originalDefault)
+ return null;
+
+ // If the current engine wasn't set or was hidden, we used a fallback
+ // to pick a new current engine. As soon as we return it, this new
+ // current engine will become user-visible, so we should persist it.
+ // by calling the setter.
+ this.currentEngine = originalDefault;
+ }
+
+ return this._currentEngine;
+ },
+
+ set currentEngine(val) {
+ this._ensureInitialized();
+ // Sometimes we get wrapped nsISearchEngine objects (external XPCOM callers),
+ // and sometimes we get raw Engine JS objects (callers in this file), so
+ // handle both.
+ if (!(val instanceof Ci.nsISearchEngine) && !(val instanceof Engine))
+ FAIL("Invalid argument passed to currentEngine setter");
+
+ var newCurrentEngine = this.getEngineByName(val.name);
+ if (!newCurrentEngine)
+ FAIL("Can't find engine in store!", Cr.NS_ERROR_UNEXPECTED);
+
+ if (!newCurrentEngine._isDefault) {
+ // If a non default engine is being set as the current engine, ensure
+ // its loadPath has a verification hash.
+ if (!newCurrentEngine._loadPath)
+ newCurrentEngine._loadPath = "[other]unknown";
+ let loadPathHash = getVerificationHash(newCurrentEngine._loadPath);
+ let currentHash = newCurrentEngine.getAttr("loadPathHash");
+ if (!currentHash || currentHash != loadPathHash) {
+ newCurrentEngine.setAttr("loadPathHash", loadPathHash);
+ notifyAction(newCurrentEngine, SEARCH_ENGINE_CHANGED);
+ }
+ }
+
+ if (newCurrentEngine == this._currentEngine)
+ return;
+
+ this._currentEngine = newCurrentEngine;
+
+ // If we change the default engine in the future, that change should impact
+ // users who have switched away from and then back to the build's "default"
+ // engine. So clear the user pref when the currentEngine is set to the
+ // build's default engine, so that the currentEngine getter falls back to
+ // whatever the default is.
+ let newName = this._currentEngine.name;
+ if (this._currentEngine == this.originalDefaultEngine) {
+ newName = "";
+ }
+
+ this.setGlobalAttr("current", newName);
+ this.setGlobalAttr("hash", getVerificationHash(newName));
+
+ notifyAction(this._currentEngine, SEARCH_ENGINE_DEFAULT);
+ notifyAction(this._currentEngine, SEARCH_ENGINE_CURRENT);
+ },
+
+ getDefaultEngineInfo() {
+ let result = {};
+
+ let engine;
+ try {
+ engine = this.defaultEngine;
+ } catch (e) {
+ // The defaultEngine getter will throw if there's no engine at all,
+ // which shouldn't happen unless an add-on or a test deleted all of them.
+ // Our preferences UI doesn't let users do that.
+ Cu.reportError("getDefaultEngineInfo: No default engine");
+ }
+
+ if (!engine) {
+ result.name = "NONE";
+ } else {
+ if (engine.name)
+ result.name = engine.name;
+
+ result.loadPath = engine._loadPath;
+
+ let origin;
+ if (engine._isDefault)
+ origin = "default";
+ else {
+ let currentHash = engine.getAttr("loadPathHash");
+ if (!currentHash)
+ origin = "unverified";
+ else {
+ let loadPathHash = getVerificationHash(engine._loadPath);
+ origin = currentHash == loadPathHash ? "verified" : "invalid";
+ }
+ }
+ result.origin = origin;
+
+ // For privacy, we only collect the submission URL for default engines...
+ let sendSubmissionURL = engine._isDefault;
+
+ // ... or engines sorted by default near the top of the list.
+ if (!sendSubmissionURL) {
+ let extras =
+ Services.prefs.getChildList(BROWSER_SEARCH_PREF + "order.extra.");
+
+ for (let prefName of extras) {
+ try {
+ if (result.name == Services.prefs.getCharPref(prefName)) {
+ sendSubmissionURL = true;
+ break;
+ }
+ } catch (e) {}
+ }
+
+ let prefNameBase = getGeoSpecificPrefName(BROWSER_SEARCH_PREF + "order");
+ let i = 0;
+ while (!sendSubmissionURL) {
+ let prefName = prefNameBase + "." + (++i);
+ let engineName = getLocalizedPref(prefName);
+ if (!engineName)
+ break;
+ if (result.name == engineName) {
+ sendSubmissionURL = true;
+ break;
+ }
+ }
+ }
+
+ if (sendSubmissionURL) {
+ let uri = engine._getURLOfType("text/html")
+ .getSubmission("", engine, "searchbar").uri;
+ uri.userPass = ""; // Avoid reporting a username or password.
+ result.submissionURL = uri.spec;
+ }
+ }
+
+ return result;
+ },
+
+ _recordEngineTelemetry: function() {
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_ENGINE_COUNT")
+ .add(Object.keys(this._engines).length);
+ let hasUpdates = false;
+ let hasIconUpdates = false;
+ for (let name in this._engines) {
+ let engine = this._engines[name];
+ if (engine._hasUpdates) {
+ hasUpdates = true;
+ if (engine._iconUpdateURL) {
+ hasIconUpdates = true;
+ break;
+ }
+ }
+ }
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_HAS_UPDATES").add(hasUpdates);
+ Services.telemetry.getHistogramById("SEARCH_SERVICE_HAS_ICON_UPDATES").add(hasIconUpdates);
+ },
+
+ /**
+ * This map is built lazily after the available search engines change. It
+ * allows quick parsing of an URL representing a search submission into the
+ * search engine name and original terms.
+ *
+ * The keys are strings containing the domain name and lowercase path of the
+ * engine submission, for example "www.google.com/search".
+ *
+ * The values are objects with these properties:
+ * {
+ * engine: The associated nsISearchEngine.
+ * termsParameterName: Name of the URL parameter containing the search
+ * terms, for example "q".
+ * }
+ */
+ _parseSubmissionMap: null,
+
+ _buildParseSubmissionMap: function SRCH_SVC__buildParseSubmissionMap() {
+ LOG("_buildParseSubmissionMap");
+ this._parseSubmissionMap = new Map();
+
+ // Used only while building the map, indicates which entries do not refer to
+ // the main domain of the engine but to an alternate domain, for example
+ // "www.google.fr" for the "www.google.com" search engine.
+ let keysOfAlternates = new Set();
+
+ for (let engine of this._sortedEngines) {
+ LOG("Processing engine: " + engine.name);
+
+ if (engine.hidden) {
+ LOG("Engine is hidden.");
+ continue;
+ }
+
+ let urlParsingInfo = engine.getURLParsingInfo();
+ if (!urlParsingInfo) {
+ LOG("Engine does not support URL parsing.");
+ continue;
+ }
+
+ // Store the same object on each matching map key, as an optimization.
+ let mapValueForEngine = {
+ engine: engine,
+ termsParameterName: urlParsingInfo.termsParameterName,
+ };
+
+ let processDomain = (domain, isAlternate) => {
+ let key = domain + urlParsingInfo.path;
+
+ // Apply the logic for which main domains take priority over alternate
+ // domains, even if they are found later in the ordered engine list.
+ let existingEntry = this._parseSubmissionMap.get(key);
+ if (!existingEntry) {
+ LOG("Adding new entry: " + key);
+ if (isAlternate) {
+ keysOfAlternates.add(key);
+ }
+ } else if (!isAlternate && keysOfAlternates.has(key)) {
+ LOG("Overriding alternate entry: " + key +
+ " (" + existingEntry.engine.name + ")");
+ keysOfAlternates.delete(key);
+ } else {
+ LOG("Keeping existing entry: " + key +
+ " (" + existingEntry.engine.name + ")");
+ return;
+ }
+
+ this._parseSubmissionMap.set(key, mapValueForEngine);
+ };
+
+ processDomain(urlParsingInfo.mainDomain, false);
+ SearchStaticData.getAlternateDomains(urlParsingInfo.mainDomain)
+ .forEach(d => processDomain(d, true));
+ }
+ },
+
+ /**
+ * Checks to see if any engine has an EngineURL of type URLTYPE_SEARCH_HTML
+ * for this request-method, template URL, and query params.
+ */
+ hasEngineWithURL: function(method, template, formData) {
+ this._ensureInitialized();
+
+ // Quick helper method to ensure formData filtered/sorted for compares.
+ let getSortedFormData = data => {
+ return data.filter(a => a.name && a.value).sort((a, b) => {
+ if (a.name > b.name) {
+ return 1;
+ } else if (b.name > a.name) {
+ return -1;
+ } else if (a.value > b.value) {
+ return 1;
+ }
+ return (b.value > a.value) ? -1 : 0;
+ });
+ };
+
+ // Sanitize method, ensure formData is pre-sorted.
+ let methodUpper = method.toUpperCase();
+ let sortedFormData = getSortedFormData(formData);
+ let sortedFormLength = sortedFormData.length;
+
+ return this._getSortedEngines(false).some(engine => {
+ return engine._urls.some(url => {
+ // Not an engineURL match if type, method, url, #params don't match.
+ if (url.type != URLTYPE_SEARCH_HTML ||
+ url.method != methodUpper ||
+ url.template != template ||
+ url.params.length != sortedFormLength) {
+ return false;
+ }
+
+ // Ensure engineURL formData is pre-sorted. Then, we're
+ // not an engineURL match if any queryParam doesn't compare.
+ let sortedParams = getSortedFormData(url.params);
+ for (let i = 0; i < sortedFormLength; i++) {
+ let formData = sortedFormData[i];
+ let param = sortedParams[i];
+ if (param.name != formData.name ||
+ param.value != formData.value ||
+ param.purpose != formData.purpose) {
+ return false;
+ }
+ }
+ // Else we're a match.
+ return true;
+ });
+ });
+ },
+
+ parseSubmissionURL: function SRCH_SVC_parseSubmissionURL(aURL) {
+ this._ensureInitialized();
+ LOG("parseSubmissionURL: Parsing \"" + aURL + "\".");
+
+ if (!this._parseSubmissionMap) {
+ this._buildParseSubmissionMap();
+ }
+
+ // Extract the elements of the provided URL first.
+ let soughtKey, soughtQuery;
+ try {
+ let soughtUrl = NetUtil.newURI(aURL).QueryInterface(Ci.nsIURL);
+
+ // Exclude any URL that is not HTTP or HTTPS from the beginning.
+ if (soughtUrl.scheme != "http" && soughtUrl.scheme != "https") {
+ LOG("The URL scheme is not HTTP or HTTPS.");
+ return gEmptyParseSubmissionResult;
+ }
+
+ // Reading these URL properties may fail and raise an exception.
+ soughtKey = soughtUrl.host + soughtUrl.filePath.toLowerCase();
+ soughtQuery = soughtUrl.query;
+ } catch (ex) {
+ // Errors while parsing the URL or accessing the properties are not fatal.
+ LOG("The value does not look like a structured URL.");
+ return gEmptyParseSubmissionResult;
+ }
+
+ // Look up the domain and path in the map to identify the search engine.
+ let mapEntry = this._parseSubmissionMap.get(soughtKey);
+ if (!mapEntry) {
+ LOG("No engine associated with domain and path: " + soughtKey);
+ return gEmptyParseSubmissionResult;
+ }
+
+ // Extract the search terms from the parameter, for example "caff%C3%A8"
+ // from the URL "https://www.google.com/search?q=caff%C3%A8&client=firefox".
+ let encodedTerms = null;
+ for (let param of soughtQuery.split("&")) {
+ let equalPos = param.indexOf("=");
+ if (equalPos != -1 &&
+ param.substr(0, equalPos) == mapEntry.termsParameterName) {
+ // This is the parameter we are looking for.
+ encodedTerms = param.substr(equalPos + 1);
+ break;
+ }
+ }
+ if (encodedTerms === null) {
+ LOG("Missing terms parameter: " + mapEntry.termsParameterName);
+ return gEmptyParseSubmissionResult;
+ }
+
+ let length = 0;
+ let offset = aURL.indexOf("?") + 1;
+ let query = aURL.slice(offset);
+ // Iterate a second time over the original input string to determine the
+ // correct search term offset and length in the original encoding.
+ for (let param of query.split("&")) {
+ let equalPos = param.indexOf("=");
+ if (equalPos != -1 &&
+ param.substr(0, equalPos) == mapEntry.termsParameterName) {
+ // This is the parameter we are looking for.
+ offset += equalPos + 1;
+ length = param.length - equalPos - 1;
+ break;
+ }
+ offset += param.length + 1;
+ }
+
+ // Decode the terms using the charset defined in the search engine.
+ let terms;
+ try {
+ terms = gTextToSubURI.UnEscapeAndConvert(
+ mapEntry.engine.queryCharset,
+ encodedTerms.replace(/\+/g, " "));
+ } catch (ex) {
+ // Decoding errors will cause this match to be ignored.
+ LOG("Parameter decoding failed. Charset: " +
+ mapEntry.engine.queryCharset);
+ return gEmptyParseSubmissionResult;
+ }
+
+ LOG("Match found. Terms: " + terms);
+ return new ParseSubmissionResult(mapEntry.engine, terms, offset, length);
+ },
+
+ // nsIObserver
+ observe: function SRCH_SVC_observe(aEngine, aTopic, aVerb) {
+ switch (aTopic) {
+ case SEARCH_ENGINE_TOPIC:
+ switch (aVerb) {
+ case SEARCH_ENGINE_LOADED:
+ var engine = aEngine.QueryInterface(Ci.nsISearchEngine);
+ LOG("nsSearchService::observe: Done installation of " + engine.name
+ + ".");
+ this._addEngineToStore(engine.wrappedJSObject);
+ if (engine.wrappedJSObject._useNow) {
+ LOG("nsSearchService::observe: setting current");
+ this.currentEngine = aEngine;
+ }
+ // The addition of the engine to the store always triggers an ADDED
+ // or a CHANGED notification, that will trigger the task below.
+ break;
+ case SEARCH_ENGINE_ADDED:
+ case SEARCH_ENGINE_CHANGED:
+ case SEARCH_ENGINE_REMOVED:
+ this.batchTask.disarm();
+ this.batchTask.arm();
+ // Invalidate the map used to parse URLs to search engines.
+ this._parseSubmissionMap = null;
+ break;
+ }
+ break;
+
+ case QUIT_APPLICATION_TOPIC:
+ this._removeObservers();
+ break;
+
+ case "nsPref:changed":
+ if (aVerb == LOCALE_PREF) {
+ // Locale changed. Re-init. We rely on observers, because we can't
+ // return this promise to anyone.
+ this._asyncReInit();
+ break;
+ }
+ }
+ },
+
+ // nsITimerCallback
+ notify: function SRCH_SVC_notify(aTimer) {
+ LOG("_notify: checking for updates");
+
+ if (!getBoolPref(BROWSER_SEARCH_PREF + "update", true))
+ return;
+
+ // Our timer has expired, but unfortunately, we can't get any data from it.
+ // Therefore, we need to walk our engine-list, looking for expired engines
+ var currentTime = Date.now();
+ LOG("currentTime: " + currentTime);
+ for (let name in this._engines) {
+ let engine = this._engines[name].wrappedJSObject;
+ if (!engine._hasUpdates)
+ continue;
+
+ LOG("checking " + engine.name);
+
+ var expirTime = engine.getAttr("updateexpir");
+ LOG("expirTime: " + expirTime + "\nupdateURL: " + engine._updateURL +
+ "\niconUpdateURL: " + engine._iconUpdateURL);
+
+ var engineExpired = expirTime <= currentTime;
+
+ if (!expirTime || !engineExpired) {
+ LOG("skipping engine");
+ continue;
+ }
+
+ LOG(engine.name + " has expired");
+
+ engineUpdateService.update(engine);
+
+ // Schedule the next update
+ engineUpdateService.scheduleNextUpdate(engine);
+
+ } // end engine iteration
+ },
+
+ _addObservers: function SRCH_SVC_addObservers() {
+ if (this._observersAdded) {
+ // There might be a race between synchronous and asynchronous
+ // initialization for which we try to register the observers twice.
+ return;
+ }
+ this._observersAdded = true;
+
+ Services.obs.addObserver(this, SEARCH_ENGINE_TOPIC, false);
+ Services.obs.addObserver(this, QUIT_APPLICATION_TOPIC, false);
+
+ if (AppConstants.MOZ_BUILD_APP == "mobile/android") {
+ Services.prefs.addObserver(LOCALE_PREF, this, false);
+ }
+
+ // The current stage of shutdown. Used to help analyze crash
+ // signatures in case of shutdown timeout.
+ let shutdownState = {
+ step: "Not started",
+ latestError: {
+ message: undefined,
+ stack: undefined
+ }
+ };
+ OS.File.profileBeforeChange.addBlocker(
+ "Search service: shutting down",
+ () => Task.spawn(function* () {
+ if (this._batchTask) {
+ shutdownState.step = "Finalizing batched task";
+ try {
+ yield this._batchTask.finalize();
+ shutdownState.step = "Batched task finalized";
+ } catch (ex) {
+ shutdownState.step = "Batched task failed to finalize";
+
+ shutdownState.latestError.message = "" + ex;
+ if (ex && typeof ex == "object") {
+ shutdownState.latestError.stack = ex.stack || undefined;
+ }
+
+ // Ensure that error is reported and that it causes tests
+ // to fail.
+ Promise.reject(ex);
+ }
+ }
+ }.bind(this)),
+
+ () => shutdownState
+ );
+ },
+ _observersAdded: false,
+
+ _removeObservers: function SRCH_SVC_removeObservers() {
+ Services.obs.removeObserver(this, SEARCH_ENGINE_TOPIC);
+ Services.obs.removeObserver(this, QUIT_APPLICATION_TOPIC);
+
+ if (AppConstants.MOZ_BUILD_APP == "mobile/android") {
+ Services.prefs.removeObserver(LOCALE_PREF, this);
+ }
+ },
+
+ QueryInterface: XPCOMUtils.generateQI([
+ Ci.nsIBrowserSearchService,
+ Ci.nsIObserver,
+ Ci.nsITimerCallback
+ ])
+};
+
+
+const SEARCH_UPDATE_LOG_PREFIX = "*** Search update: ";
+
+/**
+ * Outputs aText to the JavaScript console as well as to stdout, if the search
+ * logging pref (browser.search.update.log) is set to true.
+ */
+function ULOG(aText) {
+ if (getBoolPref(BROWSER_SEARCH_PREF + "update.log", false)) {
+ dump(SEARCH_UPDATE_LOG_PREFIX + aText + "\n");
+ Services.console.logStringMessage(aText);
+ }
+}
+
+var engineUpdateService = {
+ scheduleNextUpdate: function eus_scheduleNextUpdate(aEngine) {
+ var interval = aEngine._updateInterval || SEARCH_DEFAULT_UPDATE_INTERVAL;
+ var milliseconds = interval * 86400000; // |interval| is in days
+ aEngine.setAttr("updateexpir", Date.now() + milliseconds);
+ },
+
+ update: function eus_Update(aEngine) {
+ let engine = aEngine.wrappedJSObject;
+ ULOG("update called for " + aEngine._name);
+ if (!getBoolPref(BROWSER_SEARCH_PREF + "update", true) || !engine._hasUpdates)
+ return;
+
+ let testEngine = null;
+ let updateURL = engine._getURLOfType(URLTYPE_OPENSEARCH);
+ let updateURI = (updateURL && updateURL._hasRelation("self")) ?
+ updateURL.getSubmission("", engine).uri :
+ makeURI(engine._updateURL);
+ if (updateURI) {
+ if (engine._isDefault && !updateURI.schemeIs("https")) {
+ ULOG("Invalid scheme for default engine update");
+ return;
+ }
+
+ ULOG("updating " + engine.name + " from " + updateURI.spec);
+ testEngine = new Engine(updateURI, false);
+ testEngine._engineToUpdate = engine;
+ testEngine._initFromURIAndLoad(updateURI);
+ } else
+ ULOG("invalid updateURI");
+
+ if (engine._iconUpdateURL) {
+ // If we're updating the engine too, use the new engine object,
+ // otherwise use the existing engine object.
+ (testEngine || engine)._setIcon(engine._iconUpdateURL, true);
+ }
+ }
+};
+
+this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SearchService]);
diff --git a/toolkit/components/search/nsSearchSuggestions.js b/toolkit/components/search/nsSearchSuggestions.js
new file mode 100644
index 000000000..a05d8b4b4
--- /dev/null
+++ b/toolkit/components/search/nsSearchSuggestions.js
@@ -0,0 +1,197 @@
+/* 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/. */
+
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/nsFormAutoCompleteResult.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "SearchSuggestionController",
+ "resource://gre/modules/SearchSuggestionController.jsm");
+
+/**
+ * SuggestAutoComplete is a base class that implements nsIAutoCompleteSearch
+ * and can collect results for a given search by using this._suggestionController.
+ * We do it this way since the AutoCompleteController in Mozilla requires a
+ * unique XPCOM Service for every search provider, even if the logic for two
+ * providers is identical.
+ * @constructor
+ */
+function SuggestAutoComplete() {
+ this._init();
+}
+SuggestAutoComplete.prototype = {
+
+ _init: function() {
+ this._suggestionController = new SearchSuggestionController(obj => this.onResultsReturned(obj));
+ this._suggestionController.maxLocalResults = this._historyLimit;
+ },
+
+ get _suggestionLabel() {
+ let bundle = Services.strings.createBundle("chrome://global/locale/search/search.properties");
+ let label = bundle.GetStringFromName("suggestion_label");
+ Object.defineProperty(SuggestAutoComplete.prototype, "_suggestionLabel", {value: label});
+ return label;
+ },
+
+ /**
+ * The object implementing nsIAutoCompleteObserver that we notify when
+ * we have found results
+ * @private
+ */
+ _listener: null,
+
+ /**
+ * Maximum number of history items displayed. This is capped at 7
+ * because the primary consumer (Firefox search bar) displays 10 rows
+ * by default, and so we want to leave some space for suggestions
+ * to be visible.
+ */
+ _historyLimit: 7,
+
+ /**
+ * Callback for handling results from SearchSuggestionController.jsm
+ * @private
+ */
+ onResultsReturned: function(results) {
+ let finalResults = [];
+ let finalComments = [];
+
+ // If form history has results, add them to the list.
+ for (let i = 0; i < results.local.length; ++i) {
+ finalResults.push(results.local[i]);
+ finalComments.push("");
+ }
+
+ // If there are remote matches, add them.
+ if (results.remote.length) {
+ // "comments" column values for suggestions starts as empty strings
+ let comments = new Array(results.remote.length).fill("", 1);
+ comments[0] = this._suggestionLabel;
+ // now put the history results above the suggestions
+ finalResults = finalResults.concat(results.remote);
+ finalComments = finalComments.concat(comments);
+ }
+
+ // Notify the FE of our new results
+ this.onResultsReady(results.term, finalResults, finalComments, results.formHistoryResult);
+ },
+
+ /**
+ * Notifies the front end of new results.
+ * @param searchString the user's query string
+ * @param results an array of results to the search
+ * @param comments an array of metadata corresponding to the results
+ * @private
+ */
+ onResultsReady: function(searchString, results, comments, formHistoryResult) {
+ if (this._listener) {
+ // Create a copy of the results array to use as labels, since
+ // FormAutoCompleteResult doesn't like being passed the same array
+ // for both.
+ let labels = results.slice();
+ let result = new FormAutoCompleteResult(
+ searchString,
+ Ci.nsIAutoCompleteResult.RESULT_SUCCESS,
+ 0,
+ "",
+ results,
+ labels,
+ comments,
+ formHistoryResult);
+
+ this._listener.onSearchResult(this, result);
+
+ // Null out listener to make sure we don't notify it twice
+ this._listener = null;
+ }
+ },
+
+ /**
+ * Initiates the search result gathering process. Part of
+ * nsIAutoCompleteSearch implementation.
+ *
+ * @param searchString the user's query string
+ * @param searchParam unused, "an extra parameter"; even though
+ * this parameter and the next are unused, pass
+ * them through in case the form history
+ * service wants them
+ * @param previousResult unused, a client-cached store of the previous
+ * generated resultset for faster searching.
+ * @param listener object implementing nsIAutoCompleteObserver which
+ * we notify when results are ready.
+ */
+ startSearch: function(searchString, searchParam, previousResult, listener) {
+ // Don't reuse a previous form history result when it no longer applies.
+ if (!previousResult)
+ this._formHistoryResult = null;
+
+ var formHistorySearchParam = searchParam.split("|")[0];
+
+ // Receive the information about the privacy mode of the window to which
+ // this search box belongs. The front-end's search.xml bindings passes this
+ // information in the searchParam parameter. The alternative would have
+ // been to modify nsIAutoCompleteSearch to add an argument to startSearch
+ // and patch all of autocomplete to be aware of this, but the searchParam
+ // argument is already an opaque argument, so this solution is hopefully
+ // less hackish (although still gross.)
+ var privacyMode = (searchParam.split("|")[1] == "private");
+
+ // Start search immediately if possible, otherwise once the search
+ // service is initialized
+ if (Services.search.isInitialized) {
+ this._triggerSearch(searchString, formHistorySearchParam, listener, privacyMode);
+ return;
+ }
+
+ Services.search.init((function startSearch_cb(aResult) {
+ if (!Components.isSuccessCode(aResult)) {
+ Cu.reportError("Could not initialize search service, bailing out: " + aResult);
+ return;
+ }
+ this._triggerSearch(searchString, formHistorySearchParam, listener, privacyMode);
+ }).bind(this));
+ },
+
+ /**
+ * Actual implementation of search.
+ */
+ _triggerSearch: function(searchString, searchParam, listener, privacyMode) {
+ this._listener = listener;
+ this._suggestionController.fetch(searchString,
+ privacyMode,
+ Services.search.currentEngine);
+ },
+
+ /**
+ * Ends the search result gathering process. Part of nsIAutoCompleteSearch
+ * implementation.
+ */
+ stopSearch: function() {
+ this._suggestionController.stop();
+ },
+
+ // nsISupports
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteSearch,
+ Ci.nsIAutoCompleteObserver])
+};
+
+/**
+ * SearchSuggestAutoComplete is a service implementation that handles suggest
+ * results specific to web searches.
+ * @constructor
+ */
+function SearchSuggestAutoComplete() {
+ // This calls _init() in the parent class (SuggestAutoComplete) via the
+ // prototype, below.
+ this._init();
+}
+SearchSuggestAutoComplete.prototype = {
+ classID: Components.ID("{aa892eb4-ffbf-477d-9f9a-06c995ae9f27}"),
+ __proto__: SuggestAutoComplete.prototype,
+ serviceURL: ""
+};
+
+var component = [SearchSuggestAutoComplete];
+this.NSGetFactory = XPCOMUtils.generateNSGetFactory(component);
diff --git a/toolkit/components/search/nsSidebar.js b/toolkit/components/search/nsSidebar.js
new file mode 100644
index 000000000..63976cba7
--- /dev/null
+++ b/toolkit/components/search/nsSidebar.js
@@ -0,0 +1,66 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 4 -*- */
+/* 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/. */
+
+const { interfaces: Ci, utils: Cu } = Components;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+// File extension for Sherlock search plugin description files
+const SHERLOCK_FILE_EXT_REGEXP = /\.src$/i;
+
+function nsSidebar() {
+}
+
+nsSidebar.prototype = {
+ init: function(window) {
+ this.window = window;
+ try {
+ this.mm = window.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDocShell)
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIContentFrameMessageManager);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ },
+
+ // Deprecated, only left here to avoid breaking old browser-detection scripts.
+ addSearchEngine: function(engineURL, iconURL, suggestedTitle, suggestedCategory) {
+ if (SHERLOCK_FILE_EXT_REGEXP.test(engineURL)) {
+ Cu.reportError("Installing Sherlock search plugins is no longer supported.");
+ return;
+ }
+
+ this.AddSearchProvider(engineURL);
+ },
+
+ // This function implements window.external.AddSearchProvider().
+ // The capitalization, although nonstandard here, is to match other browsers'
+ // APIs and is therefore important.
+ AddSearchProvider: function(engineURL) {
+ if (!this.mm) {
+ Cu.reportError(`Installing a search provider from this context is not currently supported: ${Error().stack}.`);
+ return;
+ }
+
+ this.mm.sendAsyncMessage("Search:AddEngine", {
+ pageURL: this.window.document.documentURIObject.spec,
+ engineURL
+ });
+ },
+
+ // This function exists to implement window.external.IsSearchProviderInstalled(),
+ // for compatibility with other browsers. The function has been deprecated
+ // and so will not be implemented.
+ IsSearchProviderInstalled: function(engineURL) {
+ return 0;
+ },
+
+ classID: Components.ID("{22117140-9c6e-11d3-aaf1-00805f8a4905}"),
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
+ Ci.nsIDOMGlobalPropertyInitializer])
+}
+
+this.NSGetFactory = XPCOMUtils.generateNSGetFactory([nsSidebar]);
diff --git a/toolkit/components/search/tests/xpcshell/.eslintrc.js b/toolkit/components/search/tests/xpcshell/.eslintrc.js
new file mode 100644
index 000000000..d35787cd2
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/.eslintrc.js
@@ -0,0 +1,7 @@
+"use strict";
+
+module.exports = {
+ "extends": [
+ "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
+ ]
+};
diff --git a/toolkit/components/search/tests/xpcshell/data/chrome.manifest b/toolkit/components/search/tests/xpcshell/data/chrome.manifest
new file mode 100644
index 000000000..ec412e050
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/chrome.manifest
@@ -0,0 +1,3 @@
+locale testsearchplugin ar jar:jar:searchTest.jar!/chrome/searchTest.jar!/
+content testsearchplugin ./
+
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-addon.xml b/toolkit/components/search/tests/xpcshell/data/engine-addon.xml
new file mode 100644
index 000000000..24e53d0c1
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-addon.xml
@@ -0,0 +1,8 @@
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>addon</ShortName>
+<Description>addon</Description>
+<InputEncoding>UTF-8</InputEncoding>
+<Url type="text/html" method="GET" template="http://searchtest.local">
+ <Param name="search" value="{searchTerms}"/>
+</Url>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-app.xml b/toolkit/components/search/tests/xpcshell/data/engine-app.xml
new file mode 100644
index 000000000..fe1b3a67c
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-app.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>TestEngineApp</ShortName>
+<Description>A test search engine installed in the application directory</Description>
+<InputEncoding>ISO-8859-1</InputEncoding>
+<Url type="text/html" method="GET" template="http://localhost/" resultdomain="localhost">
+ <Param name="q" value="{searchTerms}"/>
+</Url>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-chromeicon.xml b/toolkit/components/search/tests/xpcshell/data/engine-chromeicon.xml
new file mode 100644
index 000000000..856732c6d
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-chromeicon.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>engine-chromeicon</ShortName>
+<Image width="16" height="16">chrome://branding/content/icon16.png</Image>
+<Image width="32" height="32">chrome://branding/content/icon32.png</Image>
+<Url type="text/html" method="GET" template="http://www.google.com/search">
+ <Param name="q" value="{searchTerms}"/>
+</Url>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-fr.xml b/toolkit/components/search/tests/xpcshell/data/engine-fr.xml
new file mode 100644
index 000000000..fad3e7574
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-fr.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>Test search engine (fr)</ShortName>
+<Description>A test search engine (based on Google search for a different locale)</Description>
+<InputEncoding>ISO-8859-1</InputEncoding>
+<Url type="text/html" method="GET" template="http://www.google.fr/search" resultdomain="google.fr">
+ <Param name="q" value="{searchTerms}"/>
+ <Param name="ie" value="iso-8859-1"/>
+ <Param name="oe" value="iso-8859-1"/>
+</Url>
+<SearchForm>http://www.google.fr/</SearchForm>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-override.xml b/toolkit/components/search/tests/xpcshell/data/engine-override.xml
new file mode 100644
index 000000000..473be82fd
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-override.xml
@@ -0,0 +1,8 @@
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>bug645970</ShortName>
+<Description>override</Description>
+<InputEncoding>UTF-8</InputEncoding>
+<Url type="text/html" method="GET" template="http://searchtest.local">
+ <Param name="search" value="{searchTerms}"/>
+</Url>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-pref.xml b/toolkit/components/search/tests/xpcshell/data/engine-pref.xml
new file mode 100644
index 000000000..0555caf3e
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-pref.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>engine-pref</ShortName>
+<Url type="text/html" method="GET" template="http://www.google.com/search">
+ <Param name="q" value="{searchTerms}"/>
+ <!-- Dynamic parameters -->
+ <MozParam name="code" condition="pref" pref="code"/>
+</Url>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-rel-searchform-post.xml b/toolkit/components/search/tests/xpcshell/data/engine-rel-searchform-post.xml
new file mode 100644
index 000000000..8b6eb7cab
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-rel-searchform-post.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>engine-rel-searchform-post.xml</ShortName>
+<Url type="text/html" method="POST" template="http://engine-rel-searchform-post.xml/POST" rel="searchform"/>
+<SearchForm>http://engine-rel-searchform-post.xml/?search</SearchForm>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-rel-searchform-purpose.xml b/toolkit/components/search/tests/xpcshell/data/engine-rel-searchform-purpose.xml
new file mode 100644
index 000000000..18026210f
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-rel-searchform-purpose.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>engine-rel-searchform-purpose</ShortName>
+<Url type="text/html" method="GET" template="http://www.google.com/search" resultdomain="google.com" rel="searchform">
+ <Param name="q" value="{searchTerms}"/>
+ <!-- Dynamic parameters -->
+ <MozParam name="channel" condition="purpose" purpose="contextmenu" value="rcs"/>
+ <MozParam name="channel" condition="purpose" purpose="keyword" value="fflb"/>
+ <MozParam name="channel" condition="purpose" purpose="searchbar" value="sb"/>
+</Url>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-rel-searchform.xml b/toolkit/components/search/tests/xpcshell/data/engine-rel-searchform.xml
new file mode 100644
index 000000000..bcd164877
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-rel-searchform.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>engine-rel-searchform.xml</ShortName>
+<Url type="text/html" method="GET" template="http://engine-rel-searchform.xml/?search" rel="searchform"/>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-resourceicon.xml b/toolkit/components/search/tests/xpcshell/data/engine-resourceicon.xml
new file mode 100644
index 000000000..6fb2a778d
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-resourceicon.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>engine-resourceicon</ShortName>
+<Image width="16" height="16">resource://search-plugins/icon16.png</Image>
+<Image width="32" height="32">resource://search-plugins/icon32.png</Image>
+<Url type="text/html" method="GET" template="http://www.google.com/search">
+ <Param name="q" value="{searchTerms}"/>
+</Url>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-system-purpose.xml b/toolkit/components/search/tests/xpcshell/data/engine-system-purpose.xml
new file mode 100644
index 000000000..57ecd32d7
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-system-purpose.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>engine-system-purpose</ShortName>
+<Url type="text/html" method="GET" template="http://www.google.com/search">
+ <Param name="q" value="{searchTerms}"/>
+ <!-- Dynamic parameters -->
+ <MozParam name="channel" condition="purpose" purpose="searchbar" value="sb"/>
+ <MozParam name="channel" condition="purpose" purpose="system" value="sys"/>
+</Url>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine-update.xml b/toolkit/components/search/tests/xpcshell/data/engine-update.xml
new file mode 100644
index 000000000..b8ef7224d
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine-update.xml
@@ -0,0 +1,10 @@
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>update</ShortName>
+<Description>update</Description>
+<InputEncoding>UTF-8</InputEncoding>
+<Url type="text/html" method="GET" template="http://searchtest.local">
+ <Param name="search" value="{searchTerms}"/>
+</Url>
+<UpdateUrl>http://searchtest.local/opensearch.xml</UpdateUrl>
+<IconUpdateUrl>http://searchtest.local/favicon.ico</IconUpdateUrl>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine.xml b/toolkit/components/search/tests/xpcshell/data/engine.xml
new file mode 100644
index 000000000..e7af1d9e9
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+<ShortName>Test search engine</ShortName>
+<Description>A test search engine (based on Google search)</Description>
+<InputEncoding>UTF-8</InputEncoding>
+<Image width="16" height="16">data:image/png;base64,AAABAAEAEBAAAAEAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs9Pt8xetPtu9FsfFNtu%2BTzvb2%2B%2Fne4dFJeBw0egA%2FfAJAfAA8ewBBegAAAAD%2B%2FPtft98Mp%2BwWsfAVsvEbs%2FQeqvF8xO7%2F%2F%2F63yqkxdgM7gwE%2FggM%2BfQA%2BegBDeQDe7PIbotgQufcMufEPtfIPsvAbs%2FQvq%2Bfz%2Bf%2F%2B%2B%2FZKhR05hgBBhQI8hgBAgAI9ewD0%2B%2Fg3pswAtO8Cxf4Kw%2FsJvvYAqupKsNv%2B%2Fv7%2F%2FP5VkSU0iQA7jQA9hgBDgQU%2BfQH%2F%2Ff%2FQ6fM4sM4KsN8AteMCruIqqdbZ7PH8%2Fv%2Fg6Nc%2Fhg05kAA8jAM9iQI%2BhQA%2BgQDQu6b97uv%2F%2F%2F7V8Pqw3eiWz97q8%2Ff%2F%2F%2F%2F7%2FPptpkkqjQE4kwA7kAA5iwI8iAA8hQCOSSKdXjiyflbAkG7u2s%2F%2B%2F%2F39%2F%2F7r8utrqEYtjQE8lgA7kwA7kwA9jwA9igA9hACiWSekVRyeSgiYSBHx6N%2F%2B%2Fv7k7OFRmiYtlAA5lwI7lwI4lAA7kgI9jwE9iwI4iQCoVhWcTxCmb0K%2BooT8%2Fv%2F7%2F%2F%2FJ2r8fdwI1mwA3mQA3mgA8lAE8lAE4jwA9iwE%2BhwGfXifWvqz%2B%2Ff%2F58u%2Fev6Dt4tr%2B%2F%2F2ZuIUsggA7mgM6mAM3lgA5lgA6kQE%2FkwBChwHt4dv%2F%2F%2F728ei1bCi7VAC5XQ7kz7n%2F%2F%2F6bsZkgcB03lQA9lgM7kwA2iQktZToPK4r9%2F%2F%2F9%2F%2F%2FSqYK5UwDKZAS9WALIkFn%2B%2F%2F3%2F%2BP8oKccGGcIRJrERILYFEMwAAuEAAdX%2F%2Ff7%2F%2FP%2B%2BfDvGXQLIZgLEWgLOjlf7%2F%2F%2F%2F%2F%2F9QU90EAPQAAf8DAP0AAfMAAOUDAtr%2F%2F%2F%2F7%2B%2Fu2bCTIYwDPZgDBWQDSr4P%2F%2Fv%2F%2F%2FP5GRuABAPkAA%2FwBAfkDAPAAAesAAN%2F%2F%2B%2Fz%2F%2F%2F64g1C5VwDMYwK8Yg7y5tz8%2Fv%2FV1PYKDOcAAP0DAf4AAf0AAfYEAOwAAuAAAAD%2F%2FPvi28ymXyChTATRrIb8%2F%2F3v8fk6P8MAAdUCAvoAAP0CAP0AAfYAAO4AAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQAA</Image>
+<Url type="application/x-suggestions+json" method="GET" template="http://suggestqueries.google.com/complete/search?output=firefox&amp;client=firefox&amp;hl={moz:locale}&amp;q={searchTerms}"/>
+<Url type="text/html" method="GET" template="http://www.google.com/search" resultdomain="google.com">
+ <Param name="q" value="{searchTerms}"/>
+ <Param name="ie" value="utf-8"/>
+ <Param name="oe" value="utf-8"/>
+ <Param name="aq" value="t"/>
+ <!-- Dynamic parameters -->
+ <MozParam name="channel" condition="purpose" purpose="contextmenu" value="rcs"/>
+ <MozParam name="channel" condition="purpose" purpose="keyword" value="fflb"/>
+</Url>
+<Url type="application/x-moz-default-purpose" method="GET" template="http://www.google.com/search" resultdomain="purpose.google.com">
+ <Param name="q" value="{searchTerms}"/>
+ <!-- MozParam uses searchbar if purpose is not specified -->
+ <MozParam name="channel" condition="purpose" purpose="searchbar" value="ffsb"/>
+ <MozParam name="channel" condition="purpose" purpose="contextmenu" value="rcs"/>
+ <MozParam name="channel" condition="purpose" purpose="keyword" value="fflb"/>
+</Url>
+<SearchForm>http://www.google.com/</SearchForm>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engine2.xml b/toolkit/components/search/tests/xpcshell/data/engine2.xml
new file mode 100644
index 000000000..9957bfdf4
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engine2.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
+ <ShortName>A second test engine</ShortName>
+ <Description>A second test search engine (based on DuckDuckGo)</Description>
+ <InputEncoding>UTF-8</InputEncoding>
+ <LongName>A second test search engine (based on DuckDuckGo)</LongName>
+ <Image width="16" height="16">data:image/vnd.microsoft.icon;base64,AAABAAMAEBAAAAEACABoBQAANgAAACAgAAABAAgAqAgAAJ4FAAAwMAAAAQAIAKgOAABGDgAAKAAAABAAAAAgAAAAAQAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUvgAAFMAAABfDAAAYwQAAGscAAB7KAAAgzAAAIcwAACHNAAAizgAAI9AAACTQAAAnzAAAJtMAACnXABktyAAALtgAAC/bAAAx3QAAM+AAADbjAAA34wAAOOQAADzYAAA65wAWPdcAADvoAABG1QC6cg0AAFXdAERS0AAAVd8AAF3cAABp5wAAcOUATGziAAB36AAAeugATHLqAF165ABlg+0A0qRkAACS7wAAlO8AeI7nAIGX6gCVndwAAKX1AACr9gAAr/YAALX4AAC3+QCdrvIAALz6AAC9+QAAv/kAAMD7AADH+wAAyvwAAND9ALHB9QAA0vwA5c68AADT/gAA1P0AANT+AADU/wAA1/8AANj/AADZ/wAA3P8AAN3/AGrV+wAA3/8AAOH/AMrS9ADs3tYA39zmAOHj8AB+6v8A5ur6AKDw/wCq8f8A9fDtAPby7wD38vAA6/D8APfz8QD69O4A8PP8APL0/AD69/IA+/fzAPr39QDd+f8A+/n1APb4/QD7+fgA+/r5AOz8/gD1/P8A+vz/AP7+/QD//v8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABpLGhoaGhQHgEAAQEBAQFpGUtoaGhoSw8CAwICAgICAiNQaGhoaC0EBAwgIBsEBAQnWmhoaGgnIjY5PUBHOyUFLWhoaGheR0MdBgYGByQrCEtoaGhoT0I3CQkJCQkJCQlQaGhoaFI/QTIzNSoXCgsLWmhoaGhoUUVEQ0RKRDEfDWhoXFxoaGhjZWRILzpJRjhoXBwcWGhoaFtbYg4QIS8waFwcKVhoaF8cHF8REREREWhnXFxoaGhfHClOEhISEhJVU2hoaGhoaF9fNBMTExMTVz5MZmhoaFdMTSYUFBQUFDxhVGhoaGhdPi4VFhYWFhZpVmBoaGhoWSgYGhoaGhppgAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAEAACgAAAAgAAAAQAAAAAEACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFL8AABTAAAEWvAABF74AABbCAAAXwwABGMAAABjDAAAYxAAAGsUAABrGAAAbxgAAG8cAAh3BAAEcxQAAHMgAAR3HAAgewgAAHcoAAB/LAAAgzAAFIckAiEYiAAAhzgAAI88AACPQAAAk0AAAJc8AACXSAAUmzQAAJ9IAACfTABAqxwAAKNQAjE0rAAAp1QAAKdYAACrXAAAr2AAGLdMAAC3ZAAAu2wAAL9wAADPVAAAx3QAAMt8AADPgAAA04QAAONQAADnXAAA24wAGN94ACjfdAAA34wAAN+QACznbAAA45QAJOeAAFTzUABY81AAAOeYAFj3UAAo74AAAP9YAADrnAAs74AAAPtoABT/pAABF2wAARd0AAEbaAABI1gAASdoAEETmAABJ2wAAS98AAFHfAAFV3ABTc2EAWYA+AAFa4gAAXd0AAF3hADyeAAABZd4AAWTjADZf5wABZuIAQKETAD2jDwBGZ9gARKEYADhk6wA8pBMAPKUVAK+DbABKbN8ATGziAAF15ABTpioAaKE1AEGtJAABfOkAOrIiAH6hRQABgOkAAYLmAAGC5wACgucAXXrkAAGE5wBEr0AAAYToAAGG6gA9s0AAObkuAD20QQA5ui8AaIHhAEe3OABxgeAAAo3sAFasbABshukAOcA5AGmI7gABleoAbovsAAKZ7QCFtmEAAp7vAD7CagCBl+oAPsNuAAKo8QACqvIAA6zyAAOs9AACr/QAkKfxAGLJlQBfypUAZMqWAAO49QDSuawAc8qaAMPCngADwfgAA8H5AAPE+QAEyPsABMr7AATO/AAE0PwABND9AATR/QAE0v0ACNP9ABvW/QDj1MwAMtr9ADvc/QDK0vQA59rTAOjb1ADp3tcA6+DaAG/l/gB15v4A29/0AO3k3wDu5eAA4eT3AJDr/gDy6+cA5uj3APLs6ADj6PsA8+zpAObq+gDz7uoA8+7rANHt+gD07usA6e35APbx7wDy9PwA5fr/APv7+wD2+/8A7fz/APz8+gDw/P8A/fz7APv8/gD9/f4A+P7/AP/+/gD+/v8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyMgAAAAAPYyDb4HHx8fHw05dUwAAAAAAAAAAAAAAyMjIAQEBAQFhkYNyXmV3Y2h6dF1TAgEBAQEBAQEBAQEByAQEBAQEBG2Og3JedXxnWYV0XVMDBAQEBAQEBAQEBAQEBQUFBQURhIyDcl5zfGdbhXRdUwYFBQUFBQUFBQUFBQUICAgICDuijYNyXmV3ZE96dF1TBwgICAgICAgICAgICAoKCgoKYbOMg5K/x8esCg5OWFMJCgoKCgoKCgoKCgoKDAwMDAxtusfHx8fHx3gMDAwLDQwMDAwMDAwMDAwMDAwPDw8PEITHx8fHx8fHFQ8PDw8PDw8PDw8PDw8PDw8PDxISEhIgosfHx8fHx8YSEhISEhISEhISEhISEhISEhISExMTEzuzx8fHx8fHrxMTExMTExMTExMTExMTExMTExMUFBQUYbrHx8fHx8epFBQUboiXnJqGVEcUFBQUFBQUFBcXFxdtx8fHx8fHx7YbbJyYj2tigpObnIAXFxcXFxcXGBgYHYTHx8fHx8e7npybcE0wGBgYP1F+ahgYGBgYGBgaGho6osfHx8fHx6icnIcZGhoaGhoaGhoaGhoaGhoaGhwcHGGzx8fHx8fHp5ycnEgeRjErHBwcHBwcHBwcHBwcISEhbbrHx8fHx8e+oZycnJycnJyViVdEISEhISEhISEhIR+Ex8fHx8fHx8fEraCdnJycnJycnJZxSiEhISEhISMjJ6LHx8fHx8fHx8fHx8fAvcBCVXmUnJyZUiMjIyMjJSU6s8fHx6Wlx8fHx8fHx8fHxyUkJUxpmZuKJSUlJSUmJmG6x8WjIhaqx8fHx8fHtLTHJiYmJkVQZksmJiYmJigobcXHx6QiX6rHx8fHx7AiFrUoKCgoKCgoKCgoKCgoKSmEx8fHx6urx8fHx8fHsiJfeykpKSkpKSkpKSkpKSkqKoTHt8fHx8fHx8fHx8fHubk0KioqKioqKioqKioqKiwsbcemx8fHx8fHx8fHwcfHuCwsLCwsLCwsLCwsLCwsLi43s8eQkJ/Hx8fHx8eukJA5Li4uLi4uLi4uLi4uLi4uLi2Ex8fHx8fHx8fHx8fHfy4uLi4uLi4uLi4uLi4uLi8vLzOzx8fHx8fHx8fHx4svLy8vLy8vLy8vLy8vLy8vMjIyMkGEvMfHx8fHx7FWMjIyMjIyMjIyMjIyMjIyMjI2NjY2MjI+drPHx8d9NTY2NjY2NjY2NjY2NjY2NjY2Njg4NlrHx8fHx8fGSTg4ODg4ODg4ODg4ODg4ODg4ODg4yEBAPGDHx8fCXEBAQEBAQEBAQEBAQEBAQEBAQEBAQMjIyENDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0PIyMAAAAOAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAHAAAADKAAAADAAAABgAAAAAQAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARwQAAE8IAABXEAAAXxQAAGcYAARvHAAAfwAAAHsoAFSucAIdGHgAAIs0Ai0kjAAAlzwAHJc8AID59AAAo0gCPTSgAACnTACQ8lwAYMsgAADDaAAI01AA+WkgAADTeABU4zgAEM+YAl1o3AAg52QAANukAADfqAAA65AA5Y0cAAEDYABc+3QAARtYANEPPAJ1lQgA6eSUAGUbeAAFK2wAVRucAMknWAAJQ2gA8hBkANoQfAB9M5QAXTeYANo0FAABT3gAmUeEAVoMvAEaYAAAAXeIASJIcAABg3gA9WeEAPZ4AADefBACneGMAA2TiAAFn3gAwX+oAU4ZkADqiDwAAauIArH9hAKx9aABWZtYAW4pfAFJp2gAAcOIAX2raAEOkJABJoi4AXKErAEtt4ABGpykANa0bAElu6gA6qiYAaXLbAAZ66ABFricAPq4tAFZ24wBseNoAeaVCALiPdwBtedsANrgeAF955gBBsjIAY6dMAFx86gBYfu0AAIjrAD61RwBCuzMAZILpAAKM6QCipWMAYrZCAL+bhwA3wjQAaIbuADy6UABrifEAAJXtAHCL6wBZtmgATLduAG2O8AACnO8APMFkAIuW4wCltXMAq7J+AIKX6AB9mOsAyamaAImb5AA5xXMAi6DjAACq9ACsuYgAT8iDAAaw8wBBzIIAjqbyAACz9wCVqu0AmK3xAJ+u8AClru4AC8P2AKa48wAAx/wAAMv5ALvQtgAJz/4AAND/ALPB9QDDzscAANP8AMDF7QAQ1PwAwsz3ACna/AC9zfoANtv8AObYzACr4sYA6NrOAMvS8wCu5M8ATuD/AGDi/wCy59MAaOP/ANPn1ABp5vwA5eHjAOzk2wDU3vgAwurYAIHq/ADr6t0Akev/AObm8wDh5vYA9e3kAOTq+gDz8OsAsPH/AOjt/QC38v8A6u//AN327QDx8f4A+PT2AM73/gDz9foA+/jzAPX2/AD8+fQA3fr8AP369QD4+v8A+v37AP/++AD8//4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC/vwAAAAAAAAAAAAAAAAF2obO9vr6+vr6+vr28RwAAAAAAAAAAAAAAAAAAAAAAv7+/AAYAAAAAAAAAAAABAgGZfW18vr6+vr6+vr6pAAAAAAAAAAAAAAAAAAAAAQAGAL8BAQEBQ5Cyvru+vb1QAxiff3FgSWS+vr6+vr5HAggWDgETvb67vr2+vrWQQwEGAQEBAQFyvlUTAAEBAQEAAUukfXFgTzhMYFJKc44+ST9IKwEBAQEBAQEBAQFVvnIBAQEBAUO+IwEBAQEAAQEBAVSdf3FgT0hnZ1lNSHlpWz85LwEBAQEBAQEBAQEBI7tDAQECApBYAgICAgICAgICAnWaf3FgUjhnZ2FPP31pUzhILwICAgICAgICAgICAliQAgICArUCAgICAgICAgICApmaf3FgTzlnZ1lNSHlpUzg5LwICAgICAgICAgICAgK1AgICAr0CAgICAgICAgICS6mXf3FgTzNWZVtPMm5pWz9ILAICAgICAgICAgICAgK7AgICAr4CAgICAgICAgICVLWXf3FcdL6+vr6FBAJEUzg4JQICAgICAgICAgICAgK9AgICArsCAgICAgICAgICdb6xiqa+vr6+vrMpCgICEjU4HwICAgICAgICAgICAgK7AgIDA74DAwMDAwMDAwMDmb6+vr6+vr6+vrAKAwMDAwMSAwMDAwMDAwMDAwMDAwO+AwMDA7sDAwMDAwMDAwMDqb6+vr6+vr6+voUDAwMDAwMDAwMDAwMDAwMDAwMDAwO9AwMFBb4FBQUFBQUFBQVLtb6+vr6+vr6+vkUFBQUFBQUFBQUFBQUFBQUFBQUFBQW+BQUFBbsFBQUFBQUFBQVavr6+vr6+vr6+vikFBQUFBQUFBQUFBQUFBQUFBQUFBQW9BQUHB7sHBwcHBwcHBwd1vr6+vr6+vr6+vgcHBwcHBwcHBwcHBwcHBwcHBwcHBwe+BwcHB70HBwcHBwcHBweZvr6+vr6+vr6+vgcHBwciUXuIj4+PhmsqBwcHBwcHBwe+BwcKCr4MCgoKCgoKCgqrvr6+vr6+vr6+vgoKY4uRj5GRkYyPi4uRiDYKCgoKCgq7CgoKCr4MCgoKCgoKCku1vr6+vr6+vr6+r4aPi4twOycgIjBAcIaLj488CgoKCgq9CgoKCr4KCgoKCgoKClS+vr6+vr6+vr60kYyMiyoKCgoKCgoKCgoVKkYVCgoKCgq9CgoMDLsMDAwMDAwMDHW+vr6+vr6+vrubjI+RYw0KCgoKCgoMCgwMDAwMDAwMCgy+CgwMDL4MDAwMDAwMDJm+vr6+vr6+vr2Tj4+PiBUMDAwMDAwMDAwMDAwMDAwMDAy9DwwMDL4MDAwMDAwMIam+vr6+vr6+vrugi4+Mj4uIi4yIflEgDAwMDAwMDAwMDAy8DAwMDL4MDAwMDAwMS7W+vr6+vr6+vr6+npGLj4yPj4+Pj4+PiF8gDAwMDAwMDAy+DAwPDL0PDwwPDA8PWr6+vr6+vr6+vr6+vq2Tj4+Lj4yPj5GLj4+PgTsPDA8MDwy9DA8PD74PDw8PDw8Pdb6+vr6+vr6+vr6+vr67ua2npZyVjI+LkY+Rj4+INA8PDw++Dw8PD70PDw8PDw8Pmb6+vr6+vr6+vr6+vr69vr6+vr69VCpffoyLjI+Jj4EPDw++Dw8PD70PDw8PDw8Pq76+vqEaGqq+vr6+vr6+vr68vr6+NxEPDw82e5GMiVEPDw++Dw8REbwRERERERFLtb6+vgsQCzq+vr6+vr6+vpYaGqy7ERERERERERERERERERG9EREUEb4RFBEUERRdvr6+vhAQoma+vr6+vr6+vgkaCTq+FBEUERQRFBEUERQRFBG+ERQUFL4UFBQUFBR1vr6+vqpBQra+vr6+vr6+uxAQoWa+FBQUFBQUFBQUFBQUFBS9FBQUFL4UFBQUFBR2vr6+vr6+vr6+vr6+vr6+vqpCQrayFBQUFBQUFBQUFBQUFBS+FBQUFL4UFBQUFBRivr6qvr6+vr6+vr6+vr6+vr6+vr6CFBQUFBQUFBQUFBQUFBS9FBQXFL4UFxQXFBdLvrNXvr6+vr6+vr6+vr6+vr6+vr4UFxQXFBcUFxQXFBcUFxS+FBcUF74XFBcUFxQXvr62JFd3s72+vr6+vr67rLO7mKgXFBcUFxQXFBcUFxQXFBe+FxQXF74XFxcXFxcXrr6+vrq9vr6+vr6+vr6+uCRXljEXFxcXFxcXFxcXFxcXFxe+FxcXF74XFxcXFxcXhL2+vr6+vr6+vr6+vr6+vb69gxcXFxcXFxcXFxcXFxcXFxe+FxcXF74XFxcXFxcXG667vr6+vr6+vr6+vr6+vrupFxcXFxcXFxcXFxcXFxcXFxe+FxcXHr4eFx4XHhceFx68vb6+vr6+vr6+vr69vrUXHhceFx4XHhceFx4XHhceFx6+HhceF74XHhceFx4XHhceeLu9vb6+vr6+vb6zhxceFx4XHhceFx4XHhceFx4XHhe+Fx4eHr4eHh4eHh4eHh4eHhctXZm+vr6+sGIeHh4eHh4eHh4eHh4eHh4eHh4eHh69Hh4eHr0eHh4eHh4eHmJsdoKNo7u+vr61LR4eHh4eHh4eHh4eHh4eHh4eHh4eHh69Hh4eHLUcHhweHB4cG6u8vr6+vr6+voMeHB4cHhweHB4cHhweHB4cHhweHB4cHhy1HB4cHpJqHB4cHhweHCaZvr6+vr2DLhwcHhweHB4cHhweHB4cHhweHB4cHhweHGqSHhwcHF6+PRwcHBwcHlR6hINoTigZGRwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcPb5eHBwcHByAvW8cHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBxvvYAcHBwcHBwcXpS3vr6+vr6+vr6+vr6+vr6+vr6+vr6+vr6+vr6+vr6+vr6+vreUXhwcHBy/HBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHL+/vx0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dv7/AAAAAAAMAAIAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAQAAwAAAAAADAAA=</Image>
+ <Url type="text/html" method="get" template="https://duckduckgo.com/?q={searchTerms}"/>
+</OpenSearchDescription>
diff --git a/toolkit/components/search/tests/xpcshell/data/engineImages.xml b/toolkit/components/search/tests/xpcshell/data/engineImages.xml
new file mode 100644
index 000000000..65b550b31
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engineImages.xml
@@ -0,0 +1,22 @@
+<!-- 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/. -->
+
+<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
+ <ShortName>IconsTest</ShortName>
+ <Description>IconsTest. Search by Test.</Description>
+ <InputEncoding>UTF-8</InputEncoding>
+ <Image width="16" height="16">data:image/x-icon;base64,ico16</Image>
+ <Image width="32" height="32">data:image/x-icon;base64,ico32</Image>
+ <Image width="74" height="74">data:image/png;base64,ico74</Image>
+ <Url type="application/x-suggestions+json" template="http://api.bing.com/osjson.aspx">
+ <Param name="query" value="{searchTerms}"/>
+ <Param name="form" value="MOZW"/>
+ </Url>
+ <Url type="text/html" method="GET" template="http://www.bing.com/search">
+ <Param name="q" value="{searchTerms}"/>
+ <MozParam name="pc" condition="pref" pref="ms-pc"/>
+ <Param name="form" value="MOZW"/>
+ </Url>
+ <SearchForm>http://www.bing.com/search</SearchForm>
+</SearchPlugin>
diff --git a/toolkit/components/search/tests/xpcshell/data/engineMaker.sjs b/toolkit/components/search/tests/xpcshell/data/engineMaker.sjs
new file mode 100644
index 000000000..4c432e7ee
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/engineMaker.sjs
@@ -0,0 +1,54 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
+
+/**
+ * Dynamically create a search engine offering search suggestions via searchSuggestions.sjs.
+ *
+ * The engine is constructed by passing a JSON object with engine datails as the query string.
+ */
+
+function handleRequest(request, response) {
+ let engineData = JSON.parse(unescape(request.queryString).replace("+", " "));
+
+ if (!engineData.baseURL) {
+ response.setStatusLine(request.httpVersion, 500, "baseURL required");
+ return;
+ }
+
+ engineData.name = engineData.name || "Generated test engine";
+ engineData.description = engineData.description || "Generated test engine description";
+ engineData.method = engineData.method || "GET";
+
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ createOpenSearchEngine(response, engineData);
+}
+
+/**
+ * Create an OpenSearch engine for the given base URL.
+ */
+function createOpenSearchEngine(response, engineData) {
+ let params = "", queryString = "";
+ if (engineData.method == "POST") {
+ params = "<Param name='q' value='{searchTerms}'/>";
+ } else {
+ queryString = "?q={searchTerms}";
+ }
+
+ let result = "<?xml version='1.0' encoding='utf-8'?>\
+<OpenSearchDescription xmlns='http://a9.com/-/spec/opensearch/1.1/'>\
+ <ShortName>" + engineData.name + "</ShortName>\
+ <Description>" + engineData.description + "</Description>\
+ <InputEncoding>UTF-8</InputEncoding>\
+ <LongName>" + engineData.name + "</LongName>\
+ <Url type='application/x-suggestions+json' method='" + engineData.method + "'\
+ template='" + engineData.baseURL + "searchSuggestions.sjs" + queryString + "'>\
+ " + params + "\
+ </Url>\
+ <Url type='text/html' method='" + engineData.method + "'\
+ template='" + engineData.baseURL + queryString + "'/>\
+</OpenSearchDescription>\
+";
+ response.write(result);
+}
diff --git a/toolkit/components/search/tests/xpcshell/data/ico-size-16x16-png.ico b/toolkit/components/search/tests/xpcshell/data/ico-size-16x16-png.ico
new file mode 100644
index 000000000..442ab4dc8
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/ico-size-16x16-png.ico
Binary files differ
diff --git a/toolkit/components/search/tests/xpcshell/data/install.rdf b/toolkit/components/search/tests/xpcshell/data/install.rdf
new file mode 100644
index 000000000..df361ade4
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/install.rdf
@@ -0,0 +1,23 @@
+<?xml version="1.0"?>
+
+<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:em="http://www.mozilla.org/2004/em-rdf#">
+
+ <Description about="urn:mozilla:install-manifest">
+ <em:id>search-engine@tests.mozilla.org</em:id>
+ <em:unpack>true</em:unpack>
+ <em:version>1.0</em:version>
+
+ <em:targetApplication>
+ <Description>
+ <em:id>toolkit@mozilla.org</em:id>
+ <em:minVersion>0</em:minVersion>
+ <em:maxVersion>*</em:maxVersion>
+ </Description>
+ </em:targetApplication>
+
+ <!-- Front End MetaData -->
+ <em:name>Search Engine</em:name>
+
+ </Description>
+</RDF>
diff --git a/toolkit/components/search/tests/xpcshell/data/invalid-engine.xml b/toolkit/components/search/tests/xpcshell/data/invalid-engine.xml
new file mode 100644
index 000000000..e8efce672
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/invalid-engine.xml
@@ -0,0 +1 @@
+# An invalid xml engine file.
diff --git a/toolkit/components/search/tests/xpcshell/data/langpack-metadata.json b/toolkit/components/search/tests/xpcshell/data/langpack-metadata.json
new file mode 100644
index 000000000..e1ff95bc0
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/langpack-metadata.json
@@ -0,0 +1,5 @@
+{
+ "[app]/bug645970.xml": {
+ "alias": "lp"
+ }
+}
diff --git a/toolkit/components/search/tests/xpcshell/data/list.json b/toolkit/components/search/tests/xpcshell/data/list.json
new file mode 100644
index 000000000..68163bb88
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/list.json
@@ -0,0 +1,7 @@
+{
+ "default": {
+ "visibleDefaultEngines": [
+ "engine", "engine-pref", "engine-rel-searchform-purpose", "engine-system-purpose", "engine-chromeicon", "engine-resourceicon"
+ ]
+ }
+}
diff --git a/toolkit/components/search/tests/xpcshell/data/metadata.json b/toolkit/components/search/tests/xpcshell/data/metadata.json
new file mode 100644
index 000000000..77b003d4e
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/metadata.json
@@ -0,0 +1,30 @@
+{
+ "[global]": {
+ "searchdefaultexpir": 1471013469846
+ },
+ "[profile]\/engine.xml": {
+ "order": 1,
+ "alias": "foo"
+ },
+ "[app]\/google.xml": {
+ "order": 2
+ },
+ "[app]\/yahoo.xml": {
+ "order": 3
+ },
+ "[app]\/bing.xml": {
+ "order": 4
+ },
+ "[app]\/amazondotcom.xml": {
+ "order": 5
+ },
+ "[app]\/ddg.xml": {
+ "order": 6
+ },
+ "[app]\/twitter.xml": {
+ "order": 7
+ },
+ "[app]\/wikipedia.xml": {
+ "order": 8
+ }
+}
diff --git a/toolkit/components/search/tests/xpcshell/data/search.json b/toolkit/components/search/tests/xpcshell/data/search.json
new file mode 100644
index 000000000..f4f907778
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/search.json
@@ -0,0 +1,86 @@
+{
+ "version": 1,
+ "buildID": "20121106",
+ "locale": "en-US",
+ "metaData": {},
+ "engines": [
+ {
+ "_name": "Test search engine",
+ "_shortName": "test-search-engine",
+ "description": "A test search engine (based on Google search)",
+ "extensionID": "test-addon-id@mozilla.org",
+ "__searchForm": "http://www.google.com/",
+ "_iconURL": "data:image/png;base64,AAABAAEAEBAAAAEAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs9Pt8xetPtu9FsfFNtu%2BTzvb2%2B%2Fne4dFJeBw0egA%2FfAJAfAA8ewBBegAAAAD%2B%2FPtft98Mp%2BwWsfAVsvEbs%2FQeqvF8xO7%2F%2F%2F63yqkxdgM7gwE%2FggM%2BfQA%2BegBDeQDe7PIbotgQufcMufEPtfIPsvAbs%2FQvq%2Bfz%2Bf%2F%2B%2B%2FZKhR05hgBBhQI8hgBAgAI9ewD0%2B%2Fg3pswAtO8Cxf4Kw%2FsJvvYAqupKsNv%2B%2Fv7%2F%2FP5VkSU0iQA7jQA9hgBDgQU%2BfQH%2F%2Ff%2FQ6fM4sM4KsN8AteMCruIqqdbZ7PH8%2Fv%2Fg6Nc%2Fhg05kAA8jAM9iQI%2BhQA%2BgQDQu6b97uv%2F%2F%2F7V8Pqw3eiWz97q8%2Ff%2F%2F%2F%2F7%2FPptpkkqjQE4kwA7kAA5iwI8iAA8hQCOSSKdXjiyflbAkG7u2s%2F%2B%2F%2F39%2F%2F7r8utrqEYtjQE8lgA7kwA7kwA9jwA9igA9hACiWSekVRyeSgiYSBHx6N%2F%2B%2Fv7k7OFRmiYtlAA5lwI7lwI4lAA7kgI9jwE9iwI4iQCoVhWcTxCmb0K%2BooT8%2Fv%2F7%2F%2F%2FJ2r8fdwI1mwA3mQA3mgA8lAE8lAE4jwA9iwE%2BhwGfXifWvqz%2B%2Ff%2F58u%2Fev6Dt4tr%2B%2F%2F2ZuIUsggA7mgM6mAM3lgA5lgA6kQE%2FkwBChwHt4dv%2F%2F%2F728ei1bCi7VAC5XQ7kz7n%2F%2F%2F6bsZkgcB03lQA9lgM7kwA2iQktZToPK4r9%2F%2F%2F9%2F%2F%2FSqYK5UwDKZAS9WALIkFn%2B%2F%2F3%2F%2BP8oKccGGcIRJrERILYFEMwAAuEAAdX%2F%2Ff7%2F%2FP%2B%2BfDvGXQLIZgLEWgLOjlf7%2F%2F%2F%2F%2F%2F9QU90EAPQAAf8DAP0AAfMAAOUDAtr%2F%2F%2F%2F7%2B%2Fu2bCTIYwDPZgDBWQDSr4P%2F%2Fv%2F%2F%2FP5GRuABAPkAA%2FwBAfkDAPAAAesAAN%2F%2F%2B%2Fz%2F%2F%2F64g1C5VwDMYwK8Yg7y5tz8%2Fv%2FV1PYKDOcAAP0DAf4AAf0AAfYEAOwAAuAAAAD%2F%2FPvi28ymXyChTATRrIb8%2F%2F3v8fk6P8MAAdUCAvoAAP0CAP0AAfYAAO4AAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQAA",
+ "_metaData": {},
+ "_urls": [
+ {
+ "template": "http://suggestqueries.google.com/complete/search?output=firefox&client=firefox&hl={moz:locale}&q={searchTerms}",
+ "rels": [
+ ],
+ "type": "application/x-suggestions+json",
+ "params": [
+ ]
+ },
+ {
+ "template": "http://www.google.com/search",
+ "resultDomain": "google.com",
+ "rels": [
+ ],
+ "params": [
+ {
+ "name": "q",
+ "value": "{searchTerms}"
+ },
+ {
+ "name": "ie",
+ "value": "utf-8"
+ },
+ {
+ "name": "oe",
+ "value": "utf-8"
+ },
+ {
+ "name": "aq",
+ "value": "t"
+ },
+ {
+ "name": "channel",
+ "value": "fflb",
+ "purpose": "keyword"
+ },
+ {
+ "name": "channel",
+ "value": "rcs",
+ "purpose": "contextmenu"
+ }
+ ]
+ },
+ {
+ "template": "http://www.google.com/search",
+ "resultDomain": "purpose.google.com",
+ "rels": [
+ ],
+ "type": "application/x-moz-default-purpose",
+ "params": [
+ {
+ "name": "q",
+ "value": "{searchTerms}"
+ },
+ {
+ "name": "channel",
+ "value": "fflb",
+ "purpose": "keyword"
+ },
+ {
+ "name": "channel",
+ "value": "rcs",
+ "purpose": "contextmenu"
+ }
+ ]
+ }
+ ],
+ "queryCharset": "UTF-8",
+ "_readOnly": false
+ }
+ ]
+}
diff --git a/toolkit/components/search/tests/xpcshell/data/search.sqlite b/toolkit/components/search/tests/xpcshell/data/search.sqlite
new file mode 100644
index 000000000..983bb831a
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/search.sqlite
Binary files differ
diff --git a/toolkit/components/search/tests/xpcshell/data/searchSuggestions.sjs b/toolkit/components/search/tests/xpcshell/data/searchSuggestions.sjs
new file mode 100644
index 000000000..abd94428e
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/searchSuggestions.sjs
@@ -0,0 +1,78 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
+
+Cu.import("resource://gre/modules/Timer.jsm");
+Cu.import("resource://gre/modules/NetUtil.jsm");
+
+/**
+ * Provide search suggestions in the OpenSearch JSON format.
+ */
+
+function handleRequest(request, response) {
+ // Get the query parameters from the query string.
+ let query = parseQueryString(request.queryString);
+
+ function writeSuggestions(query, completions = []) {
+ let result = [query, completions];
+ response.write(JSON.stringify(result));
+ return result;
+ }
+
+ response.setStatusLine(request.httpVersion, 200, "OK");
+
+ let q = request.method == "GET" ? query.q : undefined;
+ if (q == "no remote" || q == "no results") {
+ writeSuggestions(q);
+ } else if (q == "Query Mismatch") {
+ writeSuggestions("This is an incorrect query string", ["some result"]);
+ } else if (q == "Query Case Mismatch") {
+ writeSuggestions(q.toUpperCase(), [q]);
+ } else if (q == "") {
+ writeSuggestions("", ["The server should never be sent an empty query"]);
+ } else if (q && q.startsWith("mo")) {
+ writeSuggestions(q, ["Mozilla", "modern", "mom"]);
+ } else if (q && q.startsWith("I ❤️")) {
+ writeSuggestions(q, ["I ❤️ Mozilla"]);
+ } else if (q && q.startsWith("letter ")) {
+ let letters = [];
+ for (let charCode = "A".charCodeAt(); charCode <= "Z".charCodeAt(); charCode++) {
+ letters.push("letter " + String.fromCharCode(charCode));
+ }
+ writeSuggestions(q, letters);
+ } else if (q && q.startsWith("HTTP ")) {
+ response.setStatusLine(request.httpVersion, q.replace("HTTP ", ""), q);
+ writeSuggestions(q, [q]);
+ } else if (q && q.startsWith("delay")) {
+ // Delay the response by 200 milliseconds (less than the timeout but hopefully enough to abort
+ // before completion).
+ response.processAsync();
+ writeSuggestions(q, [q]);
+ setTimeout(() => response.finish(), 200);
+ } else if (q && q.startsWith("slow ")) {
+ // Delay the response by 10 seconds so the client timeout is reached.
+ response.processAsync();
+ writeSuggestions(q, [q]);
+ setTimeout(() => response.finish(), 10000);
+ } else if (request.method == "POST") {
+ // This includes headers, not just the body
+ let requestText = NetUtil.readInputStreamToString(request.bodyInputStream,
+ request.bodyInputStream.available());
+ // Only use the last line which contains the encoded params
+ let requestLines = requestText.split("\n");
+ let postParams = parseQueryString(requestLines[requestLines.length - 1]);
+ writeSuggestions(postParams.q, ["Mozilla", "modern", "mom"]);
+ } else {
+ response.setStatusLine(request.httpVersion, 404, "Not Found");
+ }
+}
+
+function parseQueryString(queryString) {
+ let query = {};
+ queryString.split('&').forEach(function (val) {
+ let [name, value] = val.split('=');
+ query[name] = unescape(value).replace(/[+]/g, " ");
+ });
+ return query;
+}
diff --git a/toolkit/components/search/tests/xpcshell/data/searchTest.jar b/toolkit/components/search/tests/xpcshell/data/searchTest.jar
new file mode 100644
index 000000000..8bfbe6f21
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/data/searchTest.jar
Binary files differ
diff --git a/toolkit/components/search/tests/xpcshell/head_search.js b/toolkit/components/search/tests/xpcshell/head_search.js
new file mode 100644
index 000000000..2f40d84f8
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/head_search.js
@@ -0,0 +1,544 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+
+var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
+
+Cu.import("resource://gre/modules/FileUtils.jsm");
+Cu.import("resource://gre/modules/osfile.jsm");
+Cu.import("resource://gre/modules/NetUtil.jsm");
+Cu.import("resource://gre/modules/Promise.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/Task.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://testing-common/AppInfo.jsm");
+Cu.import("resource://testing-common/httpd.js");
+
+const BROWSER_SEARCH_PREF = "browser.search.";
+const NS_APP_SEARCH_DIR = "SrchPlugns";
+
+const MODE_RDONLY = FileUtils.MODE_RDONLY;
+const MODE_WRONLY = FileUtils.MODE_WRONLY;
+const MODE_CREATE = FileUtils.MODE_CREATE;
+const MODE_TRUNCATE = FileUtils.MODE_TRUNCATE;
+
+const CACHE_FILENAME = "search.json.mozlz4";
+
+// nsSearchService.js uses Services.appinfo.name to build a salt for a hash.
+var XULRuntime = Components.classesByID["{95d89e3e-a169-41a3-8e56-719978e15b12}"]
+ .getService(Ci.nsIXULRuntime);
+
+var isChild = XULRuntime.processType == XULRuntime.PROCESS_TYPE_CONTENT;
+
+updateAppInfo({
+ name: "XPCShell",
+ ID: "xpcshell@test.mozilla.org",
+ version: "5",
+ platformVersion: "1.9",
+ // mirror OS from the base impl as some of the "location" tests rely on it
+ OS: XULRuntime.OS,
+ // mirror processType from the base implementation
+ extraProps: {
+ processType: XULRuntime.processType,
+ },
+});
+
+var gProfD;
+if (!isChild) {
+ // Need to create and register a profile folder.
+ gProfD = do_get_profile();
+}
+
+function dumpn(text)
+{
+ dump("search test: " + text + "\n");
+}
+
+/**
+ * Configure preferences to load engines from
+ * chrome://testsearchplugin/locale/searchplugins/
+ */
+function configureToLoadJarEngines()
+{
+ let url = "chrome://testsearchplugin/locale/searchplugins/";
+ let resProt = Services.io.getProtocolHandler("resource")
+ .QueryInterface(Ci.nsIResProtocolHandler);
+ resProt.setSubstitution("search-plugins",
+ Services.io.newURI(url, null, null));
+
+ // Ensure a test engine exists in the app dir anyway.
+ let dir = Services.dirsvc.get(NS_APP_SEARCH_DIR, Ci.nsIFile);
+ if (!dir.exists())
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+ do_get_file("data/engine-app.xml").copyTo(dir, "app.xml");
+}
+
+/**
+ * Fake the installation of an add-on in the profile, by creating the
+ * directory and registering it with the directory service.
+ */
+function installAddonEngine(name = "engine-addon")
+{
+ const XRE_EXTENSIONS_DIR_LIST = "XREExtDL";
+ const profD = do_get_profile().QueryInterface(Ci.nsILocalFile);
+
+ let dir = profD.clone();
+ dir.append("extensions");
+ if (!dir.exists())
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ dir.append("search-engine@tests.mozilla.org");
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ do_get_file("data/install.rdf").copyTo(dir, "install.rdf");
+ let addonDir = dir.clone();
+ dir.append("searchplugins");
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+ do_get_file("data/" + name + ".xml").copyTo(dir, "bug645970.xml");
+
+ Services.dirsvc.registerProvider({
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIDirectoryServiceProvider,
+ Ci.nsIDirectoryServiceProvider2]),
+
+ getFile: function (prop, persistant) {
+ throw Cr.NS_ERROR_FAILURE;
+ },
+
+ getFiles: function (prop) {
+ let result = [];
+
+ switch (prop) {
+ case XRE_EXTENSIONS_DIR_LIST:
+ result.push(addonDir);
+ break;
+ default:
+ throw Cr.NS_ERROR_FAILURE;
+ }
+
+ return {
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsISimpleEnumerator]),
+ hasMoreElements: () => result.length > 0,
+ getNext: () => result.shift()
+ };
+ }
+ });
+}
+
+/**
+ * Copy the engine-distribution.xml engine to a fake distribution
+ * created in the profile, and registered with the directory service.
+ */
+function installDistributionEngine()
+{
+ const XRE_APP_DISTRIBUTION_DIR = "XREAppDist";
+
+ const profD = do_get_profile().QueryInterface(Ci.nsILocalFile);
+
+ let dir = profD.clone();
+ dir.append("distribution");
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+ let distDir = dir.clone();
+
+ dir.append("searchplugins");
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ dir.append("common");
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ do_get_file("data/engine-override.xml").copyTo(dir, "bug645970.xml");
+
+ Services.dirsvc.registerProvider({
+ getFile: function(aProp, aPersistent) {
+ aPersistent.value = true;
+ if (aProp == XRE_APP_DISTRIBUTION_DIR)
+ return distDir.clone();
+ return null;
+ }
+ });
+}
+
+/**
+ * Clean the profile of any metadata files left from a previous run.
+ */
+function removeMetadata()
+{
+ let file = gProfD.clone();
+ file.append("search-metadata.json");
+ if (file.exists()) {
+ file.remove(false);
+ }
+
+ file = gProfD.clone();
+ file.append("search.sqlite");
+ if (file.exists()) {
+ file.remove(false);
+ }
+}
+
+function promiseCacheData() {
+ return new Promise(resolve => Task.spawn(function* () {
+ let path = OS.Path.join(OS.Constants.Path.profileDir, CACHE_FILENAME);
+ let bytes = yield OS.File.read(path, {compression: "lz4"});
+ resolve(JSON.parse(new TextDecoder().decode(bytes)));
+ }));
+}
+
+function promiseSaveCacheData(data) {
+ return OS.File.writeAtomic(OS.Path.join(OS.Constants.Path.profileDir, CACHE_FILENAME),
+ new TextEncoder().encode(JSON.stringify(data)),
+ {compression: "lz4"});
+}
+
+function promiseEngineMetadata() {
+ return new Promise(resolve => Task.spawn(function* () {
+ let cache = yield promiseCacheData();
+ let data = {};
+ for (let engine of cache.engines) {
+ data[engine._shortName] = engine._metaData;
+ }
+ resolve(data);
+ }));
+}
+
+function promiseGlobalMetadata() {
+ return new Promise(resolve => Task.spawn(function* () {
+ let cache = yield promiseCacheData();
+ resolve(cache.metaData);
+ }));
+}
+
+function promiseSaveGlobalMetadata(globalData) {
+ return new Promise(resolve => Task.spawn(function* () {
+ let data = yield promiseCacheData();
+ data.metaData = globalData;
+ yield promiseSaveCacheData(data);
+ resolve();
+ }));
+}
+
+var forceExpiration = Task.async(function* () {
+ let metadata = yield promiseGlobalMetadata();
+
+ // Make the current geodefaults expire 1s ago.
+ metadata.searchDefaultExpir = Date.now() - 1000;
+ yield promiseSaveGlobalMetadata(metadata);
+});
+
+/**
+ * Clean the profile of any cache file left from a previous run.
+ * Returns a boolean indicating if the cache file existed.
+ */
+function removeCacheFile()
+{
+ let file = gProfD.clone();
+ file.append(CACHE_FILENAME);
+ if (file.exists()) {
+ file.remove(false);
+ return true;
+ }
+ return false;
+}
+
+/**
+ * isUSTimezone taken from nsSearchService.js
+ */
+function isUSTimezone() {
+ // Timezone assumptions! We assume that if the system clock's timezone is
+ // between Newfoundland and Hawaii, that the user is in North America.
+
+ // This includes all of South America as well, but we have relatively few
+ // en-US users there, so that's OK.
+
+ // 150 minutes = 2.5 hours (UTC-2.5), which is
+ // Newfoundland Daylight Time (http://www.timeanddate.com/time/zones/ndt)
+
+ // 600 minutes = 10 hours (UTC-10), which is
+ // Hawaii-Aleutian Standard Time (http://www.timeanddate.com/time/zones/hast)
+
+ let UTCOffset = (new Date()).getTimezoneOffset();
+ return UTCOffset >= 150 && UTCOffset <= 600;
+}
+
+const kDefaultenginenamePref = "browser.search.defaultenginename";
+const kTestEngineName = "Test search engine";
+const kLocalePref = "general.useragent.locale";
+
+function getDefaultEngineName(isUS) {
+ const nsIPLS = Ci.nsIPrefLocalizedString;
+ // Copy the logic from nsSearchService
+ let pref = kDefaultenginenamePref;
+ if (isUS === undefined)
+ isUS = Services.prefs.getCharPref(kLocalePref) == "en-US" && isUSTimezone();
+ if (isUS) {
+ pref += ".US";
+ }
+ return Services.prefs.getComplexValue(pref, nsIPLS).data;
+}
+
+/**
+ * Waits for the cache file to be saved.
+ * @return {Promise} Resolved when the cache file is saved.
+ */
+function promiseAfterCache() {
+ return waitForSearchNotification("write-cache-to-disk-complete");
+}
+
+function parseJsonFromStream(aInputStream) {
+ const json = Cc["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON);
+ const data = json.decodeFromStream(aInputStream, aInputStream.available());
+ return data;
+}
+
+/**
+ * Read a JSON file and return the JS object
+ */
+function readJSONFile(aFile) {
+ let stream = Cc["@mozilla.org/network/file-input-stream;1"].
+ createInstance(Ci.nsIFileInputStream);
+ try {
+ stream.init(aFile, MODE_RDONLY, FileUtils.PERMS_FILE, 0);
+ return parseJsonFromStream(stream, stream.available());
+ } catch (ex) {
+ dumpn("readJSONFile: Error reading JSON file: " + ex);
+ } finally {
+ stream.close();
+ }
+ return false;
+}
+
+/**
+ * Recursively compare two objects and check that every property of expectedObj has the same value
+ * on actualObj.
+ */
+function isSubObjectOf(expectedObj, actualObj) {
+ for (let prop in expectedObj) {
+ if (expectedObj[prop] instanceof Object) {
+ do_check_eq(expectedObj[prop].length, actualObj[prop].length);
+ isSubObjectOf(expectedObj[prop], actualObj[prop]);
+ } else {
+ if (expectedObj[prop] != actualObj[prop])
+ do_print("comparing property " + prop);
+ do_check_eq(expectedObj[prop], actualObj[prop]);
+ }
+ }
+}
+
+// Can't set prefs if we're running in a child process, but the search service
+// doesn't run in child processes anyways.
+if (!isChild) {
+ // Expand the amount of information available in error logs
+ Services.prefs.setBoolPref("browser.search.log", true);
+
+ // The geo-specific search tests assume certain prefs are already setup, which
+ // might not be true when run in comm-central etc. So create them here.
+ Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", true);
+ Services.prefs.setIntPref("browser.search.geoip.timeout", 3000);
+ // But still disable geoip lookups - tests that need it will re-configure this.
+ Services.prefs.setCharPref("browser.search.geoip.url", "");
+ // Also disable region defaults - tests using it will also re-configure it.
+ Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref("geoSpecificDefaults.url", "");
+}
+
+/**
+ * After useHttpServer() is called, this string contains the URL of the "data"
+ * directory, including the final slash.
+ */
+var gDataUrl;
+
+/**
+ * Initializes the HTTP server and ensures that it is terminated when tests end.
+ *
+ * @return The HttpServer object in case further customization is needed.
+ */
+function useHttpServer() {
+ let httpServer = new HttpServer();
+ httpServer.start(-1);
+ httpServer.registerDirectory("/", do_get_cwd());
+ gDataUrl = "http://localhost:" + httpServer.identity.primaryPort + "/data/";
+ do_register_cleanup(() => httpServer.stop(() => {}));
+ return httpServer;
+}
+
+/**
+ * Adds test engines and returns a promise resolved when they are installed.
+ *
+ * The engines are added in the given order.
+ *
+ * @param aItems
+ * Array of objects with the following properties:
+ * {
+ * name: Engine name, used to wait for it to be loaded.
+ * xmlFileName: Name of the XML file in the "data" folder.
+ * details: Array containing the parameters of addEngineWithDetails,
+ * except for the engine name. Alternative to xmlFileName.
+ * }
+ */
+var addTestEngines = Task.async(function* (aItems) {
+ if (!gDataUrl) {
+ do_throw("useHttpServer must be called before addTestEngines.");
+ }
+
+ let engines = [];
+
+ for (let item of aItems) {
+ do_print("Adding engine: " + item.name);
+ yield new Promise((resolve, reject) => {
+ Services.obs.addObserver(function obs(subject, topic, data) {
+ try {
+ let engine = subject.QueryInterface(Ci.nsISearchEngine);
+ do_print("Observed " + data + " for " + engine.name);
+ if (data != "engine-added" || engine.name != item.name) {
+ return;
+ }
+
+ Services.obs.removeObserver(obs, "browser-search-engine-modified");
+ engines.push(engine);
+ resolve();
+ } catch (ex) {
+ reject(ex);
+ }
+ }, "browser-search-engine-modified", false);
+
+ if (item.xmlFileName) {
+ Services.search.addEngine(gDataUrl + item.xmlFileName,
+ null, null, false);
+ } else {
+ Services.search.addEngineWithDetails(item.name, ...item.details);
+ }
+ });
+ }
+
+ return engines;
+});
+
+/**
+ * Installs a test engine into the test profile.
+ */
+function installTestEngine() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_check_false(Services.search.isInitialized);
+
+ let engineDummyFile = gProfD.clone();
+ engineDummyFile.append("searchplugins");
+ engineDummyFile.append("test-search-engine.xml");
+ let engineDir = engineDummyFile.parent;
+ engineDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ do_get_file("data/engine.xml").copyTo(engineDir, "engine.xml");
+
+ do_register_cleanup(function() {
+ removeMetadata();
+ removeCacheFile();
+ });
+}
+
+/**
+ * Set a localized preference on the default branch
+ * @param aPrefName
+ * The name of the pref to set.
+ */
+function setLocalizedDefaultPref(aPrefName, aValue) {
+ let value = "data:text/plain," + BROWSER_SEARCH_PREF + aPrefName + "=" + aValue;
+ Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF)
+ .setCharPref(aPrefName, value);
+}
+
+
+/**
+ * Installs two test engines, sets them as default for US vs. general.
+ */
+function setUpGeoDefaults() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_check_false(Services.search.isInitialized);
+
+ let engineDummyFile = gProfD.clone();
+ engineDummyFile.append("searchplugins");
+ engineDummyFile.append("test-search-engine.xml");
+ let engineDir = engineDummyFile.parent;
+ engineDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ do_get_file("data/engine.xml").copyTo(engineDir, "engine.xml");
+
+ engineDummyFile = gProfD.clone();
+ engineDummyFile.append("searchplugins");
+ engineDummyFile.append("test-search-engine2.xml");
+
+ do_get_file("data/engine2.xml").copyTo(engineDir, "engine2.xml");
+
+ setLocalizedDefaultPref("defaultenginename", "Test search engine");
+ setLocalizedDefaultPref("defaultenginename.US", "A second test engine");
+
+ do_register_cleanup(function() {
+ removeMetadata();
+ removeCacheFile();
+ });
+}
+
+/**
+ * Returns a promise that is resolved when an observer notification from the
+ * search service fires with the specified data.
+ *
+ * @param aExpectedData
+ * The value the observer notification sends that causes us to resolve
+ * the promise.
+ */
+function waitForSearchNotification(aExpectedData) {
+ return new Promise(resolve => {
+ const SEARCH_SERVICE_TOPIC = "browser-search-service";
+ Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
+ if (aData != aExpectedData)
+ return;
+
+ Services.obs.removeObserver(observer, SEARCH_SERVICE_TOPIC);
+ resolve(aSubject);
+ }, SEARCH_SERVICE_TOPIC, false);
+ });
+}
+
+function asyncInit() {
+ return new Promise(resolve => {
+ Services.search.init(function() {
+ do_check_true(Services.search.isInitialized);
+ resolve();
+ });
+ });
+}
+
+function asyncReInit() {
+ let promise = waitForSearchNotification("reinit-complete");
+
+ Services.search.QueryInterface(Ci.nsIObserver)
+ .observe(null, "nsPref:changed", kLocalePref);
+
+ return promise;
+}
+
+// This "enum" from nsSearchService.js
+const TELEMETRY_RESULT_ENUM = {
+ SUCCESS: 0,
+ SUCCESS_WITHOUT_DATA: 1,
+ XHRTIMEOUT: 2,
+ ERROR: 3,
+};
+
+/**
+ * Checks the value of the SEARCH_SERVICE_COUNTRY_FETCH_RESULT probe.
+ *
+ * @param aExpectedValue
+ * If a value from TELEMETRY_RESULT_ENUM, we expect to see this value
+ * recorded exactly once in the probe. If |null|, we expect to see
+ * nothing recorded in the probe at all.
+ */
+function checkCountryResultTelemetry(aExpectedValue) {
+ let histogram = Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_FETCH_RESULT");
+ let snapshot = histogram.snapshot();
+ // The probe is declared with 8 values, but we get 9 back from .counts
+ let expectedCounts = [0, 0, 0, 0, 0, 0, 0, 0, 0];
+ if (aExpectedValue != null) {
+ expectedCounts[aExpectedValue] = 1;
+ }
+ deepEqual(snapshot.counts, expectedCounts);
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_645970.js b/toolkit/components/search/tests/xpcshell/test_645970.js
new file mode 100644
index 000000000..3204e03d9
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_645970.js
@@ -0,0 +1,22 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* 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/. */
+
+/**
+ * Test nsSearchService with nested jar: uris, without async initialization
+ */
+function run_test() {
+ updateAppInfo();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+
+ // The search service needs to be started after the jarURIs pref has been
+ // set in order to initiate it correctly
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+ Services.obs.notifyObservers(null, "quit-application", null);
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_SearchStaticData.js b/toolkit/components/search/tests/xpcshell/test_SearchStaticData.js
new file mode 100644
index 000000000..4e50ed2a9
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_SearchStaticData.js
@@ -0,0 +1,27 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Tests the SearchStaticData module.
+ */
+
+"use strict";
+
+Cu.import("resource://gre/modules/SearchStaticData.jsm", this);
+
+function run_test() {
+ do_check_true(SearchStaticData.getAlternateDomains("www.google.com")
+ .indexOf("www.google.fr") != -1);
+ do_check_true(SearchStaticData.getAlternateDomains("www.google.fr")
+ .indexOf("www.google.com") != -1);
+ do_check_true(SearchStaticData.getAlternateDomains("www.google.com")
+ .every(d => d.startsWith("www.google.")));
+ do_check_true(SearchStaticData.getAlternateDomains("google.com").length == 0);
+
+ // Test that methods from SearchStaticData module can be overwritten,
+ // needed for hotfixing.
+ let backup = SearchStaticData.getAlternateDomains;
+ SearchStaticData.getAlternateDomains = () => ["www.bing.fr"];
+ do_check_matches(SearchStaticData.getAlternateDomains("www.bing.com"), ["www.bing.fr"]);
+ SearchStaticData.getAlternateDomains = backup;
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_addEngineWithDetails.js b/toolkit/components/search/tests/xpcshell/test_addEngineWithDetails.js
new file mode 100644
index 000000000..14411eaaa
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_addEngineWithDetails.js
@@ -0,0 +1,34 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const kSearchEngineID = "addEngineWithDetails_test_engine";
+const kSearchEngineURL = "http://example.com/?search={searchTerms}";
+const kSearchTerm = "foo";
+
+add_task(function* test_addEngineWithDetails() {
+ do_check_false(Services.search.isInitialized);
+
+ Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF)
+ .setBoolPref("reset.enabled", true);
+
+ yield asyncInit();
+
+ Services.search.addEngineWithDetails(kSearchEngineID, "", "", "", "get",
+ kSearchEngineURL);
+
+ // An engine added with addEngineWithDetails should have a load path, even
+ // though we can't point to a specific file.
+ let engine = Services.search.getEngineByName(kSearchEngineID);
+ do_check_eq(engine.wrappedJSObject._loadPath, "[other]addEngineWithDetails");
+
+ // Set the engine as default; this should set a loadPath verification hash,
+ // which should ensure we don't show the search reset prompt.
+ Services.search.currentEngine = engine;
+
+ let expectedURL = kSearchEngineURL.replace("{searchTerms}", kSearchTerm);
+ let submission =
+ Services.search.currentEngine.getSubmission(kSearchTerm, null, "searchbar");
+ do_check_eq(submission.uri.spec, expectedURL);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_addEngine_callback.js b/toolkit/components/search/tests/xpcshell/test_addEngine_callback.js
new file mode 100644
index 000000000..07eaf38bb
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_addEngine_callback.js
@@ -0,0 +1,95 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Tests covering nsIBrowserSearchService::addEngine's optional callback.
+ */
+
+Components.utils.import("resource://testing-common/MockRegistrar.jsm");
+
+"use strict";
+
+// Only need to stub the methods actually called by nsSearchService
+var promptService = {
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIPromptService]),
+ confirmEx: function() {}
+};
+var prompt = {
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIPrompt]),
+ alert: function() {}
+};
+// Override the prompt service and nsIPrompt, since the search service currently
+// prompts in response to certain installation failures we test here
+// XXX this should disappear once bug 863474 is fixed
+MockRegistrar.register("@mozilla.org/embedcomp/prompt-service;1", promptService);
+MockRegistrar.register("@mozilla.org/prompter;1", prompt);
+
+
+// First test inits the search service
+add_test(function init_search_service() {
+ Services.search.init(function (status) {
+ if (!Components.isSuccessCode(status))
+ do_throw("Failed to initialize search service");
+
+ run_next_test();
+ });
+});
+
+// Simple test of the search callback
+add_test(function simple_callback_test() {
+ let searchCallback = {
+ onSuccess: function (engine) {
+ do_check_true(!!engine);
+ do_check_neq(engine.name, Services.search.defaultEngine.name);
+ do_check_eq(engine.wrappedJSObject._loadPath,
+ "[http]localhost/test-search-engine.xml");
+ run_next_test();
+ },
+ onError: function (errorCode) {
+ do_throw("search callback returned error: " + errorCode);
+ }
+ }
+ Services.search.addEngine(gDataUrl + "engine.xml", null,
+ null, false, searchCallback);
+});
+
+// Test of the search callback on duplicate engine failures
+add_test(function duplicate_failure_test() {
+ let searchCallback = {
+ onSuccess: function (engine) {
+ do_throw("this addition should not have succeeded");
+ },
+ onError: function (errorCode) {
+ do_check_true(!!errorCode);
+ do_check_eq(errorCode, Ci.nsISearchInstallCallback.ERROR_DUPLICATE_ENGINE);
+ run_next_test();
+ }
+ }
+ // Re-add the same engine added in the previous test
+ Services.search.addEngine(gDataUrl + "engine.xml", null,
+ null, false, searchCallback);
+});
+
+// Test of the search callback on failure to load the engine failures
+add_test(function load_failure_test() {
+ let searchCallback = {
+ onSuccess: function (engine) {
+ do_throw("this addition should not have succeeded");
+ },
+ onError: function (errorCode) {
+ do_check_true(!!errorCode);
+ do_check_eq(errorCode, Ci.nsISearchInstallCallback.ERROR_UNKNOWN_FAILURE);
+ run_next_test();
+ }
+ }
+ // Try adding an engine that doesn't exist
+ Services.search.addEngine("http://invalid/data/engine.xml", null,
+ null, false, searchCallback);
+});
+
+function run_test() {
+ updateAppInfo();
+ useHttpServer();
+
+ run_next_test();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_async.js b/toolkit/components/search/tests/xpcshell/test_async.js
new file mode 100644
index 000000000..58b530464
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_async.js
@@ -0,0 +1,34 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ do_test_pending();
+
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+
+ do_check_false(Services.search.isInitialized);
+
+ Services.search.init(function search_initialized(aStatus) {
+ do_check_true(Components.isSuccessCode(aStatus));
+ do_check_true(Services.search.isInitialized);
+
+ // test engines from dir are not loaded.
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ // Check the hidden engine is not loaded.
+ engine = Services.search.getEngineByName("hidden");
+ do_check_eq(engine, null);
+
+ do_test_finished();
+ });
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_async_addon.js b/toolkit/components/search/tests/xpcshell/test_async_addon.js
new file mode 100644
index 000000000..af488f301
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_async_addon.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ do_test_pending();
+
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+ installAddonEngine();
+
+ do_check_false(Services.search.isInitialized);
+
+ Services.search.init(function search_initialized(aStatus) {
+ do_check_true(Components.isSuccessCode(aStatus));
+ do_check_true(Services.search.isInitialized);
+
+ // test the add-on engine is loaded in addition to our jar engine
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 2);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("addon");
+ do_check_neq(engine, null);
+
+ do_check_eq(engine.description, "addon");
+
+ do_test_finished();
+ });
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_async_addon_no_override.js b/toolkit/components/search/tests/xpcshell/test_async_addon_no_override.js
new file mode 100644
index 000000000..5c48c108a
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_async_addon_no_override.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ do_test_pending();
+
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+ installAddonEngine("engine-override");
+
+ do_check_false(Services.search.isInitialized);
+
+ Services.search.init(function search_initialized(aStatus) {
+ do_check_true(Components.isSuccessCode(aStatus));
+ do_check_true(Services.search.isInitialized);
+
+ // test the add-on engine isn't overriding our jar engine
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ do_check_eq(engine.description, "bug645970");
+
+ do_test_finished();
+ });
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_async_distribution.js b/toolkit/components/search/tests/xpcshell/test_async_distribution.js
new file mode 100644
index 000000000..4f3af0419
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_async_distribution.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ do_test_pending();
+
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+ installDistributionEngine();
+
+ do_check_false(Services.search.isInitialized);
+
+ Services.search.init(function search_initialized(aStatus) {
+ do_check_true(Components.isSuccessCode(aStatus));
+ do_check_true(Services.search.isInitialized);
+
+ // test that the engine from the distribution overrides our jar engine
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ // check the engine we have is actually the one from the distribution
+ do_check_eq(engine.description, "override");
+
+ do_test_finished();
+ });
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_async_migration.js b/toolkit/components/search/tests/xpcshell/test_async_migration.js
new file mode 100644
index 000000000..4d0335c45
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_async_migration.js
@@ -0,0 +1,27 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/* Test that legacy metadata from search-metadata.json is correctly
+ * transferred to the new metadata storage. */
+
+function run_test() {
+ updateAppInfo();
+ installTestEngine();
+
+ do_get_file("data/metadata.json").copyTo(gProfD, "search-metadata.json");
+
+ run_next_test();
+}
+
+add_task(function* test_async_metadata_migration() {
+ yield asyncInit();
+ yield promiseAfterCache();
+
+ // Check that the entries are placed as specified correctly
+ let metadata = yield promiseEngineMetadata();
+ do_check_eq(metadata["engine"].order, 1);
+ do_check_eq(metadata["engine"].alias, "foo");
+
+ metadata = yield promiseGlobalMetadata();
+ do_check_eq(metadata["searchDefaultExpir"], 1471013469846);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_async_profile_engine.js b/toolkit/components/search/tests/xpcshell/test_async_profile_engine.js
new file mode 100644
index 000000000..cbcdbdcb0
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_async_profile_engine.js
@@ -0,0 +1,42 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const NS_APP_USER_SEARCH_DIR = "UsrSrchPlugns";
+
+function run_test() {
+ do_test_pending();
+
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+
+ // Copy an engine in [profile]/searchplugin/ and ensure it's not
+ // overriding the same file from a jar.
+ // The description in the file we are copying is 'profile'.
+ let dir = Services.dirsvc.get(NS_APP_USER_SEARCH_DIR, Ci.nsIFile);
+ if (!dir.exists())
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+ do_get_file("data/engine-override.xml").copyTo(dir, "bug645970.xml");
+
+ do_check_false(Services.search.isInitialized);
+
+ Services.search.init(function search_initialized(aStatus) {
+ do_check_true(Components.isSuccessCode(aStatus));
+ do_check_true(Services.search.isInitialized);
+
+ // test engines from dir are not loaded.
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ do_check_eq(engine.description, "bug645970");
+
+ do_test_finished();
+ });
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_bug930456.js b/toolkit/components/search/tests/xpcshell/test_bug930456.js
new file mode 100644
index 000000000..1dbb06c59
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_bug930456.js
@@ -0,0 +1,11 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test()
+{
+ if (isChild) {
+ do_check_false("@mozilla.org/browser/search-service;1" in Cc);
+ } else {
+ do_check_true("@mozilla.org/browser/search-service;1" in Cc);
+ }
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_bug930456_child.js b/toolkit/components/search/tests/xpcshell/test_bug930456_child.js
new file mode 100644
index 000000000..8540a37f4
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_bug930456_child.js
@@ -0,0 +1,3 @@
+function run_test() {
+ run_test_in_child("test_bug930456.js");
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_chromeresource_icon1.js b/toolkit/components/search/tests/xpcshell/test_chromeresource_icon1.js
new file mode 100644
index 000000000..7d3b1698a
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_chromeresource_icon1.js
@@ -0,0 +1,31 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/* Test that resource URLs can be used in default engines */
+
+"use strict";
+
+function run_test() {
+ updateAppInfo();
+
+ // The test engines used in this test need to be recognized as 'default'
+ // engines or the resource URL won't be used
+ let url = "resource://test/data/";
+ let resProt = Services.io.getProtocolHandler("resource")
+ .QueryInterface(Ci.nsIResProtocolHandler);
+ resProt.setSubstitution("search-plugins",
+ Services.io.newURI(url, null, null));
+
+ run_next_test();
+}
+
+add_task(function* test_defaultresourceicon() {
+ yield asyncInit();
+
+ let engine1 = Services.search.getEngineByName("engine-resourceicon");
+ do_check_eq(engine1.iconURI.spec, "resource://search-plugins/icon16.png");
+ do_check_eq(engine1.getIconURLBySize(32, 32), "resource://search-plugins/icon32.png");
+ let engine2 = Services.search.getEngineByName("engine-chromeicon");
+ do_check_eq(engine2.iconURI.spec, "chrome://branding/content/icon16.png");
+ do_check_eq(engine2.getIconURLBySize(32, 32), "chrome://branding/content/icon32.png");
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_chromeresource_icon2.js b/toolkit/components/search/tests/xpcshell/test_chromeresource_icon2.js
new file mode 100644
index 000000000..52aff1168
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_chromeresource_icon2.js
@@ -0,0 +1,23 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/* Test that an installed engine can't use a resource URL for an icon */
+
+"use strict";
+
+function run_test() {
+ removeMetadata();
+ updateAppInfo();
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_installedresourceicon() {
+ let [engine1, engine2] = yield addTestEngines([
+ { name: "engine-resourceicon", xmlFileName: "engine-resourceicon.xml" },
+ { name: "engine-chromeicon", xmlFileName: "engine-chromeicon.xml" },
+ ]);
+ do_check_null(engine1.iconURI);
+ do_check_null(engine2.iconURI);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_currentEngine_fallback.js b/toolkit/components/search/tests/xpcshell/test_currentEngine_fallback.js
new file mode 100644
index 000000000..d4c699d97
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_currentEngine_fallback.js
@@ -0,0 +1,25 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ do_check_true(Services.search.getVisibleEngines().length > 1);
+ do_check_true(Services.search.isInitialized);
+
+ // Remove the current engine...
+ let currentEngine = Services.search.currentEngine;
+ Services.search.removeEngine(currentEngine);
+
+ // ... and verify a new current engine has been set.
+ do_check_neq(Services.search.currentEngine.name, currentEngine.name);
+ do_check_true(currentEngine.hidden);
+
+ // Remove all the other engines.
+ Services.search.getVisibleEngines().forEach(Services.search.removeEngine);
+ do_check_eq(Services.search.getVisibleEngines().length, 0);
+
+ // Verify the original default engine is used as a fallback and no
+ // longer hidden.
+ do_check_eq(Services.search.currentEngine.name, currentEngine.name);
+ do_check_false(currentEngine.hidden);
+ do_check_eq(Services.search.getVisibleEngines().length, 1);
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_defaultEngine.js b/toolkit/components/search/tests/xpcshell/test_defaultEngine.js
new file mode 100644
index 000000000..13d9922de
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_defaultEngine.js
@@ -0,0 +1,51 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Test that currentEngine and defaultEngine properties can be set and yield the
+ * proper events and behavior (search results)
+ */
+
+"use strict";
+
+function run_test() {
+ removeMetadata();
+ updateAppInfo();
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_defaultEngine() {
+ let search = Services.search;
+
+ let originalDefault = search.defaultEngine;
+
+ let [engine1, engine2] = yield addTestEngines([
+ { name: "Test search engine", xmlFileName: "engine.xml" },
+ { name: "A second test engine", xmlFileName: "engine2.xml" },
+ ]);
+
+ search.defaultEngine = engine1;
+ do_check_eq(search.defaultEngine, engine1);
+ search.defaultEngine = engine2
+ do_check_eq(search.defaultEngine, engine2);
+ search.defaultEngine = engine1;
+ do_check_eq(search.defaultEngine, engine1);
+
+ // Test that hiding the currently-default engine affects the defaultEngine getter
+ // We fallback first to the original default...
+ engine1.hidden = true;
+ do_check_eq(search.defaultEngine, originalDefault);
+
+ // ... and then to the first visible engine in the list, so move our second
+ // engine to that position.
+ search.moveEngine(engine2, 0);
+ originalDefault.hidden = true;
+ do_check_eq(search.defaultEngine, engine2);
+
+ // Test that setting defaultEngine to an already-hidden engine works, but
+ // doesn't change the return value of the getter
+ search.defaultEngine = engine1;
+ do_check_eq(search.defaultEngine, engine2);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_engineUpdate.js b/toolkit/components/search/tests/xpcshell/test_engineUpdate.js
new file mode 100644
index 000000000..adff41ffb
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_engineUpdate.js
@@ -0,0 +1,50 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/* Test that user-set metadata isn't lost on engine update */
+
+"use strict";
+
+function run_test() {
+ updateAppInfo();
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_engineUpdate() {
+ const KEYWORD = "keyword";
+ const FILENAME = "engine.xml"
+ const TOPIC = "browser-search-engine-modified";
+ const ONE_DAY_IN_MS = 24 * 60 * 60 * 1000;
+
+ yield asyncInit();
+
+ let [engine] = yield addTestEngines([
+ { name: "Test search engine", xmlFileName: FILENAME },
+ ]);
+
+ engine.alias = KEYWORD;
+ Services.search.moveEngine(engine, 0);
+ // can't have an accurate updateURL in the file since we can't know the test
+ // server origin, so manually set it
+ engine.wrappedJSObject._updateURL = gDataUrl + FILENAME;
+
+ yield new Promise(resolve => {
+ Services.obs.addObserver(function obs(subject, topic, data) {
+ if (data == "engine-loaded") {
+ let loadedEngine = subject.QueryInterface(Ci.nsISearchEngine);
+ let rawEngine = loadedEngine.wrappedJSObject;
+ equal(loadedEngine.alias, KEYWORD, "Keyword not cleared by update");
+ equal(rawEngine.getAttr("order"), 1, "Order not cleared by update");
+ Services.obs.removeObserver(obs, TOPIC, false);
+ resolve();
+ }
+ }, TOPIC, false);
+
+ // set last update to 8 days ago, since the default interval is 7, then
+ // trigger an update
+ engine.wrappedJSObject.setAttr("updateexpir", Date.now() - (ONE_DAY_IN_MS * 8));
+ Services.search.QueryInterface(Components.interfaces.nsITimerCallback).notify(null);
+ });
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_engine_set_alias.js b/toolkit/components/search/tests/xpcshell/test_engine_set_alias.js
new file mode 100644
index 000000000..b3c51caa5
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_engine_set_alias.js
@@ -0,0 +1,80 @@
+"use strict";
+
+function run_test() {
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_engine_set_alias() {
+ yield asyncInit();
+ do_print("Set engine alias");
+ let [engine1] = yield addTestEngines([
+ {
+ name: "bacon",
+ details: ["", "b", "Search Bacon", "GET", "http://www.bacon.test/find"]
+ }
+ ]);
+ Assert.equal(engine1.alias, "b");
+ engine1.alias = "a";
+ Assert.equal(engine1.alias, "a");
+ Services.search.removeEngine(engine1);
+});
+
+add_task(function* test_engine_set_alias_with_left_space() {
+ do_print("Set engine alias with left space");
+ let [engine2] = yield addTestEngines([
+ {
+ name: "bacon",
+ details: ["", " a", "Search Bacon", "GET", "http://www.bacon.test/find"]
+ }
+ ]);
+ Assert.equal(engine2.alias, "a");
+ engine2.alias = " c";
+ Assert.equal(engine2.alias, "c");
+ Services.search.removeEngine(engine2);
+});
+
+add_task(function* test_engine_set_alias_with_right_space() {
+ do_print("Set engine alias with right space");
+ let [engine3] = yield addTestEngines([
+ {
+ name: "bacon",
+ details: ["", "c ", "Search Bacon", "GET", "http://www.bacon.test/find"]
+ }
+ ]);
+ Assert.equal(engine3.alias, "c");
+ engine3.alias = "o ";
+ Assert.equal(engine3.alias, "o");
+ Services.search.removeEngine(engine3);
+});
+
+add_task(function* test_engine_set_alias_with_right_left_space() {
+ do_print("Set engine alias with left and right space");
+ let [engine4] = yield addTestEngines([
+ {
+ name: "bacon",
+ details: ["", " o ", "Search Bacon", "GET", "http://www.bacon.test/find"]
+ }
+ ]);
+ Assert.equal(engine4.alias, "o");
+ engine4.alias = " n ";
+ Assert.equal(engine4.alias, "n");
+ Services.search.removeEngine(engine4);
+});
+
+add_task(function* test_engine_set_alias_with_space() {
+ do_print("Set engine alias with space");
+ let [engine5] = yield addTestEngines([
+ {
+ name: "bacon",
+ details: ["", " ", "Search Bacon", "GET", "http://www.bacon.test/find"]
+ }
+ ]);
+ Assert.equal(engine5.alias, null);
+ engine5.alias = "b";
+ Assert.equal(engine5.alias, "b");
+ engine5.alias = " ";
+ Assert.equal(engine5.alias, null);
+ Services.search.removeEngine(engine5);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_geodefaults.js b/toolkit/components/search/tests/xpcshell/test_geodefaults.js
new file mode 100644
index 000000000..2367bbbc2
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_geodefaults.js
@@ -0,0 +1,253 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+var requests = [];
+var gServerCohort = "";
+
+const kUrlPref = "geoSpecificDefaults.url";
+
+const kDayInSeconds = 86400;
+const kYearInSeconds = kDayInSeconds * 365;
+
+function run_test() {
+ updateAppInfo();
+ installTestEngine();
+
+ let srv = new HttpServer();
+
+ srv.registerPathHandler("/lookup_defaults", (metadata, response) => {
+ response.setStatusLine("1.1", 200, "OK");
+ let data = {interval: kYearInSeconds,
+ settings: {searchDefault: "Test search engine"}};
+ if (gServerCohort)
+ data.cohort = gServerCohort;
+ response.write(JSON.stringify(data));
+ requests.push(metadata);
+ });
+
+ srv.registerPathHandler("/lookup_fail", (metadata, response) => {
+ response.setStatusLine("1.1", 404, "Not Found");
+ requests.push(metadata);
+ });
+
+ srv.registerPathHandler("/lookup_unavailable", (metadata, response) => {
+ response.setStatusLine("1.1", 503, "Service Unavailable");
+ response.setHeader("Retry-After", kDayInSeconds.toString());
+ requests.push(metadata);
+ });
+
+ srv.start(-1);
+ do_register_cleanup(() => srv.stop(() => {}));
+
+ let url = "http://localhost:" + srv.identity.primaryPort + "/lookup_defaults?";
+ Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref(kUrlPref, url);
+ // Set a bogus user value so that running the test ensures we ignore it.
+ Services.prefs.setCharPref(BROWSER_SEARCH_PREF + kUrlPref, "about:blank");
+ Services.prefs.setCharPref("browser.search.geoip.url",
+ 'data:application/json,{"country_code": "FR"}');
+
+ run_next_test();
+}
+
+function checkNoRequest() {
+ do_check_eq(requests.length, 0);
+}
+
+function checkRequest(cohort = "") {
+ do_check_eq(requests.length, 1);
+ let req = requests.pop();
+ do_check_eq(req._method, "GET");
+ do_check_eq(req._queryString, cohort ? "/" + cohort : "");
+}
+
+add_task(function* no_request_if_prefed_off() {
+ // Disable geoSpecificDefaults and check no HTTP request is made.
+ Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", false);
+ yield asyncInit();
+ checkNoRequest();
+ yield promiseAfterCache();
+
+ // The default engine should be set based on the prefs.
+ do_check_eq(Services.search.currentEngine.name, getDefaultEngineName(false));
+
+ // Ensure nothing related to geoSpecificDefaults has been written in the metadata.
+ let metadata = yield promiseGlobalMetadata();
+ do_check_eq(typeof metadata.searchDefaultExpir, "undefined");
+ do_check_eq(typeof metadata.searchDefault, "undefined");
+ do_check_eq(typeof metadata.searchDefaultHash, "undefined");
+
+ Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", true);
+});
+
+add_task(function* should_get_geo_defaults_only_once() {
+ // (Re)initializing the search service should trigger a request,
+ // and set the default engine based on it.
+ // Due to the previous initialization, we expect the countryCode to already be set.
+ do_check_true(Services.prefs.prefHasUserValue("browser.search.countryCode"));
+ do_check_eq(Services.prefs.getCharPref("browser.search.countryCode"), "FR");
+ yield asyncReInit();
+ checkRequest();
+ do_check_eq(Services.search.currentEngine.name, kTestEngineName);
+ yield promiseAfterCache();
+
+ // Verify the metadata was written correctly.
+ let metadata = yield promiseGlobalMetadata();
+ do_check_eq(typeof metadata.searchDefaultExpir, "number");
+ do_check_true(metadata.searchDefaultExpir > Date.now());
+ do_check_eq(typeof metadata.searchDefault, "string");
+ do_check_eq(metadata.searchDefault, "Test search engine");
+ do_check_eq(typeof metadata.searchDefaultHash, "string");
+ do_check_eq(metadata.searchDefaultHash.length, 44);
+
+ // The next restart shouldn't trigger a request.
+ yield asyncReInit();
+ checkNoRequest();
+ do_check_eq(Services.search.currentEngine.name, kTestEngineName);
+});
+
+add_task(function* should_request_when_countryCode_not_set() {
+ Services.prefs.clearUserPref("browser.search.countryCode");
+ yield asyncReInit();
+ checkRequest();
+ yield promiseAfterCache();
+});
+
+add_task(function* should_recheck_if_interval_expired() {
+ yield forceExpiration();
+
+ let date = Date.now();
+ yield asyncReInit();
+ checkRequest();
+ yield promiseAfterCache();
+
+ // Check that the expiration timestamp has been updated.
+ let metadata = yield promiseGlobalMetadata();
+ do_check_eq(typeof metadata.searchDefaultExpir, "number");
+ do_check_true(metadata.searchDefaultExpir >= date + kYearInSeconds * 1000);
+ do_check_true(metadata.searchDefaultExpir < date + (kYearInSeconds + 3600) * 1000);
+});
+
+add_task(function* should_recheck_when_broken_hash() {
+ // This test verifies both that we ignore saved geo-defaults if the
+ // hash is invalid, and that we keep the local preferences-based
+ // default for all of the session in case a synchronous
+ // initialization was triggered before our HTTP request completed.
+
+ let metadata = yield promiseGlobalMetadata();
+
+ // Break the hash.
+ let hash = metadata.searchDefaultHash;
+ metadata.searchDefaultHash = "broken";
+ yield promiseSaveGlobalMetadata(metadata);
+
+ let commitPromise = promiseAfterCache();
+ let unInitPromise = waitForSearchNotification("uninit-complete");
+ let reInitPromise = asyncReInit();
+ yield unInitPromise;
+
+ // Synchronously check the current default engine, to force a sync init.
+ // The hash is wrong, so we should fallback to the default engine from prefs.
+ do_check_false(Services.search.isInitialized)
+ do_check_eq(Services.search.currentEngine.name, getDefaultEngineName(false));
+ do_check_true(Services.search.isInitialized)
+
+ yield reInitPromise;
+ checkRequest();
+ yield commitPromise;
+
+ // Check that the hash is back to its previous value.
+ metadata = yield promiseGlobalMetadata();
+ do_check_eq(typeof metadata.searchDefaultHash, "string");
+ if (metadata.searchDefaultHash == "broken") {
+ // If the server takes more than 1000ms to return the result,
+ // the commitPromise was resolved by a first save of the cache
+ // that saved the engines, but not the request's results.
+ do_print("waiting for the cache to be saved a second time");
+ yield promiseAfterCache();
+ metadata = yield promiseGlobalMetadata();
+ }
+ do_check_eq(metadata.searchDefaultHash, hash);
+
+ // The current default engine shouldn't change during a session.
+ do_check_eq(Services.search.currentEngine.name, getDefaultEngineName(false));
+
+ // After another restart, the current engine should be back to the geo default,
+ // without doing yet another request.
+ yield asyncReInit();
+ checkNoRequest();
+ do_check_eq(Services.search.currentEngine.name, kTestEngineName);
+});
+
+add_task(function* should_remember_cohort_id() {
+ // Check that initially the cohort pref doesn't exist.
+ const cohortPref = "browser.search.cohort";
+ do_check_eq(Services.prefs.getPrefType(cohortPref), Services.prefs.PREF_INVALID);
+
+ // Make the server send a cohort id.
+ let cohort = gServerCohort = "xpcshell";
+
+ // Trigger a new request.
+ yield forceExpiration();
+ let commitPromise = promiseAfterCache();
+ yield asyncReInit();
+ checkRequest();
+ yield commitPromise;
+
+ // Check that the cohort was saved.
+ do_check_eq(Services.prefs.getPrefType(cohortPref), Services.prefs.PREF_STRING);
+ do_check_eq(Services.prefs.getCharPref(cohortPref), cohort);
+
+ // Make the server stop sending the cohort.
+ gServerCohort = "";
+
+ // Check that the next request sends the previous cohort id, and
+ // will remove it from the prefs due to the server no longer sending it.
+ yield forceExpiration();
+ commitPromise = promiseAfterCache();
+ yield asyncReInit();
+ checkRequest(cohort);
+ yield commitPromise;
+ do_check_eq(Services.prefs.getPrefType(cohortPref), Services.prefs.PREF_INVALID);
+});
+
+add_task(function* should_retry_after_failure() {
+ let defaultBranch = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF);
+ let originalUrl = defaultBranch.getCharPref(kUrlPref);
+ defaultBranch.setCharPref(kUrlPref, originalUrl.replace("defaults", "fail"));
+
+ // Trigger a new request.
+ yield forceExpiration();
+ yield asyncReInit();
+ checkRequest();
+
+ // After another restart, a new request should be triggered automatically without
+ // the test having to call forceExpiration again.
+ yield asyncReInit();
+ checkRequest();
+});
+
+add_task(function* should_honor_retry_after_header() {
+ let defaultBranch = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF);
+ let originalUrl = defaultBranch.getCharPref(kUrlPref);
+ defaultBranch.setCharPref(kUrlPref, originalUrl.replace("fail", "unavailable"));
+
+ // Trigger a new request.
+ yield forceExpiration();
+ let date = Date.now();
+ let commitPromise = promiseAfterCache();
+ yield asyncReInit();
+ checkRequest();
+ yield commitPromise;
+
+ // Check that the expiration timestamp has been updated.
+ let metadata = yield promiseGlobalMetadata();
+ do_check_eq(typeof metadata.searchDefaultExpir, "number");
+ do_check_true(metadata.searchDefaultExpir >= date + kDayInSeconds * 1000);
+ do_check_true(metadata.searchDefaultExpir < date + (kDayInSeconds + 3600) * 1000);
+
+ // After another restart, a new request should not be triggered.
+ yield asyncReInit();
+ checkNoRequest();
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_hasEngineWithURL.js b/toolkit/components/search/tests/xpcshell/test_hasEngineWithURL.js
new file mode 100644
index 000000000..e48b1673c
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_hasEngineWithURL.js
@@ -0,0 +1,135 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/**
+ * Tests the hasEngineWithURL() method of the nsIBrowserSearchService.
+ */
+function run_test() {
+ do_print("Setting up test");
+
+ updateAppInfo();
+ useHttpServer();
+
+ do_print("Test starting");
+ run_next_test();
+}
+
+
+// Return a discreet, cloned copy of an (engine) object.
+function getEngineClone(engine) {
+ return JSON.parse(JSON.stringify(engine));
+}
+
+// Check whether and engine does or doesn't exist.
+function checkEngineState(exists, engine) {
+ do_check_eq(exists, Services.search.hasEngineWithURL(engine.method,
+ engine.formURL,
+ engine.queryParams));
+}
+
+// Add a search engine for testing.
+function addEngineWithParams(engine) {
+ Services.search.addEngineWithDetails(engine.name, null, null, null,
+ engine.method, engine.formURL);
+
+ let addedEngine = Services.search.getEngineByName(engine.name);
+ for (let param of engine.queryParams) {
+ addedEngine.addParam(param.name, param.value, null);
+ }
+}
+
+// Main test.
+add_task(function* test_hasEngineWithURL() {
+ // Avoid deprecated synchronous initialization.
+ yield asyncInit();
+
+ // Setup various Engine definitions for method tests.
+ let UNSORTED_ENGINE = {
+ name: "mySearch Engine",
+ method: "GET",
+ formURL: "https://totallyNotRealSearchEngine.com/",
+ queryParams: [
+ { name: "DDs", value: "38s" },
+ { name: "DCs", value: "39s" },
+ { name: "DDs", value: "39s" },
+ { name: "DDs", value: "38s" },
+ { name: "DDs", value: "37s" },
+ { name: "DDs", value: "38s" },
+ { name: "DEs", value: "38s" },
+ { name: "DCs", value: "38s" },
+ { name: "DEs", value: "37s" },
+ ],
+ };
+
+ // Same as UNSORTED_ENGINE, but sorted.
+ let SORTED_ENGINE = {
+ name: "mySearch Engine",
+ method: "GET",
+ formURL: "https://totallyNotRealSearchEngine.com/",
+ queryParams: [
+ { name: "DCs", value: "38s" },
+ { name: "DCs", value: "39s" },
+ { name: "DDs", value: "37s" },
+ { name: "DDs", value: "38s" },
+ { name: "DDs", value: "38s" },
+ { name: "DDs", value: "38s" },
+ { name: "DDs", value: "39s" },
+ { name: "DEs", value: "37s" },
+ { name: "DEs", value: "38s" },
+ ],
+ };
+
+ // Unique variations of the SORTED_ENGINE.
+ let SORTED_ENGINE_METHOD_CHANGE = getEngineClone(SORTED_ENGINE);
+ SORTED_ENGINE_METHOD_CHANGE.method = "PoST";
+
+ let SORTED_ENGINE_FORMURL_CHANGE = getEngineClone(SORTED_ENGINE);
+ SORTED_ENGINE_FORMURL_CHANGE.formURL = "http://www.ahighrpowr.com/"
+
+ let SORTED_ENGINE_QUERYPARM_CHANGE = getEngineClone(SORTED_ENGINE);
+ SORTED_ENGINE_QUERYPARM_CHANGE.queryParams = [];
+
+ let SORTED_ENGINE_NAME_CHANGE = getEngineClone(SORTED_ENGINE);
+ SORTED_ENGINE_NAME_CHANGE.name += " 2";
+
+
+ // First ensure neither the unsorted engine, nor the same engine
+ // with a pre-sorted list of query parms matches.
+ checkEngineState(false, UNSORTED_ENGINE);
+ do_print("The unsorted version of the test engine does not exist.");
+ checkEngineState(false, SORTED_ENGINE);
+ do_print("The sorted version of the test engine does not exist.");
+
+ // Ensure variations of the engine definition do not match.
+ checkEngineState(false, SORTED_ENGINE_METHOD_CHANGE);
+ checkEngineState(false, SORTED_ENGINE_FORMURL_CHANGE);
+ checkEngineState(false, SORTED_ENGINE_QUERYPARM_CHANGE);
+ do_print("There are no modified versions of the sorted test engine.");
+
+ // Note that this method doesn't check name variations.
+ checkEngineState(false, SORTED_ENGINE_NAME_CHANGE);
+ do_print("There is no NAME modified version of the sorted test engine.");
+
+
+ // Add the unsorted engine and it's queryParams.
+ addEngineWithParams(UNSORTED_ENGINE);
+ do_print("The unsorted engine has been added.");
+
+
+ // Then, ensure we find a match for the unsorted engine, and for the
+ // same engine with a pre-sorted list of query parms.
+ checkEngineState(true, UNSORTED_ENGINE);
+ do_print("The unsorted version of the test engine now exists.");
+ checkEngineState(true, SORTED_ENGINE);
+ do_print("The sorted version of the same test engine also now exists.");
+
+ // Ensure variations of the engine definition still do not match.
+ checkEngineState(false, SORTED_ENGINE_METHOD_CHANGE);
+ checkEngineState(false, SORTED_ENGINE_FORMURL_CHANGE);
+ checkEngineState(false, SORTED_ENGINE_QUERYPARM_CHANGE);
+ do_print("There are still no modified versions of the sorted test engine.");
+
+ // Note that this method still doesn't check name variations.
+ checkEngineState(true, SORTED_ENGINE_NAME_CHANGE);
+ do_print("There IS now a NAME modified version of the sorted test engine.");
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_hidden.js b/toolkit/components/search/tests/xpcshell/test_hidden.js
new file mode 100644
index 000000000..b784f3624
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_hidden.js
@@ -0,0 +1,93 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const kUrlPref = "geoSpecificDefaults.url";
+
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+
+ // Geo specific defaults won't be fetched if there's no country code.
+ Services.prefs.setCharPref("browser.search.geoip.url",
+ 'data:application/json,{"country_code": "US"}');
+
+ // Make 'hidden' the only visible engine.
+ let url = "data:application/json,{\"interval\": 31536000, \"settings\": {\"searchDefault\": \"hidden\", \"visibleDefaultEngines\": [\"hidden\"]}}";
+ Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref(kUrlPref, url);
+
+ do_check_false(Services.search.isInitialized);
+
+ run_next_test();
+}
+
+add_task(function* async_init() {
+ let commitPromise = promiseAfterCache()
+ yield asyncInit();
+
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ // The default test jar engine has been hidden.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_eq(engine, null);
+
+ // The hidden engine is visible.
+ engine = Services.search.getEngineByName("hidden");
+ do_check_neq(engine, null);
+
+ // The next test does a sync init, which won't do the geoSpecificDefaults XHR,
+ // so it depends on the metadata having been written to disk.
+ yield commitPromise;
+});
+
+add_task(function* sync_init() {
+ let unInitPromise = waitForSearchNotification("uninit-complete");
+ let reInitPromise = asyncReInit();
+ yield unInitPromise;
+ do_check_false(Services.search.isInitialized);
+
+ // Synchronously check the current default engine, to force a sync init.
+ do_check_eq(Services.search.currentEngine.name, "hidden");
+ do_check_true(Services.search.isInitialized);
+
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ // The default test jar engine has been hidden.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_eq(engine, null);
+
+ // The hidden engine is visible.
+ engine = Services.search.getEngineByName("hidden");
+ do_check_neq(engine, null);
+
+ yield reInitPromise;
+});
+
+add_task(function* invalid_engine() {
+ // Trigger a new request.
+ yield forceExpiration();
+
+ // Set the visibleDefaultEngines list to something that contains a non-existent engine.
+ // This should cause the search service to ignore the list altogether and fallback to
+ // local defaults.
+ let url = "data:application/json,{\"interval\": 31536000, \"settings\": {\"searchDefault\": \"hidden\", \"visibleDefaultEngines\": [\"hidden\", \"bogus\"]}}";
+ Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref(kUrlPref, url);
+
+ yield asyncReInit();
+
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ // The default test jar engine is visible.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ // The hidden engine is... hidden.
+ engine = Services.search.getEngineByName("hidden");
+ do_check_eq(engine, null);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_identifiers.js b/toolkit/components/search/tests/xpcshell/test_identifiers.js
new file mode 100644
index 000000000..0d5ca5b90
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_identifiers.js
@@ -0,0 +1,56 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Test that a search engine's identifier can be extracted from the filename.
+ */
+
+"use strict";
+
+const SEARCH_APP_DIR = 1;
+
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+
+ updateAppInfo();
+
+ run_next_test();
+}
+
+add_test(function test_identifier() {
+ let engineFile = gProfD.clone();
+ engineFile.append("searchplugins");
+ engineFile.append("test-search-engine.xml");
+ engineFile.parent.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ // Copy the test engine to the test profile.
+ let engineTemplateFile = do_get_file("data/engine.xml");
+ engineTemplateFile.copyTo(engineFile.parent, "test-search-engine.xml");
+
+ Services.search.init(function initComplete(aResult) {
+ do_print("init'd search service");
+ do_check_true(Components.isSuccessCode(aResult));
+
+ let profileEngine = Services.search.getEngineByName("Test search engine");
+ let jarEngine = Services.search.getEngineByName("bug645970");
+
+ do_check_true(profileEngine instanceof Ci.nsISearchEngine);
+ do_check_true(jarEngine instanceof Ci.nsISearchEngine);
+
+ // An engine loaded from the profile directory won't have an identifier,
+ // because it's not built-in.
+ do_check_eq(profileEngine.identifier, null);
+
+ // An engine loaded from a JAR will have an identifier corresponding to
+ // the filename inside the JAR. (In this case it's the same as the name.)
+ do_check_eq(jarEngine.identifier, "bug645970");
+
+ removeMetadata();
+ removeCacheFile();
+ run_next_test();
+ });
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_init_async_multiple.js b/toolkit/components/search/tests/xpcshell/test_init_async_multiple.js
new file mode 100644
index 000000000..3aa3353ce
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_init_async_multiple.js
@@ -0,0 +1,55 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* 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/. */
+
+/**
+ * Test nsSearchService with with the following initialization scenario:
+ * - launch asynchronous initialization several times;
+ * - all asynchronous initializations must complete.
+ *
+ * Test case comes from test_645970.js
+ */
+function run_test() {
+ do_print("Setting up test");
+
+ do_test_pending();
+ updateAppInfo();
+
+ do_print("Test starting");
+ let numberOfInitializers = 4;
+ let pending = [];
+ let numberPending = numberOfInitializers;
+
+ // Start asynchronous initializations
+ for (let i = 0; i < numberOfInitializers; ++i) {
+ let me = i;
+ pending[me] = true;
+ Services.search.init(function search_initialized_0(aStatus) {
+ do_check_true(Components.isSuccessCode(aStatus));
+ init_complete(me);
+ });
+ }
+
+ // Wait until all initializers have completed
+ let init_complete = function init_complete(i) {
+ do_check_true(pending[i]);
+ pending[i] = false;
+ numberPending--;
+ do_check_true(numberPending >= 0);
+ do_check_true(Services.search.isInitialized);
+ if (numberPending == 0) {
+ // Just check that we can access a list of engines.
+ let engines = Services.search.getEngines();
+ do_check_neq(engines, null);
+
+ // Wait a little before quitting: if some initializer is
+ // triggered twice, we want to catch that error.
+ do_timeout(1000, function() {
+ do_test_finished();
+ });
+ }
+ };
+}
+
diff --git a/toolkit/components/search/tests/xpcshell/test_init_async_multiple_then_sync.js b/toolkit/components/search/tests/xpcshell/test_init_async_multiple_then_sync.js
new file mode 100644
index 000000000..ed4ecdcd8
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_init_async_multiple_then_sync.js
@@ -0,0 +1,68 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* 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/. */
+
+/**
+ * Test nsSearchService with with the following initialization scenario:
+ * - launch asynchronous initialization several times;
+ * - force fallback to synchronous initialization.
+ * - all asynchronous initializations must complete;
+ * - no asynchronous initialization must complete more than once.
+ *
+ * Test case comes from test_645970.js
+ */
+function run_test() {
+ do_print("Setting up test");
+ do_test_pending();
+ updateAppInfo();
+
+ do_print("Test starting");
+
+ let numberOfInitializers = 4;
+ let pending = [];
+ let numberPending = numberOfInitializers;
+
+ // Start asynchronous initializations
+ for (let i = 0; i < numberOfInitializers; ++i) {
+ let me = i;
+ pending[me] = true;
+ Services.search.init(function search_initialized(aStatus) {
+ do_check_true(Components.isSuccessCode(aStatus));
+ init_complete(me);
+ });
+ }
+
+ // Ensure that all asynchronous initializers eventually complete
+ let init_complete = function init_complete(i) {
+ do_print("init complete " + i);
+ do_check_true(pending[i]);
+ pending[i] = false;
+ numberPending--;
+ do_check_true(numberPending >= 0);
+ do_check_true(Services.search.isInitialized);
+ if (numberPending != 0) {
+ do_print("Still waiting for the following initializations: " + JSON.stringify(pending));
+ return;
+ }
+ do_print("All initializations have completed");
+ // Just check that we can access a list of engines.
+ let engines = Services.search.getEngines();
+ do_check_neq(engines, null);
+
+ do_print("Waiting a second before quitting");
+ // Wait a little before quitting: if some initializer is
+ // triggered twice, we want to catch that error.
+ do_timeout(1000, function() {
+ do_print("Test is complete");
+ do_test_finished();
+ });
+ };
+
+ // ... but don't wait for asynchronous initializations to complete
+ let engines = Services.search.getEngines();
+ do_check_neq(engines, null);
+ do_print("Synchronous part of the test complete");
+}
+
diff --git a/toolkit/components/search/tests/xpcshell/test_invalid_engine_from_dir.js b/toolkit/components/search/tests/xpcshell/test_invalid_engine_from_dir.js
new file mode 100644
index 000000000..c6455735a
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_invalid_engine_from_dir.js
@@ -0,0 +1,35 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Test that invalid engine files with xml extensions will not break
+ * initialization. See Bug 940446.
+ */
+function run_test() {
+ do_test_pending();
+
+ removeMetadata();
+ removeCacheFile();
+
+ do_check_false(Services.search.isInitialized);
+
+ let engineFile = gProfD.clone();
+ engineFile.append("searchplugins");
+ engineFile.append("test-search-engine.xml");
+ engineFile.parent.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ // Copy the invalid engine to the test profile.
+ let engineTemplateFile = do_get_file("data/invalid-engine.xml");
+ engineTemplateFile.copyTo(engineFile.parent, "test-search-engine.xml");
+
+ Services.search.init(function search_initialized(aStatus) {
+ // The invalid engine should have been skipped and should not
+ // have caused an exception.
+ do_check_true(Components.isSuccessCode(aStatus));
+ do_check_true(Services.search.isInitialized);
+
+ removeMetadata();
+ removeCacheFile();
+ do_test_finished();
+ });
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_json_cache.js b/toolkit/components/search/tests/xpcshell/test_json_cache.js
new file mode 100644
index 000000000..c804b0bca
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_json_cache.js
@@ -0,0 +1,227 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Test initializing from the search cache.
+ */
+
+"use strict";
+
+/**
+ * Gets a directory from the directory service.
+ * @param aKey
+ * The directory service key indicating the directory to get.
+ */
+var _dirSvc = null;
+function getDir(aKey, aIFace) {
+ if (!aKey) {
+ FAIL("getDir requires a directory key!");
+ }
+
+ if (!_dirSvc) {
+ _dirSvc = Cc["@mozilla.org/file/directory_service;1"].
+ getService(Ci.nsIProperties);
+ }
+ return _dirSvc.get(aKey, aIFace || Ci.nsIFile);
+}
+
+function makeURI(uri) {
+ return Services.io.newURI(uri, null, null);
+}
+
+var cacheTemplate, appPluginsPath, profPlugins;
+
+/**
+ * Test reading from search.json.mozlz4
+ */
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+
+ updateAppInfo();
+
+ let cacheTemplateFile = do_get_file("data/search.json");
+ cacheTemplate = readJSONFile(cacheTemplateFile);
+ cacheTemplate.buildID = getAppInfo().platformBuildID;
+
+ let engineFile = gProfD.clone();
+ engineFile.append("searchplugins");
+ engineFile.append("test-search-engine.xml");
+ engineFile.parent.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ // Copy the test engine to the test profile.
+ let engineTemplateFile = do_get_file("data/engine.xml");
+ engineTemplateFile.copyTo(engineFile.parent, "test-search-engine.xml");
+
+ // The list of visibleDefaultEngines needs to match or the cache will be ignored.
+ let chan = NetUtil.newChannel({
+ uri: "resource://search-plugins/list.json",
+ loadUsingSystemPrincipal: true
+ });
+ let sis = Cc["@mozilla.org/scriptableinputstream;1"].
+ createInstance(Ci.nsIScriptableInputStream);
+ sis.init(chan.open2());
+ let list = sis.read(sis.available());
+ let searchSettings = JSON.parse(list);
+
+ cacheTemplate.visibleDefaultEngines = searchSettings["default"]["visibleDefaultEngines"];
+
+ run_next_test();
+}
+
+add_test(function prepare_test_data() {
+ OS.File.writeAtomic(OS.Path.join(OS.Constants.Path.profileDir, CACHE_FILENAME),
+ new TextEncoder().encode(JSON.stringify(cacheTemplate)),
+ {compression: "lz4"})
+ .then(run_next_test);
+});
+
+/**
+ * Start the search service and confirm the engine properties match the expected values.
+ */
+add_test(function test_cached_engine_properties() {
+ do_print("init search service");
+
+ Services.search.init(function initComplete(aResult) {
+ do_print("init'd search service");
+ do_check_true(Components.isSuccessCode(aResult));
+
+ let engines = Services.search.getEngines({});
+ let engine = engines[0];
+
+ do_check_true(engine instanceof Ci.nsISearchEngine);
+ isSubObjectOf(EXPECTED_ENGINE.engine, engine);
+
+ let engineFromSS = Services.search.getEngineByName(EXPECTED_ENGINE.engine.name);
+ do_check_true(!!engineFromSS);
+ isSubObjectOf(EXPECTED_ENGINE.engine, engineFromSS);
+
+ removeMetadata();
+ removeCacheFile();
+ run_next_test();
+ });
+});
+
+/**
+ * Test that the JSON cache written in the profile is correct.
+ */
+add_test(function test_cache_write() {
+ do_print("test cache writing");
+
+ let cache = gProfD.clone();
+ cache.append(CACHE_FILENAME);
+ do_check_false(cache.exists());
+
+ do_print("Next step is forcing flush");
+ do_timeout(0, function forceFlush() {
+ do_print("Forcing flush");
+ // Force flush
+ // Note: the timeout is needed, to avoid some reentrency
+ // issues in nsSearchService.
+
+ let cacheWriteObserver = {
+ observe: function cacheWriteObserver_observe(aEngine, aTopic, aVerb) {
+ if (aTopic != "browser-search-service" || aVerb != "write-cache-to-disk-complete") {
+ return;
+ }
+ Services.obs.removeObserver(cacheWriteObserver, "browser-search-service");
+ do_print("Cache write complete");
+ do_check_true(cache.exists());
+ // Check that the search.json.mozlz4 cache matches the template
+
+ promiseCacheData().then(cacheWritten => {
+ do_print("Check search.json.mozlz4");
+ isSubObjectOf(cacheTemplate, cacheWritten);
+
+ run_next_test();
+ });
+ }
+ };
+ Services.obs.addObserver(cacheWriteObserver, "browser-search-service", false);
+
+ Services.search.QueryInterface(Ci.nsIObserver).observe(null, "browser-search-engine-modified", "engine-removed");
+ });
+});
+
+var EXPECTED_ENGINE = {
+ engine: {
+ name: "Test search engine",
+ alias: null,
+ description: "A test search engine (based on Google search)",
+ searchForm: "http://www.google.com/",
+ wrappedJSObject: {
+ _extensionID: "test-addon-id@mozilla.org",
+ "_iconURL": "data:image/png;base64,AAABAAEAEBAAAAEAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs9Pt8xetPtu9FsfFNtu%2BTzvb2%2B%2Fne4dFJeBw0egA%2FfAJAfAA8ewBBegAAAAD%2B%2FPtft98Mp%2BwWsfAVsvEbs%2FQeqvF8xO7%2F%2F%2F63yqkxdgM7gwE%2FggM%2BfQA%2BegBDeQDe7PIbotgQufcMufEPtfIPsvAbs%2FQvq%2Bfz%2Bf%2F%2B%2B%2FZKhR05hgBBhQI8hgBAgAI9ewD0%2B%2Fg3pswAtO8Cxf4Kw%2FsJvvYAqupKsNv%2B%2Fv7%2F%2FP5VkSU0iQA7jQA9hgBDgQU%2BfQH%2F%2Ff%2FQ6fM4sM4KsN8AteMCruIqqdbZ7PH8%2Fv%2Fg6Nc%2Fhg05kAA8jAM9iQI%2BhQA%2BgQDQu6b97uv%2F%2F%2F7V8Pqw3eiWz97q8%2Ff%2F%2F%2F%2F7%2FPptpkkqjQE4kwA7kAA5iwI8iAA8hQCOSSKdXjiyflbAkG7u2s%2F%2B%2F%2F39%2F%2F7r8utrqEYtjQE8lgA7kwA7kwA9jwA9igA9hACiWSekVRyeSgiYSBHx6N%2F%2B%2Fv7k7OFRmiYtlAA5lwI7lwI4lAA7kgI9jwE9iwI4iQCoVhWcTxCmb0K%2BooT8%2Fv%2F7%2F%2F%2FJ2r8fdwI1mwA3mQA3mgA8lAE8lAE4jwA9iwE%2BhwGfXifWvqz%2B%2Ff%2F58u%2Fev6Dt4tr%2B%2F%2F2ZuIUsggA7mgM6mAM3lgA5lgA6kQE%2FkwBChwHt4dv%2F%2F%2F728ei1bCi7VAC5XQ7kz7n%2F%2F%2F6bsZkgcB03lQA9lgM7kwA2iQktZToPK4r9%2F%2F%2F9%2F%2F%2FSqYK5UwDKZAS9WALIkFn%2B%2F%2F3%2F%2BP8oKccGGcIRJrERILYFEMwAAuEAAdX%2F%2Ff7%2F%2FP%2B%2BfDvGXQLIZgLEWgLOjlf7%2F%2F%2F%2F%2F%2F9QU90EAPQAAf8DAP0AAfMAAOUDAtr%2F%2F%2F%2F7%2B%2Fu2bCTIYwDPZgDBWQDSr4P%2F%2Fv%2F%2F%2FP5GRuABAPkAA%2FwBAfkDAPAAAesAAN%2F%2F%2B%2Fz%2F%2F%2F64g1C5VwDMYwK8Yg7y5tz8%2Fv%2FV1PYKDOcAAP0DAf4AAf0AAfYEAOwAAuAAAAD%2F%2FPvi28ymXyChTATRrIb8%2F%2F3v8fk6P8MAAdUCAvoAAP0CAP0AAfYAAO4AAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQAA",
+ _urls : [
+ {
+ type: "application/x-suggestions+json",
+ method: "GET",
+ template: "http://suggestqueries.google.com/complete/search?output=firefox&client=firefox" +
+ "&hl={moz:locale}&q={searchTerms}",
+ params: "",
+ },
+ {
+ type: "text/html",
+ method: "GET",
+ template: "http://www.google.com/search",
+ resultDomain: "google.com",
+ params: [
+ {
+ "name": "q",
+ "value": "{searchTerms}",
+ "purpose": undefined,
+ },
+ {
+ "name": "ie",
+ "value": "utf-8",
+ "purpose": undefined,
+ },
+ {
+ "name": "oe",
+ "value": "utf-8",
+ "purpose": undefined,
+ },
+ {
+ "name": "aq",
+ "value": "t",
+ "purpose": undefined,
+ },
+ {
+ "name": "channel",
+ "value": "fflb",
+ "purpose": "keyword",
+ },
+ {
+ "name": "channel",
+ "value": "rcs",
+ "purpose": "contextmenu",
+ },
+ ],
+ },
+ {
+ type: "application/x-moz-default-purpose",
+ method: "GET",
+ template: "http://www.google.com/search",
+ resultDomain: "purpose.google.com",
+ params: [
+ {
+ "name": "q",
+ "value": "{searchTerms}",
+ "purpose": undefined,
+ },
+ {
+ "name": "channel",
+ "value": "fflb",
+ "purpose": "keyword",
+ },
+ {
+ "name": "channel",
+ "value": "rcs",
+ "purpose": "contextmenu",
+ },
+ ],
+ },
+ ],
+ },
+ },
+};
diff --git a/toolkit/components/search/tests/xpcshell/test_location.js b/toolkit/components/search/tests/xpcshell/test_location.js
new file mode 100644
index 000000000..93e6139f6
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location.js
@@ -0,0 +1,66 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ installTestEngine();
+
+ Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "AU"}');
+ Services.search.init(() => {
+ equal(Services.prefs.getCharPref("browser.search.countryCode"), "AU", "got the correct country code.");
+ equal(Services.prefs.getCharPref("browser.search.region"), "AU", "region pref also set to the countryCode.")
+ // No isUS pref is ever written
+ ok(!Services.prefs.prefHasUserValue("browser.search.isUS"), "no isUS pref")
+ // check we have "success" recorded in telemetry
+ checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS);
+ // a false value for each of SEARCH_SERVICE_COUNTRY_TIMEOUT and SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT
+ for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT",
+ "SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) {
+ let histogram = Services.telemetry.getHistogramById(hid);
+ let snapshot = histogram.snapshot();
+ deepEqual(snapshot.counts, [1, 0, 0]); // boolean probe so 3 buckets, expect 1 result for |0|.
+
+ }
+
+ // simple checks for our platform-specific telemetry. We can't influence
+ // what they return (as we can't influence the countryCode the platform
+ // thinks we are in), but we can check the values are correct given reality.
+ let probeUSMismatched, probeNonUSMismatched;
+ switch (Services.appinfo.OS) {
+ case "Darwin":
+ probeUSMismatched = "SEARCH_SERVICE_US_COUNTRY_MISMATCHED_PLATFORM_OSX";
+ probeNonUSMismatched = "SEARCH_SERVICE_NONUS_COUNTRY_MISMATCHED_PLATFORM_OSX";
+ break;
+ case "WINNT":
+ probeUSMismatched = "SEARCH_SERVICE_US_COUNTRY_MISMATCHED_PLATFORM_WIN";
+ probeNonUSMismatched = "SEARCH_SERVICE_NONUS_COUNTRY_MISMATCHED_PLATFORM_WIN";
+ break;
+ default:
+ break;
+ }
+
+ if (probeUSMismatched && probeNonUSMismatched) {
+ let countryCode = Services.sysinfo.get("countryCode");
+ print("Platform says the country-code is", countryCode);
+ let expectedResult;
+ let hid;
+ // We know geoip said AU - if the platform thinks US then we expect
+ // probeUSMismatched with true (ie, a mismatch)
+ if (countryCode == "US") {
+ hid = probeUSMismatched;
+ expectedResult = [0, 1, 0]; // boolean probe so 3 buckets, expect 1 result for |1|.
+ } else {
+ // We are expecting probeNonUSMismatched with false if the platform
+ // says AU (not a mismatch) and true otherwise.
+ hid = probeNonUSMismatched;
+ expectedResult = countryCode == "AU" ? [1, 0, 0] : [0, 1, 0];
+ }
+
+ let histogram = Services.telemetry.getHistogramById(hid);
+ let snapshot = histogram.snapshot();
+ deepEqual(snapshot.counts, expectedResult);
+ }
+ do_test_finished();
+ run_next_test();
+ });
+ do_test_pending();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_location_error.js b/toolkit/components/search/tests/xpcshell/test_location_error.js
new file mode 100644
index 000000000..049189351
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location_error.js
@@ -0,0 +1,30 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ installTestEngine();
+
+ // We use an invalid port that parses but won't open
+ let url = "http://localhost:0";
+
+ Services.prefs.setCharPref("browser.search.geoip.url", url);
+ Services.search.init(() => {
+ try {
+ Services.prefs.getCharPref("browser.search.countryCode");
+ ok(false, "not expecting countryCode to be set");
+ } catch (ex) {}
+ // should have an error recorded.
+ checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.ERROR);
+ // but false values for timeout and forced-sync-init.
+ for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT",
+ "SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) {
+ let histogram = Services.telemetry.getHistogramById(hid);
+ let snapshot = histogram.snapshot();
+ deepEqual(snapshot.counts, [1, 0, 0]); // boolean probe so 3 buckets, expect 1 result for |0|.
+ }
+
+ do_test_finished();
+ run_next_test();
+ });
+ do_test_pending();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_location_funnelcake.js b/toolkit/components/search/tests/xpcshell/test_location_funnelcake.js
new file mode 100644
index 000000000..970ba5521
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location_funnelcake.js
@@ -0,0 +1,17 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "US"}');
+ // funnelcake builds start with "mozilla"
+ Services.prefs.setCharPref("distribution.id", 'mozilla38');
+ setUpGeoDefaults();
+
+ Services.search.init(() => {
+ equal(Services.search.defaultEngine.name, "A second test engine");
+
+ do_test_finished();
+ run_next_test();
+ });
+ do_test_pending();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_location_malformed_json.js b/toolkit/components/search/tests/xpcshell/test_location_malformed_json.js
new file mode 100644
index 000000000..b1f30ad7c
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location_malformed_json.js
@@ -0,0 +1,57 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// A console listener so we can listen for a log message from nsSearchService.
+function promiseTimezoneMessage() {
+ return new Promise(resolve => {
+ let listener = {
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIConsoleListener]),
+ observe : function (msg) {
+ if (msg.message.startsWith("getIsUS() fell back to a timezone check with the result=")) {
+ Services.console.unregisterListener(listener);
+ resolve(msg);
+ }
+ }
+ };
+ Services.console.registerListener(listener);
+ });
+}
+
+function run_test() {
+ installTestEngine();
+
+ // setup a console listener for the timezone fallback message.
+ let promiseTzMessage = promiseTimezoneMessage();
+
+ // Here we have malformed JSON
+ Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code"');
+ Services.search.init(() => {
+ ok(!Services.prefs.prefHasUserValue("browser.search.countryCode"), "should be no countryCode pref");
+ ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
+ ok(!Services.prefs.prefHasUserValue("browser.search.isUS"), "should never be an isUS pref");
+ // fetch the engines - this should force the timezone check, but still
+ // doesn't persist any prefs.
+ Services.search.getEngines();
+ ok(!Services.prefs.prefHasUserValue("browser.search.countryCode"), "should be no countryCode pref");
+ ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
+ ok(!Services.prefs.prefHasUserValue("browser.search.isUS"), "should never be an isUS pref");
+ // should have recorded SUCCESS_WITHOUT_DATA
+ checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS_WITHOUT_DATA);
+ // and false values for timeout and forced-sync-init.
+ for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT",
+ "SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) {
+ let histogram = Services.telemetry.getHistogramById(hid);
+ let snapshot = histogram.snapshot();
+ deepEqual(snapshot.counts, [1, 0, 0]); // boolean probe so 3 buckets, expect 1 result for |0|.
+ }
+
+ // Check we saw the timezone fallback message.
+ promiseTzMessage.then(msg => {
+ print("Timezone message:", msg.message);
+ ok(msg.message.endsWith(isUSTimezone().toString()), "fell back to timezone and it matches our timezone");
+ do_test_finished();
+ run_next_test();
+ });
+ });
+ do_test_pending();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_location_migrate_countrycode_isUS.js b/toolkit/components/search/tests/xpcshell/test_location_migrate_countrycode_isUS.js
new file mode 100644
index 000000000..9e1019761
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location_migrate_countrycode_isUS.js
@@ -0,0 +1,24 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Here we are testing the "migration" when both isUS and countryCode are
+// set.
+function run_test() {
+ installTestEngine();
+
+ // Set the prefs we care about.
+ Services.prefs.setBoolPref("browser.search.isUS", true);
+ Services.prefs.setCharPref("browser.search.countryCode", "US");
+ // And the geoip request that will return AU - it shouldn't be used.
+ Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "AU"}');
+ Services.search.init(() => {
+ // "region" and countryCode should still reflect US.
+ equal(Services.prefs.getCharPref("browser.search.region"), "US", "got the correct region.");
+ equal(Services.prefs.getCharPref("browser.search.countryCode"), "US", "got the correct country code.");
+ // should be no geoip evidence.
+ checkCountryResultTelemetry(null);
+ do_test_finished();
+ run_next_test();
+ });
+ do_test_pending();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_location_migrate_no_countrycode_isUS.js b/toolkit/components/search/tests/xpcshell/test_location_migrate_no_countrycode_isUS.js
new file mode 100644
index 000000000..b294b038b
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location_migrate_no_countrycode_isUS.js
@@ -0,0 +1,30 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Here we are testing the "migration" from the isUS pref being true but when
+// no country-code exists.
+function run_test() {
+ installTestEngine();
+
+ // Set the pref we care about.
+ Services.prefs.setBoolPref("browser.search.isUS", true);
+ // And the geoip request that will return *not* US.
+ Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "AU"}');
+ Services.search.init(() => {
+ // "region" should be set to US, but countryCode to AU.
+ equal(Services.prefs.getCharPref("browser.search.region"), "US", "got the correct region.");
+ equal(Services.prefs.getCharPref("browser.search.countryCode"), "AU", "got the correct country code.");
+ // check we have "success" recorded in telemetry
+ checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS);
+ // a false value for each of SEARCH_SERVICE_COUNTRY_TIMEOUT and SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT
+ for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT",
+ "SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) {
+ let histogram = Services.telemetry.getHistogramById(hid);
+ let snapshot = histogram.snapshot();
+ deepEqual(snapshot.counts, [1, 0, 0]); // boolean probe so 3 buckets, expect 1 result for |0|.
+ }
+ do_test_finished();
+ run_next_test();
+ });
+ do_test_pending();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_location_migrate_no_countrycode_notUS.js b/toolkit/components/search/tests/xpcshell/test_location_migrate_no_countrycode_notUS.js
new file mode 100644
index 000000000..9c0b810d3
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location_migrate_no_countrycode_notUS.js
@@ -0,0 +1,30 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Here we are testing the "migration" from the isUS pref being false but when
+// no country-code exists.
+function run_test() {
+ installTestEngine();
+
+ // Set the pref we care about.
+ Services.prefs.setBoolPref("browser.search.isUS", false);
+ // And the geoip request that will return US.
+ Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "US"}');
+ Services.search.init(() => {
+ // "region" and countryCode should reflect US.
+ equal(Services.prefs.getCharPref("browser.search.region"), "US", "got the correct region.");
+ equal(Services.prefs.getCharPref("browser.search.countryCode"), "US", "got the correct country code.");
+ // check we have "success" recorded in telemetry
+ checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS);
+ // a false value for each of SEARCH_SERVICE_COUNTRY_TIMEOUT and SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT
+ for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT",
+ "SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) {
+ let histogram = Services.telemetry.getHistogramById(hid);
+ let snapshot = histogram.snapshot();
+ deepEqual(snapshot.counts, [1, 0, 0]); // boolean probe so 3 buckets, expect 1 result for |0|.
+ }
+ do_test_finished();
+ run_next_test();
+ });
+ do_test_pending();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_location_partner.js b/toolkit/components/search/tests/xpcshell/test_location_partner.js
new file mode 100644
index 000000000..9151add9a
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location_partner.js
@@ -0,0 +1,16 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "US"}');
+ Services.prefs.setCharPref("distribution.id", 'partner-1');
+ setUpGeoDefaults();
+
+ Services.search.init(() => {
+ equal(Services.search.defaultEngine.name, "Test search engine");
+
+ do_test_finished();
+ run_next_test();
+ });
+ do_test_pending();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_location_sync.js b/toolkit/components/search/tests/xpcshell/test_location_sync.js
new file mode 100644
index 000000000..524a440fb
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location_sync.js
@@ -0,0 +1,101 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function getCountryCodePref() {
+ try {
+ return Services.prefs.getCharPref("browser.search.countryCode");
+ } catch (_) {
+ return undefined;
+ }
+}
+
+function getIsUSPref() {
+ try {
+ return Services.prefs.getBoolPref("browser.search.isUS");
+ } catch (_) {
+ return undefined;
+ }
+}
+
+// A console listener so we can listen for a log message from nsSearchService.
+function promiseTimezoneMessage() {
+ return new Promise(resolve => {
+ let listener = {
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIConsoleListener]),
+ observe : function (msg) {
+ if (msg.message.startsWith("getIsUS() fell back to a timezone check with the result=")) {
+ Services.console.unregisterListener(listener);
+ resolve(msg);
+ }
+ }
+ };
+ Services.console.registerListener(listener);
+ });
+}
+
+function run_test() {
+ installTestEngine();
+
+ run_next_test();
+}
+
+// Force a sync init and ensure the right thing happens (ie, that no xhr
+// request is made and we fall back to the timezone-only trick)
+add_task(function* test_simple() {
+ deepEqual(getCountryCodePref(), undefined, "no countryCode pref");
+ deepEqual(getIsUSPref(), undefined, "no isUS pref");
+
+ // Still set a geoip pref so we can (indirectly) check it wasn't used.
+ Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "AU"}');
+
+ ok(!Services.search.isInitialized);
+
+ // setup a console listener for the timezone fallback message.
+ let promiseTzMessage = promiseTimezoneMessage();
+
+ // fetching the engines forces a sync init, and should have caused us to
+ // check the timezone.
+ Services.search.getEngines();
+ ok(Services.search.isInitialized);
+
+ // a little wait to check we didn't do the xhr thang.
+ yield new Promise(resolve => {
+ do_timeout(500, resolve);
+ });
+
+ let msg = yield promiseTzMessage;
+ print("Timezone message:", msg.message);
+ ok(msg.message.endsWith(isUSTimezone().toString()), "fell back to timezone and it matches our timezone");
+
+ deepEqual(getCountryCodePref(), undefined, "didn't do the geoip xhr");
+ // and no telemetry evidence of geoip.
+ for (let hid of [
+ "SEARCH_SERVICE_COUNTRY_FETCH_RESULT",
+ "SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS",
+ "SEARCH_SERVICE_COUNTRY_TIMEOUT",
+ "SEARCH_SERVICE_US_COUNTRY_MISMATCHED_TIMEZONE",
+ "SEARCH_SERVICE_US_TIMEZONE_MISMATCHED_COUNTRY",
+ "SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT",
+ ]) {
+ let histogram = Services.telemetry.getHistogramById(hid);
+ let snapshot = histogram.snapshot();
+ equal(snapshot.sum, 0, hid);
+ switch (snapshot.histogram_type) {
+ case Ci.nsITelemetry.HISTOGRAM_FLAG:
+ // flags are a special case in that they are initialized with a default
+ // of one |0|.
+ deepEqual(snapshot.counts, [1, 0, 0], hid);
+ break;
+ case Ci.nsITelemetry.HISTOGRAM_BOOLEAN:
+ // booleans aren't initialized at all, so should have all zeros.
+ deepEqual(snapshot.counts, [0, 0, 0], hid);
+ break;
+ case Ci.nsITelemetry.HISTOGRAM_EXPONENTIAL:
+ case Ci.nsITelemetry.HISTOGRAM_LINEAR:
+ equal(snapshot.counts.reduce((a, b) => a+b), 0, hid);
+ break;
+ default:
+ ok(false, "unknown histogram type " + snapshot.histogram_type + " for " + hid);
+ }
+ }
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_location_timeout.js b/toolkit/components/search/tests/xpcshell/test_location_timeout.js
new file mode 100644
index 000000000..c1d5270e5
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location_timeout.js
@@ -0,0 +1,78 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// This is testing the "normal" timer-based timeout for the location search.
+
+function startServer(continuePromise) {
+ let srv = new HttpServer();
+ function lookupCountry(metadata, response) {
+ response.processAsync();
+ // wait for our continuePromise to resolve before writing a valid
+ // response.
+ // This will be resolved after the timeout period, so we can check
+ // the behaviour in that case.
+ continuePromise.then(() => {
+ response.setStatusLine("1.1", 200, "OK");
+ response.write('{"country_code" : "AU"}');
+ response.finish();
+ });
+ }
+ srv.registerPathHandler("/lookup_country", lookupCountry);
+ srv.start(-1);
+ return srv;
+}
+
+function getProbeSum(probe, sum) {
+ let histogram = Services.telemetry.getHistogramById(probe);
+ return histogram.snapshot().sum;
+}
+
+function run_test() {
+ installTestEngine();
+
+ let resolveContinuePromise;
+ let continuePromise = new Promise(resolve => {
+ resolveContinuePromise = resolve;
+ });
+
+ let server = startServer(continuePromise);
+ let url = "http://localhost:" + server.identity.primaryPort + "/lookup_country";
+ Services.prefs.setCharPref("browser.search.geoip.url", url);
+ Services.prefs.setIntPref("browser.search.geoip.timeout", 50);
+ Services.search.init(() => {
+ ok(!Services.prefs.prefHasUserValue("browser.search.countryCode"), "should be no countryCode pref");
+ ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
+ // should be no result recorded at all.
+ checkCountryResultTelemetry(null);
+
+ // should have set the flag indicating we saw a timeout.
+ let histogram = Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_TIMEOUT");
+ let snapshot = histogram.snapshot();
+ deepEqual(snapshot.counts, [0, 1, 0]);
+ // should not yet have SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS recorded as our
+ // test server is still blocked on our promise.
+ equal(getProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS"), 0);
+
+ waitForSearchNotification("geoip-lookup-xhr-complete").then(() => {
+ // now we *should* have a report of how long the response took even though
+ // it timed out.
+ // The telemetry "sum" will be the actual time in ms - just check it's non-zero.
+ ok(getProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS") != 0);
+ // should have reported the fetch ended up being successful
+ checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS);
+
+ // and should have the result of the response that finally came in, and
+ // everything dependent should also be updated.
+ equal(Services.prefs.getCharPref("browser.search.countryCode"), "AU");
+ equal(Services.prefs.getCharPref("browser.search.region"), "AU");
+ ok(!Services.prefs.prefHasUserValue("browser.search.isUS"), "should never have an isUS pref");
+
+ do_test_finished();
+ server.stop(run_next_test);
+ });
+ // now tell the server to send its response. That will end up causing the
+ // search service to notify of that the response was received.
+ resolveContinuePromise();
+ });
+ do_test_pending();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_location_timeout_xhr.js b/toolkit/components/search/tests/xpcshell/test_location_timeout_xhr.js
new file mode 100644
index 000000000..4054cf0c2
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_location_timeout_xhr.js
@@ -0,0 +1,85 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// This is testing the long, last-resort XHR-based timeout for the location
+// search.
+
+function startServer(continuePromise) {
+ let srv = new HttpServer();
+ function lookupCountry(metadata, response) {
+ response.processAsync();
+ // wait for our continuePromise to resolve before writing a valid
+ // response.
+ // This will be resolved after the timeout period, so we can check
+ // the behaviour in that case.
+ continuePromise.then(() => {
+ response.setStatusLine("1.1", 200, "OK");
+ response.write('{"country_code" : "AU"}');
+ response.finish();
+ });
+ }
+ srv.registerPathHandler("/lookup_country", lookupCountry);
+ srv.start(-1);
+ return srv;
+}
+
+function verifyProbeSum(probe, sum) {
+ let histogram = Services.telemetry.getHistogramById(probe);
+ let snapshot = histogram.snapshot();
+ equal(snapshot.sum, sum, probe);
+}
+
+function run_test() {
+ installTestEngine();
+
+ let resolveContinuePromise;
+ let continuePromise = new Promise(resolve => {
+ resolveContinuePromise = resolve;
+ });
+
+ let server = startServer(continuePromise);
+ let url = "http://localhost:" + server.identity.primaryPort + "/lookup_country";
+ Services.prefs.setCharPref("browser.search.geoip.url", url);
+ // The timeout for the timer.
+ Services.prefs.setIntPref("browser.search.geoip.timeout", 10);
+ let promiseXHRStarted = waitForSearchNotification("geoip-lookup-xhr-starting");
+ Services.search.init(() => {
+ ok(!Services.prefs.prefHasUserValue("browser.search.countryCode"), "should be no countryCode pref");
+ ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
+ // should be no result recorded at all.
+ checkCountryResultTelemetry(null);
+
+ // should have set the flag indicating we saw a timeout.
+ let histogram = Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_TIMEOUT");
+ let snapshot = histogram.snapshot();
+ deepEqual(snapshot.counts, [0, 1, 0]);
+
+ // should not have SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS recorded as our
+ // test server is still blocked on our promise.
+ verifyProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS", 0);
+
+ promiseXHRStarted.then(xhr => {
+ // Set the timeout on the xhr object to an extremely low value, so it
+ // should timeout immediately.
+ xhr.timeout = 10;
+ // wait for the xhr timeout to fire.
+ waitForSearchNotification("geoip-lookup-xhr-complete").then(() => {
+ // should have the XHR timeout recorded.
+ checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.XHRTIMEOUT);
+ // still should not have a report of how long the response took as we
+ // only record that on success responses.
+ verifyProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS", 0);
+ // and we still don't know the country code or region.
+ ok(!Services.prefs.prefHasUserValue("browser.search.countryCode"), "should be no countryCode pref");
+ ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
+
+ // unblock the server even though nothing is listening.
+ resolveContinuePromise();
+
+ do_test_finished();
+ server.stop(run_next_test);
+ });
+ });
+ });
+ do_test_pending();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_migration_langpack.js b/toolkit/components/search/tests/xpcshell/test_migration_langpack.js
new file mode 100644
index 000000000..8cb2014bd
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_migration_langpack.js
@@ -0,0 +1,37 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+
+ // Unless we unset the XPCSHELL_TEST_PROFILE_DIR environment variable,
+ // engine._isDefault will be true for engines from the resource:// scheme,
+ // bypassing the codepath we want to test.
+ let env = Cc["@mozilla.org/process/environment;1"]
+ .getService(Ci.nsIEnvironment);
+ env.set("XPCSHELL_TEST_PROFILE_DIR", "");
+
+ do_get_file("data/langpack-metadata.json").copyTo(gProfD, "search-metadata.json");
+
+ do_check_false(Services.search.isInitialized);
+
+ run_next_test();
+}
+
+add_task(function* async_init() {
+ let commitPromise = promiseAfterCache()
+ yield asyncInit();
+
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+ do_check_eq(engine.wrappedJSObject._id, "[app]/bug645970.xml");
+
+ yield commitPromise;
+ let metadata = yield promiseEngineMetadata();
+ do_check_eq(metadata["bug645970"].alias, "lp");
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_multipleIcons.js b/toolkit/components/search/tests/xpcshell/test_multipleIcons.js
new file mode 100644
index 000000000..314515f6d
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_multipleIcons.js
@@ -0,0 +1,61 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Tests getIcons() and getIconURLBySize() on engine with multiple icons.
+ */
+
+"use strict";
+
+function run_test() {
+ removeMetadata();
+ updateAppInfo();
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_multipleIcons() {
+ let [engine] = yield addTestEngines([
+ { name: "IconsTest", xmlFileName: "engineImages.xml" },
+ ]);
+
+ do_print("The default should be the 16x16 icon");
+ do_check_true(engine.iconURI.spec.includes("ico16"));
+
+ do_check_true(engine.getIconURLBySize(16, 16).includes("ico16"));
+ do_check_true(engine.getIconURLBySize(32, 32).includes("ico32"));
+ do_check_true(engine.getIconURLBySize(74, 74).includes("ico74"));
+
+ do_print("Invalid dimensions should return null.");
+ do_check_null(engine.getIconURLBySize(50, 50));
+
+ let allIcons = engine.getIcons();
+
+ do_print("Check that allIcons contains expected icon sizes");
+ do_check_eq(allIcons.length, 3);
+ let expectedWidths = [16, 32, 74];
+ do_check_true(allIcons.every((item) => {
+ let width = item.width;
+ do_check_neq(expectedWidths.indexOf(width), -1);
+ do_check_eq(width, item.height);
+
+ let icon = item.url.split(",").pop();
+ do_check_eq(icon, "ico" + width);
+
+ return true;
+ }));
+});
+
+add_task(function* test_icon_not_in_file() {
+ let engineUrl = gDataUrl + "engine-fr.xml";
+ let engine = yield new Promise((resolve, reject) => {
+ Services.search.addEngine(engineUrl, null, "data:image/x-icon;base64,ico16",
+ false, {onSuccess: resolve, onError: reject});
+ });
+
+ // Even though the icon wasn't specified inside the XML file, it should be
+ // available both in the iconURI attribute and with getIconURLBySize.
+ do_check_true(engine.iconURI.spec.includes("ico16"));
+ do_check_true(engine.getIconURLBySize(16, 16).includes("ico16"));
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_nocache.js b/toolkit/components/search/tests/xpcshell/test_nocache.js
new file mode 100644
index 000000000..42776aef0
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_nocache.js
@@ -0,0 +1,60 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * test_nocache: Start search engine
+ * - without search.json.mozlz4
+ *
+ * Ensure that :
+ * - nothing explodes;
+ * - search.json.mozlz4 is created.
+ */
+
+function run_test()
+{
+ removeCacheFile();
+ updateAppInfo();
+ do_load_manifest("data/chrome.manifest");
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_nocache() {
+ let search = Services.search;
+
+ let afterCachePromise = promiseAfterCache();
+
+ yield new Promise((resolve, reject) => search.init(rv => {
+ Components.isSuccessCode(rv) ? resolve() : reject();
+ }));
+
+ // Check that the cache is created at startup
+ yield afterCachePromise;
+
+ // Check that search.json has been created.
+ let cacheFile = gProfD.clone();
+ cacheFile.append(CACHE_FILENAME);
+ do_check_true(cacheFile.exists());
+
+ // Add engine and wait for cache update
+ yield addTestEngines([
+ { name: "Test search engine", xmlFileName: "engine.xml" },
+ ]);
+
+ do_print("Engine has been added, let's wait for the cache to be built");
+ yield promiseAfterCache();
+
+ do_print("Searching test engine in cache");
+ let cache = yield promiseCacheData();
+ let found = false;
+ for (let engine of cache.engines) {
+ if (engine._shortName == "test-search-engine") {
+ found = true;
+ break;
+ }
+ }
+ do_check_true(found);
+
+ removeCacheFile();
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_nodb.js b/toolkit/components/search/tests/xpcshell/test_nodb.js
new file mode 100644
index 000000000..66a003a5d
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_nodb.js
@@ -0,0 +1,37 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * test_nodb: Start search engine
+ * - without search-metadata.json
+ * - without search.sqlite
+ *
+ * Ensure that :
+ * - nothing explodes;
+ * - no search-metadata.json is created.
+ */
+
+
+function run_test()
+{
+ removeMetadata();
+ updateAppInfo();
+
+ let search = Services.search;
+
+ do_test_pending();
+ search.init(function ss_initialized(rv) {
+ do_check_true(Components.isSuccessCode(rv));
+ do_timeout(500, function() {
+ // Check that search-metadata.json has not been
+ // created. Note that we cannot do much better
+ // than a timeout for checking a non-event.
+ let metadata = gProfD.clone();
+ metadata.append("search-metadata.json");
+ do_check_true(!metadata.exists());
+ removeMetadata();
+
+ do_test_finished();
+ });
+ });
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_nodb_pluschanges.js b/toolkit/components/search/tests/xpcshell/test_nodb_pluschanges.js
new file mode 100644
index 000000000..e6789e964
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_nodb_pluschanges.js
@@ -0,0 +1,57 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+
+/*
+ * test_nodb: Start search engine
+ * - without search-metadata.json
+ * - without search.sqlite
+ *
+ * Ensure that :
+ * - nothing explodes;
+ * - if we change the order, search.json.mozlz4 is updated;
+ * - this search.json.mozlz4 can be parsed;
+ * - the order stored in search.json.mozlz4 is consistent.
+ *
+ * Notes:
+ * - we install the search engines of test "test_downloadAndAddEngines.js"
+ * to ensure that this test is independent from locale, commercial agreements
+ * and configuration of Firefox.
+ */
+
+function run_test() {
+ updateAppInfo();
+ do_load_manifest("data/chrome.manifest");
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_nodb_pluschanges() {
+ let [engine1, engine2] = yield addTestEngines([
+ { name: "Test search engine", xmlFileName: "engine.xml" },
+ { name: "A second test engine", xmlFileName: "engine2.xml"},
+ ]);
+ yield promiseAfterCache();
+
+ let search = Services.search;
+
+ search.moveEngine(engine1, 0);
+ search.moveEngine(engine2, 1);
+
+ // This is needed to avoid some reentrency issues in nsSearchService.
+ do_print("Next step is forcing flush");
+ yield new Promise(resolve => do_execute_soon(resolve));
+
+ do_print("Forcing flush");
+ let promiseCommit = promiseAfterCache();
+ search.QueryInterface(Ci.nsIObserver)
+ .observe(null, "quit-application", "");
+ yield promiseCommit;
+ do_print("Commit complete");
+
+ // Check that the entries are placed as specified correctly
+ let metadata = yield promiseEngineMetadata();
+ do_check_eq(metadata["test-search-engine"].order, 1);
+ do_check_eq(metadata["a-second-test-engine"].order, 2);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_notifications.js b/toolkit/components/search/tests/xpcshell/test_notifications.js
new file mode 100644
index 000000000..3eecbf8b1
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_notifications.js
@@ -0,0 +1,72 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+var gTestLog = [];
+
+/**
+ * The order of notifications expected for this test is:
+ * - engine-changed (while we're installing the engine, we modify it, which notifies - bug 606886)
+ * - engine-added (engine was added to the store by the search service)
+ * -> our search observer is called, which sets:
+ * - .defaultEngine, triggering engine-default
+ * - .currentEngine, triggering engine-current (after bug 493051 - for now the search service sets this after engine-added)
+ * ...and then schedules a removal
+ * - engine-loaded (the search service's observer is garanteed to fire first, which is what causes engine-added to fire)
+ * - engine-removed (due to the removal schedule above)
+ */
+var expectedLog = [
+ "engine-changed", // XXX bug 606886
+ "engine-added",
+ "engine-default",
+ "engine-current",
+ "engine-loaded",
+ "engine-removed"
+];
+
+function search_observer(subject, topic, data) {
+ let engine = subject.QueryInterface(Ci.nsISearchEngine);
+ gTestLog.push(data + " for " + engine.name);
+
+ do_print("Observer: " + data + " for " + engine.name);
+
+ switch (data) {
+ case "engine-added":
+ let retrievedEngine = Services.search.getEngineByName("Test search engine");
+ do_check_eq(engine, retrievedEngine);
+ Services.search.defaultEngine = engine;
+ Services.search.currentEngine = engine;
+ do_execute_soon(function () {
+ Services.search.removeEngine(engine);
+ });
+ break;
+ case "engine-removed":
+ let engineNameOutput = " for Test search engine";
+ expectedLog = expectedLog.map(logLine => logLine + engineNameOutput);
+ do_print("expectedLog:\n" + expectedLog.join("\n"))
+ do_print("gTestLog:\n" + gTestLog.join("\n"))
+ for (let i = 0; i < expectedLog.length; i++) {
+ do_check_eq(gTestLog[i], expectedLog[i]);
+ }
+ do_check_eq(gTestLog.length, expectedLog.length);
+ do_test_finished();
+ break;
+ }
+}
+
+function run_test() {
+ removeMetadata();
+ updateAppInfo();
+ useHttpServer();
+
+ do_register_cleanup(function cleanup() {
+ Services.obs.removeObserver(search_observer, "browser-search-engine-modified");
+ });
+
+ do_test_pending();
+
+ Services.obs.addObserver(search_observer, "browser-search-engine-modified", false);
+
+ Services.search.addEngine(gDataUrl + "engine.xml", null, null, false);
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_parseSubmissionURL.js b/toolkit/components/search/tests/xpcshell/test_parseSubmissionURL.js
new file mode 100644
index 000000000..d6e21fc61
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_parseSubmissionURL.js
@@ -0,0 +1,148 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Tests getAlternateDomains API.
+ */
+
+"use strict";
+
+function run_test() {
+ removeMetadata();
+ updateAppInfo();
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_parseSubmissionURL() {
+ // Hide the default engines to prevent them from being used in the search.
+ for (let engine of Services.search.getEngines()) {
+ Services.search.removeEngine(engine);
+ }
+
+ let [engine1, engine2, engine3, engine4] = yield addTestEngines([
+ { name: "Test search engine", xmlFileName: "engine.xml" },
+ { name: "Test search engine (fr)", xmlFileName: "engine-fr.xml" },
+ { name: "bacon_addParam", details: ["", "bacon_addParam", "Search Bacon",
+ "GET", "http://www.bacon.test/find"] },
+ { name: "idn_addParam", details: ["", "idn_addParam", "Search IDN",
+ "GET", "http://www.xn--bcher-kva.ch/search"] },
+ // The following engines cannot identify the search parameter.
+ { name: "A second test engine", xmlFileName: "engine2.xml" },
+ { name: "bacon", details: ["", "bacon", "Search Bacon", "GET",
+ "http://www.bacon.moz/search?q={searchTerms}"] },
+ ]);
+
+ engine3.addParam("q", "{searchTerms}", null);
+ engine4.addParam("q", "{searchTerms}", null);
+
+ // Test the first engine, whose URLs use UTF-8 encoding.
+ let url = "http://www.google.com/search?foo=bar&q=caff%C3%A8";
+ let result = Services.search.parseSubmissionURL(url);
+ do_check_eq(result.engine, engine1);
+ do_check_eq(result.terms, "caff\u00E8");
+ do_check_true(url.slice(result.termsOffset).startsWith("caff%C3%A8"));
+ do_check_eq(result.termsLength, "caff%C3%A8".length);
+
+ // The second engine uses a locale-specific domain that is an alternate domain
+ // of the first one, but the second engine should get priority when matching.
+ // The URL used with this engine uses ISO-8859-1 encoding instead.
+ url = "http://www.google.fr/search?q=caff%E8";
+ result = Services.search.parseSubmissionURL(url);
+ do_check_eq(result.engine, engine2);
+ do_check_eq(result.terms, "caff\u00E8");
+ do_check_true(url.slice(result.termsOffset).startsWith("caff%E8"));
+ do_check_eq(result.termsLength, "caff%E8".length);
+
+ // Test a domain that is an alternate domain of those defined. In this case,
+ // the first matching engine from the ordered list should be returned.
+ url = "http://www.google.co.uk/search?q=caff%C3%A8";
+ result = Services.search.parseSubmissionURL(url);
+ do_check_eq(result.engine, engine1);
+ do_check_eq(result.terms, "caff\u00E8");
+ do_check_true(url.slice(result.termsOffset).startsWith("caff%C3%A8"));
+ do_check_eq(result.termsLength, "caff%C3%A8".length);
+
+ // We support parsing URLs from a dynamically added engine. Those engines use
+ // windows-1252 encoding by default.
+ url = "http://www.bacon.test/find?q=caff%E8";
+ result = Services.search.parseSubmissionURL(url);
+ do_check_eq(result.engine, engine3);
+ do_check_eq(result.terms, "caff\u00E8");
+ do_check_true(url.slice(result.termsOffset).startsWith("caff%E8"));
+ do_check_eq(result.termsLength, "caff%E8".length);
+
+ // Test URLs with unescaped unicode characters.
+ url = "http://www.google.com/search?q=foo+b\u00E4r";
+ result = Services.search.parseSubmissionURL(url);
+ do_check_eq(result.engine, engine1);
+ do_check_eq(result.terms, "foo b\u00E4r");
+ do_check_true(url.slice(result.termsOffset).startsWith("foo+b\u00E4r"));
+ do_check_eq(result.termsLength, "foo+b\u00E4r".length);
+
+ // Test search engines with unescaped IDNs.
+ url = "http://www.b\u00FCcher.ch/search?q=foo+bar";
+ result = Services.search.parseSubmissionURL(url);
+ do_check_eq(result.engine, engine4);
+ do_check_eq(result.terms, "foo bar");
+ do_check_true(url.slice(result.termsOffset).startsWith("foo+bar"));
+ do_check_eq(result.termsLength, "foo+bar".length);
+
+ // Test search engines with escaped IDNs.
+ url = "http://www.xn--bcher-kva.ch/search?q=foo+bar";
+ result = Services.search.parseSubmissionURL(url);
+ do_check_eq(result.engine, engine4);
+ do_check_eq(result.terms, "foo bar");
+ do_check_true(url.slice(result.termsOffset).startsWith("foo+bar"));
+ do_check_eq(result.termsLength, "foo+bar".length);
+
+ // Parsing of parameters from an engine template URL is not supported.
+ do_check_eq(Services.search.parseSubmissionURL(
+ "http://www.bacon.moz/search?q=").engine, null);
+ do_check_eq(Services.search.parseSubmissionURL(
+ "https://duckduckgo.com?q=test").engine, null);
+ do_check_eq(Services.search.parseSubmissionURL(
+ "https://duckduckgo.com/?q=test").engine, null);
+
+ // HTTP and HTTPS schemes are interchangeable.
+ url = "https://www.google.com/search?q=caff%C3%A8";
+ result = Services.search.parseSubmissionURL(url);
+ do_check_eq(result.engine, engine1);
+ do_check_eq(result.terms, "caff\u00E8");
+ do_check_true(url.slice(result.termsOffset).startsWith("caff%C3%A8"));
+
+ // Decoding search terms with multiple spaces should work.
+ result = Services.search.parseSubmissionURL(
+ "http://www.google.com/search?q=+with++spaces+");
+ do_check_eq(result.engine, engine1);
+ do_check_eq(result.terms, " with spaces ");
+
+ // An empty query parameter should work the same.
+ url = "http://www.google.com/search?q=";
+ result = Services.search.parseSubmissionURL(url);
+ do_check_eq(result.engine, engine1);
+ do_check_eq(result.terms, "");
+ do_check_eq(result.termsOffset, url.length);
+
+ // There should be no match when the path is different.
+ result = Services.search.parseSubmissionURL(
+ "http://www.google.com/search/?q=test");
+ do_check_eq(result.engine, null);
+ do_check_eq(result.terms, "");
+ do_check_eq(result.termsOffset, -1);
+
+ // There should be no match when the argument is different.
+ result = Services.search.parseSubmissionURL(
+ "http://www.google.com/search?q2=test");
+ do_check_eq(result.engine, null);
+ do_check_eq(result.terms, "");
+ do_check_eq(result.termsOffset, -1);
+
+ // There should be no match for URIs that are not HTTP or HTTPS.
+ result = Services.search.parseSubmissionURL(
+ "file://localhost/search?q=test");
+ do_check_eq(result.engine, null);
+ do_check_eq(result.terms, "");
+ do_check_eq(result.termsOffset, -1);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_pref.js b/toolkit/components/search/tests/xpcshell/test_pref.js
new file mode 100644
index 000000000..f51ab4ee8
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_pref.js
@@ -0,0 +1,36 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/* Test that MozParam condition="pref" values used in search URLs are from the
+ * default branch, and that their special characters are URL encoded. */
+
+"use strict";
+
+function run_test() {
+ updateAppInfo();
+
+ // The test engines used in this test need to be recognized as 'default'
+ // engines, or their MozParams will be ignored.
+ let url = "resource://test/data/";
+ let resProt = Services.io.getProtocolHandler("resource")
+ .QueryInterface(Ci.nsIResProtocolHandler);
+ resProt.setSubstitution("search-plugins",
+ Services.io.newURI(url, null, null));
+
+ run_next_test();
+}
+
+add_task(function* test_pref() {
+ let defaultBranch = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF);
+ defaultBranch.setCharPref("param.code", "good&id=unique");
+ Services.prefs.setCharPref(BROWSER_SEARCH_PREF + "param.code", "bad");
+
+ yield asyncInit();
+
+ let engine = Services.search.getEngineByName("engine-pref");
+ let base = "http://www.google.com/search?q=foo&code=";
+ do_check_eq(engine.getSubmission("foo").uri.spec,
+ base + "good%26id%3Dunique");
+
+ do_test_finished();
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_purpose.js b/toolkit/components/search/tests/xpcshell/test_purpose.js
new file mode 100644
index 000000000..46465e0a3
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_purpose.js
@@ -0,0 +1,70 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Test that a search purpose can be specified and that query parameters for
+ * that purpose are included in the search URL.
+ */
+
+"use strict";
+
+function run_test() {
+ removeMetadata();
+ updateAppInfo();
+
+ // The test engines used in this test need to be recognized as 'default'
+ // engines, or their MozParams used to set the purpose will be ignored.
+ let url = "resource://test/data/";
+ let resProt = Services.io.getProtocolHandler("resource")
+ .QueryInterface(Ci.nsIResProtocolHandler);
+ resProt.setSubstitution("search-plugins",
+ Services.io.newURI(url, null, null));
+
+ run_next_test();
+}
+
+add_task(function* test_purpose() {
+ let engine = Services.search.getEngineByName("Test search engine");
+
+ function check_submission(aExpected, aSearchTerm, aType, aPurpose) {
+ do_check_eq(engine.getSubmission(aSearchTerm, aType, aPurpose).uri.spec,
+ base + aExpected);
+ }
+
+ let base = "http://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&aq=t";
+ check_submission("", "foo");
+ check_submission("", "foo", null);
+ check_submission("", "foo", "text/html");
+ check_submission("&channel=rcs", "foo", null, "contextmenu");
+ check_submission("&channel=rcs", "foo", "text/html", "contextmenu");
+ check_submission("&channel=fflb", "foo", null, "keyword");
+ check_submission("&channel=fflb", "foo", "text/html", "keyword");
+ check_submission("", "foo", "text/html", "invalid");
+
+ // Tests for a param that varies with a purpose but has a default value.
+ base = "http://www.google.com/search?q=foo";
+ check_submission("&channel=ffsb", "foo", "application/x-moz-default-purpose");
+ check_submission("&channel=ffsb", "foo", "application/x-moz-default-purpose", null);
+ check_submission("&channel=ffsb", "foo", "application/x-moz-default-purpose", "");
+ check_submission("&channel=rcs", "foo", "application/x-moz-default-purpose", "contextmenu");
+ check_submission("&channel=fflb", "foo", "application/x-moz-default-purpose", "keyword");
+ check_submission("&channel=ffsb", "foo", "application/x-moz-default-purpose", "searchbar");
+ check_submission("&channel=ffsb", "foo", "application/x-moz-default-purpose", "invalid");
+
+ // Tests for a purpose on the search form (ie. empty query).
+ engine = Services.search.getEngineByName("engine-rel-searchform-purpose");
+ base = "http://www.google.com/search?q=";
+ check_submission("&channel=sb", "", null, "searchbar");
+ check_submission("&channel=sb", "", "text/html", "searchbar");
+
+ // verify that the 'system' purpose falls back to the 'searchbar' purpose.
+ base = "http://www.google.com/search?q=foo";
+ check_submission("&channel=sb", "foo", "text/html", "system");
+ check_submission("&channel=sb", "foo", "text/html", "searchbar");
+ // Use an engine that actually defines the 'system' purpose...
+ engine = Services.search.getEngineByName("engine-system-purpose");
+ // ... and check that the system purpose is used correctly.
+ check_submission("&channel=sys", "foo", "text/html", "system");
+
+ do_test_finished();
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_rel_searchform.js b/toolkit/components/search/tests/xpcshell/test_rel_searchform.js
new file mode 100644
index 000000000..79f217e0d
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_rel_searchform.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Tests that <Url rel="searchform"/> is properly recognized as a searchForm.
+ */
+
+"use strict";
+
+function run_test() {
+ removeMetadata();
+ updateAppInfo();
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_rel_searchform() {
+ let engineNames = [
+ "engine-rel-searchform.xml",
+ "engine-rel-searchform-post.xml",
+ ];
+
+ // The final searchForm of the engine should be a URL whose domain is the
+ // <ShortName> in the engine's XML and that has a ?search parameter. The
+ // point of the ?search parameter is to avoid accidentally matching the value
+ // returned as a last resort by Engine's searchForm getter, which is simply
+ // the prePath of the engine's first HTML <Url>.
+ let items = engineNames.map(e => ({ name: e, xmlFileName: e }));
+ for (let engine of yield addTestEngines(items)) {
+ do_check_eq(engine.searchForm, "http://" + engine.name + "/?search");
+ }
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_remove_profile_engine.js b/toolkit/components/search/tests/xpcshell/test_remove_profile_engine.js
new file mode 100644
index 000000000..3a985db9e
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_remove_profile_engine.js
@@ -0,0 +1,35 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const NS_APP_USER_SEARCH_DIR = "UsrSrchPlugns";
+
+function run_test() {
+ do_test_pending();
+
+ // Copy an engine to [profile]/searchplugin/
+ let dir = Services.dirsvc.get(NS_APP_USER_SEARCH_DIR, Ci.nsIFile);
+ if (!dir.exists())
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+ do_get_file("data/engine-override.xml").copyTo(dir, "bug645970.xml");
+
+ let file = dir.clone();
+ file.append("bug645970.xml");
+ do_check_true(file.exists());
+
+ do_check_false(Services.search.isInitialized);
+
+ Services.search.init(function search_initialized(aStatus) {
+ do_check_true(Components.isSuccessCode(aStatus));
+ do_check_true(Services.search.isInitialized);
+
+ // test the engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ // remove the engine and verify the file has been removed too.
+ Services.search.removeEngine(engine);
+ do_check_false(file.exists());
+
+ do_test_finished();
+ });
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_require_engines_in_cache.js b/toolkit/components/search/tests/xpcshell/test_require_engines_in_cache.js
new file mode 100644
index 000000000..299121c4f
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_require_engines_in_cache.js
@@ -0,0 +1,74 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+ do_check_false(Services.search.isInitialized);
+
+ run_next_test();
+}
+
+add_task(function* ignore_cache_files_without_engines() {
+ let commitPromise = promiseAfterCache()
+ yield asyncInit();
+
+ let engineCount = Services.search.getEngines().length;
+ do_check_eq(engineCount, 1);
+
+ // Wait for the file to be saved to disk, so that we can mess with it.
+ yield commitPromise;
+
+ // Remove all engines from the cache file.
+ let cache = yield promiseCacheData();
+ cache.engines = [];
+ yield promiseSaveCacheData(cache);
+
+ // Check that after an async re-initialization, we still have the same engine count.
+ commitPromise = promiseAfterCache()
+ yield asyncReInit();
+ do_check_eq(engineCount, Services.search.getEngines().length);
+ yield commitPromise;
+
+ // Check that after a sync re-initialization, we still have the same engine count.
+ yield promiseSaveCacheData(cache);
+ let unInitPromise = waitForSearchNotification("uninit-complete");
+ let reInitPromise = asyncReInit();
+ yield unInitPromise;
+ do_check_false(Services.search.isInitialized);
+ // Synchronously check the engine count; will force a sync init.
+ do_check_eq(engineCount, Services.search.getEngines().length);
+ do_check_true(Services.search.isInitialized);
+ yield reInitPromise;
+});
+
+add_task(function* skip_writing_cache_without_engines() {
+ let unInitPromise = waitForSearchNotification("uninit-complete");
+ let reInitPromise = asyncReInit();
+ yield unInitPromise;
+
+ // Configure so that no engines will be found.
+ do_check_true(removeCacheFile());
+ let resProt = Services.io.getProtocolHandler("resource")
+ .QueryInterface(Ci.nsIResProtocolHandler);
+ resProt.setSubstitution("search-plugins",
+ Services.io.newURI("about:blank", null, null));
+
+ // Let the async-reInit happen.
+ yield reInitPromise;
+ do_check_eq(0, Services.search.getEngines().length);
+
+ // Trigger yet another re-init, to flush of any pending cache writing task.
+ unInitPromise = waitForSearchNotification("uninit-complete");
+ reInitPromise = asyncReInit();
+ yield unInitPromise;
+
+ // Now check that a cache file doesn't exist.
+ do_check_false(removeCacheFile());
+
+ yield reInitPromise;
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_resultDomain.js b/toolkit/components/search/tests/xpcshell/test_resultDomain.js
new file mode 100644
index 000000000..d7458a923
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_resultDomain.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * Tests getResultDomain API.
+ */
+
+"use strict";
+
+function run_test() {
+ removeMetadata();
+ updateAppInfo();
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_resultDomain() {
+ let [engine1, engine2, engine3] = yield addTestEngines([
+ { name: "Test search engine", xmlFileName: "engine.xml" },
+ { name: "A second test engine", xmlFileName: "engine2.xml" },
+ { name: "bacon", details: ["", "bacon", "Search Bacon", "GET",
+ "http://www.bacon.moz/?search={searchTerms}"] },
+ ]);
+
+ do_check_eq(engine1.getResultDomain(), "google.com");
+ do_check_eq(engine1.getResultDomain("text/html"), "google.com");
+ do_check_eq(engine1.getResultDomain("application/x-moz-default-purpose"),
+ "purpose.google.com");
+ do_check_eq(engine1.getResultDomain("fake-response-type"), "");
+ do_check_eq(engine2.getResultDomain(), "duckduckgo.com");
+ do_check_eq(engine3.getResultDomain(), "bacon.moz");
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_save_sorted_engines.js b/toolkit/components/search/tests/xpcshell/test_save_sorted_engines.js
new file mode 100644
index 000000000..c509c5f77
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_save_sorted_engines.js
@@ -0,0 +1,67 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * test_save_sorted_engines: Start search engine
+ * - without search-metadata.json
+ * - without search.sqlite
+ *
+ * Ensure that search-metadata.json is correct after:
+ * - moving an engine
+ * - removing an engine
+ * - adding a new engine
+ *
+ * Notes:
+ * - we install the search engines of test "test_downloadAndAddEngines.js"
+ * to ensure that this test is independent from locale, commercial agreements
+ * and configuration of Firefox.
+ */
+
+function run_test() {
+ updateAppInfo();
+ useHttpServer();
+
+ run_next_test();
+}
+
+add_task(function* test_save_sorted_engines() {
+ let [engine1, engine2] = yield addTestEngines([
+ { name: "Test search engine", xmlFileName: "engine.xml" },
+ { name: "A second test engine", xmlFileName: "engine2.xml"},
+ ]);
+ yield promiseAfterCache();
+
+ let search = Services.search;
+
+ // Test moving the engines
+ search.moveEngine(engine1, 0);
+ search.moveEngine(engine2, 1);
+
+ // Changes should be commited immediately
+ yield promiseAfterCache();
+ do_print("Commit complete after moveEngine");
+
+ // Check that the entries are placed as specified correctly
+ let metadata = yield promiseEngineMetadata();
+ do_check_eq(metadata["test-search-engine"].order, 1);
+ do_check_eq(metadata["a-second-test-engine"].order, 2);
+
+ // Test removing an engine
+ search.removeEngine(engine1);
+ yield promiseAfterCache();
+ do_print("Commit complete after removeEngine");
+
+ // Check that the order of the remaining engine was updated correctly
+ metadata = yield promiseEngineMetadata();
+ do_check_eq(metadata["a-second-test-engine"].order, 1);
+
+ // Test adding a new engine
+ search.addEngineWithDetails("foo", "", "foo", "", "GET",
+ "http://searchget/?search={searchTerms}");
+ yield promiseAfterCache();
+ do_print("Commit complete after addEngineWithDetails");
+
+ metadata = yield promiseEngineMetadata();
+ do_check_eq(metadata["foo"].alias, "foo");
+ do_check_true(metadata["foo"].order > 0);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_searchReset.js b/toolkit/components/search/tests/xpcshell/test_searchReset.js
new file mode 100644
index 000000000..316069c95
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_searchReset.js
@@ -0,0 +1,137 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const NS_APP_USER_SEARCH_DIR = "UsrSrchPlugns";
+
+const kTestEngineShortName = "engine";
+const kWhiteListPrefName = "reset.whitelist";
+
+function run_test() {
+ // Copy an engine to [profile]/searchplugin/
+ let dir = Services.dirsvc.get(NS_APP_USER_SEARCH_DIR, Ci.nsIFile);
+ if (!dir.exists())
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+ do_get_file("data/engine.xml").copyTo(dir, kTestEngineShortName + ".xml");
+
+ let file = dir.clone();
+ file.append(kTestEngineShortName + ".xml");
+ do_check_true(file.exists());
+
+ do_check_false(Services.search.isInitialized);
+
+ Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF)
+ .setBoolPref("reset.enabled", true);
+
+ run_next_test();
+}
+
+function* removeLoadPathHash() {
+ // Remove the loadPathHash and re-initialize the search service.
+ let cache = yield promiseCacheData();
+ for (let engine of cache.engines) {
+ if (engine._shortName == kTestEngineShortName) {
+ delete engine._metaData["loadPathHash"];
+ break;
+ }
+ }
+ yield promiseSaveCacheData(cache);
+ yield asyncReInit();
+}
+
+add_task(function* test_no_prompt_when_valid_loadPathHash() {
+ yield asyncInit();
+
+ // test the engine is loaded ok.
+ let engine = Services.search.getEngineByName(kTestEngineName);
+ do_check_neq(engine, null);
+
+ yield promiseAfterCache();
+
+ // The test engine has been found in the profile directory and imported,
+ // so it shouldn't have a loadPathHash.
+ let metadata = yield promiseEngineMetadata();
+ do_check_true(kTestEngineShortName in metadata);
+ do_check_false("loadPathHash" in metadata[kTestEngineShortName]);
+
+ // After making it the currentEngine with the search service API,
+ // the test engine should have a valid loadPathHash.
+ Services.search.currentEngine = engine;
+ yield promiseAfterCache();
+ metadata = yield promiseEngineMetadata();
+ do_check_true("loadPathHash" in metadata[kTestEngineShortName]);
+ let loadPathHash = metadata[kTestEngineShortName].loadPathHash;
+ do_check_eq(typeof loadPathHash, "string");
+ do_check_eq(loadPathHash.length, 44);
+
+ // A search should not cause the search reset prompt.
+ let submission =
+ Services.search.currentEngine.getSubmission("foo", null, "searchbar");
+ do_check_eq(submission.uri.spec,
+ "http://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&aq=t");
+});
+
+add_task(function* test_promptURLs() {
+ yield removeLoadPathHash();
+
+ // The default should still be the test engine.
+ let currentEngine = Services.search.currentEngine;
+ do_check_eq(currentEngine.name, kTestEngineName);
+ // but the submission url should be about:searchreset
+ let url = (data, purpose) =>
+ currentEngine.getSubmission(data, null, purpose).uri.spec;
+ do_check_eq(url("foo", "searchbar"),
+ "about:searchreset?data=foo&purpose=searchbar");
+ do_check_eq(url("foo"), "about:searchreset?data=foo");
+ do_check_eq(url("", "searchbar"), "about:searchreset?purpose=searchbar");
+ do_check_eq(url(""), "about:searchreset");
+ do_check_eq(url("", ""), "about:searchreset");
+
+ // Calling the currentEngine setter for the same engine should
+ // prevent further prompts.
+ Services.search.currentEngine = Services.search.currentEngine;
+ do_check_eq(url("foo", "searchbar"),
+ "http://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&aq=t");
+
+ // And the loadPathHash should be back.
+ yield promiseAfterCache();
+ let metadata = yield promiseEngineMetadata();
+ do_check_true("loadPathHash" in metadata[kTestEngineShortName]);
+ let loadPathHash = metadata[kTestEngineShortName].loadPathHash;
+ do_check_eq(typeof loadPathHash, "string");
+ do_check_eq(loadPathHash.length, 44);
+});
+
+add_task(function* test_whitelist() {
+ yield removeLoadPathHash();
+
+ // The default should still be the test engine.
+ let currentEngine = Services.search.currentEngine;
+ do_check_eq(currentEngine.name, kTestEngineName);
+ let expectPrompt = shouldPrompt => {
+ let expectedURL =
+ shouldPrompt ? "about:searchreset?data=foo&purpose=searchbar"
+ : "http://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&aq=t";
+ let url = currentEngine.getSubmission("foo", null, "searchbar").uri.spec;
+ do_check_eq(url, expectedURL);
+ };
+ expectPrompt(true);
+
+ // Unless we whitelist our test engine.
+ let branch = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF);
+ let initialWhiteList = branch.getCharPref(kWhiteListPrefName);
+ branch.setCharPref(kWhiteListPrefName, "example.com,test.tld");
+ expectPrompt(true);
+ branch.setCharPref(kWhiteListPrefName, "www.google.com");
+ expectPrompt(false);
+ branch.setCharPref(kWhiteListPrefName, "example.com,www.google.com,test.tld");
+ expectPrompt(false);
+
+ // The loadPathHash should not be back after the prompt was skipped due to the
+ // whitelist.
+ yield asyncReInit();
+ let metadata = yield promiseEngineMetadata();
+ do_check_false("loadPathHash" in metadata[kTestEngineShortName]);
+
+ branch.setCharPref(kWhiteListPrefName, initialWhiteList);
+ expectPrompt(true);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_searchSuggest.js b/toolkit/components/search/tests/xpcshell/test_searchSuggest.js
new file mode 100644
index 000000000..9de2967fc
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_searchSuggest.js
@@ -0,0 +1,572 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/**
+ * Testing search suggestions from SearchSuggestionController.jsm.
+ */
+
+"use strict";
+
+Cu.import("resource://gre/modules/FormHistory.jsm");
+Cu.import("resource://gre/modules/SearchSuggestionController.jsm");
+Cu.import("resource://gre/modules/Timer.jsm");
+
+// We must make sure the FormHistoryStartup component is
+// initialized in order for it to respond to FormHistory
+// requests from nsFormAutoComplete.js.
+var formHistoryStartup = Cc["@mozilla.org/satchel/form-history-startup;1"].
+ getService(Ci.nsIObserver);
+formHistoryStartup.observe(null, "profile-after-change", null);
+
+var httpServer = new HttpServer();
+var getEngine, postEngine, unresolvableEngine;
+
+function run_test() {
+ Services.prefs.setBoolPref("browser.search.suggest.enabled", true);
+
+ removeMetadata();
+ updateAppInfo();
+
+ let server = useHttpServer();
+ server.registerContentType("sjs", "sjs");
+
+ do_register_cleanup(() => Task.spawn(function* cleanup() {
+ // Remove added form history entries
+ yield updateSearchHistory("remove", null);
+ FormHistory.shutdown();
+ Services.prefs.clearUserPref("browser.search.suggest.enabled");
+ }));
+
+ run_next_test();
+}
+
+add_task(function* add_test_engines() {
+ let getEngineData = {
+ baseURL: gDataUrl,
+ name: "GET suggestion engine",
+ method: "GET",
+ };
+
+ let postEngineData = {
+ baseURL: gDataUrl,
+ name: "POST suggestion engine",
+ method: "POST",
+ };
+
+ let unresolvableEngineData = {
+ baseURL: "http://example.invalid/",
+ name: "Offline suggestion engine",
+ method: "GET",
+ };
+
+ [getEngine, postEngine, unresolvableEngine] = yield addTestEngines([
+ {
+ name: getEngineData.name,
+ xmlFileName: "engineMaker.sjs?" + JSON.stringify(getEngineData),
+ },
+ {
+ name: postEngineData.name,
+ xmlFileName: "engineMaker.sjs?" + JSON.stringify(postEngineData),
+ },
+ {
+ name: unresolvableEngineData.name,
+ xmlFileName: "engineMaker.sjs?" + JSON.stringify(unresolvableEngineData),
+ },
+ ]);
+});
+
+
+// Begin tests
+
+add_task(function* simple_no_result_callback() {
+ let deferred = Promise.defer();
+ let controller = new SearchSuggestionController((result) => {
+ do_check_eq(result.term, "no remote");
+ do_check_eq(result.local.length, 0);
+ do_check_eq(result.remote.length, 0);
+ deferred.resolve();
+ });
+
+ controller.fetch("no remote", false, getEngine);
+ yield deferred.promise;
+});
+
+add_task(function* simple_no_result_callback_and_promise() {
+ // Make sure both the callback and promise get results
+ let deferred = Promise.defer();
+ let controller = new SearchSuggestionController((result) => {
+ do_check_eq(result.term, "no results");
+ do_check_eq(result.local.length, 0);
+ do_check_eq(result.remote.length, 0);
+ deferred.resolve();
+ });
+
+ let result = yield controller.fetch("no results", false, getEngine);
+ do_check_eq(result.term, "no results");
+ do_check_eq(result.local.length, 0);
+ do_check_eq(result.remote.length, 0);
+
+ yield deferred.promise;
+});
+
+add_task(function* simple_no_result_promise() {
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("no remote", false, getEngine);
+ do_check_eq(result.term, "no remote");
+ do_check_eq(result.local.length, 0);
+ do_check_eq(result.remote.length, 0);
+});
+
+add_task(function* simple_remote_no_local_result() {
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("mo", false, getEngine);
+ do_check_eq(result.term, "mo");
+ do_check_eq(result.local.length, 0);
+ do_check_eq(result.remote.length, 3);
+ do_check_eq(result.remote[0], "Mozilla");
+ do_check_eq(result.remote[1], "modern");
+ do_check_eq(result.remote[2], "mom");
+});
+
+add_task(function* remote_term_case_mismatch() {
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("Query Case Mismatch", false, getEngine);
+ do_check_eq(result.term, "Query Case Mismatch");
+ do_check_eq(result.remote.length, 1);
+ do_check_eq(result.remote[0], "Query Case Mismatch");
+});
+
+add_task(function* simple_local_no_remote_result() {
+ yield updateSearchHistory("bump", "no remote entries");
+
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("no remote", false, getEngine);
+ do_check_eq(result.term, "no remote");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "no remote entries");
+ do_check_eq(result.remote.length, 0);
+
+ yield updateSearchHistory("remove", "no remote entries");
+});
+
+add_task(function* simple_non_ascii() {
+ yield updateSearchHistory("bump", "I ❤️ XUL");
+
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("I ❤️", false, getEngine);
+ do_check_eq(result.term, "I ❤️");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "I ❤️ XUL");
+ do_check_eq(result.remote.length, 1);
+ do_check_eq(result.remote[0], "I ❤️ Mozilla");
+});
+
+add_task(function* both_local_remote_result_dedupe() {
+ yield updateSearchHistory("bump", "Mozilla");
+
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("mo", false, getEngine);
+ do_check_eq(result.term, "mo");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "Mozilla");
+ do_check_eq(result.remote.length, 2);
+ do_check_eq(result.remote[0], "modern");
+ do_check_eq(result.remote[1], "mom");
+});
+
+add_task(function* POST_both_local_remote_result_dedupe() {
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("mo", false, postEngine);
+ do_check_eq(result.term, "mo");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "Mozilla");
+ do_check_eq(result.remote.length, 2);
+ do_check_eq(result.remote[0], "modern");
+ do_check_eq(result.remote[1], "mom");
+});
+
+add_task(function* both_local_remote_result_dedupe2() {
+ yield updateSearchHistory("bump", "mom");
+
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("mo", false, getEngine);
+ do_check_eq(result.term, "mo");
+ do_check_eq(result.local.length, 2);
+ do_check_eq(result.local[0], "mom");
+ do_check_eq(result.local[1], "Mozilla");
+ do_check_eq(result.remote.length, 1);
+ do_check_eq(result.remote[0], "modern");
+});
+
+add_task(function* both_local_remote_result_dedupe3() {
+ // All of the server entries also exist locally
+ yield updateSearchHistory("bump", "modern");
+
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("mo", false, getEngine);
+ do_check_eq(result.term, "mo");
+ do_check_eq(result.local.length, 3);
+ do_check_eq(result.local[0], "modern");
+ do_check_eq(result.local[1], "mom");
+ do_check_eq(result.local[2], "Mozilla");
+ do_check_eq(result.remote.length, 0);
+});
+
+add_task(function* fetch_twice_in_a_row() {
+ // Two entries since the first will match the first fetch but not the second.
+ yield updateSearchHistory("bump", "delay local");
+ yield updateSearchHistory("bump", "delayed local");
+
+ let controller = new SearchSuggestionController();
+ let resultPromise1 = controller.fetch("delay", false, getEngine);
+
+ // A second fetch while the server is still waiting to return results leads to an abort.
+ let resultPromise2 = controller.fetch("delayed ", false, getEngine);
+ yield resultPromise1.then((results) => do_check_null(results));
+
+ let result = yield resultPromise2;
+ do_check_eq(result.term, "delayed ");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "delayed local");
+ do_check_eq(result.remote.length, 1);
+ do_check_eq(result.remote[0], "delayed ");
+});
+
+add_task(function* fetch_twice_subset_reuse_formHistoryResult() {
+ // This tests if we mess up re-using the cached form history result.
+ // Two entries since the first will match the first fetch but not the second.
+ yield updateSearchHistory("bump", "delay local");
+ yield updateSearchHistory("bump", "delayed local");
+
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("delay", false, getEngine);
+ do_check_eq(result.term, "delay");
+ do_check_eq(result.local.length, 2);
+ do_check_eq(result.local[0], "delay local");
+ do_check_eq(result.local[1], "delayed local");
+ do_check_eq(result.remote.length, 1);
+ do_check_eq(result.remote[0], "delay");
+
+ // Remove the entry from the DB but it should remain in the cached formHistoryResult.
+ yield updateSearchHistory("remove", "delayed local");
+
+ let result2 = yield controller.fetch("delayed ", false, getEngine);
+ do_check_eq(result2.term, "delayed ");
+ do_check_eq(result2.local.length, 1);
+ do_check_eq(result2.local[0], "delayed local");
+ do_check_eq(result2.remote.length, 1);
+ do_check_eq(result2.remote[0], "delayed ");
+});
+
+add_task(function* both_identical_with_more_than_max_results() {
+ // Add letters A through Z to form history which will match the server
+ for (let charCode = "A".charCodeAt(); charCode <= "Z".charCodeAt(); charCode++) {
+ yield updateSearchHistory("bump", "letter " + String.fromCharCode(charCode));
+ }
+
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = 7;
+ controller.maxRemoteResults = 10;
+ let result = yield controller.fetch("letter ", false, getEngine);
+ do_check_eq(result.term, "letter ");
+ do_check_eq(result.local.length, 7);
+ for (let i = 0; i < controller.maxLocalResults; i++) {
+ do_check_eq(result.local[i], "letter " + String.fromCharCode("A".charCodeAt() + i));
+ }
+ do_check_eq(result.local.length + result.remote.length, 10);
+ for (let i = 0; i < result.remote.length; i++) {
+ do_check_eq(result.remote[i],
+ "letter " + String.fromCharCode("A".charCodeAt() + controller.maxLocalResults + i));
+ }
+});
+
+add_task(function* noremote_maxLocal() {
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = 2; // (should be ignored because no remote results)
+ controller.maxRemoteResults = 0;
+ let result = yield controller.fetch("letter ", false, getEngine);
+ do_check_eq(result.term, "letter ");
+ do_check_eq(result.local.length, 26);
+ for (let i = 0; i < result.local.length; i++) {
+ do_check_eq(result.local[i], "letter " + String.fromCharCode("A".charCodeAt() + i));
+ }
+ do_check_eq(result.remote.length, 0);
+});
+
+add_task(function* someremote_maxLocal() {
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = 2;
+ controller.maxRemoteResults = 4;
+ let result = yield controller.fetch("letter ", false, getEngine);
+ do_check_eq(result.term, "letter ");
+ do_check_eq(result.local.length, 2);
+ for (let i = 0; i < result.local.length; i++) {
+ do_check_eq(result.local[i], "letter " + String.fromCharCode("A".charCodeAt() + i));
+ }
+ do_check_eq(result.remote.length, 2);
+ // "A" and "B" will have been de-duped, start at C for remote results
+ for (let i = 0; i < result.remote.length; i++) {
+ do_check_eq(result.remote[i], "letter " + String.fromCharCode("C".charCodeAt() + i));
+ }
+});
+
+add_task(function* one_of_each() {
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = 1;
+ controller.maxRemoteResults = 2;
+ let result = yield controller.fetch("letter ", false, getEngine);
+ do_check_eq(result.term, "letter ");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "letter A");
+ do_check_eq(result.remote.length, 1);
+ do_check_eq(result.remote[0], "letter B");
+});
+
+add_task(function* local_result_returned_remote_result_disabled() {
+ Services.prefs.setBoolPref("browser.search.suggest.enabled", false);
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = 1;
+ controller.maxRemoteResults = 1;
+ let result = yield controller.fetch("letter ", false, getEngine);
+ do_check_eq(result.term, "letter ");
+ do_check_eq(result.local.length, 26);
+ for (let i = 0; i < 26; i++) {
+ do_check_eq(result.local[i], "letter " + String.fromCharCode("A".charCodeAt() + i));
+ }
+ do_check_eq(result.remote.length, 0);
+ Services.prefs.setBoolPref("browser.search.suggest.enabled", true);
+});
+
+add_task(function* local_result_returned_remote_result_disabled_after_creation_of_controller() {
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = 1;
+ controller.maxRemoteResults = 1;
+ Services.prefs.setBoolPref("browser.search.suggest.enabled", false);
+ let result = yield controller.fetch("letter ", false, getEngine);
+ do_check_eq(result.term, "letter ");
+ do_check_eq(result.local.length, 26);
+ for (let i = 0; i < 26; i++) {
+ do_check_eq(result.local[i], "letter " + String.fromCharCode("A".charCodeAt() + i));
+ }
+ do_check_eq(result.remote.length, 0);
+ Services.prefs.setBoolPref("browser.search.suggest.enabled", true);
+});
+
+add_task(function* one_of_each_disabled_before_creation_enabled_after_creation_of_controller() {
+ Services.prefs.setBoolPref("browser.search.suggest.enabled", false);
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = 1;
+ controller.maxRemoteResults = 2;
+ Services.prefs.setBoolPref("browser.search.suggest.enabled", true);
+ let result = yield controller.fetch("letter ", false, getEngine);
+ do_check_eq(result.term, "letter ");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "letter A");
+ do_check_eq(result.remote.length, 1);
+ do_check_eq(result.remote[0], "letter B");
+});
+
+add_task(function* reset_suggestions_pref() {
+ Services.prefs.setBoolPref("browser.search.suggest.enabled", true);
+});
+
+add_task(function* one_local_zero_remote() {
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = 1;
+ controller.maxRemoteResults = 0;
+ let result = yield controller.fetch("letter ", false, getEngine);
+ do_check_eq(result.term, "letter ");
+ do_check_eq(result.local.length, 26);
+ for (let i = 0; i < 26; i++) {
+ do_check_eq(result.local[i], "letter " + String.fromCharCode("A".charCodeAt() + i));
+ }
+ do_check_eq(result.remote.length, 0);
+});
+
+add_task(function* zero_local_one_remote() {
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = 0;
+ controller.maxRemoteResults = 1;
+ let result = yield controller.fetch("letter ", false, getEngine);
+ do_check_eq(result.term, "letter ");
+ do_check_eq(result.local.length, 0);
+ do_check_eq(result.remote.length, 1);
+ do_check_eq(result.remote[0], "letter A");
+});
+
+add_task(function* stop_search() {
+ let controller = new SearchSuggestionController((result) => {
+ do_throw("The callback shouldn't be called after stop()");
+ });
+ let resultPromise = controller.fetch("mo", false, getEngine);
+ controller.stop();
+ yield resultPromise.then((result) => {
+ do_check_null(result);
+ });
+});
+
+add_task(function* empty_searchTerm() {
+ // Empty searches don't go to the server but still get form history.
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("", false, getEngine);
+ do_check_eq(result.term, "");
+ do_check_true(result.local.length > 0);
+ do_check_eq(result.remote.length, 0);
+});
+
+add_task(function* slow_timeout() {
+ let d = Promise.defer();
+ function check_result(result) {
+ do_check_eq(result.term, "slow ");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "slow local result");
+ do_check_eq(result.remote.length, 0);
+ }
+ yield updateSearchHistory("bump", "slow local result");
+
+ let controller = new SearchSuggestionController();
+ setTimeout(function check_timeout() {
+ // The HTTP response takes 10 seconds so check that we already have results after 2 seconds.
+ check_result(result);
+ d.resolve();
+ }, 2000);
+ let result = yield controller.fetch("slow ", false, getEngine);
+ check_result(result);
+ yield d.promise;
+});
+
+add_task(function* slow_stop() {
+ let d = Promise.defer();
+ let controller = new SearchSuggestionController();
+ let resultPromise = controller.fetch("slow ", false, getEngine);
+ setTimeout(function check_timeout() {
+ // The HTTP response takes 10 seconds but we timeout in less than a second so just use 0.
+ controller.stop();
+ d.resolve();
+ }, 0);
+ yield resultPromise.then((result) => {
+ do_check_null(result);
+ });
+
+ yield d.promise;
+});
+
+
+// Error handling
+
+add_task(function* remote_term_mismatch() {
+ yield updateSearchHistory("bump", "Query Mismatch Entry");
+
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("Query Mismatch", false, getEngine);
+ do_check_eq(result.term, "Query Mismatch");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "Query Mismatch Entry");
+ do_check_eq(result.remote.length, 0);
+});
+
+add_task(function* http_404() {
+ yield updateSearchHistory("bump", "HTTP 404 Entry");
+
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("HTTP 404", false, getEngine);
+ do_check_eq(result.term, "HTTP 404");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "HTTP 404 Entry");
+ do_check_eq(result.remote.length, 0);
+});
+
+add_task(function* http_500() {
+ yield updateSearchHistory("bump", "HTTP 500 Entry");
+
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("HTTP 500", false, getEngine);
+ do_check_eq(result.term, "HTTP 500");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "HTTP 500 Entry");
+ do_check_eq(result.remote.length, 0);
+});
+
+add_task(function* unresolvable_server() {
+ yield updateSearchHistory("bump", "Unresolvable Server Entry");
+
+ let controller = new SearchSuggestionController();
+ let result = yield controller.fetch("Unresolvable Server", false, unresolvableEngine);
+ do_check_eq(result.term, "Unresolvable Server");
+ do_check_eq(result.local.length, 1);
+ do_check_eq(result.local[0], "Unresolvable Server Entry");
+ do_check_eq(result.remote.length, 0);
+});
+
+
+// Exception handling
+
+add_task(function* missing_pb() {
+ Assert.throws(() => {
+ let controller = new SearchSuggestionController();
+ controller.fetch("No privacy");
+ }, /priva/i);
+});
+
+add_task(function* missing_engine() {
+ Assert.throws(() => {
+ let controller = new SearchSuggestionController();
+ controller.fetch("No engine", false);
+ }, /engine/i);
+});
+
+add_task(function* invalid_engine() {
+ Assert.throws(() => {
+ let controller = new SearchSuggestionController();
+ controller.fetch("invalid engine", false, {});
+ }, /engine/i);
+});
+
+add_task(function* no_results_requested() {
+ Assert.throws(() => {
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = 0;
+ controller.maxRemoteResults = 0;
+ controller.fetch("No results requested", false, getEngine);
+ }, /result/i);
+});
+
+add_task(function* minus_one_results_requested() {
+ Assert.throws(() => {
+ let controller = new SearchSuggestionController();
+ controller.maxLocalResults = -1;
+ controller.fetch("-1 results requested", false, getEngine);
+ }, /result/i);
+});
+
+add_task(function* test_userContextId() {
+ let controller = new SearchSuggestionController();
+ controller._fetchRemote = function(searchTerm, engine, privateMode, userContextId) {
+ Assert.equal(userContextId, 1);
+ return Promise.defer();
+ };
+
+ controller.fetch("test", false, getEngine, 1);
+});
+
+// Helpers
+
+function updateSearchHistory(operation, value) {
+ let deferred = Promise.defer();
+ FormHistory.update({
+ op: operation,
+ fieldname: "searchbar-history",
+ value: value,
+ },
+ {
+ handleError: function (error) {
+ do_throw("Error occurred updating form history: " + error);
+ deferred.reject(error);
+ },
+ handleCompletion: function (reason) {
+ if (!reason)
+ deferred.resolve();
+ }
+ });
+ return deferred.promise;
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_selectedEngine.js b/toolkit/components/search/tests/xpcshell/test_selectedEngine.js
new file mode 100644
index 000000000..a1c0f363e
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_selectedEngine.js
@@ -0,0 +1,165 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+Components.utils.import("resource://gre/modules/osfile.jsm");
+
+const kSelectedEnginePref = "browser.search.selectedEngine";
+
+// Check that the default engine matches the defaultenginename pref
+add_task(function* test_defaultEngine() {
+ yield asyncInit();
+
+ do_check_eq(Services.search.currentEngine.name, getDefaultEngineName());
+});
+
+// Giving prefs a user value shouldn't change the selected engine.
+add_task(function* test_selectedEngine() {
+ let defaultEngineName = getDefaultEngineName();
+ // Test the selectedEngine pref.
+ Services.prefs.setCharPref(kSelectedEnginePref, kTestEngineName);
+
+ yield asyncReInit();
+ do_check_eq(Services.search.currentEngine.name, defaultEngineName);
+
+ Services.prefs.clearUserPref(kSelectedEnginePref);
+
+ // Test the defaultenginename pref.
+ Services.prefs.setCharPref(kDefaultenginenamePref, kTestEngineName);
+
+ yield asyncReInit();
+ do_check_eq(Services.search.currentEngine.name, defaultEngineName);
+
+ Services.prefs.clearUserPref(kDefaultenginenamePref);
+});
+
+// Setting the search engine should be persisted across restarts.
+add_task(function* test_persistAcrossRestarts() {
+ // Set the engine through the API.
+ Services.search.currentEngine = Services.search.getEngineByName(kTestEngineName);
+ do_check_eq(Services.search.currentEngine.name, kTestEngineName);
+ yield promiseAfterCache();
+
+ // Check that the a hash was saved.
+ let metadata = yield promiseGlobalMetadata();
+ do_check_eq(metadata.hash.length, 44);
+
+ // Re-init and check the engine is still the same.
+ yield asyncReInit();
+ do_check_eq(Services.search.currentEngine.name, kTestEngineName);
+
+ // Cleanup (set the engine back to default).
+ Services.search.resetToOriginalDefaultEngine();
+ do_check_eq(Services.search.currentEngine.name, getDefaultEngineName());
+});
+
+// An engine set without a valid hash should be ignored.
+add_task(function* test_ignoreInvalidHash() {
+ // Set the engine through the API.
+ Services.search.currentEngine = Services.search.getEngineByName(kTestEngineName);
+ do_check_eq(Services.search.currentEngine.name, kTestEngineName);
+ yield promiseAfterCache();
+
+ // Then mess with the file (make the hash invalid).
+ let metadata = yield promiseGlobalMetadata();
+ metadata.hash = "invalid";
+ yield promiseSaveGlobalMetadata(metadata);
+
+ // Re-init the search service, and check that the json file is ignored.
+ yield asyncReInit();
+ do_check_eq(Services.search.currentEngine.name, getDefaultEngineName());
+});
+
+// Resetting the engine to the default should remove the saved value.
+add_task(function* test_settingToDefault() {
+ // Set the engine through the API.
+ Services.search.currentEngine = Services.search.getEngineByName(kTestEngineName);
+ do_check_eq(Services.search.currentEngine.name, kTestEngineName);
+ yield promiseAfterCache();
+
+ // Check that the current engine was saved.
+ let metadata = yield promiseGlobalMetadata();
+ do_check_eq(metadata.current, kTestEngineName);
+
+ // Then set the engine back to the default through the API.
+ Services.search.currentEngine =
+ Services.search.getEngineByName(getDefaultEngineName());
+ yield promiseAfterCache();
+
+ // Check that the current engine is no longer saved in the JSON file.
+ metadata = yield promiseGlobalMetadata();
+ do_check_eq(metadata.current, "");
+});
+
+add_task(function* test_resetToOriginalDefaultEngine() {
+ let defaultName = getDefaultEngineName();
+ do_check_eq(Services.search.currentEngine.name, defaultName);
+
+ Services.search.currentEngine =
+ Services.search.getEngineByName(kTestEngineName);
+ do_check_eq(Services.search.currentEngine.name, kTestEngineName);
+ yield promiseAfterCache();
+
+ Services.search.resetToOriginalDefaultEngine();
+ do_check_eq(Services.search.currentEngine.name, defaultName);
+ yield promiseAfterCache();
+});
+
+add_task(function* test_fallback_kept_after_restart() {
+ // Set current engine to a default engine that isn't the original default.
+ let builtInEngines = Services.search.getDefaultEngines();
+ let defaultName = getDefaultEngineName();
+ let nonDefaultBuiltInEngine;
+ for (let engine of builtInEngines) {
+ if (engine.name != defaultName) {
+ nonDefaultBuiltInEngine = engine;
+ break;
+ }
+ }
+ Services.search.currentEngine = nonDefaultBuiltInEngine;
+ do_check_eq(Services.search.currentEngine.name, nonDefaultBuiltInEngine.name);
+ yield promiseAfterCache();
+
+ // Remove that engine...
+ Services.search.removeEngine(nonDefaultBuiltInEngine);
+ // The engine being a default (built-in) one, it should be hidden
+ // rather than actually removed.
+ do_check_true(nonDefaultBuiltInEngine.hidden);
+
+ // Using the currentEngine getter should force a fallback to the
+ // original default engine.
+ do_check_eq(Services.search.currentEngine.name, defaultName);
+
+ // Restoring the default engines should unhide our built-in test
+ // engine, but not change the value of currentEngine.
+ Services.search.restoreDefaultEngines();
+ do_check_false(nonDefaultBuiltInEngine.hidden);
+ do_check_eq(Services.search.currentEngine.name, defaultName);
+ yield promiseAfterCache();
+
+ // After a restart, the currentEngine value should still be unchanged.
+ yield asyncReInit();
+ do_check_eq(Services.search.currentEngine.name, defaultName);
+});
+
+
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_check_false(Services.search.isInitialized);
+
+ let engineDummyFile = gProfD.clone();
+ engineDummyFile.append("searchplugins");
+ engineDummyFile.append("test-search-engine.xml");
+ let engineDir = engineDummyFile.parent;
+ engineDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ do_get_file("data/engine.xml").copyTo(engineDir, "engine.xml");
+
+ do_register_cleanup(function() {
+ removeMetadata();
+ removeCacheFile();
+ });
+
+ run_next_test();
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_svg_icon.js b/toolkit/components/search/tests/xpcshell/test_svg_icon.js
new file mode 100644
index 000000000..5fd4781a1
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_svg_icon.js
@@ -0,0 +1,52 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+var url;
+var requestHandled;
+
+const icon =
+ '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' +
+ '<svg xmlns="http://www.w3.org/2000/svg" ' +
+ 'width="16" height="16" viewBox="0 0 16 16">' +
+ '<rect x="4" y="4" width="8px" height="8px" style="fill: blue"/>' +
+ '</svg>';
+
+function run_test() {
+ updateAppInfo();
+ useHttpServer(); // Unused, but required to call addTestEngines.
+
+ requestHandled = new Promise(resolve => {
+ let srv = new HttpServer();
+ srv.registerPathHandler("/icon.svg", (metadata, response) => {
+ response.setStatusLine("1.0", 200, "OK");
+ response.setHeader("Content-Type", "image/svg+xml", false);
+
+ response.write(icon);
+ resolve();
+ });
+ srv.start(-1);
+ do_register_cleanup(() => srv.stop(() => {}));
+
+ url = "http://localhost:" + srv.identity.primaryPort + "/icon.svg";
+ });
+
+ run_next_test();
+}
+
+add_task(function* test_svg_icon() {
+ yield asyncInit();
+
+ let [engine] = yield addTestEngines([
+ { name: "SVGIcon", details: [url, "", "SVG icon", "GET",
+ "http://icon.svg/search?q={searchTerms}"] },
+ ]);
+
+ yield requestHandled;
+ yield promiseAfterCache();
+
+ ok(engine.iconURI, "the engine has an icon");
+ ok(engine.iconURI.spec.startsWith("data:image/svg+xml"),
+ "the icon is saved as an SVG data url");
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_sync.js b/toolkit/components/search/tests/xpcshell/test_sync.js
new file mode 100644
index 000000000..8f4eb22ee
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_sync.js
@@ -0,0 +1,27 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+
+ do_check_false(Services.search.isInitialized);
+
+ // test engines from dir are not loaded.
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ do_check_true(Services.search.isInitialized);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ // Check the hidden engine is not loaded.
+ engine = Services.search.getEngineByName("hidden");
+ do_check_eq(engine, null);
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_sync_addon.js b/toolkit/components/search/tests/xpcshell/test_sync_addon.js
new file mode 100644
index 000000000..7af957506
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_sync_addon.js
@@ -0,0 +1,26 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+ installAddonEngine();
+
+ do_check_false(Services.search.isInitialized);
+
+ // test the add-on engine is loaded in addition to our jar engine
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 2);
+
+ do_check_true(Services.search.isInitialized);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("addon");
+ do_check_neq(engine, null);
+
+ do_check_eq(engine.description, "addon");
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_sync_addon_no_override.js b/toolkit/components/search/tests/xpcshell/test_sync_addon_no_override.js
new file mode 100644
index 000000000..3f4494905
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_sync_addon_no_override.js
@@ -0,0 +1,26 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+ installAddonEngine("engine-override");
+
+ do_check_false(Services.search.isInitialized);
+
+ // test the add-on engine isn't overriding our jar engine
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ do_check_true(Services.search.isInitialized);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ do_check_eq(engine.description, "bug645970");
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_sync_delay_fallback.js b/toolkit/components/search/tests/xpcshell/test_sync_delay_fallback.js
new file mode 100644
index 000000000..1b41a71bf
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_sync_delay_fallback.js
@@ -0,0 +1,52 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ do_test_pending();
+
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+
+ do_check_false(Services.search.isInitialized);
+ let fallback = false;
+
+ Services.search.init(function search_initialized(aStatus) {
+ do_check_true(fallback);
+ do_check_true(Components.isSuccessCode(aStatus));
+ do_check_true(Services.search.isInitialized);
+
+ // test engines from dir are not loaded.
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ do_test_finished();
+ });
+
+ // Execute test for the sync fallback while the async code is being executed.
+ Services.obs.addObserver(function searchServiceObserver(aResult, aTopic, aVerb) {
+ if (aVerb == "find-jar-engines") {
+ Services.obs.removeObserver(searchServiceObserver, aTopic);
+ fallback = true;
+
+ do_check_false(Services.search.isInitialized);
+
+ // test engines from dir are not loaded.
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ do_check_true(Services.search.isInitialized);
+ }
+ }, "browser-search-service", false);
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_sync_distribution.js b/toolkit/components/search/tests/xpcshell/test_sync_distribution.js
new file mode 100644
index 000000000..63a8b66f0
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_sync_distribution.js
@@ -0,0 +1,26 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+ installDistributionEngine();
+
+ do_check_false(Services.search.isInitialized);
+
+ // test that the engine from the distribution overrides our jar engine
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ do_check_true(Services.search.isInitialized);
+
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ // check the engine we have is actually the one from the distribution
+ do_check_eq(engine.description, "override");
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_sync_fallback.js b/toolkit/components/search/tests/xpcshell/test_sync_fallback.js
new file mode 100644
index 000000000..dad73fabc
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_sync_fallback.js
@@ -0,0 +1,42 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ do_test_pending();
+
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+
+ do_check_false(Services.search.isInitialized);
+
+ Services.search.init(function search_initialized(aStatus) {
+ do_check_true(Components.isSuccessCode(aStatus));
+ do_check_true(Services.search.isInitialized);
+
+ // test engines from dir are not loaded.
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ do_test_finished();
+ });
+
+ do_check_false(Services.search.isInitialized);
+
+ // test engines from dir are not loaded.
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ do_check_true(Services.search.isInitialized);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_sync_migration.js b/toolkit/components/search/tests/xpcshell/test_sync_migration.js
new file mode 100644
index 000000000..53e945dfd
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_sync_migration.js
@@ -0,0 +1,29 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/* Test that legacy metadata from search-metadata.json is correctly
+ * transferred to the new metadata storage. */
+
+function run_test() {
+ updateAppInfo();
+ installTestEngine();
+
+ do_get_file("data/metadata.json").copyTo(gProfD, "search-metadata.json");
+
+ run_next_test();
+}
+
+add_task(function* test_sync_metadata_migration() {
+ do_check_false(Services.search.isInitialized);
+ Services.search.getEngines();
+ do_check_true(Services.search.isInitialized);
+ yield promiseAfterCache();
+
+ // Check that the entries are placed as specified correctly
+ let metadata = yield promiseEngineMetadata();
+ do_check_eq(metadata["engine"].order, 1);
+ do_check_eq(metadata["engine"].alias, "foo");
+
+ metadata = yield promiseGlobalMetadata();
+ do_check_eq(metadata["searchDefaultExpir"], 1471013469846);
+});
diff --git a/toolkit/components/search/tests/xpcshell/test_sync_profile_engine.js b/toolkit/components/search/tests/xpcshell/test_sync_profile_engine.js
new file mode 100644
index 000000000..f8d38e571
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_sync_profile_engine.js
@@ -0,0 +1,35 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const NS_APP_USER_SEARCH_DIR = "UsrSrchPlugns";
+
+function run_test() {
+ removeMetadata();
+ removeCacheFile();
+
+ do_load_manifest("data/chrome.manifest");
+
+ configureToLoadJarEngines();
+
+ // Copy an engine in [profile]/searchplugin/ and ensure it's not
+ // overriding the same file from a jar.
+ // The description in the file we are copying is 'profile'.
+ let dir = Services.dirsvc.get(NS_APP_USER_SEARCH_DIR, Ci.nsIFile);
+ if (!dir.exists())
+ dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+ do_get_file("data/engine-override.xml").copyTo(dir, "bug645970.xml");
+
+ do_check_false(Services.search.isInitialized);
+
+ // test engines from dir are not loaded.
+ let engines = Services.search.getEngines();
+ do_check_eq(engines.length, 1);
+
+ do_check_true(Services.search.isInitialized);
+
+ // test jar engine is loaded ok.
+ let engine = Services.search.getEngineByName("bug645970");
+ do_check_neq(engine, null);
+
+ do_check_eq(engine.description, "bug645970");
+}
diff --git a/toolkit/components/search/tests/xpcshell/test_update_telemetry.js b/toolkit/components/search/tests/xpcshell/test_update_telemetry.js
new file mode 100644
index 000000000..f73e765c6
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/test_update_telemetry.js
@@ -0,0 +1,36 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function run_test() {
+ do_check_false(Services.search.isInitialized);
+
+ useHttpServer();
+ run_next_test();
+}
+
+function checkTelemetry(histogramName, expected) {
+ let histogram = Services.telemetry.getHistogramById(histogramName);
+ let snapshot = histogram.snapshot();
+ let expectedCounts = [0, 0, 0];
+ expectedCounts[expected ? 1 : 0] = 1;
+ Assert.deepEqual(snapshot.counts, expectedCounts,
+ "histogram has expected content");
+ histogram.clear();
+}
+
+add_task(function* ignore_cache_files_without_engines() {
+ yield asyncInit();
+
+ checkTelemetry("SEARCH_SERVICE_HAS_UPDATES", false);
+ checkTelemetry("SEARCH_SERVICE_HAS_ICON_UPDATES", false);
+
+ // Add an engine with update urls and re-init, as we record the presence of
+ // engine update urls only while initializing the search service.
+ yield addTestEngines([
+ { name: "update", xmlFileName: "engine-update.xml" },
+ ]);
+ yield asyncReInit();
+
+ checkTelemetry("SEARCH_SERVICE_HAS_UPDATES", true);
+ checkTelemetry("SEARCH_SERVICE_HAS_ICON_UPDATES", true);
+});
diff --git a/toolkit/components/search/tests/xpcshell/xpcshell.ini b/toolkit/components/search/tests/xpcshell/xpcshell.ini
new file mode 100644
index 000000000..1fb5a3423
--- /dev/null
+++ b/toolkit/components/search/tests/xpcshell/xpcshell.ini
@@ -0,0 +1,102 @@
+[DEFAULT]
+head = head_search.js
+tail =
+firefox-appdir = browser
+skip-if = toolkit == 'android'
+support-files =
+ data/chrome.manifest
+ data/engine.xml
+ data/engine2.xml
+ data/engine-addon.xml
+ data/engine-override.xml
+ data/engine-app.xml
+ data/engine-fr.xml
+ data/engineMaker.sjs
+ data/engine-pref.xml
+ data/engine-rel-searchform.xml
+ data/engine-rel-searchform-post.xml
+ data/engine-rel-searchform-purpose.xml
+ data/engine-system-purpose.xml
+ data/engine-update.xml
+ data/engineImages.xml
+ data/engine-chromeicon.xml
+ data/engine-resourceicon.xml
+ data/ico-size-16x16-png.ico
+ data/invalid-engine.xml
+ data/install.rdf
+ data/list.json
+ data/langpack-metadata.json
+ data/metadata.json
+ data/search.json
+ data/search.sqlite
+ data/searchSuggestions.sjs
+ data/searchTest.jar
+
+[test_nocache.js]
+[test_645970.js]
+[test_bug930456.js]
+[test_bug930456_child.js]
+[test_engine_set_alias.js]
+[test_hasEngineWithURL.js]
+[test_identifiers.js]
+[test_invalid_engine_from_dir.js]
+[test_init_async_multiple.js]
+[test_init_async_multiple_then_sync.js]
+[test_json_cache.js]
+[test_location.js]
+[test_location_error.js]
+[test_location_malformed_json.js]
+[test_location_migrate_countrycode_isUS.js]
+[test_location_migrate_no_countrycode_isUS.js]
+[test_location_migrate_no_countrycode_notUS.js]
+[test_location_partner.js]
+[test_location_funnelcake.js]
+[test_location_sync.js]
+[test_location_timeout.js]
+[test_location_timeout_xhr.js]
+[test_nodb.js]
+[test_nodb_pluschanges.js]
+[test_save_sorted_engines.js]
+[test_pref.js]
+[test_purpose.js]
+[test_defaultEngine.js]
+[test_notifications.js]
+[test_parseSubmissionURL.js]
+[test_SearchStaticData.js]
+[test_addEngine_callback.js]
+[test_migration_langpack.js]
+[test_multipleIcons.js]
+[test_resultDomain.js]
+[test_searchSuggest.js]
+[test_async.js]
+[test_async_addon.js]
+tags = addons
+[test_async_addon_no_override.js]
+tags = addons
+[test_async_distribution.js]
+[test_async_migration.js]
+[test_async_profile_engine.js]
+[test_sync.js]
+[test_sync_addon.js]
+tags = addons
+[test_sync_addon_no_override.js]
+tags = addons
+[test_sync_distribution.js]
+[test_sync_fallback.js]
+[test_sync_delay_fallback.js]
+[test_sync_migration.js]
+[test_sync_profile_engine.js]
+[test_rel_searchform.js]
+[test_remove_profile_engine.js]
+[test_selectedEngine.js]
+[test_geodefaults.js]
+[test_hidden.js]
+[test_currentEngine_fallback.js]
+[test_require_engines_in_cache.js]
+[test_update_telemetry.js]
+[test_svg_icon.js]
+[test_searchReset.js]
+[test_addEngineWithDetails.js]
+[test_chromeresource_icon1.js]
+[test_chromeresource_icon2.js]
+[test_engineUpdate.js]
diff --git a/toolkit/components/search/toolkitsearch.manifest b/toolkit/components/search/toolkitsearch.manifest
new file mode 100644
index 000000000..b7c55da0e
--- /dev/null
+++ b/toolkit/components/search/toolkitsearch.manifest
@@ -0,0 +1,10 @@
+component {7319788a-fe93-4db3-9f39-818cf08f4256} nsSearchService.js process=main
+contract @mozilla.org/browser/search-service;1 {7319788a-fe93-4db3-9f39-818cf08f4256} process=main
+# 21600 == 6 hours
+category update-timer nsSearchService @mozilla.org/browser/search-service;1,getService,search-engine-update-timer,browser.search.update.interval,21600
+component {aa892eb4-ffbf-477d-9f9a-06c995ae9f27} nsSearchSuggestions.js
+contract @mozilla.org/autocomplete/search;1?name=search-autocomplete {aa892eb4-ffbf-477d-9f9a-06c995ae9f27}
+#ifdef HAVE_SIDEBAR
+component {22117140-9c6e-11d3-aaf1-00805f8a4905} nsSidebar.js
+contract @mozilla.org/sidebar;1 {22117140-9c6e-11d3-aaf1-00805f8a4905}
+#endif