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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
|
/* 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/. */
ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.import("resource://gre/modules/ContentPrefUtils.jsm");
ChromeUtils.import("resource://gre/modules/ContentPrefStore.jsm");
const CACHE_MAX_GROUP_ENTRIES = 100;
const GROUP_CLAUSE = `
SELECT id
FROM groups
WHERE name = :group OR
(:includeSubdomains AND name LIKE :pattern ESCAPE '/')
`;
function ContentPrefService2() {
if (Services.appinfo.processType === Services.appinfo.PROCESS_TYPE_CONTENT) {
return ChromeUtils.import("resource://gre/modules/ContentPrefServiceChild.jsm")
.ContentPrefServiceChild;
}
// If this throws an exception, it causes the getService call to fail,
// but the next time a consumer tries to retrieve the service, we'll try
// to initialize the database again, which might work if the failure
// was due to a temporary condition (like being out of disk space).
this._dbInit();
Services.obs.addObserver(this, "last-pb-context-exited");
// Observe shutdown so we can shut down the database connection.
Services.obs.addObserver(this, "xpcom-shutdown");
}
const cache = new ContentPrefStore();
cache.set = function CPS_cache_set(group, name, val) {
Object.getPrototypeOf(this).set.apply(this, arguments);
let groupCount = this._groups.size;
if (groupCount >= CACHE_MAX_GROUP_ENTRIES) {
// Clean half of the entries
for (let [group, name, ] of this) {
this.remove(group, name);
groupCount--;
if (groupCount < CACHE_MAX_GROUP_ENTRIES / 2)
break;
}
}
};
const privModeStorage = new ContentPrefStore();
ContentPrefService2.prototype = {
// XPCOM Plumbing
classID: Components.ID("{e3f772f3-023f-4b32-b074-36cf0fd5d414}"),
// Destruction
_destroy: function ContentPrefService__destroy() {
Services.obs.removeObserver(this, "xpcom-shutdown");
Services.obs.removeObserver(this, "last-pb-context-exited");
this.destroy();
this._dbConnection.asyncClose(() => {
Services.obs.notifyObservers(null, "content-prefs-db-closed");
});
// Delete references to XPCOM components to make sure we don't leak them
// (although we haven't observed leakage in tests). Also delete references
// in _observers and _genericObservers to avoid cycles with those that
// refer to us and don't remove themselves from those observer pools.
delete this._observers;
delete this._genericObservers;
delete this.__grouper;
},
// in-memory cache and private-browsing stores
_cache: cache,
_pbStore: privModeStorage,
// nsIContentPrefService
getByName: function CPS2_getByName(name, context, callback) {
checkNameArg(name);
checkCallbackArg(callback, true);
// Some prefs may be in both the database and the private browsing store.
// Notify the caller of such prefs only once, using the values from private
// browsing.
let pbPrefs = new ContentPrefStore();
if (context && context.usePrivateBrowsing) {
for (let [sgroup, sname, val] of this._pbStore) {
if (sname == name) {
pbPrefs.set(sgroup, sname, val);
}
}
}
let stmt1 = this._stmt(`
SELECT groups.name AS grp, prefs.value AS value
FROM prefs
JOIN settings ON settings.id = prefs.settingID
JOIN groups ON groups.id = prefs.groupID
WHERE settings.name = :name
`);
stmt1.params.name = name;
let stmt2 = this._stmt(`
SELECT NULL AS grp, prefs.value AS value
FROM prefs
JOIN settings ON settings.id = prefs.settingID
WHERE settings.name = :name AND prefs.groupID ISNULL
`);
stmt2.params.name = name;
this._execStmts([stmt1, stmt2], {
onRow: function onRow(row) {
let grp = row.getResultByName("grp");
let val = row.getResultByName("value");
this._cache.set(grp, name, val);
if (!pbPrefs.has(grp, name))
cbHandleResult(callback, new ContentPref(grp, name, val));
},
onDone: function onDone(reason, ok, gotRow) {
if (ok) {
for (let [pbGroup, pbName, pbVal] of pbPrefs) {
cbHandleResult(callback, new ContentPref(pbGroup, pbName, pbVal));
}
}
cbHandleCompletion(callback, reason);
},
onError: function onError(nsresult) {
cbHandleError(callback, nsresult);
}
});
},
getByDomainAndName: function CPS2_getByDomainAndName(group, name, context,
callback) {
checkGroupArg(group);
this._get(group, name, false, context, callback);
},
getBySubdomainAndName: function CPS2_getBySubdomainAndName(group, name,
context,
callback) {
checkGroupArg(group);
this._get(group, name, true, context, callback);
},
getGlobal: function CPS2_getGlobal(name, context, callback) {
this._get(null, name, false, context, callback);
},
_get: function CPS2__get(group, name, includeSubdomains, context, callback) {
group = this._parseGroup(group);
checkNameArg(name);
checkCallbackArg(callback, true);
// Some prefs may be in both the database and the private browsing store.
// Notify the caller of such prefs only once, using the values from private
// browsing.
let pbPrefs = new ContentPrefStore();
if (context && context.usePrivateBrowsing) {
for (let [sgroup, val] of
this._pbStore.match(group, name, includeSubdomains)) {
pbPrefs.set(sgroup, name, val);
}
}
this._execStmts([this._commonGetStmt(group, name, includeSubdomains)], {
onRow: function onRow(row) {
let grp = row.getResultByName("grp");
let val = row.getResultByName("value");
this._cache.set(grp, name, val);
if (!pbPrefs.has(group, name))
cbHandleResult(callback, new ContentPref(grp, name, val));
},
onDone: function onDone(reason, ok, gotRow) {
if (ok) {
if (!gotRow)
this._cache.set(group, name, undefined);
for (let [pbGroup, pbName, pbVal] of pbPrefs) {
cbHandleResult(callback, new ContentPref(pbGroup, pbName, pbVal));
}
}
cbHandleCompletion(callback, reason);
},
onError: function onError(nsresult) {
cbHandleError(callback, nsresult);
}
});
},
_commonGetStmt: function CPS2__commonGetStmt(group, name, includeSubdomains) {
let stmt = group ?
this._stmtWithGroupClause(group, includeSubdomains, `
SELECT groups.name AS grp, prefs.value AS value
FROM prefs
JOIN settings ON settings.id = prefs.settingID
JOIN groups ON groups.id = prefs.groupID
WHERE settings.name = :name AND prefs.groupID IN (${GROUP_CLAUSE})
`) :
this._stmt(`
SELECT NULL AS grp, prefs.value AS value
FROM prefs
JOIN settings ON settings.id = prefs.settingID
WHERE settings.name = :name AND prefs.groupID ISNULL
`);
stmt.params.name = name;
return stmt;
},
_stmtWithGroupClause: function CPS2__stmtWithGroupClause(group,
includeSubdomains,
sql) {
let stmt = this._stmt(sql);
stmt.params.group = group;
stmt.params.includeSubdomains = includeSubdomains || false;
stmt.params.pattern = "%." + stmt.escapeStringForLIKE(group, "/");
return stmt;
},
getCachedByDomainAndName: function CPS2_getCachedByDomainAndName(group,
name,
context) {
checkGroupArg(group);
let prefs = this._getCached(group, name, false, context);
return prefs[0] || null;
},
getCachedBySubdomainAndName: function CPS2_getCachedBySubdomainAndName(group,
name,
context,
len) {
checkGroupArg(group);
let prefs = this._getCached(group, name, true, context);
if (len)
len.value = prefs.length;
return prefs;
},
getCachedGlobal: function CPS2_getCachedGlobal(name, context) {
let prefs = this._getCached(null, name, false, context);
return prefs[0] || null;
},
_getCached: function CPS2__getCached(group, name, includeSubdomains,
context) {
group = this._parseGroup(group);
checkNameArg(name);
let storesToCheck = [this._cache];
if (context && context.usePrivateBrowsing)
storesToCheck.push(this._pbStore);
let outStore = new ContentPrefStore();
storesToCheck.forEach(function(store) {
for (let [sgroup, val] of store.match(group, name, includeSubdomains)) {
outStore.set(sgroup, name, val);
}
});
let prefs = [];
for (let [sgroup, sname, val] of outStore) {
prefs.push(new ContentPref(sgroup, sname, val));
}
return prefs;
},
set: function CPS2_set(group, name, value, context, callback) {
checkGroupArg(group);
this._set(group, name, value, context, callback);
},
setGlobal: function CPS2_setGlobal(name, value, context, callback) {
this._set(null, name, value, context, callback);
},
_set: function CPS2__set(group, name, value, context, callback) {
group = this._parseGroup(group);
checkNameArg(name);
checkValueArg(value);
checkCallbackArg(callback, false);
if (context && context.usePrivateBrowsing) {
this._pbStore.set(group, name, value);
this._schedule(function() {
cbHandleCompletion(callback, Ci.nsIContentPrefCallback2.COMPLETE_OK);
this._notifyPrefSet(group, name, value, context.usePrivateBrowsing);
});
return;
}
// Invalidate the cached value so consumers accessing the cache between now
// and when the operation finishes don't get old data.
this._cache.remove(group, name);
let stmts = [];
// Create the setting if it doesn't exist.
let stmt = this._stmt(`
INSERT OR IGNORE INTO settings (id, name)
VALUES((SELECT id FROM settings WHERE name = :name), :name)
`);
stmt.params.name = name;
stmts.push(stmt);
// Create the group if it doesn't exist.
if (group) {
stmt = this._stmt(`
INSERT OR IGNORE INTO groups (id, name)
VALUES((SELECT id FROM groups WHERE name = :group), :group)
`);
stmt.params.group = group;
stmts.push(stmt);
}
// Finally create or update the pref.
if (group) {
stmt = this._stmt(`
INSERT OR REPLACE INTO prefs (id, groupID, settingID, value, timestamp)
VALUES(
(SELECT prefs.id
FROM prefs
JOIN groups ON groups.id = prefs.groupID
JOIN settings ON settings.id = prefs.settingID
WHERE groups.name = :group AND settings.name = :name),
(SELECT id FROM groups WHERE name = :group),
(SELECT id FROM settings WHERE name = :name),
:value,
:now
)
`);
stmt.params.group = group;
} else {
stmt = this._stmt(`
INSERT OR REPLACE INTO prefs (id, groupID, settingID, value, timestamp)
VALUES(
(SELECT prefs.id
FROM prefs
JOIN settings ON settings.id = prefs.settingID
WHERE prefs.groupID IS NULL AND settings.name = :name),
NULL,
(SELECT id FROM settings WHERE name = :name),
:value,
:now
)
`);
}
stmt.params.name = name;
stmt.params.value = value;
stmt.params.now = Date.now() / 1000;
stmts.push(stmt);
this._execStmts(stmts, {
onDone: function onDone(reason, ok) {
if (ok)
this._cache.setWithCast(group, name, value);
cbHandleCompletion(callback, reason);
if (ok)
this._notifyPrefSet(group, name, value, context && context.usePrivateBrowsing);
},
onError: function onError(nsresult) {
cbHandleError(callback, nsresult);
}
});
},
removeByDomainAndName: function CPS2_removeByDomainAndName(group, name,
context,
callback) {
checkGroupArg(group);
this._remove(group, name, false, context, callback);
},
removeBySubdomainAndName: function CPS2_removeBySubdomainAndName(group, name,
context,
callback) {
checkGroupArg(group);
this._remove(group, name, true, context, callback);
},
removeGlobal: function CPS2_removeGlobal(name, context, callback) {
this._remove(null, name, false, context, callback);
},
_remove: function CPS2__remove(group, name, includeSubdomains, context,
callback) {
group = this._parseGroup(group);
checkNameArg(name);
checkCallbackArg(callback, false);
// Invalidate the cached values so consumers accessing the cache between now
// and when the operation finishes don't get old data.
for (let sgroup of this._cache.matchGroups(group, includeSubdomains)) {
this._cache.remove(sgroup, name);
}
let stmts = [];
// First get the matching prefs.
stmts.push(this._commonGetStmt(group, name, includeSubdomains));
// Delete the matching prefs.
let stmt = this._stmtWithGroupClause(group, includeSubdomains, `
DELETE FROM prefs
WHERE settingID = (SELECT id FROM settings WHERE name = :name) AND
CASE typeof(:group)
WHEN 'null' THEN prefs.groupID IS NULL
ELSE prefs.groupID IN (${GROUP_CLAUSE})
END
`);
stmt.params.name = name;
stmts.push(stmt);
stmts = stmts.concat(this._settingsAndGroupsCleanupStmts());
let prefs = new ContentPrefStore();
let isPrivate = context && context.usePrivateBrowsing;
this._execStmts(stmts, {
onRow: function onRow(row) {
let grp = row.getResultByName("grp");
prefs.set(grp, name, undefined);
this._cache.set(grp, name, undefined);
},
onDone: function onDone(reason, ok) {
if (ok) {
this._cache.set(group, name, undefined);
if (isPrivate) {
for (let [sgroup, ] of
this._pbStore.match(group, name, includeSubdomains)) {
prefs.set(sgroup, name, undefined);
this._pbStore.remove(sgroup, name);
}
}
}
cbHandleCompletion(callback, reason);
if (ok) {
for (let [sgroup, , ] of prefs) {
this._notifyPrefRemoved(sgroup, name, isPrivate);
}
}
},
onError: function onError(nsresult) {
cbHandleError(callback, nsresult);
}
});
},
// Deletes settings and groups that are no longer used.
_settingsAndGroupsCleanupStmts() {
// The NOTNULL term in the subquery of the second statment is needed because of
// SQLite's weird IN behavior vis-a-vis NULLs. See http://sqlite.org/lang_expr.html.
return [
this._stmt(`
DELETE FROM settings
WHERE id NOT IN (SELECT DISTINCT settingID FROM prefs)
`),
this._stmt(`
DELETE FROM groups WHERE id NOT IN (
SELECT DISTINCT groupID FROM prefs WHERE groupID NOTNULL
)
`)
];
},
removeByDomain: function CPS2_removeByDomain(group, context, callback) {
checkGroupArg(group);
this._removeByDomain(group, false, context, callback);
},
removeBySubdomain: function CPS2_removeBySubdomain(group, context, callback) {
checkGroupArg(group);
this._removeByDomain(group, true, context, callback);
},
removeAllGlobals: function CPS2_removeAllGlobals(context, callback) {
this._removeByDomain(null, false, context, callback);
},
_removeByDomain: function CPS2__removeByDomain(group, includeSubdomains,
context, callback) {
group = this._parseGroup(group);
checkCallbackArg(callback, false);
// Invalidate the cached values so consumers accessing the cache between now
// and when the operation finishes don't get old data.
for (let sgroup of this._cache.matchGroups(group, includeSubdomains)) {
this._cache.removeGroup(sgroup);
}
let stmts = [];
// First get the matching prefs, then delete groups and prefs that reference
// deleted groups.
if (group) {
stmts.push(this._stmtWithGroupClause(group, includeSubdomains, `
SELECT groups.name AS grp, settings.name AS name
FROM prefs
JOIN settings ON settings.id = prefs.settingID
JOIN groups ON groups.id = prefs.groupID
WHERE prefs.groupID IN (${GROUP_CLAUSE})
`));
stmts.push(this._stmtWithGroupClause(group, includeSubdomains,
`DELETE FROM groups WHERE id IN (${GROUP_CLAUSE})`
));
stmts.push(this._stmt(`
DELETE FROM prefs
WHERE groupID NOTNULL AND groupID NOT IN (SELECT id FROM groups)
`));
} else {
stmts.push(this._stmt(`
SELECT NULL AS grp, settings.name AS name
FROM prefs
JOIN settings ON settings.id = prefs.settingID
WHERE prefs.groupID IS NULL
`));
stmts.push(this._stmt(
"DELETE FROM prefs WHERE groupID IS NULL"
));
}
// Finally delete settings that are no longer referenced.
stmts.push(this._stmt(`
DELETE FROM settings
WHERE id NOT IN (SELECT DISTINCT settingID FROM prefs)
`));
let prefs = new ContentPrefStore();
let isPrivate = context && context.usePrivateBrowsing;
this._execStmts(stmts, {
onRow: function onRow(row) {
let grp = row.getResultByName("grp");
let name = row.getResultByName("name");
prefs.set(grp, name, undefined);
this._cache.set(grp, name, undefined);
},
onDone: function onDone(reason, ok) {
if (ok && isPrivate) {
for (let [sgroup, sname, ] of this._pbStore) {
if (!group ||
(!includeSubdomains && group == sgroup) ||
(includeSubdomains && sgroup && this._pbStore.groupsMatchIncludingSubdomains(group, sgroup))) {
prefs.set(sgroup, sname, undefined);
this._pbStore.remove(sgroup, sname);
}
}
}
cbHandleCompletion(callback, reason);
if (ok) {
for (let [sgroup, sname, ] of prefs) {
this._notifyPrefRemoved(sgroup, sname, isPrivate);
}
}
},
onError: function onError(nsresult) {
cbHandleError(callback, nsresult);
}
});
},
_removeAllDomainsSince: function CPS2__removeAllDomainsSince(since, context, callback) {
checkCallbackArg(callback, false);
since /= 1000;
// Invalidate the cached values so consumers accessing the cache between now
// and when the operation finishes don't get old data.
// Invalidate all the group cache because we don't know which groups will be removed.
this._cache.removeAllGroups();
let stmts = [];
// Get prefs that are about to be removed to notify about their removal.
let stmt = this._stmt(`
SELECT groups.name AS grp, settings.name AS name
FROM prefs
JOIN settings ON settings.id = prefs.settingID
JOIN groups ON groups.id = prefs.groupID
WHERE timestamp >= :since
`);
stmt.params.since = since;
stmts.push(stmt);
// Do the actual remove.
stmt = this._stmt(`
DELETE FROM prefs WHERE groupID NOTNULL AND timestamp >= :since
`);
stmt.params.since = since;
stmts.push(stmt);
// Cleanup no longer used values.
stmts = stmts.concat(this._settingsAndGroupsCleanupStmts());
let prefs = new ContentPrefStore();
let isPrivate = context && context.usePrivateBrowsing;
this._execStmts(stmts, {
onRow: function onRow(row) {
let grp = row.getResultByName("grp");
let name = row.getResultByName("name");
prefs.set(grp, name, undefined);
this._cache.set(grp, name, undefined);
},
onDone: function onDone(reason, ok) {
// This nukes all the groups in _pbStore since we don't have their timestamp
// information.
if (ok && isPrivate) {
for (let [sgroup, sname, ] of this._pbStore) {
if (sgroup) {
prefs.set(sgroup, sname, undefined);
}
}
this._pbStore.removeAllGroups();
}
cbHandleCompletion(callback, reason);
if (ok) {
for (let [sgroup, sname, ] of prefs) {
this._notifyPrefRemoved(sgroup, sname, isPrivate);
}
}
},
onError: function onError(nsresult) {
cbHandleError(callback, nsresult);
}
});
},
removeAllDomainsSince: function CPS2_removeAllDomainsSince(since, context, callback) {
this._removeAllDomainsSince(since, context, callback);
},
removeAllDomains: function CPS2_removeAllDomains(context, callback) {
this._removeAllDomainsSince(0, context, callback);
},
removeByName: function CPS2_removeByName(name, context, callback) {
checkNameArg(name);
checkCallbackArg(callback, false);
// Invalidate the cached values so consumers accessing the cache between now
// and when the operation finishes don't get old data.
for (let [group, sname, ] of this._cache) {
if (sname == name)
this._cache.remove(group, name);
}
let stmts = [];
// First get the matching prefs. Include null if any of those prefs are
// global.
let stmt = this._stmt(`
SELECT groups.name AS grp
FROM prefs
JOIN settings ON settings.id = prefs.settingID
JOIN groups ON groups.id = prefs.groupID
WHERE settings.name = :name
UNION
SELECT NULL AS grp
WHERE EXISTS (
SELECT prefs.id
FROM prefs
JOIN settings ON settings.id = prefs.settingID
WHERE settings.name = :name AND prefs.groupID IS NULL
)
`);
stmt.params.name = name;
stmts.push(stmt);
// Delete the target settings.
stmt = this._stmt(
"DELETE FROM settings WHERE name = :name"
);
stmt.params.name = name;
stmts.push(stmt);
// Delete prefs and groups that are no longer used.
stmts.push(this._stmt(
"DELETE FROM prefs WHERE settingID NOT IN (SELECT id FROM settings)"
));
stmts.push(this._stmt(`
DELETE FROM groups WHERE id NOT IN (
SELECT DISTINCT groupID FROM prefs WHERE groupID NOTNULL
)
`));
let prefs = new ContentPrefStore();
let isPrivate = context && context.usePrivateBrowsing;
this._execStmts(stmts, {
onRow: function onRow(row) {
let grp = row.getResultByName("grp");
prefs.set(grp, name, undefined);
this._cache.set(grp, name, undefined);
},
onDone: function onDone(reason, ok) {
if (ok && isPrivate) {
for (let [sgroup, sname, ] of this._pbStore) {
if (sname === name) {
prefs.set(sgroup, name, undefined);
this._pbStore.remove(sgroup, name);
}
}
}
cbHandleCompletion(callback, reason);
if (ok) {
for (let [sgroup, , ] of prefs) {
this._notifyPrefRemoved(sgroup, name, isPrivate);
}
}
},
onError: function onError(nsresult) {
cbHandleError(callback, nsresult);
}
});
},
destroy: function CPS2_destroy() {
if (this._statements) {
for (let sql in this._statements) {
let stmt = this._statements[sql];
stmt.finalize();
}
}
},
/**
* Returns the cached mozIStorageAsyncStatement for the given SQL. If no such
* statement is cached, one is created and cached.
*
* @param sql The SQL query string.
* @return The cached, possibly new, statement.
*/
_stmt: function CPS2__stmt(sql) {
if (!this._statements)
this._statements = {};
if (!this._statements[sql])
this._statements[sql] = this._dbConnection.createAsyncStatement(sql);
return this._statements[sql];
},
/**
* Executes some async statements.
*
* @param stmts An array of mozIStorageAsyncStatements.
* @param callbacks An object with the following methods:
* onRow(row) (optional)
* Called once for each result row.
* row: A mozIStorageRow.
* onDone(reason, reasonOK, didGetRow) (required)
* Called when done.
* reason: A nsIContentPrefService2.COMPLETE_* value.
* reasonOK: reason == nsIContentPrefService2.COMPLETE_OK.
* didGetRow: True if onRow was ever called.
* onError(nsresult) (optional)
* Called on error.
* nsresult: The error code.
*/
_execStmts: function CPS2__execStmts(stmts, callbacks) {
let self = this;
let gotRow = false;
this._dbConnection.executeAsync(stmts, stmts.length, {
handleResult: function handleResult(results) {
try {
let row = null;
while ((row = results.getNextRow())) {
gotRow = true;
if (callbacks.onRow)
callbacks.onRow.call(self, row);
}
} catch (err) {
Cu.reportError(err);
}
},
handleCompletion: function handleCompletion(reason) {
try {
let ok = reason == Ci.mozIStorageStatementCallback.REASON_FINISHED;
callbacks.onDone.call(self,
ok ? Ci.nsIContentPrefCallback2.COMPLETE_OK :
Ci.nsIContentPrefCallback2.COMPLETE_ERROR,
ok, gotRow);
} catch (err) {
Cu.reportError(err);
}
},
handleError: function handleError(error) {
try {
if (callbacks.onError)
callbacks.onError.call(self, Cr.NS_ERROR_FAILURE);
} catch (err) {
Cu.reportError(err);
}
}
});
},
__grouper: null,
get _grouper() {
if (!this.__grouper)
this.__grouper = Cc["@mozilla.org/content-pref/hostname-grouper;1"].
getService(Ci.nsIContentURIGrouper);
return this.__grouper;
},
/**
* Parses the domain (the "group", to use the database's term) from the given
* string.
*
* @param groupStr Assumed to be either a string or falsey.
* @return If groupStr is a valid URL string, returns the domain of
* that URL. If groupStr is some other nonempty string,
* returns groupStr itself. Otherwise returns null.
*/
_parseGroup: function CPS2__parseGroup(groupStr) {
if (!groupStr)
return null;
try {
var groupURI = Services.io.newURI(groupStr);
} catch (err) {
return groupStr;
}
return this._grouper.group(groupURI);
},
_schedule: function CPS2__schedule(fn) {
Services.tm.dispatchToMainThread(fn.bind(this));
},
// A hash of arrays of observers, indexed by setting name.
_observers: {},
// An array of generic observers, which observe all settings.
_genericObservers: [],
addObserverForName: function CPS2_addObserverForName(aName, aObserver) {
var observers;
if (aName) {
if (!this._observers[aName])
this._observers[aName] = [];
observers = this._observers[aName];
} else
observers = this._genericObservers;
if (!observers.includes(aObserver))
observers.push(aObserver);
},
removeObserverForName: function CPS2_removeObserverForName(aName, aObserver) {
var observers;
if (aName) {
if (!this._observers[aName])
return;
observers = this._observers[aName];
} else
observers = this._genericObservers;
if (observers.includes(aObserver))
observers.splice(observers.indexOf(aObserver), 1);
},
/**
* Construct a list of observers to notify about a change to some setting,
* putting setting-specific observers before before generic ones, so observers
* that initialize individual settings (like the page style controller)
* execute before observers that display multiple settings and depend on them
* being initialized first (like the content prefs sidebar).
*/
_getObservers: function ContentPrefService__getObservers(aName) {
var observers = [];
if (aName && this._observers[aName])
observers = observers.concat(this._observers[aName]);
observers = observers.concat(this._genericObservers);
return observers;
},
/**
* Notify all observers about the removal of a preference.
*/
_notifyPrefRemoved: function ContentPrefService__notifyPrefRemoved(aGroup, aName, aIsPrivate) {
for (var observer of this._getObservers(aName)) {
try {
observer.onContentPrefRemoved(aGroup, aName, aIsPrivate);
} catch (ex) {
Cu.reportError(ex);
}
}
},
/**
* Notify all observers about a preference change.
*/
_notifyPrefSet: function ContentPrefService__notifyPrefSet(aGroup, aName, aValue, aIsPrivate) {
for (var observer of this._getObservers(aName)) {
try {
observer.onContentPrefSet(aGroup, aName, aValue, aIsPrivate);
} catch (ex) {
Cu.reportError(ex);
}
}
},
extractDomain: function CPS2_extractDomain(str) {
return this._parseGroup(str);
},
/**
* Tests use this as a backchannel by calling it directly.
*
* @param subj This value depends on topic.
* @param topic The backchannel "method" name.
* @param data This value depends on topic.
*/
observe: function CPS2_observe(subj, topic, data) {
switch (topic) {
case "xpcom-shutdown":
this._destroy();
break;
case "last-pb-context-exited":
this._pbStore.removeAll();
break;
case "test:reset":
let fn = subj.QueryInterface(Ci.xpcIJSWeakReference).get();
this._reset(fn);
break;
case "test:db":
let obj = subj.QueryInterface(Ci.xpcIJSWeakReference).get();
obj.value = this._dbConnection;
break;
}
},
/**
* Removes all state from the service. Used by tests.
*
* @param callback A function that will be called when done.
*/
_reset: function CPS2__reset(callback) {
this._pbStore.removeAll();
this._cache.removeAll();
this._observers = {};
this._genericObservers = [];
let tables = ["prefs", "groups", "settings"];
let stmts = tables.map(t => this._stmt(`DELETE FROM ${t}`));
this._execStmts(stmts, { onDone: () => callback() });
},
QueryInterface: function CPS2_QueryInterface(iid) {
let supportedIIDs = [
Ci.nsIContentPrefService2,
Ci.nsIObserver,
Ci.nsISupports,
];
if (supportedIIDs.some(i => iid.equals(i)))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
// Database Creation & Access
_dbVersion: 4,
_dbSchema: {
tables: {
groups: "id INTEGER PRIMARY KEY, \
name TEXT NOT NULL",
settings: "id INTEGER PRIMARY KEY, \
name TEXT NOT NULL",
prefs: "id INTEGER PRIMARY KEY, \
groupID INTEGER REFERENCES groups(id), \
settingID INTEGER NOT NULL REFERENCES settings(id), \
value BLOB, \
timestamp INTEGER NOT NULL DEFAULT 0" // Storage in seconds, API in ms. 0 for migrated values.
},
indices: {
groups_idx: {
table: "groups",
columns: ["name"]
},
settings_idx: {
table: "settings",
columns: ["name"]
},
prefs_idx: {
table: "prefs",
columns: ["timestamp", "groupID", "settingID"]
}
}
},
_dbConnection: null,
// _dbInit and the methods it calls (_dbCreate, _dbMigrate, and version-
// specific migration methods) must be careful not to call any method
// of the service that assumes the database connection has already been
// initialized, since it won't be initialized until at the end of _dbInit.
_dbInit: function ContentPrefService__dbInit() {
var dbFile = Services.dirsvc.get("ProfD", Ci.nsIFile);
dbFile.append("content-prefs.sqlite");
var dbConnection;
if (!dbFile.exists())
dbConnection = this._dbCreate(dbFile);
else {
try {
dbConnection = Services.storage.openDatabase(dbFile);
} catch (e) {
// If the connection isn't ready after we open the database, that means
// the database has been corrupted, so we back it up and then recreate it.
if (e.result != Cr.NS_ERROR_FILE_CORRUPTED)
throw e;
dbConnection = this._dbBackUpAndRecreate(dbFile, dbConnection);
}
// Get the version of the schema in the file.
var version = dbConnection.schemaVersion;
// Try to migrate the schema in the database to the current schema used by
// the service. If migration fails, back up the database and recreate it.
if (version != this._dbVersion) {
try {
this._dbMigrate(dbConnection, version, this._dbVersion);
} catch (ex) {
Cu.reportError("error migrating DB: " + ex + "; backing up and recreating");
dbConnection = this._dbBackUpAndRecreate(dbFile, dbConnection);
}
}
}
// Turn off disk synchronization checking to reduce disk churn and speed up
// operations when prefs are changed rapidly (such as when a user repeatedly
// changes the value of the browser zoom setting for a site).
//
// Note: this could cause database corruption if the OS crashes or machine
// loses power before the data gets written to disk, but this is considered
// a reasonable risk for the not-so-critical data stored in this database.
//
// If you really don't want to take this risk, however, just set the
// toolkit.storage.synchronous pref to 1 (NORMAL synchronization) or 2
// (FULL synchronization), in which case mozStorageConnection::Initialize
// will use that value, and we won't override it here.
if (!Services.prefs.prefHasUserValue("toolkit.storage.synchronous"))
dbConnection.executeSimpleSQL("PRAGMA synchronous = OFF");
this._dbConnection = dbConnection;
},
_dbCreate: function ContentPrefService__dbCreate(aDBFile) {
var dbConnection = Services.storage.openDatabase(aDBFile);
try {
this._dbCreateSchema(dbConnection);
dbConnection.schemaVersion = this._dbVersion;
} catch (ex) {
// If we failed to create the database (perhaps because the disk ran out
// of space), then remove the database file so we don't leave it in some
// half-created state from which we won't know how to recover.
dbConnection.close();
aDBFile.remove(false);
throw ex;
}
return dbConnection;
},
_dbCreateSchema: function ContentPrefService__dbCreateSchema(aDBConnection) {
this._dbCreateTables(aDBConnection);
this._dbCreateIndices(aDBConnection);
},
_dbCreateTables: function ContentPrefService__dbCreateTables(aDBConnection) {
for (let name in this._dbSchema.tables)
aDBConnection.createTable(name, this._dbSchema.tables[name]);
},
_dbCreateIndices: function ContentPrefService__dbCreateIndices(aDBConnection) {
for (let name in this._dbSchema.indices) {
let index = this._dbSchema.indices[name];
let statement = `
CREATE INDEX IF NOT EXISTS ${name} ON ${index.table}
(${index.columns.join(", ")})
`;
aDBConnection.executeSimpleSQL(statement);
}
},
_dbBackUpAndRecreate: function ContentPrefService__dbBackUpAndRecreate(aDBFile,
aDBConnection) {
Services.storage.backupDatabaseFile(aDBFile, "content-prefs.sqlite.corrupt");
// Close the database, ignoring the "already closed" exception, if any.
// It'll be open if we're here because of a migration failure but closed
// if we're here because of database corruption.
try { aDBConnection.close(); } catch (ex) {}
aDBFile.remove(false);
let dbConnection = this._dbCreate(aDBFile);
return dbConnection;
},
_dbMigrate: function ContentPrefService__dbMigrate(aDBConnection, aOldVersion, aNewVersion) {
/**
* Migrations should follow the template rules in bug 1074817 comment 3 which are:
* 1. Migration should be incremental and non-breaking.
* 2. It should be idempotent because one can downgrade an upgrade again.
* On downgrade:
* 1. Decrement schema version so that upgrade runs the migrations again.
*/
aDBConnection.beginTransaction();
try {
/**
* If the schema version is 0, that means it was never set, which means
* the database was somehow created without the schema being applied, perhaps
* because the system ran out of disk space (although we check for this
* in _createDB) or because some other code created the database file without
* applying the schema. In any case, recover by simply reapplying the schema.
*/
if (aOldVersion == 0) {
this._dbCreateSchema(aDBConnection);
} else {
for (let i = aOldVersion; i < aNewVersion; i++) {
let migrationName = "_dbMigrate" + i + "To" + (i + 1);
if (typeof this[migrationName] != "function") {
throw new Error("no migrator function from version " + aOldVersion + " to version " +
aNewVersion);
}
this[migrationName](aDBConnection);
}
}
aDBConnection.schemaVersion = aNewVersion;
aDBConnection.commitTransaction();
} catch (ex) {
aDBConnection.rollbackTransaction();
throw ex;
}
},
_dbMigrate1To2: function ContentPrefService___dbMigrate1To2(aDBConnection) {
aDBConnection.executeSimpleSQL("ALTER TABLE groups RENAME TO groupsOld");
aDBConnection.createTable("groups", this._dbSchema.tables.groups);
aDBConnection.executeSimpleSQL(`
INSERT INTO groups (id, name)
SELECT id, name FROM groupsOld
`);
aDBConnection.executeSimpleSQL("DROP TABLE groupers");
aDBConnection.executeSimpleSQL("DROP TABLE groupsOld");
},
_dbMigrate2To3: function ContentPrefService__dbMigrate2To3(aDBConnection) {
this._dbCreateIndices(aDBConnection);
},
_dbMigrate3To4: function ContentPrefService__dbMigrate3To4(aDBConnection) {
// Add timestamp column if it does not exist yet. This operation is idempotent.
try {
let stmt = aDBConnection.createStatement("SELECT timestamp FROM prefs");
stmt.finalize();
} catch (e) {
aDBConnection.executeSimpleSQL("ALTER TABLE prefs ADD COLUMN timestamp INTEGER NOT NULL DEFAULT 0");
}
// To modify prefs_idx drop it and create again.
aDBConnection.executeSimpleSQL("DROP INDEX IF EXISTS prefs_idx");
this._dbCreateIndices(aDBConnection);
},
};
function checkGroupArg(group) {
if (!group || typeof(group) != "string")
throw invalidArg("domain must be nonempty string.");
}
function checkNameArg(name) {
if (!name || typeof(name) != "string")
throw invalidArg("name must be nonempty string.");
}
function checkValueArg(value) {
if (value === undefined)
throw invalidArg("value must not be undefined.");
}
function checkCallbackArg(callback, required) {
if (callback && !(callback instanceof Ci.nsIContentPrefCallback2))
throw invalidArg("callback must be an nsIContentPrefCallback2.");
if (!callback && required)
throw invalidArg("callback must be given.");
}
function invalidArg(msg) {
return Components.Exception(msg, Cr.NS_ERROR_INVALID_ARG);
}
function HostnameGrouper() {}
HostnameGrouper.prototype = {
// XPCOM Plumbing
classID: Components.ID("{8df290ae-dcaa-4c11-98a5-2429a4dc97bb}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentURIGrouper]),
// nsIContentURIGrouper
group: function HostnameGrouper_group(aURI) {
var group;
try {
// Accessing the host property of the URI will throw an exception
// if the URI is of a type that doesn't have a host property.
// Otherwise, we manually throw an exception if the host is empty,
// since the effect is the same (we can't derive a group from it).
group = aURI.host;
if (!group)
throw new Error("can't derive group from host; no host in URI");
} catch (ex) {
// If we don't have a host, then use the entire URI (minus the query,
// reference, and hash, if possible) as the group. This means that URIs
// like about:mozilla and about:blank will be considered separate groups,
// but at least they'll be grouped somehow.
// This also means that each individual file: URL will be considered
// its own group. This seems suboptimal, but so does treating the entire
// file: URL space as a single group (especially if folks start setting
// group-specific capabilities prefs).
// XXX Is there something better we can do here?
try {
var url = aURI.QueryInterface(Ci.nsIURL);
group = aURI.prePath + url.filePath;
} catch (ex) {
group = aURI.spec;
}
}
return group;
}
};
// XPCOM Plumbing
var components = [ContentPrefService2, HostnameGrouper];
this.NSGetFactory = XPCOMUtils.generateNSGetFactory(components);
|