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 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */
#include "ServiceWorkerPrivate.h"
#include <utility>
#include "MainThreadUtils.h"
#include "ServiceWorkerCloneData.h"
#include "ServiceWorkerManager.h"
#include "ServiceWorkerRegistrationInfo.h"
#include "ServiceWorkerUtils.h"
#include "js/ErrorReport.h"
#include "mozIThirdPartyUtil.h"
#include "mozilla/Assertions.h"
#include "mozilla/ContentBlockingAllowList.h"
#include "mozilla/CycleCollectedJSContext.h" // for MicroTaskRunnable
#include "mozilla/ErrorResult.h"
#include "mozilla/JSObjectHolder.h"
#include "mozilla/Maybe.h"
#include "mozilla/OriginAttributes.h"
#include "mozilla/Preferences.h"
#include "mozilla/RemoteLazyInputStreamStorage.h"
#include "mozilla/Result.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_privacy.h"
#include "mozilla/StoragePrincipalHelper.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/Client.h"
#include "mozilla/dom/ClientIPCTypes.h"
#include "mozilla/dom/ClientManager.h"
#include "mozilla/dom/DOMTypes.h"
#include "mozilla/dom/FetchEventOpChild.h"
#include "mozilla/dom/FetchUtil.h"
#include "mozilla/dom/IndexedDatabaseManager.h"
#include "mozilla/dom/InternalHeaders.h"
#include "mozilla/dom/InternalRequest.h"
#include "mozilla/dom/NotificationEvent.h"
#include "mozilla/dom/PromiseNativeHandler.h"
#include "mozilla/dom/PushEventBinding.h"
#include "mozilla/dom/PushManager.h"
#include "mozilla/dom/ReferrerInfo.h"
#include "mozilla/dom/RemoteType.h"
#include "mozilla/dom/RemoteWorkerControllerChild.h"
#include "mozilla/dom/RemoteWorkerManager.h" // RemoteWorkerManager::GetRemoteType
#include "mozilla/dom/RequestBinding.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/ServiceWorkerBinding.h"
#include "mozilla/dom/ServiceWorkerLifetimeExtension.h"
#include "mozilla/dom/WorkerDebugger.h"
#include "mozilla/dom/WorkerRef.h"
#include "mozilla/dom/WorkerRunnable.h"
#include "mozilla/dom/WorkerScope.h"
#include "mozilla/dom/ipc/StructuredCloneData.h"
#include "mozilla/extensions/WebExtensionPolicy.h" // WebExtensionPolicy
#include "mozilla/glean/DomServiceworkersMetrics.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/ipc/IPCStreamUtils.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/ipc/URIUtils.h"
#include "mozilla/net/CookieJarSettings.h"
#include "mozilla/net/CookieService.h"
#include "mozilla/net/NeckoChannelParams.h"
#include "nsContentUtils.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsICacheInfoChannel.h"
#include "nsIChannel.h"
#include "nsIHttpChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsIHttpHeaderVisitor.h"
#include "nsINamed.h"
#include "nsINetworkInterceptController.h"
#include "nsIObserverService.h"
#include "nsIRedirectHistoryEntry.h"
#include "nsIReferrerInfo.h"
#include "nsIScriptError.h"
#include "nsIScriptSecurityManager.h"
#include "nsISupportsImpl.h"
#include "nsISupportsPriority.h"
#include "nsIURI.h"
#include "nsIUploadChannel2.h"
#include "nsNetUtil.h"
#include "nsProxyRelease.h"
#include "nsQueryObject.h"
#include "nsRFPService.h"
#include "nsStreamUtils.h"
#include "nsStringStream.h"
#include "nsThreadUtils.h"
extern mozilla::LazyLogModule sWorkerTelemetryLog;
#ifdef LOG
# undef LOG
#endif
#define LOG(_args) MOZ_LOG(sWorkerTelemetryLog, LogLevel::Debug, _args);
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::ipc;
namespace mozilla::dom {
uint32_t ServiceWorkerPrivate::sRunningServiceWorkers = 0;
uint32_t ServiceWorkerPrivate::sRunningServiceWorkersFetch = 0;
uint32_t ServiceWorkerPrivate::sRunningServiceWorkersMax = 0;
uint32_t ServiceWorkerPrivate::sRunningServiceWorkersFetchMax = 0;
/**
* KeepAliveToken
*/
KeepAliveToken::KeepAliveToken(ServiceWorkerPrivate* aPrivate)
: mPrivate(aPrivate) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aPrivate);
mPrivate->AddToken();
}
KeepAliveToken::~KeepAliveToken() {
MOZ_ASSERT(NS_IsMainThread());
mPrivate->ReleaseToken();
}
NS_IMPL_ISUPPORTS0(KeepAliveToken)
/**
* RAIIActorPtrHolder
*/
ServiceWorkerPrivate::RAIIActorPtrHolder::RAIIActorPtrHolder(
already_AddRefed<RemoteWorkerControllerChild> aActor)
: mActor(aActor) {
AssertIsOnMainThread();
MOZ_ASSERT(mActor);
MOZ_ASSERT(mActor->Manager());
}
ServiceWorkerPrivate::RAIIActorPtrHolder::~RAIIActorPtrHolder() {
AssertIsOnMainThread();
mDestructorPromiseHolder.ResolveIfExists(true, __func__);
mActor->MaybeSendDelete();
}
RemoteWorkerControllerChild*
ServiceWorkerPrivate::RAIIActorPtrHolder::operator->() const {
AssertIsOnMainThread();
return get();
}
RemoteWorkerControllerChild* ServiceWorkerPrivate::RAIIActorPtrHolder::get()
const {
AssertIsOnMainThread();
return mActor.get();
}
RefPtr<GenericPromise>
ServiceWorkerPrivate::RAIIActorPtrHolder::OnDestructor() {
AssertIsOnMainThread();
return mDestructorPromiseHolder.Ensure(__func__);
}
/**
* PendingFunctionEvent
*/
ServiceWorkerPrivate::PendingFunctionalEvent::PendingFunctionalEvent(
ServiceWorkerPrivate* aOwner,
RefPtr<ServiceWorkerRegistrationInfo>&& aRegistration)
: mOwner(aOwner), mRegistration(std::move(aRegistration)) {
AssertIsOnMainThread();
MOZ_ASSERT(mOwner);
MOZ_ASSERT(mOwner->mInfo);
MOZ_ASSERT(mOwner->mInfo->State() == ServiceWorkerState::Activating);
MOZ_ASSERT(mRegistration);
}
ServiceWorkerPrivate::PendingFunctionalEvent::~PendingFunctionalEvent() {
AssertIsOnMainThread();
}
ServiceWorkerPrivate::PendingCookieChangeEvent::PendingCookieChangeEvent(
ServiceWorkerPrivate* aOwner,
RefPtr<ServiceWorkerRegistrationInfo>&& aRegistration,
ServiceWorkerCookieChangeEventOpArgs&& aArgs)
: PendingFunctionalEvent(aOwner, std::move(aRegistration)),
mArgs(std::move(aArgs)) {
AssertIsOnMainThread();
}
nsresult ServiceWorkerPrivate::PendingCookieChangeEvent::Send() {
AssertIsOnMainThread();
MOZ_ASSERT(mOwner);
MOZ_ASSERT(mOwner->mInfo);
return mOwner->SendCookieChangeEventInternal(std::move(mRegistration),
std::move(mArgs));
}
ServiceWorkerPrivate::PendingPushEvent::PendingPushEvent(
ServiceWorkerPrivate* aOwner,
RefPtr<ServiceWorkerRegistrationInfo>&& aRegistration,
ServiceWorkerPushEventOpArgs&& aArgs)
: PendingFunctionalEvent(aOwner, std::move(aRegistration)),
mArgs(std::move(aArgs)) {
AssertIsOnMainThread();
}
nsresult ServiceWorkerPrivate::PendingPushEvent::Send() {
AssertIsOnMainThread();
MOZ_ASSERT(mOwner);
MOZ_ASSERT(mOwner->mInfo);
return mOwner->SendPushEventInternal(std::move(mRegistration),
std::move(mArgs));
}
ServiceWorkerPrivate::PendingFetchEvent::PendingFetchEvent(
ServiceWorkerPrivate* aOwner,
RefPtr<ServiceWorkerRegistrationInfo>&& aRegistration,
ParentToParentServiceWorkerFetchEventOpArgs&& aArgs,
nsCOMPtr<nsIInterceptedChannel>&& aChannel,
RefPtr<FetchServicePromises>&& aPreloadResponseReadyPromises)
: PendingFunctionalEvent(aOwner, std::move(aRegistration)),
mArgs(std::move(aArgs)),
mChannel(std::move(aChannel)),
mPreloadResponseReadyPromises(std::move(aPreloadResponseReadyPromises)) {
AssertIsOnMainThread();
MOZ_ASSERT(mChannel);
}
nsresult ServiceWorkerPrivate::PendingFetchEvent::Send() {
AssertIsOnMainThread();
MOZ_ASSERT(mOwner);
MOZ_ASSERT(mOwner->mInfo);
return mOwner->SendFetchEventInternal(
std::move(mRegistration), std::move(mArgs), std::move(mChannel),
std::move(mPreloadResponseReadyPromises));
}
ServiceWorkerPrivate::PendingFetchEvent::~PendingFetchEvent() {
AssertIsOnMainThread();
if (NS_WARN_IF(mChannel)) {
mChannel->CancelInterception(NS_ERROR_INTERCEPTION_FAILED);
}
}
namespace {
class HeaderFiller final : public nsIHttpHeaderVisitor {
public:
NS_DECL_ISUPPORTS
explicit HeaderFiller(HeadersGuardEnum aGuard)
: mInternalHeaders(new InternalHeaders(aGuard)) {
MOZ_ASSERT(mInternalHeaders);
}
NS_IMETHOD
VisitHeader(const nsACString& aHeader, const nsACString& aValue) override {
ErrorResult result;
mInternalHeaders->Append(aHeader, aValue, result);
if (NS_WARN_IF(result.Failed())) {
return result.StealNSResult();
}
return NS_OK;
}
RefPtr<InternalHeaders> Extract() {
return RefPtr<InternalHeaders>(std::move(mInternalHeaders));
}
private:
~HeaderFiller() = default;
RefPtr<InternalHeaders> mInternalHeaders;
};
NS_IMPL_ISUPPORTS(HeaderFiller, nsIHttpHeaderVisitor)
Result<IPCInternalRequest, nsresult> GetIPCInternalRequest(
nsIInterceptedChannel* aChannel) {
AssertIsOnMainThread();
nsCOMPtr<nsIURI> uri;
MOZ_TRY(aChannel->GetSecureUpgradedChannelURI(getter_AddRefs(uri)));
nsCOMPtr<nsIURI> uriNoFragment;
MOZ_TRY(NS_GetURIWithoutRef(uri, getter_AddRefs(uriNoFragment)));
nsCOMPtr<nsIChannel> underlyingChannel;
MOZ_TRY(aChannel->GetChannel(getter_AddRefs(underlyingChannel)));
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(underlyingChannel);
MOZ_ASSERT(httpChannel, "How come we don't have an HTTP channel?");
nsCOMPtr<nsIHttpChannelInternal> internalChannel =
do_QueryInterface(httpChannel);
NS_ENSURE_TRUE(internalChannel, Err(NS_ERROR_NOT_AVAILABLE));
nsCOMPtr<nsICacheInfoChannel> cacheInfoChannel =
do_QueryInterface(underlyingChannel);
nsAutoCString spec;
MOZ_TRY(uriNoFragment->GetSpec(spec));
nsAutoCString fragment;
MOZ_TRY(uri->GetRef(fragment));
nsAutoCString method;
MOZ_TRY(httpChannel->GetRequestMethod(method));
// This is safe due to static_asserts in ServiceWorkerManager.cpp
uint32_t cacheModeInt;
MOZ_ALWAYS_SUCCEEDS(internalChannel->GetFetchCacheMode(&cacheModeInt));
RequestCache cacheMode = static_cast<RequestCache>(cacheModeInt);
RequestMode requestMode =
InternalRequest::MapChannelToRequestMode(underlyingChannel);
// This is safe due to static_asserts in ServiceWorkerManager.cpp
uint32_t redirectMode;
MOZ_ALWAYS_SUCCEEDS(internalChannel->GetRedirectMode(&redirectMode));
RequestRedirect requestRedirect = static_cast<RequestRedirect>(redirectMode);
// request's priority is not copied by the new Request() constructor used by
// a fetch() call while request's internal priority is. So let's use the
// default, otherwise a fetch(event.request) from a worker on an intercepted
// fetch event would adjust priority twice.
// https://fetch.spec.whatwg.org/#dom-global-fetch
// https://fetch.spec.whatwg.org/#dom-request
RequestPriority requestPriority = RequestPriority::Auto;
RequestCredentials requestCredentials =
InternalRequest::MapChannelToRequestCredentials(underlyingChannel);
nsAutoCString referrer;
ReferrerPolicy referrerPolicy = ReferrerPolicy::_empty;
ReferrerPolicy environmentReferrerPolicy = ReferrerPolicy::_empty;
nsCOMPtr<nsIReferrerInfo> referrerInfo = httpChannel->GetReferrerInfo();
if (referrerInfo) {
referrerPolicy = referrerInfo->ReferrerPolicy();
Unused << referrerInfo->GetComputedReferrerSpec(referrer);
}
uint32_t loadFlags;
MOZ_TRY(underlyingChannel->GetLoadFlags(&loadFlags));
nsCOMPtr<nsILoadInfo> loadInfo = underlyingChannel->LoadInfo();
nsContentPolicyType contentPolicyType = loadInfo->InternalContentPolicyType();
int32_t internalPriority = nsISupportsPriority::PRIORITY_NORMAL;
if (nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(underlyingChannel)) {
p->GetPriority(&internalPriority);
}
nsAutoString integrity;
MOZ_TRY(loadInfo->GetIntegrityMetadata(integrity));
RefPtr<HeaderFiller> headerFiller =
MakeRefPtr<HeaderFiller>(HeadersGuardEnum::Request);
MOZ_TRY(httpChannel->VisitNonDefaultRequestHeaders(headerFiller));
RefPtr<InternalHeaders> internalHeaders = headerFiller->Extract();
ErrorResult result;
internalHeaders->SetGuard(HeadersGuardEnum::Immutable, result);
if (NS_WARN_IF(result.Failed())) {
return Err(result.StealNSResult());
}
nsTArray<HeadersEntry> ipcHeaders;
HeadersGuardEnum ipcHeadersGuard;
internalHeaders->ToIPC(ipcHeaders, ipcHeadersGuard);
nsAutoCString alternativeDataType;
if (cacheInfoChannel &&
!cacheInfoChannel->PreferredAlternativeDataTypes().IsEmpty()) {
// TODO: the internal request probably needs all the preferred types.
alternativeDataType.Assign(
cacheInfoChannel->PreferredAlternativeDataTypes()[0].type());
}
Maybe<PrincipalInfo> principalInfo;
Maybe<PrincipalInfo> interceptionPrincipalInfo;
if (loadInfo->TriggeringPrincipal()) {
principalInfo.emplace();
interceptionPrincipalInfo.emplace();
MOZ_ALWAYS_SUCCEEDS(PrincipalToPrincipalInfo(
loadInfo->TriggeringPrincipal(), principalInfo.ptr()));
MOZ_ALWAYS_SUCCEEDS(PrincipalToPrincipalInfo(
loadInfo->TriggeringPrincipal(), interceptionPrincipalInfo.ptr()));
}
nsTArray<RedirectHistoryEntryInfo> redirectChain;
for (const nsCOMPtr<nsIRedirectHistoryEntry>& redirectEntry :
loadInfo->RedirectChain()) {
RedirectHistoryEntryInfo* entry = redirectChain.AppendElement();
MOZ_ALWAYS_SUCCEEDS(RHEntryToRHEntryInfo(redirectEntry, entry));
}
bool isThirdPartyChannel;
// ThirdPartyUtil* thirdPartyUtil = ThirdPartyUtil::GetInstance();
nsCOMPtr<mozIThirdPartyUtil> thirdPartyUtil =
do_GetService(THIRDPARTYUTIL_CONTRACTID);
if (thirdPartyUtil) {
nsCOMPtr<nsIURI> uri;
MOZ_TRY(underlyingChannel->GetURI(getter_AddRefs(uri)));
MOZ_TRY(thirdPartyUtil->IsThirdPartyChannel(underlyingChannel, uri,
&isThirdPartyChannel));
}
nsILoadInfo::CrossOriginEmbedderPolicy embedderPolicy =
loadInfo->GetLoadingEmbedderPolicy();
// Note: all the arguments are copied rather than moved, which would be more
// efficient, because there's no move-friendly constructor generated.
return IPCInternalRequest(
method, {spec}, ipcHeadersGuard, ipcHeaders, Nothing(), -1,
alternativeDataType, contentPolicyType, internalPriority, referrer,
referrerPolicy, environmentReferrerPolicy, requestMode,
requestCredentials, cacheMode, requestRedirect, requestPriority,
integrity, false, fragment, principalInfo, interceptionPrincipalInfo,
contentPolicyType, redirectChain, isThirdPartyChannel, embedderPolicy);
}
nsresult MaybeStoreStreamForBackgroundThread(nsIInterceptedChannel* aChannel,
IPCInternalRequest& aIPCRequest) {
nsCOMPtr<nsIChannel> channel;
MOZ_ALWAYS_SUCCEEDS(aChannel->GetChannel(getter_AddRefs(channel)));
Maybe<BodyStreamVariant> body;
nsCOMPtr<nsIUploadChannel2> uploadChannel = do_QueryInterface(channel);
if (uploadChannel) {
nsCOMPtr<nsIInputStream> uploadStream;
MOZ_TRY(uploadChannel->CloneUploadStream(&aIPCRequest.bodySize(),
getter_AddRefs(uploadStream)));
if (uploadStream) {
Maybe<BodyStreamVariant>& body = aIPCRequest.body();
body.emplace(ParentToParentStream());
MOZ_TRY(
nsID::GenerateUUIDInPlace(body->get_ParentToParentStream().uuid()));
auto storageOrErr = RemoteLazyInputStreamStorage::Get();
if (NS_WARN_IF(storageOrErr.isErr())) {
return storageOrErr.unwrapErr();
}
auto storage = storageOrErr.unwrap();
storage->AddStream(uploadStream, body->get_ParentToParentStream().uuid());
}
}
return NS_OK;
}
} // anonymous namespace
/**
* ServiceWorkerPrivate
*/
ServiceWorkerPrivate::ServiceWorkerPrivate(ServiceWorkerInfo* aInfo)
: mInfo(aInfo),
mPendingSpawnLifetime(
ServiceWorkerLifetimeExtension(NoLifetimeExtension{})),
mDebuggerCount(0),
mTokenCount(0),
mLaunchCount(0) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aInfo);
MOZ_ASSERT(!mControllerChild);
mIdleWorkerTimer = NS_NewTimer();
MOZ_ASSERT(mIdleWorkerTimer);
// Assert in all debug builds as well as non-debug Nightly and Dev Edition.
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(Initialize()));
#else
MOZ_ALWAYS_SUCCEEDS(Initialize());
#endif
}
ServiceWorkerPrivate::~ServiceWorkerPrivate() {
MOZ_ASSERT(!mTokenCount);
MOZ_ASSERT(!mInfo);
MOZ_ASSERT(!mControllerChild);
MOZ_ASSERT(mIdlePromiseHolder.IsEmpty());
mIdleWorkerTimer->Cancel();
}
nsresult ServiceWorkerPrivate::Initialize() {
AssertIsOnMainThread();
MOZ_ASSERT(mInfo);
nsCOMPtr<nsIPrincipal> principal = mInfo->Principal();
nsCOMPtr<nsIURI> uri;
auto* basePrin = BasePrincipal::Cast(principal);
nsresult rv = basePrin->GetURI(getter_AddRefs(uri));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (NS_WARN_IF(!uri)) {
return NS_ERROR_FAILURE;
}
URIParams baseScriptURL;
SerializeURI(uri, baseScriptURL);
nsString id;
rv = mInfo->GetId(id);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
PrincipalInfo principalInfo;
rv = PrincipalToPrincipalInfo(principal, &principalInfo);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (NS_WARN_IF(!swm)) {
return NS_ERROR_DOM_ABORT_ERR;
}
RefPtr<ServiceWorkerRegistrationInfo> regInfo =
swm->GetRegistration(principal, mInfo->Scope());
if (NS_WARN_IF(!regInfo)) {
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
nsCOMPtr<nsICookieJarSettings> cookieJarSettings =
net::CookieJarSettings::Create(principal);
MOZ_ASSERT(cookieJarSettings);
// We can populate the partitionKey and the fingerprinting protection
// overrides using the originAttribute of the principal. If it has
// partitionKey set, It's a foreign partitioned principal and it implies that
// it's a third-party service worker. So, the cookieJarSettings can directly
// use the partitionKey from it. For first-party case, we can populate the
// partitionKey from the principal URI.
Maybe<RFPTargetSet> overriddenFingerprintingSettingsArg;
Maybe<RFPTargetSet> overriddenFingerprintingSettings;
nsCOMPtr<nsIURI> firstPartyURI;
bool foreignByAncestorContext = false;
bool isOn3PCBExceptionList = false;
// Firefox doesn't support service workers in PBM,
// but we add this just so that when we do,
// we can handle it correctly.
bool isPBM = principal->GetIsInPrivateBrowsing();
if (!principal->OriginAttributesRef().mPartitionKey.IsEmpty()) {
net::CookieJarSettings::Cast(cookieJarSettings)
->SetPartitionKey(principal->OriginAttributesRef().mPartitionKey);
// The service worker is for a third-party context, we get first-party
// domain from the partitionKey and the third-party domain from the
// principal of the service worker. Then, we can get the fingerprinting
// protection overrides using them.
nsAutoString scheme;
nsAutoString pkBaseDomain;
int32_t unused;
bool _foreignByAncestorContext;
if (OriginAttributes::ParsePartitionKey(
principal->OriginAttributesRef().mPartitionKey, scheme,
pkBaseDomain, unused, _foreignByAncestorContext)) {
foreignByAncestorContext = _foreignByAncestorContext;
rv = NS_NewURI(getter_AddRefs(firstPartyURI),
scheme + u"://"_ns + pkBaseDomain);
if (NS_SUCCEEDED(rv)) {
overriddenFingerprintingSettings =
nsRFPService::GetOverriddenFingerprintingSettingsForURI(
firstPartyURI, uri, isPBM);
if (overriddenFingerprintingSettings.isSome()) {
overriddenFingerprintingSettingsArg.emplace(
overriddenFingerprintingSettings.ref());
}
RefPtr<net::CookieService> csSingleton =
net::CookieService::GetSingleton();
isOn3PCBExceptionList =
csSingleton->ThirdPartyCookieBlockingExceptionsRef()
.CheckExceptionForURIs(firstPartyURI, uri);
}
}
} else if (!principal->OriginAttributesRef().mFirstPartyDomain.IsEmpty()) {
// Using the first party domain to know the context of the service worker.
// We will run into here if FirstPartyIsolation is enabled. In this case,
// the PartitionKey won't get populated.
// Because the service worker is only available in secure contexts, so we
// don't need to consider http and only use https as scheme to create
// the first-party URI
rv = NS_NewURI(
getter_AddRefs(firstPartyURI),
u"https://"_ns + principal->OriginAttributesRef().mFirstPartyDomain);
if (NS_SUCCEEDED(rv)) {
// If the first party domain is not a third-party domain, the service
// worker is running in first-party context.
bool isThirdParty;
rv = principal->IsThirdPartyURI(firstPartyURI, &isThirdParty);
NS_ENSURE_SUCCESS(rv, rv);
overriddenFingerprintingSettings =
isThirdParty
? nsRFPService::GetOverriddenFingerprintingSettingsForURI(
firstPartyURI, uri, isPBM)
: nsRFPService::GetOverriddenFingerprintingSettingsForURI(
uri, nullptr, isPBM);
RefPtr<net::CookieService> csSingleton =
net::CookieService::GetSingleton();
isOn3PCBExceptionList =
isThirdParty ? csSingleton->ThirdPartyCookieBlockingExceptionsRef()
.CheckExceptionForURIs(firstPartyURI, uri)
: false;
if (overriddenFingerprintingSettings.isSome()) {
overriddenFingerprintingSettingsArg.emplace(
overriddenFingerprintingSettings.ref());
}
}
} else {
net::CookieJarSettings::Cast(cookieJarSettings)
->SetPartitionKey(uri, false);
firstPartyURI = uri;
// The service worker is for a first-party context, we can use the uri of
// the service worker as the first-party domain to get the fingerprinting
// protection overrides.
overriddenFingerprintingSettings =
nsRFPService::GetOverriddenFingerprintingSettingsForURI(uri, nullptr,
isPBM);
if (overriddenFingerprintingSettings.isSome()) {
overriddenFingerprintingSettingsArg.emplace(
overriddenFingerprintingSettings.ref());
}
}
if (ContentBlockingAllowList::Check(principal, isPBM)) {
net::CookieJarSettings::Cast(cookieJarSettings)
->SetIsOnContentBlockingAllowList(true);
}
bool shouldResistFingerprinting =
nsContentUtils::ShouldResistFingerprinting_dangerous(
principal,
"Service Workers exist outside a Document or Channel; as a property "
"of the domain (and origin attributes). We don't have a "
"CookieJarSettings to perform the *nested check*, but we can rely on"
"the FPI/dFPI partition key check. The WorkerPrivate's "
"ShouldResistFingerprinting function for the ServiceWorker depends "
"on this boolean and will also consider an explicit RFPTarget.",
RFPTarget::IsAlwaysEnabledForPrecompute) &&
!nsContentUtils::ETPSaysShouldNotResistFingerprinting(cookieJarSettings,
isPBM);
if (shouldResistFingerprinting && NS_SUCCEEDED(rv) && firstPartyURI) {
auto rfpKey = nsRFPService::GenerateKeyForServiceWorker(
firstPartyURI, principal, foreignByAncestorContext);
if (rfpKey.isSome()) {
net::CookieJarSettings::Cast(cookieJarSettings)
->SetFingerprintingRandomizationKey(rfpKey.ref());
}
}
net::CookieJarSettingsArgs cjsData;
net::CookieJarSettings::Cast(cookieJarSettings)->Serialize(cjsData);
nsCOMPtr<nsIPrincipal> partitionedPrincipal;
rv = StoragePrincipalHelper::CreatePartitionedPrincipalForServiceWorker(
principal, cookieJarSettings, getter_AddRefs(partitionedPrincipal));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
PrincipalInfo partitionedPrincipalInfo;
rv =
PrincipalToPrincipalInfo(partitionedPrincipal, &partitionedPrincipalInfo);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
StorageAccess storageAccess =
StorageAllowedForServiceWorker(principal, cookieJarSettings);
ServiceWorkerData serviceWorkerData;
serviceWorkerData.cacheName() = mInfo->CacheName();
serviceWorkerData.loadFlags() = static_cast<uint32_t>(
mInfo->GetImportsLoadFlags() | nsIChannel::LOAD_BYPASS_SERVICE_WORKER);
serviceWorkerData.id() = std::move(id);
nsAutoCString domain;
rv = uri->GetHost(domain);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
auto remoteType = RemoteWorkerManager::GetRemoteType(
principal, WorkerKind::WorkerKindService);
if (NS_WARN_IF(remoteType.isErr())) {
return remoteType.unwrapErr();
}
// Determine if the service worker is registered under a third-party context
// by checking if it's running under a partitioned principal.
bool isThirdPartyContextToTopWindow =
!principal->OriginAttributesRef().mPartitionKey.IsEmpty();
mClientInfo = ClientManager::CreateInfo(
ClientType::Serviceworker,
// The partitioned principal for ServiceWorkers is currently always
// partitioned and so we only use it when in a third party context.
isThirdPartyContextToTopWindow ? partitionedPrincipal : principal);
if (NS_WARN_IF(!mClientInfo.isSome())) {
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
mClientInfo->SetAgentClusterId(regInfo->AgentClusterId());
mClientInfo->SetURL(mInfo->ScriptSpec());
mClientInfo->SetFrameType(FrameType::None);
mRemoteWorkerData = RemoteWorkerData(
NS_ConvertUTF8toUTF16(mInfo->ScriptSpec()), baseScriptURL, baseScriptURL,
WorkerOptions(),
/* loading principal */ principalInfo, principalInfo,
partitionedPrincipalInfo,
/* useRegularPrincipal */ true,
// ServiceWorkers run as first-party, no storage-access permission needed.
/* usingStorageAccess */ false,
cjsData, domain,
/* isSecureContext */ true,
/* clientInfo*/ Some(mClientInfo.ref().ToIPC()),
// The RemoteWorkerData CTOR doesn't allow to set the referrerInfo via
// already_AddRefed<>. Let's set it to null.
/* referrerInfo */ nullptr,
storageAccess, isThirdPartyContextToTopWindow, shouldResistFingerprinting,
overriddenFingerprintingSettingsArg, isOn3PCBExceptionList,
// Origin trials are associated to a window, so it doesn't make sense on
// service workers.
OriginTrials(), std::move(serviceWorkerData), regInfo->AgentClusterId(),
remoteType.unwrap());
mRemoteWorkerData.referrerInfo() = MakeAndAddRef<ReferrerInfo>();
// This fills in the rest of mRemoteWorkerData.serviceWorkerData().
RefreshRemoteWorkerData(regInfo);
return NS_OK;
}
void ServiceWorkerPrivate::RegenerateClientInfo() {
// inductively, this object can only still be alive after Initialize() if the
// mClientInfo was correctly initialized.
MOZ_DIAGNOSTIC_ASSERT(mClientInfo.isSome());
mClientInfo = ClientManager::CreateInfo(
ClientType::Serviceworker, mClientInfo->GetPrincipal().unwrap().get());
mRemoteWorkerData.clientInfo().ref() = mClientInfo.ref().ToIPC();
}
nsresult ServiceWorkerPrivate::CheckScriptEvaluation(
const ServiceWorkerLifetimeExtension& aLifetimeExtension,
RefPtr<LifeCycleEventCallback> aCallback) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aCallback);
RefPtr<ServiceWorkerPrivate> self = this;
/**
* We need to capture the actor associated with the current Service Worker so
* we can terminate it if script evaluation failed.
*/
nsresult rv = SpawnWorkerIfNeeded(aLifetimeExtension);
if (NS_WARN_IF(NS_FAILED(rv))) {
aCallback->SetResult(false);
aCallback->Run();
return rv;
}
MOZ_ASSERT(mControllerChild);
RefPtr<RAIIActorPtrHolder> holder = mControllerChild;
return ExecServiceWorkerOp(
ServiceWorkerCheckScriptEvaluationOpArgs(), aLifetimeExtension,
[self = std::move(self), holder = std::move(holder),
callback = aCallback](ServiceWorkerOpResult&& aResult) mutable {
if (aResult.type() == ServiceWorkerOpResult::
TServiceWorkerCheckScriptEvaluationOpResult) {
auto& result =
aResult.get_ServiceWorkerCheckScriptEvaluationOpResult();
if (result.workerScriptExecutedSuccessfully()) {
self->SetHandlesFetch(result.fetchHandlerWasAdded());
if (self->mHandlesFetch == Unknown) {
self->mHandlesFetch =
result.fetchHandlerWasAdded() ? Enabled : Disabled;
// Update telemetry for # of running SW - the already-running SW
// handles fetch
if (self->mHandlesFetch == Enabled) {
self->UpdateRunning(0, 1);
}
}
callback->SetResult(result.workerScriptExecutedSuccessfully());
callback->Run();
return;
}
}
/**
* If script evaluation failed, first terminate the Service Worker
* before invoking the callback.
*/
MOZ_ASSERT_IF(aResult.type() == ServiceWorkerOpResult::Tnsresult,
NS_FAILED(aResult.get_nsresult()));
// If a termination operation was already issued using `holder`...
if (self->mControllerChild != holder) {
holder->OnDestructor()->Then(
GetCurrentSerialEventTarget(), __func__,
[callback = std::move(callback)](
const GenericPromise::ResolveOrRejectValue&) {
callback->SetResult(false);
callback->Run();
});
return;
}
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm);
auto shutdownStateId = swm->MaybeInitServiceWorkerShutdownProgress();
RefPtr<GenericNonExclusivePromise> promise =
self->ShutdownInternal(shutdownStateId);
swm->BlockShutdownOn(promise, shutdownStateId);
promise->Then(
GetCurrentSerialEventTarget(), __func__,
[callback = std::move(callback)](
const GenericNonExclusivePromise::ResolveOrRejectValue&) {
callback->SetResult(false);
callback->Run();
});
},
[callback = aCallback] {
callback->SetResult(false);
callback->Run();
});
}
nsresult ServiceWorkerPrivate::SendMessageEvent(
RefPtr<ServiceWorkerCloneData>&& aData,
const ServiceWorkerLifetimeExtension& aLifetimeExtension,
const PostMessageSource& aSource) {
AssertIsOnMainThread();
MOZ_ASSERT(aData);
auto scopeExit = MakeScopeExit([&] { Shutdown(); });
PBackgroundChild* bgChild = BackgroundChild::GetForCurrentThread();
if (NS_WARN_IF(!bgChild)) {
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
ServiceWorkerMessageEventOpArgs args;
args.source() = aSource;
if (!aData->BuildClonedMessageData(args.clonedData())) {
return NS_ERROR_DOM_DATA_CLONE_ERR;
}
scopeExit.release();
return ExecServiceWorkerOp(
std::move(args), aLifetimeExtension, [](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(aResult.type() == ServiceWorkerOpResult::Tnsresult);
});
}
nsresult ServiceWorkerPrivate::SendLifeCycleEvent(
const nsAString& aEventType,
const ServiceWorkerLifetimeExtension& aLifetimeExtension,
const RefPtr<LifeCycleEventCallback>& aCallback) {
AssertIsOnMainThread();
MOZ_ASSERT(aCallback);
return ExecServiceWorkerOp(
ServiceWorkerLifeCycleEventOpArgs(nsString(aEventType)),
aLifetimeExtension,
[callback = aCallback](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(aResult.type() == ServiceWorkerOpResult::Tnsresult);
callback->SetResult(NS_SUCCEEDED(aResult.get_nsresult()));
callback->Run();
},
[callback = aCallback] {
callback->SetResult(false);
callback->Run();
});
}
nsresult ServiceWorkerPrivate::SendCookieChangeEvent(
const net::CookieStruct& aCookie, bool aCookieDeleted,
RefPtr<ServiceWorkerRegistrationInfo> aRegistration) {
AssertIsOnMainThread();
MOZ_ASSERT(mInfo);
MOZ_ASSERT(aRegistration);
ServiceWorkerCookieChangeEventOpArgs args;
args.cookie() = aCookie;
args.deleted() = aCookieDeleted;
if (mInfo->State() == ServiceWorkerState::Activating) {
UniquePtr<PendingFunctionalEvent> pendingEvent =
MakeUnique<PendingCookieChangeEvent>(this, std::move(aRegistration),
std::move(args));
mPendingFunctionalEvents.AppendElement(std::move(pendingEvent));
return NS_OK;
}
MOZ_ASSERT(mInfo->State() == ServiceWorkerState::Activated);
return SendCookieChangeEventInternal(std::move(aRegistration),
std::move(args));
}
nsresult ServiceWorkerPrivate::SendCookieChangeEventInternal(
RefPtr<ServiceWorkerRegistrationInfo>&& aRegistration,
ServiceWorkerCookieChangeEventOpArgs&& aArgs) {
MOZ_ASSERT(aRegistration);
return ExecServiceWorkerOp(
std::move(aArgs), ServiceWorkerLifetimeExtension(FullLifetimeExtension{}),
[registration = aRegistration](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(aResult.type() == ServiceWorkerOpResult::Tnsresult);
registration->MaybeScheduleTimeCheckAndUpdate();
},
[registration = aRegistration]() {
registration->MaybeScheduleTimeCheckAndUpdate();
});
}
nsresult ServiceWorkerPrivate::SendPushEvent(
const nsAString& aMessageId, const Maybe<nsTArray<uint8_t>>& aData,
RefPtr<ServiceWorkerRegistrationInfo> aRegistration) {
AssertIsOnMainThread();
MOZ_ASSERT(mInfo);
MOZ_ASSERT(aRegistration);
ServiceWorkerPushEventOpArgs args;
args.messageId() = nsString(aMessageId);
if (aData) {
args.data() = aData.ref();
} else {
args.data() = void_t();
}
if (mInfo->State() == ServiceWorkerState::Activating) {
UniquePtr<PendingFunctionalEvent> pendingEvent =
MakeUnique<PendingPushEvent>(this, std::move(aRegistration),
std::move(args));
mPendingFunctionalEvents.AppendElement(std::move(pendingEvent));
return NS_OK;
}
MOZ_ASSERT(mInfo->State() == ServiceWorkerState::Activated);
return SendPushEventInternal(std::move(aRegistration), std::move(args));
}
nsresult ServiceWorkerPrivate::SendPushEventInternal(
RefPtr<ServiceWorkerRegistrationInfo>&& aRegistration,
ServiceWorkerPushEventOpArgs&& aArgs) {
MOZ_ASSERT(aRegistration);
return ExecServiceWorkerOp(
std::move(aArgs), ServiceWorkerLifetimeExtension(FullLifetimeExtension{}),
[registration = aRegistration](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(aResult.type() == ServiceWorkerOpResult::Tnsresult);
registration->MaybeScheduleTimeCheckAndUpdate();
},
[registration = aRegistration]() {
registration->MaybeScheduleTimeCheckAndUpdate();
});
}
nsresult ServiceWorkerPrivate::SendPushSubscriptionChangeEvent(
const RefPtr<nsIPushSubscription>& aOldSubscription) {
AssertIsOnMainThread();
ServiceWorkerPushSubscriptionChangeEventOpArgs args{};
if (aOldSubscription) {
PushSubscriptionData oldSubscription{};
MOZ_TRY(GetSubscriptionParams(aOldSubscription, oldSubscription.endpoint(),
oldSubscription.rawP256dhKey(),
oldSubscription.authSecret(),
oldSubscription.appServerKey()));
args.oldSubscription().emplace(oldSubscription);
}
return ExecServiceWorkerOp(
std::move(args), ServiceWorkerLifetimeExtension(FullLifetimeExtension{}),
[](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(aResult.type() == ServiceWorkerOpResult::Tnsresult);
});
}
nsresult ServiceWorkerPrivate::SendNotificationClickEvent(
const IPCNotification& aNotification, const nsAString& aAction) {
MOZ_ASSERT(NS_IsMainThread());
ServiceWorkerNotificationClickEventOpArgs clickArgs;
clickArgs.notification() = aNotification;
clickArgs.action() = aAction;
ServiceWorkerNotificationEventOpArgs args(std::move(clickArgs));
return ExecServiceWorkerOp(
std::move(args), ServiceWorkerLifetimeExtension(FullLifetimeExtension{}),
[](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(aResult.type() == ServiceWorkerOpResult::Tnsresult);
});
}
nsresult ServiceWorkerPrivate::SendNotificationCloseEvent(
const IPCNotification& aNotification) {
MOZ_ASSERT(NS_IsMainThread());
ServiceWorkerNotificationCloseEventOpArgs closeArgs;
closeArgs.notification() = aNotification;
ServiceWorkerNotificationEventOpArgs args(std::move(closeArgs));
return ExecServiceWorkerOp(
std::move(args), ServiceWorkerLifetimeExtension(FullLifetimeExtension{}),
[](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(aResult.type() == ServiceWorkerOpResult::Tnsresult);
});
}
nsresult ServiceWorkerPrivate::SendFetchEvent(
nsCOMPtr<nsIInterceptedChannel> aChannel, nsILoadGroup* aLoadGroup,
const nsAString& aClientId, const nsAString& aResultingClientId) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aChannel);
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (NS_WARN_IF(!mInfo || !swm)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIChannel> channel;
nsresult rv = aChannel->GetChannel(getter_AddRefs(channel));
NS_ENSURE_SUCCESS(rv, rv);
bool isNonSubresourceRequest =
nsContentUtils::IsNonSubresourceRequest(channel);
RefPtr<ServiceWorkerRegistrationInfo> registration;
if (isNonSubresourceRequest) {
registration = swm->GetRegistration(mInfo->Principal(), mInfo->Scope());
} else {
nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
// We'll check for a null registration below rather than an error code here.
Unused << swm->GetClientRegistration(loadInfo->GetClientInfo().ref(),
getter_AddRefs(registration));
}
// Its possible the registration is removed between starting the interception
// and actually dispatching the fetch event. In these cases we simply
// want to restart the original network request. Since this is a normal
// condition we handle the reset here instead of returning an error which
// would in turn trigger a console report.
if (!registration) {
nsresult rv = aChannel->ResetInterception(false);
if (NS_FAILED(rv)) {
NS_WARNING("Failed to resume intercepted network request");
aChannel->CancelInterception(rv);
}
return NS_OK;
}
// Handle Fetch algorithm - step 16. If the service worker didn't register
// any fetch event handlers, then abort the interception and maybe trigger
// the soft update algorithm.
if (!mInfo->HandlesFetch()) {
nsresult rv = aChannel->ResetInterception(false);
if (NS_FAILED(rv)) {
NS_WARNING("Failed to resume intercepted network request");
aChannel->CancelInterception(rv);
}
// Trigger soft updates if necessary.
registration->MaybeScheduleTimeCheckAndUpdate();
return NS_OK;
}
auto scopeExit = MakeScopeExit([&] {
aChannel->CancelInterception(NS_ERROR_INTERCEPTION_FAILED);
Shutdown();
});
IPCInternalRequest request;
MOZ_TRY_VAR(request, GetIPCInternalRequest(aChannel));
scopeExit.release();
bool preloadNavigation = isNonSubresourceRequest &&
request.method().LowerCaseEqualsASCII("get") &&
registration->GetNavigationPreloadState().enabled();
RefPtr<FetchServicePromises> preloadResponsePromises;
if (preloadNavigation) {
preloadResponsePromises = SetupNavigationPreload(aChannel, registration);
}
ParentToParentServiceWorkerFetchEventOpArgs args(
ServiceWorkerFetchEventOpArgsCommon(
mInfo->ScriptSpec(), request, nsString(aClientId),
nsString(aResultingClientId), isNonSubresourceRequest,
preloadNavigation, mInfo->TestingInjectCancellation()),
Nothing(), Nothing(), Nothing());
if (mInfo->State() == ServiceWorkerState::Activating) {
UniquePtr<PendingFunctionalEvent> pendingEvent =
MakeUnique<PendingFetchEvent>(this, std::move(registration),
std::move(args), std::move(aChannel),
std::move(preloadResponsePromises));
mPendingFunctionalEvents.AppendElement(std::move(pendingEvent));
return NS_OK;
}
MOZ_ASSERT(mInfo->State() == ServiceWorkerState::Activated);
return SendFetchEventInternal(std::move(registration), std::move(args),
std::move(aChannel),
std::move(preloadResponsePromises));
}
nsresult ServiceWorkerPrivate::SendFetchEventInternal(
RefPtr<ServiceWorkerRegistrationInfo>&& aRegistration,
ParentToParentServiceWorkerFetchEventOpArgs&& aArgs,
nsCOMPtr<nsIInterceptedChannel>&& aChannel,
RefPtr<FetchServicePromises>&& aPreloadResponseReadyPromises) {
AssertIsOnMainThread();
auto scopeExit = MakeScopeExit([&] { Shutdown(); });
if (NS_WARN_IF(!mInfo)) {
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
MOZ_TRY(SpawnWorkerIfNeeded(
ServiceWorkerLifetimeExtension(FullLifetimeExtension{})));
MOZ_TRY(MaybeStoreStreamForBackgroundThread(
aChannel, aArgs.common().internalRequest()));
scopeExit.release();
MOZ_ASSERT(mControllerChild);
RefPtr<RAIIActorPtrHolder> holder = mControllerChild;
FetchEventOpChild::SendFetchEvent(
mControllerChild->get(), std::move(aArgs), std::move(aChannel),
std::move(aRegistration), std::move(aPreloadResponseReadyPromises),
CreateEventKeepAliveToken())
->Then(GetCurrentSerialEventTarget(), __func__,
[holder = std::move(holder)](
const GenericPromise::ResolveOrRejectValue& aResult) {
Unused << NS_WARN_IF(aResult.IsReject());
});
return NS_OK;
}
Result<RefPtr<ServiceWorkerPrivate::PromiseExtensionWorkerHasListener>,
nsresult>
ServiceWorkerPrivate::WakeForExtensionAPIEvent(
const nsAString& aExtensionAPINamespace,
const nsAString& aExtensionAPIEventName) {
AssertIsOnMainThread();
ServiceWorkerExtensionAPIEventOpArgs args;
args.apiNamespace() = nsString(aExtensionAPINamespace);
args.apiEventName() = nsString(aExtensionAPIEventName);
auto promise =
MakeRefPtr<PromiseExtensionWorkerHasListener::Private>(__func__);
nsresult rv = ExecServiceWorkerOp(
std::move(args), ServiceWorkerLifetimeExtension(FullLifetimeExtension{}),
[promise](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(
aResult.type() ==
ServiceWorkerOpResult::TServiceWorkerExtensionAPIEventOpResult);
auto& result = aResult.get_ServiceWorkerExtensionAPIEventOpResult();
promise->Resolve(result.extensionAPIEventListenerWasAdded(), __func__);
},
[promise]() { promise->Reject(NS_ERROR_FAILURE, __func__); });
if (NS_FAILED(rv)) {
promise->Reject(rv, __func__);
}
RefPtr<PromiseExtensionWorkerHasListener> outPromise(promise);
return outPromise;
}
nsresult ServiceWorkerPrivate::SpawnWorkerIfNeeded(
const ServiceWorkerLifetimeExtension& aLifetimeExtension) {
AssertIsOnMainThread();
// We don't need to spawn if we already have a spawned, non-terminated worker.
if (mControllerChild) {
// We only need to renew the keepalive token if we actually want to extend
// the worker's lifetime; we don't for termination requests.
if (aLifetimeExtension.LifetimeExtendsIntoTheFuture()) {
RenewKeepAliveToken(aLifetimeExtension);
}
return NS_OK;
}
if (!mInfo) {
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
// Don't spawn the ServiceWorker if we don't want to extend its life.
if (NS_WARN_IF(!aLifetimeExtension.LifetimeExtendsIntoTheFuture())) {
return NS_ERROR_DOM_TIMEOUT_ERR;
}
mServiceWorkerLaunchTimeStart = TimeStamp::Now();
PBackgroundChild* bgChild = BackgroundChild::GetForCurrentThread();
if (NS_WARN_IF(!bgChild)) {
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
// If the worker principal is an extension principal, then we should not spawn
// a worker if there is no WebExtensionPolicy associated to that principal
// or if the WebExtensionPolicy is not active.
auto* principal = mInfo->Principal();
if (principal->SchemeIs("moz-extension")) {
auto* addonPolicy = BasePrincipal::Cast(principal)->AddonPolicy();
if (!addonPolicy || !addonPolicy->Active()) {
NS_WARNING(
"Trying to wake up a service worker for a disabled webextension.");
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
}
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (NS_WARN_IF(!swm)) {
return NS_ERROR_DOM_ABORT_ERR;
}
RefPtr<ServiceWorkerRegistrationInfo> regInfo =
swm->GetRegistration(principal, mInfo->Scope());
if (NS_WARN_IF(!regInfo)) {
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
RefreshRemoteWorkerData(regInfo);
mLaunchCount++;
RefPtr<RemoteWorkerControllerChild> controllerChild =
new RemoteWorkerControllerChild(this);
if (NS_WARN_IF(!bgChild->SendPRemoteWorkerControllerConstructor(
controllerChild, mRemoteWorkerData))) {
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
mPendingSpawnLifetime = aLifetimeExtension;
mControllerChild = new RAIIActorPtrHolder(controllerChild.forget());
// Update Running count here because we may Terminate before we get
// CreationSucceeded(). We'll update if it handles Fetch if that changes
// (
UpdateRunning(1, mHandlesFetch == Enabled ? 1 : 0);
return NS_OK;
}
void ServiceWorkerPrivate::TerminateWorker(
Maybe<RefPtr<Promise>> aMaybePromise) {
MOZ_ASSERT(NS_IsMainThread());
mIdleWorkerTimer->Cancel();
mIdleDeadline = TimeStamp();
// We call the shutdown method prior to dropping mIdleKeepAliveToken in order
// to ensure that the passed-in promise tracks the shutdown of the current
// worker.
//
// More detail: Dropping the token can cause re-entrance to this method via
// ReleaseToken if it is not already the method calling. Shutdown() is
// idempotent except for the promise we pass in; it will only be chained to
// track the actual termination if mControllerChild is not null. On the
// second call when mControllerChild is null, it will resolved immediately
// with undefined. The call from ReleaseToken does not pass a Promise and
// does not care, so it goes second.
//
// We of course could hold onto the underlying shutdown promise until it
// resolves so that new calls could chain, but because it's conceptually
// possible to have multiple spawns and shutdowns in flight and our promise
// argument is really only for testing / devtools where we only expect a
// single actively involved party at a time, this way works sufficiently.
Shutdown(std::move(aMaybePromise));
// As per the above, this may potentially
mIdleKeepAliveToken = nullptr;
}
void ServiceWorkerPrivate::NoteDeadServiceWorkerInfo() {
MOZ_ASSERT(NS_IsMainThread());
TerminateWorker();
mInfo = nullptr;
}
void ServiceWorkerPrivate::UpdateState(ServiceWorkerState aState) {
AssertIsOnMainThread();
if (!mControllerChild) {
return;
}
nsresult rv = ExecServiceWorkerOp(
ServiceWorkerUpdateStateOpArgs(aState),
// Lifecycle events potentially update the lifetime for ServiceWorkers
// controlling a page, but there's no need to update the lifetime to tell
// a SW that its state has changed.
ServiceWorkerLifetimeExtension(NoLifetimeExtension{}),
[](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(aResult.type() == ServiceWorkerOpResult::Tnsresult);
});
if (NS_WARN_IF(NS_FAILED(rv))) {
Shutdown();
return;
}
if (aState != ServiceWorkerState::Activated) {
return;
}
for (auto& event : mPendingFunctionalEvents) {
Unused << NS_WARN_IF(NS_FAILED(event->Send()));
}
mPendingFunctionalEvents.Clear();
}
void ServiceWorkerPrivate::UpdateIsOnContentBlockingAllowList(
bool aOnContentBlockingAllowList) {
AssertIsOnMainThread();
if (!mControllerChild) {
return;
}
ExecServiceWorkerOp(
ServiceWorkerUpdateIsOnContentBlockingAllowListOpArgs(
aOnContentBlockingAllowList),
ServiceWorkerLifetimeExtension(NoLifetimeExtension{}),
[](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(aResult.type() == ServiceWorkerOpResult::Tnsresult);
});
}
nsresult ServiceWorkerPrivate::GetDebugger(nsIWorkerDebugger** aResult) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aResult);
return NS_ERROR_NOT_IMPLEMENTED;
}
nsresult ServiceWorkerPrivate::AttachDebugger() {
MOZ_ASSERT(NS_IsMainThread());
// When the first debugger attaches to a worker, we spawn a worker if needed,
// and cancel the idle timeout. The idle timeout should not be reset until
// the last debugger detached from the worker.
if (!mDebuggerCount) {
nsresult rv = SpawnWorkerIfNeeded(
ServiceWorkerLifetimeExtension(FullLifetimeExtension{}));
NS_ENSURE_SUCCESS(rv, rv);
/**
* Renewing the idle KeepAliveToken for spawning workers happens
* asynchronously, rather than synchronously.
* The asynchronous renewal is because the actual spawning of workers occurs
* in a content process, so we will only renew once notified that the worker
* has been successfully created
*
* This means that the DevTools way of starting up a worker by calling
* `AttachDebugger` immediately followed by `DetachDebugger` will spawn and
* immediately terminate a worker (because `mTokenCount` is possibly 0
* due to the idle KeepAliveToken being created asynchronously). So, just
* renew the KeepAliveToken right now.
*/
RenewKeepAliveToken(
ServiceWorkerLifetimeExtension(FullLifetimeExtension{}));
mIdleWorkerTimer->Cancel();
}
++mDebuggerCount;
return NS_OK;
}
nsresult ServiceWorkerPrivate::DetachDebugger() {
MOZ_ASSERT(NS_IsMainThread());
if (!mDebuggerCount) {
return NS_ERROR_UNEXPECTED;
}
--mDebuggerCount;
// When the last debugger detaches from a worker, we either reset the idle
// timeout, or terminate the worker if there are no more active tokens.
if (!mDebuggerCount) {
if (mTokenCount) {
ResetIdleTimeout(ServiceWorkerLifetimeExtension(FullLifetimeExtension{}));
} else {
TerminateWorker();
}
}
return NS_OK;
}
bool ServiceWorkerPrivate::IsIdle() const {
MOZ_ASSERT(NS_IsMainThread());
return mTokenCount == 0 || (mTokenCount == 1 && mIdleKeepAliveToken);
}
RefPtr<GenericPromise> ServiceWorkerPrivate::GetIdlePromise() {
#ifdef DEBUG
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(!IsIdle());
MOZ_ASSERT(!mIdlePromiseObtained, "Idle promise may only be obtained once!");
mIdlePromiseObtained = true;
#endif
RefPtr<GenericPromise> promise = mIdlePromiseHolder.Ensure(__func__);
mIdlePromiseHolder.UseDirectTaskDispatch(__func__);
return promise;
}
namespace {
class ServiceWorkerPrivateTimerCallback final : public nsITimerCallback,
public nsINamed {
public:
using Method = void (ServiceWorkerPrivate::*)(nsITimer*);
ServiceWorkerPrivateTimerCallback(ServiceWorkerPrivate* aServiceWorkerPrivate,
Method aMethod)
: mServiceWorkerPrivate(aServiceWorkerPrivate), mMethod(aMethod) {}
NS_IMETHOD
Notify(nsITimer* aTimer) override {
(mServiceWorkerPrivate->*mMethod)(aTimer);
mServiceWorkerPrivate = nullptr;
return NS_OK;
}
NS_IMETHOD
GetName(nsACString& aName) override {
aName.AssignLiteral("ServiceWorkerPrivateTimerCallback");
return NS_OK;
}
private:
~ServiceWorkerPrivateTimerCallback() = default;
RefPtr<ServiceWorkerPrivate> mServiceWorkerPrivate;
Method mMethod;
NS_DECL_THREADSAFE_ISUPPORTS
};
NS_IMPL_ISUPPORTS(ServiceWorkerPrivateTimerCallback, nsITimerCallback,
nsINamed);
} // anonymous namespace
void ServiceWorkerPrivate::NoteIdleWorkerCallback(nsITimer* aTimer) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aTimer == mIdleWorkerTimer, "Invalid timer!");
// Release ServiceWorkerPrivate's token, since the grace period has ended.
mIdleKeepAliveToken = nullptr;
// Null out our deadline as well.
mIdleDeadline = TimeStamp();
if (mControllerChild) {
// If we still have a living worker at this point it means that either there
// are pending waitUntil promises or the worker is doing some long-running
// computation. Wait a bit more until we forcibly terminate the worker.
uint32_t timeout =
Preferences::GetInt("dom.serviceWorkers.idle_extended_timeout");
nsCOMPtr<nsITimerCallback> cb = new ServiceWorkerPrivateTimerCallback(
this, &ServiceWorkerPrivate::TerminateWorkerCallback);
DebugOnly<nsresult> rv = mIdleWorkerTimer->InitWithCallback(
cb, timeout, nsITimer::TYPE_ONE_SHOT);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
void ServiceWorkerPrivate::TerminateWorkerCallback(nsITimer* aTimer) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aTimer == this->mIdleWorkerTimer, "Invalid timer!");
// mInfo must be non-null at this point because NoteDeadServiceWorkerInfo
// which zeroes it calls TerminateWorker which cancels our timer which will
// ensure we don't get invoked even if the nsTimerEvent is in the event queue.
ServiceWorkerManager::LocalizeAndReportToAllClients(
mInfo->Scope(), "ServiceWorkerGraceTimeoutTermination",
nsTArray<nsString>{NS_ConvertUTF8toUTF16(mInfo->Scope())});
TerminateWorker();
}
void ServiceWorkerPrivate::RenewKeepAliveToken(
const ServiceWorkerLifetimeExtension& aLifetimeExtension) {
// We should have an active worker if we're renewing the keep alive token.
MOZ_ASSERT(mControllerChild);
// If there is at least one debugger attached to the worker, the idle worker
// timeout was canceled when the first debugger attached to the worker. It
// should not be reset until the last debugger detaches from the worker.
if (!mDebuggerCount) {
ResetIdleTimeout(aLifetimeExtension);
}
if (!mIdleKeepAliveToken) {
mIdleKeepAliveToken = new KeepAliveToken(this);
}
}
void ServiceWorkerPrivate::ResetIdleTimeout(
const ServiceWorkerLifetimeExtension& aLifetimeExtension) {
TimeStamp now = TimeStamp::NowLoRes();
TimeStamp existing = mIdleDeadline;
// Normalize the extension, returning a Null TimeStamp if the lifetime
// extension does not actually extend our lifetime.
TimeStamp normalizedExtension = aLifetimeExtension.match(
// No extension means no extension!
[](const NoLifetimeExtension& nle) { return TimeStamp(); },
[&existing, &now](const PropagatedLifetimeExtension& ple) {
// Ignore null deadlines or deadlines that are in the past.
if (ple.mDeadline.IsNull() || ple.mDeadline < now) {
return TimeStamp();
}
// Use this new deadline if our existing deadline is null or the
// received deadline is after our current deadline.
if (existing.IsNull() || ple.mDeadline > existing) {
return ple.mDeadline;
}
// (This means our existing deadline extends further into the future so
// we don't want to change our deadline.)
return TimeStamp();
},
[&now](const FullLifetimeExtension& fle) {
return now + TimeDuration::FromMilliseconds(Preferences::GetInt(
"dom.serviceWorkers.idle_timeout"));
});
if (normalizedExtension.IsNull()) {
// Convert the unlikely situation where we are trying to reset the timeout
// without extension and where we have no existing timeout into a 0 timeout.
// This is important because we don't want to let the ServiceWorker live
// forever!
MOZ_ASSERT(!existing.IsNull());
if (NS_WARN_IF(existing.IsNull())) {
normalizedExtension = now;
} else {
// Return without altering the deadline or churning the timer.
return;
}
}
mIdleDeadline = normalizedExtension;
nsCOMPtr<nsITimerCallback> cb = new ServiceWorkerPrivateTimerCallback(
this, &ServiceWorkerPrivate::NoteIdleWorkerCallback);
// We don't need high resolution but TimeDuration provides better type safety.
DebugOnly<nsresult> rv = mIdleWorkerTimer->InitHighResolutionWithCallback(
cb, mIdleDeadline - now, nsITimer::TYPE_ONE_SHOT);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
void ServiceWorkerPrivate::AddToken() {
MOZ_ASSERT(NS_IsMainThread());
++mTokenCount;
}
void ServiceWorkerPrivate::ReleaseToken() {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mTokenCount > 0);
--mTokenCount;
if (IsIdle()) {
mIdlePromiseHolder.ResolveIfExists(true, __func__);
if (!mTokenCount) {
TerminateWorker();
}
// mInfo can be nullptr here if NoteDeadServiceWorkerInfo() is called while
// the KeepAliveToken is being proxy released as a runnable.
else if (mInfo) {
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (swm) {
swm->WorkerIsIdle(mInfo);
}
}
}
}
already_AddRefed<KeepAliveToken>
ServiceWorkerPrivate::CreateEventKeepAliveToken() {
MOZ_ASSERT(NS_IsMainThread());
// When the WorkerPrivate is in a separate process, we first hold a normal
// KeepAliveToken. Then, after we're notified that the worker is alive, we
// create the idle KeepAliveToken.
MOZ_ASSERT(mIdleKeepAliveToken || mControllerChild);
RefPtr<KeepAliveToken> ref = new KeepAliveToken(this);
return ref.forget();
}
void ServiceWorkerPrivate::SetHandlesFetch(bool aValue) {
MOZ_ASSERT(NS_IsMainThread());
if (NS_WARN_IF(!mInfo)) {
return;
}
mInfo->SetHandlesFetch(aValue);
}
RefPtr<GenericPromise> ServiceWorkerPrivate::SetSkipWaitingFlag() {
AssertIsOnMainThread();
MOZ_ASSERT(mInfo);
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (!swm) {
return GenericPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
}
RefPtr<ServiceWorkerRegistrationInfo> regInfo =
swm->GetRegistration(mInfo->Principal(), mInfo->Scope());
if (!regInfo) {
return GenericPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
}
mInfo->SetSkipWaitingFlag();
RefPtr<GenericPromise::Private> promise =
new GenericPromise::Private(__func__);
// The ServiceWorker calling skipWaiting on itself is not a basis for lifetime
// extension on its own. `TryToActivate` will upgrade the lifetime to a full
// extension iff there are any controlled pages.
auto lifetime = ServiceWorkerLifetimeExtension(NoLifetimeExtension{});
regInfo->TryToActivateAsync(lifetime,
[promise] { promise->Resolve(true, __func__); });
return promise;
}
/* static */
void ServiceWorkerPrivate::UpdateRunning(int32_t aDelta, int32_t aFetchDelta) {
// Record values for time we were running at the current values
RefPtr<ServiceWorkerManager> manager(ServiceWorkerManager::GetInstance());
manager->RecordTelemetry(sRunningServiceWorkers, sRunningServiceWorkersFetch);
MOZ_ASSERT(((int64_t)sRunningServiceWorkers) + aDelta >= 0);
sRunningServiceWorkers += aDelta;
if (sRunningServiceWorkers > sRunningServiceWorkersMax) {
sRunningServiceWorkersMax = sRunningServiceWorkers;
LOG(("ServiceWorker max now %d", sRunningServiceWorkersMax));
}
MOZ_ASSERT(((int64_t)sRunningServiceWorkersFetch) + aFetchDelta >= 0);
sRunningServiceWorkersFetch += aFetchDelta;
if (sRunningServiceWorkersFetch > sRunningServiceWorkersFetchMax) {
sRunningServiceWorkersFetchMax = sRunningServiceWorkersFetch;
LOG(("ServiceWorker Fetch max now %d", sRunningServiceWorkersFetchMax));
}
LOG(("ServiceWorkers running now %d/%d", sRunningServiceWorkers,
sRunningServiceWorkersFetch));
}
void ServiceWorkerPrivate::CreationFailed() {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mControllerChild);
if (mRemoteWorkerData.remoteType().Find(SERVICEWORKER_REMOTE_TYPE) !=
kNotFound) {
glean::service_worker::isolated_launch_time.AccumulateRawDuration(
TimeStamp::Now() - mServiceWorkerLaunchTimeStart);
} else {
glean::service_worker::launch_time.AccumulateRawDuration(
TimeStamp::Now() - mServiceWorkerLaunchTimeStart);
}
mPendingSpawnLifetime = ServiceWorkerLifetimeExtension(NoLifetimeExtension{});
Shutdown();
}
void ServiceWorkerPrivate::CreationSucceeded() {
AssertIsOnMainThread();
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mInfo);
// It's possible for a request to terminate the worker to happen while the
// worker is starting up, in which case we do not want to renew the keepalive
// timer and we probably don't want to update the telemetry below either.
if (NS_WARN_IF(!mControllerChild)) {
mPendingSpawnLifetime =
ServiceWorkerLifetimeExtension(NoLifetimeExtension{});
return;
}
if (mRemoteWorkerData.remoteType().Find(SERVICEWORKER_REMOTE_TYPE) !=
kNotFound) {
glean::service_worker::isolated_launch_time.AccumulateRawDuration(
TimeStamp::Now() - mServiceWorkerLaunchTimeStart);
} else {
glean::service_worker::launch_time.AccumulateRawDuration(
TimeStamp::Now() - mServiceWorkerLaunchTimeStart);
}
RenewKeepAliveToken(mPendingSpawnLifetime);
mPendingSpawnLifetime = ServiceWorkerLifetimeExtension(NoLifetimeExtension{});
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
nsCOMPtr<nsIPrincipal> principal = mInfo->Principal();
RefPtr<ServiceWorkerRegistrationInfo> regInfo =
swm->GetRegistration(principal, mInfo->Scope());
if (regInfo) {
// If it's already set, we're done and the running count is already set
if (mHandlesFetch == Unknown) {
if (regInfo->GetActive()) {
mHandlesFetch =
regInfo->GetActive()->HandlesFetch() ? Enabled : Disabled;
if (mHandlesFetch == Enabled) {
UpdateRunning(0, 1);
}
}
// else we're likely still in Evaluating state, and don't know if it
// handles fetch. If so, defer updating the counter for Fetch until we
// finish evaluation. We already updated the Running count for All in
// SpawnWorkerIfNeeded().
}
}
}
void ServiceWorkerPrivate::ErrorReceived(const ErrorValue& aError) {
AssertIsOnMainThread();
MOZ_ASSERT(mInfo);
MOZ_ASSERT(mControllerChild);
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm);
ServiceWorkerInfo* info = mInfo;
swm->HandleError(nullptr, info->Principal(), info->Scope(),
info->ScriptSpec(), u""_ns, ""_ns, u""_ns, 0, 0,
nsIScriptError::errorFlag, JSEXN_ERR);
}
void ServiceWorkerPrivate::Terminated() {
AssertIsOnMainThread();
MOZ_ASSERT(mInfo);
MOZ_ASSERT(mControllerChild);
Shutdown();
}
void ServiceWorkerPrivate::RefreshRemoteWorkerData(
const RefPtr<ServiceWorkerRegistrationInfo>& aRegistration) {
AssertIsOnMainThread();
MOZ_ASSERT(mInfo);
ServiceWorkerData& serviceWorkerData =
mRemoteWorkerData.serviceWorkerData().get_ServiceWorkerData();
serviceWorkerData.descriptor() = mInfo->Descriptor().ToIPC();
serviceWorkerData.registrationDescriptor() =
aRegistration->Descriptor().ToIPC();
}
RefPtr<FetchServicePromises> ServiceWorkerPrivate::SetupNavigationPreload(
nsCOMPtr<nsIInterceptedChannel>& aChannel,
const RefPtr<ServiceWorkerRegistrationInfo>& aRegistration) {
MOZ_ASSERT(XRE_IsParentProcess());
AssertIsOnMainThread();
// create IPC request from the intercepted channel.
auto result = GetIPCInternalRequest(aChannel);
if (result.isErr()) {
return nullptr;
}
IPCInternalRequest ipcRequest = result.unwrap();
// Step 1. Clone the request for preload
// Create the InternalResponse from the created IPCRequest.
SafeRefPtr<InternalRequest> preloadRequest =
MakeSafeRefPtr<InternalRequest>(ipcRequest);
// Copy the request body from uploadChannel
nsCOMPtr<nsIUploadChannel2> uploadChannel = do_QueryInterface(aChannel);
if (uploadChannel) {
nsCOMPtr<nsIInputStream> uploadStream;
nsresult rv = uploadChannel->CloneUploadStream(
&ipcRequest.bodySize(), getter_AddRefs(uploadStream));
// Fail to get the request's body, stop navigation preload by returning
// nullptr.
if (NS_WARN_IF(NS_FAILED(rv))) {
return FetchService::NetworkErrorResponse(rv);
}
preloadRequest->SetBody(uploadStream, ipcRequest.bodySize());
}
// Set SkipServiceWorker for the navigation preload request
preloadRequest->SetSkipServiceWorker();
// Step 2. Append Service-Worker-Navigation-Preload header with
// registration->GetNavigationPreloadState().headerValue() on
// request's header list.
IgnoredErrorResult err;
auto headersGuard = preloadRequest->Headers()->Guard();
preloadRequest->Headers()->SetGuard(HeadersGuardEnum::None, err);
preloadRequest->Headers()->Append(
"Service-Worker-Navigation-Preload"_ns,
aRegistration->GetNavigationPreloadState().headerValue(), err);
preloadRequest->Headers()->SetGuard(headersGuard, err);
// Step 3. Perform fetch through FetchService with the cloned request
if (!err.Failed()) {
nsCOMPtr<nsIChannel> underlyingChannel;
MOZ_ALWAYS_SUCCEEDS(
aChannel->GetChannel(getter_AddRefs(underlyingChannel)));
RefPtr<FetchService> fetchService = FetchService::GetInstance();
return fetchService->Fetch(AsVariant(FetchService::NavigationPreloadArgs{
std::move(preloadRequest), underlyingChannel}));
}
return FetchService::NetworkErrorResponse(NS_ERROR_UNEXPECTED);
}
void ServiceWorkerPrivate::Shutdown(Maybe<RefPtr<Promise>>&& aMaybePromise) {
AssertIsOnMainThread();
if (mControllerChild) {
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
MOZ_ASSERT(swm,
"All Service Workers should start shutting down before the "
"ServiceWorkerManager does!");
auto shutdownStateId = swm->MaybeInitServiceWorkerShutdownProgress();
RefPtr<GenericNonExclusivePromise> promise =
ShutdownInternal(shutdownStateId);
swm->BlockShutdownOn(promise, shutdownStateId);
if (aMaybePromise.isSome() && aMaybePromise.ref()) {
promise->Then(
GetCurrentSerialEventTarget(), __func__,
[listener = aMaybePromise.ref()] {
listener->MaybeResolveWithUndefined();
},
[listener = aMaybePromise.ref()] {
listener->MaybeResolveWithUndefined();
});
}
} else if (aMaybePromise.isSome() && aMaybePromise.ref()) {
aMaybePromise.ref()->MaybeResolveWithUndefined();
}
MOZ_ASSERT(!mControllerChild);
}
RefPtr<GenericNonExclusivePromise> ServiceWorkerPrivate::ShutdownInternal(
uint32_t aShutdownStateId) {
AssertIsOnMainThread();
MOZ_ASSERT(mControllerChild);
mPendingFunctionalEvents.Clear();
mControllerChild->get()->RevokeObserver(this);
if (StaticPrefs::dom_serviceWorkers_testing_enabled()) {
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
if (os) {
os->NotifyObservers(nullptr, "service-worker-shutdown", nullptr);
}
}
RefPtr<GenericNonExclusivePromise::Private> promise =
new GenericNonExclusivePromise::Private(__func__);
Unused << ExecServiceWorkerOp(
ServiceWorkerTerminateWorkerOpArgs(aShutdownStateId),
// It doesn't make sense to extend the lifetime in this case. This will
// also ensure that we don't try and spawn the ServiceWorker, but as our
// assert at the top of this method makes clear, we don't expect to be in
// that situation.
ServiceWorkerLifetimeExtension(NoLifetimeExtension{}),
[promise](ServiceWorkerOpResult&& aResult) {
MOZ_ASSERT(aResult.type() == ServiceWorkerOpResult::Tnsresult);
promise->Resolve(true, __func__);
},
[promise]() { promise->Reject(NS_ERROR_DOM_ABORT_ERR, __func__); });
/**
* After dispatching a termination operation, no new operations should
* be routed through this actor anymore so we can drop the controller
* reference. This also means that the next time SpawnWorkerIfNeeded is
* invoked we will spawn a new worker, creating a new mControllerChild.
*/
mControllerChild = nullptr;
// Create a new ClientInfo for the next time we potentially spawn this
// ServiceWorker. We do this now rather than immediately before spawning the
// ServiceWorker so it's possible to know what the client id will be before
// triggering the next spawn.
RegenerateClientInfo();
// Update here, since Evaluation failures directly call ShutdownInternal
UpdateRunning(-1, mHandlesFetch == Enabled ? -1 : 0);
return promise;
}
nsresult ServiceWorkerPrivate::ExecServiceWorkerOp(
ServiceWorkerOpArgs&& aArgs,
const ServiceWorkerLifetimeExtension& aLifetimeExtension,
std::function<void(ServiceWorkerOpResult&&)>&& aSuccessCallback,
std::function<void()>&& aFailureCallback) {
AssertIsOnMainThread();
MOZ_ASSERT(
aArgs.type() !=
ServiceWorkerOpArgs::TParentToChildServiceWorkerFetchEventOpArgs,
"FetchEvent operations should be sent through FetchEventOp(Proxy) "
"actors!");
MOZ_ASSERT(aSuccessCallback);
nsresult rv = SpawnWorkerIfNeeded(aLifetimeExtension);
if (NS_WARN_IF(NS_FAILED(rv))) {
aFailureCallback();
return rv;
}
MOZ_ASSERT(mControllerChild);
RefPtr<ServiceWorkerPrivate> self = this;
RefPtr<RAIIActorPtrHolder> holder = mControllerChild;
RefPtr<KeepAliveToken> token =
aArgs.type() == ServiceWorkerOpArgs::TServiceWorkerTerminateWorkerOpArgs
? nullptr
: CreateEventKeepAliveToken();
/**
* NOTE: moving `aArgs` won't do anything until IPDL `SendMethod()` methods
* can accept rvalue references rather than just const references.
*/
mControllerChild->get()->SendExecServiceWorkerOp(aArgs)->Then(
GetCurrentSerialEventTarget(), __func__,
[self = std::move(self), holder = std::move(holder),
token = std::move(token), onSuccess = std::move(aSuccessCallback),
onFailure = std::move(aFailureCallback)](
PRemoteWorkerControllerChild::ExecServiceWorkerOpPromise::
ResolveOrRejectValue&& aResult) {
if (NS_WARN_IF(aResult.IsReject())) {
onFailure();
return;
}
onSuccess(std::move(aResult.ResolveValue()));
});
return NS_OK;
}
} // namespace mozilla::dom
|