-
Notifications
You must be signed in to change notification settings - Fork 54
/
SearchService.jsm
3856 lines (3461 loc) · 123 KB
/
SearchService.jsm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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/. */
/* eslint no-shadow: error, mozilla/no-aArgs: error */
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { PromiseUtils } = ChromeUtils.import(
"resource://gre/modules/PromiseUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
AppConstants: "resource://gre/modules/AppConstants.jsm",
AddonManager: "resource://gre/modules/AddonManager.jsm",
clearTimeout: "resource://gre/modules/Timer.jsm",
DeferredTask: "resource://gre/modules/DeferredTask.jsm",
ExtensionParent: "resource://gre/modules/ExtensionParent.jsm",
getVerificationHash: "resource://gre/modules/SearchEngine.jsm",
IgnoreLists: "resource://gre/modules/IgnoreLists.jsm",
NetworkGeolocationProvider:
"resource://gre/modules/NetworkGeolocationProvider.jsm",
OS: "resource://gre/modules/osfile.jsm",
SearchEngine: "resource://gre/modules/SearchEngine.jsm",
SearchEngineSelector: "resource://gre/modules/SearchEngineSelector.jsm",
SearchStaticData: "resource://gre/modules/SearchStaticData.jsm",
SearchUtils: "resource://gre/modules/SearchUtils.jsm",
Services: "resource://gre/modules/Services.jsm",
setTimeout: "resource://gre/modules/Timer.jsm",
});
XPCOMUtils.defineLazyServiceGetters(this, {
gEnvironment: ["@mozilla.org/process/environment;1", "nsIEnvironment"],
});
XPCOMUtils.defineLazyPreferenceGetter(
this,
"gGeoSpecificDefaultsEnabled",
SearchUtils.BROWSER_SEARCH_PREF + "geoSpecificDefaults",
false
);
XPCOMUtils.defineLazyPreferenceGetter(
this,
"gModernConfig",
SearchUtils.BROWSER_SEARCH_PREF + "modernConfig",
false,
() => {
// We'll re-init the service, regardless of which way the pref-flip went.
Services.search.reInit();
}
);
// A text encoder to UTF8, used whenever we commit the cache to disk.
XPCOMUtils.defineLazyGetter(this, "gEncoder", function() {
return new TextEncoder();
});
// Directory service keys
const NS_APP_DISTRIBUTION_SEARCH_DIR_LIST = "SrchPluginsDistDL";
// We load plugins from EXT_SEARCH_PREFIX, where a list.json
// file needs to exist to list available engines.
const EXT_SEARCH_PREFIX = "resource://search-extensions/";
// The address we use to sign the built in search extensions with.
const EXT_SIGNING_ADDRESS = "search.mozilla.org";
const TOPIC_LOCALES_CHANGE = "intl:app-locales-changed";
const QUIT_APPLICATION_TOPIC = "quit-application";
// The following constants are left undocumented in nsISearchService.idl
// Cliqz. DB-927: Default search engine alias map
const SEARCH_ENGINE_ALIAS = {
"youtube": "#yt",
"youtube-de": "#yt"
}
// The following constants are left undocumented in nsISearchService.idl
// For the moment, they are meant for testing/debugging purposes only.
// Delay for batching invalidation of the JSON cache (ms)
const CACHE_INVALIDATION_DELAY = 1000;
const CACHE_FILENAME = "search.json.mozlz4";
// 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 is the amount of time we'll be idle for before applying any configuration
// changes.
const REINIT_IDLE_TIME_SEC = 5 * 60;
// Some extensions package multiple locales into a single extension, for those
// engines we use engine-locale to address the engine.
// This is to be removed in https://bugzilla.mozilla.org/show_bug.cgi?id=1532246
const MULTI_LOCALE_ENGINES = [
"amazon",
"amazondotcom",
"bolcom",
"ebay",
"google",
"marktplaats",
"mercadolibre",
"twitter",
"wikipedia",
"wiktionary",
"yandex",
"multilocale",
"qwant",
"yahoo",
"gimages",
"gmaps",
"startpage",
"youtube",
];
// 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 method that tries to determine our region via an XHR geoip lookup.
var ensureKnownRegion = async function(ss, awaitRegionCheck) {
// If we have a region already stored in our prefs we trust it.
let region = Services.prefs.getCharPref("browser.search.region", "");
try {
if (gGeoSpecificDefaultsEnabled && !region) {
// We don't have it cached, so fetch it. fetchRegion() will call
// storeRegion if it gets a result (even if that happens after the
// promise resolves) and fetchRegionDefault.
await fetchRegion(ss, awaitRegionCheck);
} else if (gGeoSpecificDefaultsEnabled && !gModernConfig) {
// The territory default we have already fetched may have expired.
let expired = (ss.getGlobalAttr("searchDefaultExpir") || 0) <= Date.now();
// 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"
);
let hasValidHashes =
(defaultEngine || defaultEngine === undefined) &&
(visibleDefaultEngines || visibleDefaultEngines === undefined);
if (expired || !hasValidHashes) {
await new Promise(resolve => {
let timeoutMS = Services.prefs.getIntPref(
"geo.provider.network.timeToWaitBeforeSending"
);
let timerId = setTimeout(() => {
timerId = null;
resolve();
}, timeoutMS);
let callback = () => {
clearTimeout(timerId);
resolve();
};
fetchRegionDefault(ss, awaitRegionCheck)
.then(callback)
.catch(err => {
Cu.reportError(err);
callback();
});
});
}
}
} catch (ex) {
Cu.reportError(ex);
} finally {
// Since bug 1492475, we don't block our init flows on the region fetch as
// performed here. But we'd still like to unit-test its implementation, thus
// we fire this observer notification.
Services.obs.notifyObservers(
null,
SearchUtils.TOPIC_SEARCH_SERVICE,
"ensure-known-region-done"
);
}
};
// Store the result of the geoip request as well as any other values and
// telemetry which depend on it.
async function storeRegion(region) {
let isTimezoneUS = isUSTimezone();
// If it's a US region, but not a US timezone, we don't store the value.
// This works because no region defaults to ZZ (unknown) in nsURLFormatter
if (region != "US" || isTimezoneUS) {
Services.prefs.setCharPref("browser.search.region", region);
}
// and telemetry...
if (region == "US" && !isTimezoneUS) {
SearchUtils.log("storeRegion mismatch - US Region, non-US timezone");
Services.telemetry
.getHistogramById("SEARCH_SERVICE_US_COUNTRY_MISMATCHED_TIMEZONE")
.add(1);
}
if (region != "US" && isTimezoneUS) {
SearchUtils.log("storeRegion mismatch - non-US Region, US timezone");
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 = await Services.sysinfo.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 (region == "US" || platformCC == "US") {
// one of the 2 said US, so record if they are the same.
Services.telemetry
.getHistogramById(probeUSMismatched)
.add(region != platformCC);
} else {
// non-US - record if they are the same
Services.telemetry
.getHistogramById(probeNonUSMismatched)
.add(region != platformCC);
}
}
}
}
// Get the region we are in via a XHR geoip request.
async function fetchRegion(ss, awaitRegionCheck) {
// values for the SEARCH_SERVICE_COUNTRY_FETCH_RESULT 'enum' telemetry probe.
const TELEMETRY_RESULT_ENUM = {
success: 0,
"xhr-empty": 1,
"xhr-timeout": 2,
"xhr-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 startTime = Date.now();
let statusCallback = status => {
switch (status) {
case "xhr-start":
// This notification is just for tests...
Services.obs.notifyObservers(
null,
SearchUtils.TOPIC_SEARCH_SERVICE,
"geoip-lookup-xhr-starting"
);
break;
case "wifi-timeout":
SearchUtils.log("_fetchRegion: timeout fetching wifi information");
// Do nothing for now.
break;
}
};
let networkGeo = new NetworkGeolocationProvider();
let result, errorResult;
try {
result = await networkGeo.getCountry(statusCallback);
} catch (ex) {
errorResult = ex;
Cu.reportError(ex);
}
let took = Date.now() - startTime;
// Even if we timed out, we want to save the region and everything
// related so next startup sees the value and doesn't retry this dance.
if (result) {
// As long as the asynchronous codepath in `storeRegion` is only used for
// telemetry, we don't need to await its completion.
storeRegion(result).catch(Cu.reportError);
}
SearchUtils.log(
"_fetchRegion got success response in " + took + "ms: " + result
);
Services.telemetry
.getHistogramById("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS")
.add(took);
// This notification is just for tests...
Services.obs.notifyObservers(
null,
SearchUtils.TOPIC_SEARCH_SERVICE,
"geoip-lookup-xhr-complete"
);
// Now that we know the current region, it's possible to fetch defaults,
// which we couldn't do before in `ensureKnownRegion`.
try {
if (result && gModernConfig) {
await ss._maybeReloadEngines(awaitRegionCheck);
} else if (result && !gModernConfig) {
await fetchRegionDefault(ss, awaitRegionCheck);
}
} catch (ex) {
Cu.reportError(ex);
}
let telemetryResult = TELEMETRY_RESULT_ENUM.success;
if (errorResult) {
telemetryResult =
TELEMETRY_RESULT_ENUM[errorResult] || TELEMETRY_RESULT_ENUM["xhr-error"];
}
Services.telemetry
.getHistogramById("SEARCH_SERVICE_COUNTRY_FETCH_RESULT")
.add(telemetryResult);
}
// This converts our legacy google engines to the
// new codes. We have to manually change them here
// because we can't change the default name in absearch.
function convertGoogleEngines(engineNames) {
let overrides = {
google: "google-b-d",
"google-2018": "google-b-1-d",
};
for (let engine in overrides) {
let index = engineNames.indexOf(engine);
if (index > -1) {
engineNames[index] = overrides[engine];
}
}
return engineNames;
}
// 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.
// @deprecated Unused in the modern config.
var fetchRegionDefault = (ss, awaitRegionCheck) =>
new Promise(resolve => {
let urlTemplate = Services.prefs
.getDefaultBranch(SearchUtils.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 = Services.prefs.getCharPref(cohortPref, "");
if (cohort) {
endpoint += "/" + cohort;
}
SearchUtils.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) {
SearchUtils.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 || {};
SearchUtils.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);
SearchUtils.log(
"fetchRegionDefault saved searchDefault: " + defaultEngine
);
}
if (response.settings && response.settings.visibleDefaultEngines) {
let visibleDefaultEngines = response.settings.visibleDefaultEngines;
let string = visibleDefaultEngines.join(",");
ss.setVerifiedGlobalAttr("visibleDefaultEngines", string);
SearchUtils.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);
SearchUtils.log(
"fetchRegionDefault got success response in " + took + "ms"
);
// If we're doing this somewhere during the app's lifetime, reload the list
// of engines in order to pick up any geo-specific changes.
ss._maybeReloadEngines(awaitRegionCheck).finally(resolve);
};
request.ontimeout = function(event) {
SearchUtils.log("fetchRegionDefault: XHR finally timed-out");
resolve();
};
request.onerror = function(event) {
SearchUtils.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();
});
/**
* Wrapper for nsIPrefBranch::getComplexValue.
* @param {string} prefName
* The name of the pref to get.
* @param {*} defaultValue
* The value to return if the preference isn't found.
* @returns {*}
* Returns either the preference value, or the default value.
*/
function getLocalizedPref(prefName, defaultValue) {
try {
return Services.prefs.getComplexValue(prefName, Ci.nsIPrefLocalizedString)
.data;
} catch (ex) {}
return defaultValue;
}
var gInitialized = false;
var gReinitializing = false;
// nsISearchParseSubmissionResult
function ParseSubmissionResult(engine, terms, termsOffset, termsLength) {
this._engine = engine;
this._terms = terms;
this._termsOffset = termsOffset;
this._termsLength = termsLength;
}
ParseSubmissionResult.prototype = {
get engine() {
return this._engine;
},
get terms() {
return this._terms;
},
get termsOffset() {
return this._termsOffset;
},
get termsLength() {
return this._termsLength;
},
QueryInterface: ChromeUtils.generateQI([Ci.nsISearchParseSubmissionResult]),
};
const gEmptyParseSubmissionResult = Object.freeze(
new ParseSubmissionResult(null, "", -1, 0)
);
/**
* The search service handles loading and maintaining of search engines. It will
* also work out the default lists for each locale/region.
*
* @implements {nsISearchService}
*/
function SearchService() {
this._initObservers = PromiseUtils.defer();
this._engines = new Map();
}
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,
// The engine selector singleton that is managing the engine configuration.
_engineSelector: null,
_ensureKnownRegionPromise: 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,
/**
* Various search engines may be ignored if their submission urls contain a
* string that is in the list. The list is controlled via remote settings.
*/
_submissionURLIgnoreList: [],
/**
* Various search engines may be ignored if their load path is contained
* in this list. The list is controlled via remote settings.
*/
_loadPathIgnoreList: [],
/**
* A map of engine display names to `SearchEngine`.
*/
_engines: null,
/**
* An array of engine short names sorted into display order.
*/
__sortedEngines: null,
/**
* This holds the current list of visible engines from the configuration,
* and is used to update the cache. If the cache value is different to those
* in the configuration, then the configuration has changed. The engines
* are loaded using both the new set, and the user's current set (if they
* still exist).
* @deprecated Unused in the modern configuration.
*/
_visibleDefaultEngines: [],
/**
* An object containing the {id, locale} of the WebExtension for the default
* engine, as suggested by the configuration.
* For the legacy configuration, this is the user visible name.
*/
_searchDefault: null,
/**
* An object containing the {id, locale} of the WebExtension for the default
* engine for private browsing mode, as suggested by the configuration.
* For the legacy configuration, this is the user visible name.
*/
_searchPrivateDefault: null,
/**
* The suggested order of engines from the configuration.
* For modern configuration:
* This is an array of objects containing the WebExtension ID and Locale.
* This is only needed whilst we investigate issues with cache corruption
* (bug 1589710).
* For legacy configuration:
* This is an array of strings which are the display name of the engines.
*/
_searchOrder: [],
/**
* A Set of installed search extensions reported by AddonManager
* startup before SearchSevice has started. Will be installed
* during init().
*/
_startupExtensions: new Set(),
/**
* The current metadata stored in the cache. This stores:
* - current
* The current user-set default engine. The associated hash is called
* 'hash'.
* - private
* The current user-set private engine. The associated hash is called
* 'privateHash'.
* - searchDefault
* The current default engine (if any) specified by the region server.
* - searchDefaultExpir
* The expiry time for the default engine when the region server should
* be re-checked.
* - visibleDefaultEngines
* The list of visible default engines supplied by the region server.
*
* All of the above except `searchDefaultExpir` have associated hash fields
* to validate the value is set by the application.
*/
_metaData: {},
// This reflects the combined values of the prefs for enabling the separate
// private default UI, and for the user choosing a separate private engine.
// If either one is disabled, then we don't enable the separate private default.
get _separatePrivateDefault() {
return (
this._separatePrivateDefaultPrefValue &&
this._separatePrivateDefaultEnabledPrefValue
);
},
/**
* Resets the locally stored data to the original empty values in preparation
* for a reinit or a reset.
*/
_resetLocalData() {
this._engines.clear();
this.__sortedEngines = null;
this._currentEngine = null;
this._currentPrivateEngine = null;
this._visibleDefaultEngines = [];
this._searchDefault = null;
this._searchPrivateDefault = null;
this._searchOrder = [];
this._metaData = {};
this._maybeReloadDebounce = false;
},
// If initialization has not been completed yet, perform synchronous
// initialization.
// Throws in case of initialization error.
_ensureInitialized() {
if (gInitialized) {
if (!Components.isSuccessCode(this._initRV)) {
SearchUtils.log("_ensureInitialized: failure");
throw Components.Exception(
"SearchService previously failed to initialize",
this._initRV
);
}
return;
}
let err = new Error(
"Something tried to use the search service before it's been " +
"properly intialized. Please examine the stack trace to figure out what and " +
"where to fix it:\n"
);
err.message += err.stack;
throw err;
},
/**
* Asynchronous implementation of the initializer.
*
* @param {boolean} [awaitRegionCheck]
* Indicates whether we should explicitly await the the region check process to
* complete, which may be fetched remotely. Pass in `true` if the caller needs
* to be absolutely certain of the correct default engine and/ or ordering of
* visible engines.
* @returns {number}
* A Components.results success code on success, otherwise a failure code.
*/
async _init(awaitRegionCheck) {
SearchUtils.log("_init start");
XPCOMUtils.defineLazyPreferenceGetter(
this,
"_separatePrivateDefaultPrefValue",
SearchUtils.BROWSER_SEARCH_PREF + "separatePrivateDefault",
false,
this._onSeparateDefaultPrefChanged.bind(this)
);
XPCOMUtils.defineLazyPreferenceGetter(
this,
"_separatePrivateDefaultEnabledPrefValue",
SearchUtils.BROWSER_SEARCH_PREF + "separatePrivateDefault.ui.enabled",
false,
this._onSeparateDefaultPrefChanged.bind(this)
);
try {
if (gModernConfig) {
// Create the search engine selector.
this._engineSelector = new SearchEngineSelector(
this._handleConfigurationUpdated.bind(this)
);
}
// See if we have a cache file so we don't have to parse a bunch of XML.
let cache = await this._readCacheFile();
// The init flow is not going to block on a fetch from an external service,
// but we're kicking it off as soon as possible to prevent UI flickering as
// much as possible.
this._ensureKnownRegionPromise = ensureKnownRegion(this, awaitRegionCheck)
.catch(ex =>
SearchUtils.log("_init: failure determining region: " + ex)
)
.finally(() => (this._ensureKnownRegionPromise = null));
if (awaitRegionCheck) {
await this._ensureKnownRegionPromise;
}
this._setupRemoteSettings().catch(Cu.reportError);
await this._loadEngines(cache);
// If we've got this far, but the application is now shutting down,
// then we need to abandon any further work, especially not writing
// the cache. We do this, because the add-on manager has also
// started shutting down and as a result, we might have an incomplete
// picture of the installed search engines. Writing the cache at
// this stage would potentially mean the user would loose their engine
// data.
// We will however, rebuild the cache on next start up if we detect
// it is necessary.
if (Services.startup.shuttingDown) {
SearchUtils.log("_init: abandoning init due to shutting down");
this._initRV = Cr.NS_ERROR_ABORT;
this._initObservers.reject(this._initRV);
return this._initRV;
}
// Make sure the current list of engines is persisted, without the need to wait.
SearchUtils.log("_init: engines loaded, writing cache");
this._buildCache();
this._addObservers();
} catch (ex) {
this._initRV = ex.result !== undefined ? ex.result : Cr.NS_ERROR_FAILURE;
SearchUtils.log(
"_init: failure initializing search: " + ex + "\n" + ex.stack
);
}
gInitialized = true;
if (Components.isSuccessCode(this._initRV)) {
this._initObservers.resolve(this._initRV);
} else {
this._initObservers.reject(this._initRV);
}
Services.obs.notifyObservers(
null,
SearchUtils.TOPIC_SEARCH_SERVICE,
"init-complete"
);
SearchUtils.log("_init: Completed _init");
return this._initRV;
},
/**
* Obtains the remote settings for the search service. This should only be
* called from init(). Any subsequent updates to the remote settings are
* handled via a sync listener.
*
* For desktop, the initial remote settings are obtained from dumps in
* `services/settings/dumps/main/`.
*
* When enabling for Android, be aware the dumps are not shipped there, and
* hence the `get` may take a while to return.
*/
async _setupRemoteSettings() {
// Now we have the values, listen for future updates.
this._ignoreListListener = this._handleIgnoreListUpdated.bind(this);
const current = await IgnoreLists.getAndSubscribe(this._ignoreListListener);
await this._handleIgnoreListUpdated({ data: { current } });
Services.obs.notifyObservers(
null,
SearchUtils.TOPIC_SEARCH_SERVICE,
"settings-update-complete"
);
},
/**
* This handles updating of the ignore list settings, and removing any ignored
* engines.
*
* @param {object} eventData
* The event in the format received from RemoteSettings.
*/
async _handleIgnoreListUpdated(eventData) {
SearchUtils.log("_handleIgnoreListUpdated");
const {
data: { current },
} = eventData;
for (const entry of current) {
if (entry.id == "load-paths") {
this._loadPathIgnoreList = [...entry.matches];
} else if (entry.id == "submission-urls") {
this._submissionURLIgnoreList = [...entry.matches];
}
}
// If we have not finished initializing, then we wait for the initialization
// to complete.
if (!this.isInitialized) {
await this._initObservers;
}
// We try to remove engines manually, as this should be more efficient and
// we don't really want to cause a re-init as this upsets unit tests.
let engineRemoved = false;
for (let engine of this._engines.values()) {
if (this._engineMatchesIgnoreLists(engine)) {
await this.removeEngine(engine);
engineRemoved = true;
}
}
// If we've removed an engine, and we don't have any left, we need to do
// a re-init - it is possible the cache just had one engine in it, and that
// is now empty, so we need to load from our main list.
if (engineRemoved && !this._engines.size) {
this._reInit();
}
},
/**
* Determines if a given engine matches the ignorelists or not.
*
* @param {Engine} engine
* The engine to check against the ignorelists.
* @returns {boolean}
* Returns true if the engine matches a ignorelists entry.
*/
_engineMatchesIgnoreLists(engine) {
if (this._loadPathIgnoreList.includes(engine._loadPath)) {
return true;
}
let url = engine
._getURLOfType("text/html")
.getSubmission("dummy", engine)
.uri.spec.toLowerCase();
if (
this._submissionURLIgnoreList.some(code =>
url.includes(code.toLowerCase())
)
) {
return true;
}
return false;
},
/**
* Handles the search configuration being - adds a wait on the user
* being idle, before the search engine update gets handled.
*/
_handleConfigurationUpdated() {
if (this._queuedIdle) {
return;
}
this._queuedIdle = true;
this.idleService.addIdleObserver(this, REINIT_IDLE_TIME_SEC);
},
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)) {
SearchUtils.log("getVerifiedGlobalAttr, invalid hash for " + name);
return "";
}
return val;
},
_listJSONURL: `${EXT_SEARCH_PREFIX}list.json`,
get _sortedEngines() {
if (!this.__sortedEngines) {
return this._buildSortedEngineList();
}
return this.__sortedEngines;
},
/**
* Returns the engine that is the default for this locale/region, ignoring any
* user changes to the default engine.
*
* @param {boolean} privateMode
* Set to true to return the default engine in private mode,
* false for normal mode.
* @returns {SearchEngine}
* The engine that is default.
*/
_originalDefaultEngine(privateMode = false) {
// The modern configuration doesn't need the verified attributes from the
// cache as we can calculate it all on startup anyway from the engines
// configuration.
if (gModernConfig) {
// We only allow the old defaultenginename pref for distributions.
// We can't use `isPartnerBuild` because we need to allow reading
// of the defaultenginename pref for funnelcakes.
if (SearchUtils.distroID && !privateMode) {
let defaultPrefB = Services.prefs.getDefaultBranch(
SearchUtils.BROWSER_SEARCH_PREF
);
try {
let defaultEngineName = defaultPrefB.getComplexValue(
"defaultenginename",
Ci.nsIPrefLocalizedString
).data;
let defaultEngine = this.getEngineByName(defaultEngineName);
if (defaultEngine) {
return defaultEngine;
}
} catch (ex) {
// If the default pref is invalid (e.g. an add-on set it to a bogus value)
// we'll fallback and use the default engine from the configuration.
// Worst case, getEngineByName will just return null, which is the best we can do.
}
}
// If we got this far, the distro hasn't set the default engine, so
// get it from the configuration.
let defaultEngine = this._getEngineByWebExtensionDetails(
privateMode && this._searchPrivateDefault
? this._searchPrivateDefault
: this._searchDefault
);
if (defaultEngine) {
return defaultEngine;
}
if (privateMode) {
// If for some reason we can't find the private mode engine, fall back
// to the non-private one.
return this._originalDefaultEngine(false);
}
// Something unexpected as happened. In order to recover the original
// default engine, use the first visible engine which is the best we can do.
return this._getSortedEngines(false)[0];
}
// Legacy configuration
let defaultEngineName = this.getVerifiedGlobalAttr(
privateMode ? "searchDefaultPrivate" : "searchDefault"
);
if (!defaultEngineName) {
// We only allow the old defaultenginename pref for distributions
// We can't use isPartnerBuild because we need to allow reading
// of the defaultengine name pref for funnelcakes.