1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=4 sw=2 cindent et: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/DebugOnly.h"
9 #include "nsIOService.h"
10 #include "nsIProtocolHandler.h"
11 #include "nsIFileProtocolHandler.h"
16 #include "nsIObserverService.h"
18 #include "nsIProxiedProtocolHandler.h"
19 #include "nsIProxyInfo.h"
20 #include "nsDNSService2.h"
22 #include "nsNetUtil.h"
25 #include "nsSimpleNestedURI.h"
26 #include "nsSocketTransport2.h"
28 #include "nsIConsoleService.h"
29 #include "nsIUploadChannel2.h"
30 #include "nsXULAppAPI.h"
31 #include "nsIProtocolProxyCallback.h"
32 #include "nsICancelable.h"
33 #include "nsINetworkLinkService.h"
34 #include "nsAsyncRedirectVerifyHelper.h"
35 #include "nsURLHelper.h"
36 #include "nsIProtocolProxyService2.h"
37 #include "MainThreadUtils.h"
39 #include "nsIWebTransport.h"
40 #include "nsIWidget.h"
41 #include "nsThreadUtils.h"
42 #include "WebTransportSessionProxy.h"
43 #include "mozilla/AppShutdown.h"
44 #include "mozilla/LoadInfo.h"
45 #include "mozilla/net/NeckoCommon.h"
46 #include "mozilla/Services.h"
47 #include "mozilla/Telemetry.h"
48 #include "mozilla/net/DNS.h"
49 #include "mozilla/ipc/URIUtils.h"
50 #include "mozilla/net/NeckoChild.h"
51 #include "mozilla/net/NeckoParent.h"
52 #include "mozilla/dom/ClientInfo.h"
53 #include "mozilla/dom/ContentParent.h"
54 #include "mozilla/dom/nsHTTPSOnlyUtils.h"
55 #include "mozilla/dom/ServiceWorkerDescriptor.h"
56 #include "mozilla/net/CaptivePortalService.h"
57 #include "mozilla/net/NetworkConnectivityService.h"
58 #include "mozilla/net/SocketProcessHost.h"
59 #include "mozilla/net/SocketProcessParent.h"
60 #include "mozilla/net/SSLTokensCache.h"
61 #include "mozilla/Unused.h"
62 #include "nsContentSecurityManager.h"
63 #include "nsContentUtils.h"
64 #include "mozilla/StaticPrefs_network.h"
65 #include "mozilla/StaticPrefs_security.h"
66 #include "nsNSSComponent.h"
68 #include "StaticComponents.h"
74 using mozilla::dom::ClientInfo
;
75 using mozilla::dom::ServiceWorkerDescriptor
;
77 #define PORT_PREF_PREFIX "network.security.ports."
78 #define PORT_PREF(x) PORT_PREF_PREFIX x
79 #define MANAGE_OFFLINE_STATUS_PREF "network.manage-offline-status"
81 // Nb: these have been misnomers since bug 715770 removed the buffer cache.
82 // "network.segment.count" and "network.segment.size" would be better names,
83 // but the old names are still used to preserve backward compatibility.
84 #define NECKO_BUFFER_CACHE_COUNT_PREF "network.buffer.cache.count"
85 #define NECKO_BUFFER_CACHE_SIZE_PREF "network.buffer.cache.size"
86 #define NETWORK_CAPTIVE_PORTAL_PREF "network.captive-portal-service.enabled"
87 #define WEBRTC_PREF_PREFIX "media.peerconnection."
88 #define NETWORK_DNS_PREF "network.dns."
89 #define FORCE_EXTERNAL_PREF_PREFIX "network.protocol-handler.external."
91 #define MAX_RECURSION_COUNT 50
93 nsIOService
* gIOService
;
94 static bool gHasWarnedUploadChannel2
;
95 static bool gCaptivePortalEnabled
= false;
96 static LazyLogModule
gIOServiceLog("nsIOService");
98 #define LOG(args) MOZ_LOG(gIOServiceLog, LogLevel::Debug, args)
100 // A general port blacklist. Connections to these ports will not be allowed
101 // unless the protocol overrides.
103 // This list is to be kept in sync with "bad ports" as defined in the
104 // WHATWG Fetch standard at <https://fetch.spec.whatwg.org/#port-blocking>
106 int16_t gBadPortList
[] = {
141 135, // loc-srv / epmap
148 427, // afp (alternate)
149 465, // smtp (alternate)
163 587, // smtp (outgoing)
170 1719, // h323gatestat
171 1720, // h323hostcall
180 6665, // irc (alternate)
181 6666, // irc (alternate)
182 6667, // irc (default)
183 6668, // irc (alternate)
184 6669, // irc (alternate)
187 0, // Sentinel value: This MUST be zero
190 static const char kProfileChangeNetTeardownTopic
[] =
191 "profile-change-net-teardown";
192 static const char kProfileChangeNetRestoreTopic
[] =
193 "profile-change-net-restore";
194 static const char kProfileDoChange
[] = "profile-do-change";
196 // Necko buffer defaults
197 uint32_t nsIOService::gDefaultSegmentSize
= 4096;
198 uint32_t nsIOService::gDefaultSegmentCount
= 24;
200 uint32_t nsIOService::sSocketProcessCrashedCount
= 0;
202 ////////////////////////////////////////////////////////////////////////////////
204 nsIOService::nsIOService()
205 : mLastOfflineStateChange(PR_IntervalNow()),
206 mLastConnectivityChange(PR_IntervalNow()),
207 mLastNetworkLinkChange(PR_IntervalNow()) {}
209 static const char* gCallbackPrefs
[] = {
211 MANAGE_OFFLINE_STATUS_PREF
,
212 NECKO_BUFFER_CACHE_COUNT_PREF
,
213 NECKO_BUFFER_CACHE_SIZE_PREF
,
214 NETWORK_CAPTIVE_PORTAL_PREF
,
215 FORCE_EXTERNAL_PREF_PREFIX
,
219 static const char* gCallbackPrefsForSocketProcess
[] = {
222 "network.send_ODA_to_content_directly",
225 "network.dns.disableIPv6",
226 "network.dns.skipTRR-when-parental-control-enabled",
227 "network.offline-mirrors-connectivity",
228 "network.disable-localhost-when-offline",
229 "network.proxy.parse_pac_on_socket_process",
230 "network.proxy.allow_hijacking_localhost",
231 "network.connectivity-service.",
232 "network.captive-portal-service.testMode",
236 static const char* gCallbackSecurityPrefs
[] = {
237 // Note the prefs listed below should be in sync with the code in
238 // HandleTLSPrefChange().
239 "security.tls.version.min",
240 "security.tls.version.max",
241 "security.tls.version.enable-deprecated",
242 "security.tls.hello_downgrade_check",
243 "security.ssl.require_safe_negotiation",
244 "security.ssl.enable_false_start",
245 "security.ssl.enable_alpn",
246 "security.tls.enable_0rtt_data",
247 "security.ssl.disable_session_identifiers",
248 "security.tls.enable_post_handshake_auth",
249 "security.tls.enable_delegated_credentials",
250 // Note the prefs listed below should be in sync with the code in
251 // SetValidationOptionsCommon().
252 "security.ssl.enable_ocsp_stapling",
253 "security.ssl.enable_ocsp_must_staple",
254 "security.pki.certificate_transparency.mode",
258 nsresult
nsIOService::Init() {
259 SSLTokensCache::Init();
261 InitializeCaptivePortalService();
263 // setup our bad port list stuff
264 for (int i
= 0; gBadPortList
[i
]; i
++) {
265 // We can't be accessed by another thread yet
266 MOZ_PUSH_IGNORE_THREAD_SAFETY
267 mRestrictedPortList
.AppendElement(gBadPortList
[i
]);
268 MOZ_POP_THREAD_SAFETY
271 // Further modifications to the port list come from prefs
272 Preferences::RegisterPrefixCallbacks(nsIOService::PrefsChanged
,
273 gCallbackPrefs
, this);
276 mSocketProcessTopicBlockedList
.Insert(
277 nsLiteralCString(NS_XPCOM_WILL_SHUTDOWN_OBSERVER_ID
));
278 mSocketProcessTopicBlockedList
.Insert(
279 nsLiteralCString(NS_XPCOM_SHUTDOWN_OBSERVER_ID
));
280 mSocketProcessTopicBlockedList
.Insert("xpcom-shutdown-threads"_ns
);
281 mSocketProcessTopicBlockedList
.Insert("profile-do-change"_ns
);
282 mSocketProcessTopicBlockedList
.Insert("network:socket-process-crashed"_ns
);
284 // Register for profile change notifications
285 mObserverService
= services::GetObserverService();
286 AddObserver(this, kProfileChangeNetTeardownTopic
, true);
287 AddObserver(this, kProfileChangeNetRestoreTopic
, true);
288 AddObserver(this, kProfileDoChange
, true);
289 AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID
, true);
290 AddObserver(this, NS_NETWORK_LINK_TOPIC
, true);
291 AddObserver(this, NS_NETWORK_ID_CHANGED_TOPIC
, true);
292 AddObserver(this, NS_WIDGET_WAKE_OBSERVER_TOPIC
, true);
294 // Register observers for sending notifications to nsSocketTransportService
295 if (XRE_IsParentProcess()) {
296 AddObserver(this, "profile-initial-state", true);
297 AddObserver(this, NS_WIDGET_SLEEP_OBSERVER_TOPIC
, true);
300 if (IsSocketProcessChild()) {
301 Preferences::RegisterCallbacks(nsIOService::OnTLSPrefChange
,
302 gCallbackSecurityPrefs
, this);
307 InitializeNetworkLinkService();
308 InitializeProtocolProxyService();
316 nsIOService::AddObserver(nsIObserver
* aObserver
, const char* aTopic
,
318 if (!mObserverService
) {
319 return NS_ERROR_FAILURE
;
322 // Register for the origional observer.
323 nsresult rv
= mObserverService
->AddObserver(aObserver
, aTopic
, aOwnsWeak
);
328 if (!XRE_IsParentProcess()) {
332 nsAutoCString
topic(aTopic
);
333 // This happens when AddObserver() is called by nsIOService::Init(). We don't
334 // want to add nsIOService again.
335 if (SameCOMIdentity(aObserver
, static_cast<nsIObserver
*>(this))) {
336 mIOServiceTopicList
.Insert(topic
);
340 if (!UseSocketProcess()) {
344 if (mSocketProcessTopicBlockedList
.Contains(topic
)) {
345 return NS_ERROR_FAILURE
;
348 // Avoid registering duplicate topics.
349 if (mObserverTopicForSocketProcess
.Contains(topic
)) {
350 return NS_ERROR_FAILURE
;
353 mObserverTopicForSocketProcess
.Insert(topic
);
355 // Avoid registering duplicate topics.
356 if (mIOServiceTopicList
.Contains(topic
)) {
357 return NS_ERROR_FAILURE
;
360 return mObserverService
->AddObserver(this, aTopic
, true);
364 nsIOService::RemoveObserver(nsIObserver
* aObserver
, const char* aTopic
) {
365 return NS_ERROR_NOT_IMPLEMENTED
;
369 nsIOService::EnumerateObservers(const char* aTopic
,
370 nsISimpleEnumerator
** anEnumerator
) {
371 return NS_ERROR_NOT_IMPLEMENTED
;
374 NS_IMETHODIMP
nsIOService::NotifyObservers(nsISupports
* aSubject
,
376 const char16_t
* aSomeData
) {
377 return NS_ERROR_NOT_IMPLEMENTED
;
380 nsIOService::~nsIOService() {
382 MOZ_ASSERT(gIOService
== this);
383 gIOService
= nullptr;
388 void nsIOService::OnTLSPrefChange(const char* aPref
, void* aSelf
) {
389 MOZ_ASSERT(IsSocketProcessChild());
391 if (!EnsureNSSInitializedChromeOrContent()) {
392 LOG(("NSS not initialized."));
396 nsAutoCString
pref(aPref
);
397 // The preferences listed in gCallbackSecurityPrefs need to be in sync with
398 // the code in HandleTLSPrefChange() and SetValidationOptionsCommon().
399 if (HandleTLSPrefChange(pref
)) {
400 LOG(("HandleTLSPrefChange done"));
401 } else if (pref
.EqualsLiteral("security.ssl.enable_ocsp_stapling") ||
402 pref
.EqualsLiteral("security.ssl.enable_ocsp_must_staple") ||
403 pref
.EqualsLiteral("security.pki.certificate_transparency.mode")) {
404 SetValidationOptionsCommon();
408 nsresult
nsIOService::InitializeCaptivePortalService() {
409 if (XRE_GetProcessType() != GeckoProcessType_Default
) {
410 // We only initalize a captive portal service in the main process
414 mCaptivePortalService
= do_GetService(NS_CAPTIVEPORTAL_CID
);
415 if (mCaptivePortalService
) {
416 return static_cast<CaptivePortalService
*>(mCaptivePortalService
.get())
420 // Instantiate and initialize the service
421 RefPtr
<NetworkConnectivityService
> ncs
=
422 NetworkConnectivityService::GetSingleton();
427 nsresult
nsIOService::InitializeSocketTransportService() {
430 if (!mSocketTransportService
) {
431 mSocketTransportService
=
432 do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID
, &rv
);
434 NS_WARNING("failed to get socket transport service");
438 if (mSocketTransportService
) {
439 rv
= mSocketTransportService
->Init();
440 NS_ASSERTION(NS_SUCCEEDED(rv
), "socket transport service init failed");
441 mSocketTransportService
->SetOffline(false);
447 nsresult
nsIOService::InitializeNetworkLinkService() {
450 if (mNetworkLinkServiceInitialized
) return rv
;
452 if (!NS_IsMainThread()) {
453 NS_WARNING("Network link service should be created on main thread");
454 return NS_ERROR_FAILURE
;
457 // go into managed mode if we can, and chrome process
458 if (!XRE_IsParentProcess()) {
459 return NS_ERROR_NOT_AVAILABLE
;
462 mNetworkLinkService
= do_GetService(NS_NETWORK_LINK_SERVICE_CONTRACTID
, &rv
);
464 if (mNetworkLinkService
) {
465 mNetworkLinkServiceInitialized
= true;
468 // After initializing the networkLinkService, query the connectivity state
469 OnNetworkLinkEvent(NS_NETWORK_LINK_DATA_UNKNOWN
);
474 nsresult
nsIOService::InitializeProtocolProxyService() {
477 if (XRE_IsParentProcess()) {
478 // for early-initialization
479 Unused
<< do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID
, &rv
);
485 already_AddRefed
<nsIOService
> nsIOService::GetInstance() {
487 RefPtr
<nsIOService
> ios
= new nsIOService();
488 if (NS_SUCCEEDED(ios
->Init())) {
489 MOZ_ASSERT(gIOService
== ios
.get());
493 return do_AddRef(gIOService
);
496 class SocketProcessListenerProxy
: public SocketProcessHost::Listener
{
498 SocketProcessListenerProxy() = default;
499 void OnProcessLaunchComplete(SocketProcessHost
* aHost
, bool aSucceeded
) {
504 gIOService
->OnProcessLaunchComplete(aHost
, aSucceeded
);
507 void OnProcessUnexpectedShutdown(SocketProcessHost
* aHost
) {
512 gIOService
->OnProcessUnexpectedShutdown(aHost
);
517 bool nsIOService::TooManySocketProcessCrash() {
518 return sSocketProcessCrashedCount
>=
519 StaticPrefs::network_max_socket_process_failed_count();
523 void nsIOService::IncreaseSocketProcessCrashCount() {
524 MOZ_ASSERT(IsNeckoChild());
525 sSocketProcessCrashedCount
++;
528 nsresult
nsIOService::LaunchSocketProcess() {
529 MOZ_ASSERT(NS_IsMainThread());
531 if (XRE_GetProcessType() != GeckoProcessType_Default
) {
535 // We shouldn't launch socket prcess when shutdown begins.
536 if (AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed
)) {
540 if (mSocketProcess
) {
544 if (PR_GetEnv("MOZ_DISABLE_SOCKET_PROCESS")) {
545 LOG(("nsIOService skipping LaunchSocketProcess because of the env"));
549 if (!StaticPrefs::network_process_enabled()) {
550 LOG(("nsIOService skipping LaunchSocketProcess because of the pref"));
554 Preferences::RegisterPrefixCallbacks(
555 nsIOService::NotifySocketProcessPrefsChanged
,
556 gCallbackPrefsForSocketProcess
, this);
558 // The subprocess is launched asynchronously, so we wait for a callback to
559 // acquire the IPDL actor.
560 mSocketProcess
= new SocketProcessHost(new SocketProcessListenerProxy());
561 LOG(("nsIOService::LaunchSocketProcess"));
562 if (!mSocketProcess
->Launch()) {
563 NS_WARNING("Failed to launch socket process!!");
564 DestroySocketProcess();
565 return NS_ERROR_FAILURE
;
571 void nsIOService::DestroySocketProcess() {
572 LOG(("nsIOService::DestroySocketProcess"));
573 MOZ_ASSERT(NS_IsMainThread());
575 if (XRE_GetProcessType() != GeckoProcessType_Default
|| !mSocketProcess
) {
579 Preferences::UnregisterPrefixCallbacks(
580 nsIOService::NotifySocketProcessPrefsChanged
,
581 gCallbackPrefsForSocketProcess
, this);
583 mSocketProcess
->Shutdown();
584 mSocketProcess
= nullptr;
587 bool nsIOService::SocketProcessReady() {
588 return mSocketProcess
&& mSocketProcess
->IsConnected();
591 static bool sUseSocketProcess
= false;
592 static bool sUseSocketProcessChecked
= false;
595 bool nsIOService::UseSocketProcess(bool aCheckAgain
) {
596 if (sUseSocketProcessChecked
&& !aCheckAgain
) {
597 return sUseSocketProcess
;
600 sUseSocketProcessChecked
= true;
601 sUseSocketProcess
= false;
603 if (PR_GetEnv("MOZ_DISABLE_SOCKET_PROCESS")) {
604 return sUseSocketProcess
;
607 if (TooManySocketProcessCrash()) {
608 LOG(("TooManySocketProcessCrash"));
609 return sUseSocketProcess
;
612 if (PR_GetEnv("MOZ_FORCE_USE_SOCKET_PROCESS")) {
613 sUseSocketProcess
= true;
614 return sUseSocketProcess
;
617 if (StaticPrefs::network_process_enabled()) {
619 StaticPrefs::network_http_network_access_on_socket_process_enabled();
621 return sUseSocketProcess
;
625 void nsIOService::NotifySocketProcessPrefsChanged(const char* aName
,
627 static_cast<nsIOService
*>(aSelf
)->NotifySocketProcessPrefsChanged(aName
);
630 void nsIOService::NotifySocketProcessPrefsChanged(const char* aName
) {
631 MOZ_ASSERT(NS_IsMainThread());
633 if (!XRE_IsParentProcess()) {
637 if (!StaticPrefs::network_process_enabled()) {
641 dom::Pref
pref(nsCString(aName
), /* isLocked */ false,
642 /* isSanitized */ false, Nothing(), Nothing());
644 Preferences::GetPreference(&pref
, GeckoProcessType_Socket
,
645 /* remoteType */ ""_ns
);
646 auto sendPrefUpdate
= [pref
]() {
647 Unused
<< gIOService
->mSocketProcess
->GetActor()->SendPreferenceUpdate(
650 CallOrWaitForSocketProcess(sendPrefUpdate
);
653 void nsIOService::OnProcessLaunchComplete(SocketProcessHost
* aHost
,
655 MOZ_ASSERT(NS_IsMainThread());
657 LOG(("nsIOService::OnProcessLaunchComplete aSucceeded=%d\n", aSucceeded
));
659 mSocketProcessLaunchComplete
= aSucceeded
;
661 if (mShutdown
|| !SocketProcessReady() || !aSucceeded
) {
662 mPendingEvents
.Clear();
666 if (!mPendingEvents
.IsEmpty()) {
667 nsTArray
<std::function
<void()>> pendingEvents
= std::move(mPendingEvents
);
668 for (auto& func
: pendingEvents
) {
674 void nsIOService::CallOrWaitForSocketProcess(
675 const std::function
<void()>& aFunc
) {
676 MOZ_ASSERT(NS_IsMainThread());
677 if (IsSocketProcessLaunchComplete() && SocketProcessReady()) {
680 mPendingEvents
.AppendElement(aFunc
); // infallible
681 LaunchSocketProcess();
685 int32_t nsIOService::SocketProcessPid() {
686 if (!mSocketProcess
) {
689 if (SocketProcessParent
* actor
= mSocketProcess
->GetActor()) {
690 return (int32_t)actor
->OtherPid();
695 bool nsIOService::IsSocketProcessLaunchComplete() {
696 MOZ_ASSERT(NS_IsMainThread());
697 return mSocketProcessLaunchComplete
;
700 void nsIOService::OnProcessUnexpectedShutdown(SocketProcessHost
* aHost
) {
701 MOZ_ASSERT(NS_IsMainThread());
703 LOG(("nsIOService::OnProcessUnexpectedShutdown\n"));
704 DestroySocketProcess();
705 mPendingEvents
.Clear();
707 // Nothing to do if socket process was not used before.
708 if (!UseSocketProcess()) {
712 sSocketProcessCrashedCount
++;
713 if (TooManySocketProcessCrash()) {
714 sUseSocketProcessChecked
= false;
715 DNSServiceWrapper::SwitchToBackupDNSService();
718 nsCOMPtr
<nsIObserverService
> observerService
= services::GetObserverService();
719 if (observerService
) {
720 (void)observerService
->NotifyObservers(
721 nullptr, "network:socket-process-crashed", nullptr);
724 // UseSocketProcess() could return false if we have too many crashes, so we
725 // should call it again.
726 if (UseSocketProcess()) {
727 MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(
728 NewRunnableMethod("nsIOService::LaunchSocketProcess", this,
729 &nsIOService::LaunchSocketProcess
)));
733 RefPtr
<MemoryReportingProcess
> nsIOService::GetSocketProcessMemoryReporter() {
734 // Check the prefs here again, since we don't want to create
735 // SocketProcessMemoryReporter for some tests.
736 if (!StaticPrefs::network_process_enabled() || !SocketProcessReady()) {
740 return new SocketProcessMemoryReporter();
744 nsIOService::SocketProcessTelemetryPing() {
745 CallOrWaitForSocketProcess([]() {
746 Unused
<< gIOService
->mSocketProcess
->GetActor()
747 ->SendSocketProcessTelemetryPing();
752 NS_IMPL_ISUPPORTS(nsIOService
, nsIIOService
, nsINetUtil
, nsISpeculativeConnect
,
753 nsIObserver
, nsIIOServiceInternal
, nsISupportsWeakReference
,
756 ////////////////////////////////////////////////////////////////////////////////
758 nsresult
nsIOService::RecheckCaptivePortal() {
759 MOZ_ASSERT(NS_IsMainThread(), "Must be called on the main thread");
760 if (!mCaptivePortalService
) {
763 nsCOMPtr
<nsIRunnable
> task
= NewRunnableMethod(
764 "nsIOService::RecheckCaptivePortal", mCaptivePortalService
,
765 &nsICaptivePortalService::RecheckCaptivePortal
);
766 return NS_DispatchToMainThread(task
);
769 nsresult
nsIOService::RecheckCaptivePortalIfLocalRedirect(nsIChannel
* newChan
) {
772 if (!mCaptivePortalService
) {
776 nsCOMPtr
<nsIURI
> uri
;
777 rv
= newChan
->GetURI(getter_AddRefs(uri
));
783 rv
= uri
->GetHost(host
);
789 // If the redirect wasn't to an IP literal, so there's probably no need
790 // to trigger the captive portal detection right now. It can wait.
791 if (NS_SUCCEEDED(addr
.InitFromString(host
)) && addr
.IsIPAddrLocal()) {
792 RecheckCaptivePortal();
798 nsresult
nsIOService::AsyncOnChannelRedirect(
799 nsIChannel
* oldChan
, nsIChannel
* newChan
, uint32_t flags
,
800 nsAsyncRedirectVerifyHelper
* helper
) {
801 // If a redirect to a local network address occurs, then chances are we
802 // are in a captive portal, so we trigger a recheck.
803 RecheckCaptivePortalIfLocalRedirect(newChan
);
805 // This is silly. I wish there was a simpler way to get at the global
806 // reference of the contentSecurityManager. But it lives in the XPCOM
808 nsCOMPtr
<nsIChannelEventSink
> sink
=
809 do_GetService(NS_CONTENTSECURITYMANAGER_CONTRACTID
);
812 helper
->DelegateOnChannelRedirect(sink
, oldChan
, newChan
, flags
);
813 if (NS_FAILED(rv
)) return rv
;
816 // Finally, our category
817 nsCOMArray
<nsIChannelEventSink
> entries
;
818 mChannelEventSinks
.GetEntries(entries
);
819 int32_t len
= entries
.Count();
820 for (int32_t i
= 0; i
< len
; ++i
) {
822 helper
->DelegateOnChannelRedirect(entries
[i
], oldChan
, newChan
, flags
);
823 if (NS_FAILED(rv
)) return rv
;
826 nsCOMPtr
<nsIHttpChannel
> httpChan(do_QueryInterface(oldChan
));
828 // Collect the redirection from HTTP(S) only.
830 MOZ_ASSERT(NS_IsMainThread());
831 nsCOMPtr
<nsIURI
> newURI
;
832 newChan
->GetURI(getter_AddRefs(newURI
));
835 nsAutoCString scheme
;
836 newURI
->GetScheme(scheme
);
837 MOZ_ASSERT(!scheme
.IsEmpty());
839 Telemetry::AccumulateCategoricalKeyed(
841 oldChan
->IsDocument()
842 ? Telemetry::LABELS_NETWORK_HTTP_REDIRECT_TO_SCHEME::topLevel
843 : Telemetry::LABELS_NETWORK_HTTP_REDIRECT_TO_SCHEME::subresource
);
849 bool nsIOService::UsesExternalProtocolHandler(const nsACString
& aScheme
) {
850 if (aScheme
== "file"_ns
|| aScheme
== "chrome"_ns
||
851 aScheme
== "resource"_ns
) {
852 // Don't allow file:, chrome: or resource: URIs to be handled with
853 // nsExternalProtocolHandler, since internally we rely on being able to
854 // use and read from these URIs.
858 if (aScheme
== "place"_ns
|| aScheme
== "fake-favicon-uri"_ns
||
859 aScheme
== "favicon"_ns
|| aScheme
== "moz-nullprincipal"_ns
) {
860 // Force place: fake-favicon-uri: favicon: and moz-nullprincipal: URIs to be
861 // handled with nsExternalProtocolHandler, and not with a dynamically
862 // registered handler.
866 // If prefs configure the URI to be handled externally, do so.
867 for (const auto& scheme
: mForceExternalSchemes
) {
868 if (aScheme
== scheme
) {
875 ProtocolHandlerInfo
nsIOService::LookupProtocolHandler(
876 const nsACString
& aScheme
) {
877 // Look-ups are ASCII-case-insensitive, so lower-case the string before
879 nsAutoCString
scheme(aScheme
);
882 // NOTE: If we could get rid of mForceExternalSchemes (or prevent them from
883 // disabling static protocols), we could avoid locking mLock until we need to
884 // check `mRuntimeProtocolHandlers.
885 AutoReadLock
lock(mLock
);
886 if (!UsesExternalProtocolHandler(scheme
)) {
887 // Try the static protocol handler first - they cannot be overridden by
888 // dynamic protocols.
889 if (const xpcom::StaticProtocolHandler
* handler
=
890 xpcom::StaticProtocolHandler::Lookup(scheme
)) {
891 return ProtocolHandlerInfo(*handler
);
893 if (auto handler
= mRuntimeProtocolHandlers
.Lookup(scheme
)) {
894 return ProtocolHandlerInfo(handler
.Data());
897 return ProtocolHandlerInfo(xpcom::StaticProtocolHandler::Default());
901 nsIOService::GetProtocolHandler(const char* scheme
,
902 nsIProtocolHandler
** result
) {
903 AssertIsOnMainThread();
904 NS_ENSURE_ARG_POINTER(scheme
);
906 *result
= LookupProtocolHandler(nsDependentCString(scheme
)).Handler().take();
907 return *result
? NS_OK
: NS_ERROR_UNKNOWN_PROTOCOL
;
911 nsIOService::ExtractScheme(const nsACString
& inURI
, nsACString
& scheme
) {
912 return net_ExtractURLScheme(inURI
, scheme
);
916 nsIOService::HostnameIsLocalIPAddress(nsIURI
* aURI
, bool* aResult
) {
917 NS_ENSURE_ARG_POINTER(aURI
);
919 nsCOMPtr
<nsIURI
> innerURI
= NS_GetInnermostURI(aURI
);
920 NS_ENSURE_ARG_POINTER(innerURI
);
923 nsresult rv
= innerURI
->GetAsciiHost(host
);
931 if (NS_SUCCEEDED(addr
.InitFromString(host
)) && addr
.IsIPAddrLocal()) {
939 nsIOService::HostnameIsSharedIPAddress(nsIURI
* aURI
, bool* aResult
) {
940 NS_ENSURE_ARG_POINTER(aURI
);
942 nsCOMPtr
<nsIURI
> innerURI
= NS_GetInnermostURI(aURI
);
943 NS_ENSURE_ARG_POINTER(innerURI
);
946 nsresult rv
= innerURI
->GetAsciiHost(host
);
954 if (NS_SUCCEEDED(addr
.InitFromString(host
)) && addr
.IsIPAddrShared()) {
962 nsIOService::GetProtocolFlags(const char* scheme
, uint32_t* flags
) {
963 NS_ENSURE_ARG_POINTER(scheme
);
966 LookupProtocolHandler(nsDependentCString(scheme
)).StaticProtocolFlags();
971 nsIOService::GetDynamicProtocolFlags(nsIURI
* uri
, uint32_t* flags
) {
972 AssertIsOnMainThread();
975 nsAutoCString scheme
;
976 nsresult rv
= uri
->GetScheme(scheme
);
977 NS_ENSURE_SUCCESS(rv
, rv
);
979 return LookupProtocolHandler(scheme
).DynamicProtocolFlags(uri
, flags
);
983 nsIOService::GetDefaultPort(const char* scheme
, int32_t* defaultPort
) {
984 NS_ENSURE_ARG_POINTER(scheme
);
987 LookupProtocolHandler(nsDependentCString(scheme
)).DefaultPort();
991 class AutoIncrement
{
993 explicit AutoIncrement(uint32_t* var
) : mVar(var
) { ++*var
; }
994 ~AutoIncrement() { --*mVar
; }
1000 nsresult
nsIOService::NewURI(const nsACString
& aSpec
, const char* aCharset
,
1001 nsIURI
* aBaseURI
, nsIURI
** result
) {
1002 return NS_NewURI(result
, aSpec
, aCharset
, aBaseURI
);
1006 nsIOService::NewFileURI(nsIFile
* file
, nsIURI
** result
) {
1008 NS_ENSURE_ARG_POINTER(file
);
1010 nsCOMPtr
<nsIProtocolHandler
> handler
;
1012 rv
= GetProtocolHandler("file", getter_AddRefs(handler
));
1013 if (NS_FAILED(rv
)) return rv
;
1015 nsCOMPtr
<nsIFileProtocolHandler
> fileHandler(do_QueryInterface(handler
, &rv
));
1016 if (NS_FAILED(rv
)) return rv
;
1018 return fileHandler
->NewFileURI(file
, result
);
1022 already_AddRefed
<nsIURI
> nsIOService::CreateExposableURI(nsIURI
* aURI
) {
1023 MOZ_ASSERT(aURI
, "Must have a URI");
1024 nsCOMPtr
<nsIURI
> uri
= aURI
;
1026 nsAutoCString userPass
;
1027 uri
->GetUserPass(userPass
);
1028 if (!userPass
.IsEmpty()) {
1029 DebugOnly
<nsresult
> rv
= NS_MutateURI(uri
).SetUserPass(""_ns
).Finalize(uri
);
1030 MOZ_ASSERT(NS_SUCCEEDED(rv
) && uri
, "Mutating URI should never fail");
1032 return uri
.forget();
1036 nsIOService::CreateExposableURI(nsIURI
* aURI
, nsIURI
** _result
) {
1037 NS_ENSURE_ARG_POINTER(aURI
);
1038 NS_ENSURE_ARG_POINTER(_result
);
1039 nsCOMPtr
<nsIURI
> exposableURI
= CreateExposableURI(aURI
);
1040 exposableURI
.forget(_result
);
1045 nsIOService::NewChannelFromURI(nsIURI
* aURI
, nsINode
* aLoadingNode
,
1046 nsIPrincipal
* aLoadingPrincipal
,
1047 nsIPrincipal
* aTriggeringPrincipal
,
1048 uint32_t aSecurityFlags
,
1049 nsContentPolicyType aContentPolicyType
,
1050 nsIChannel
** result
) {
1051 return NewChannelFromURIWithProxyFlags(aURI
,
1052 nullptr, // aProxyURI
1054 aLoadingNode
, aLoadingPrincipal
,
1055 aTriggeringPrincipal
, aSecurityFlags
,
1056 aContentPolicyType
, result
);
1058 nsresult
nsIOService::NewChannelFromURIWithClientAndController(
1059 nsIURI
* aURI
, nsINode
* aLoadingNode
, nsIPrincipal
* aLoadingPrincipal
,
1060 nsIPrincipal
* aTriggeringPrincipal
,
1061 const Maybe
<ClientInfo
>& aLoadingClientInfo
,
1062 const Maybe
<ServiceWorkerDescriptor
>& aController
, uint32_t aSecurityFlags
,
1063 nsContentPolicyType aContentPolicyType
, uint32_t aSandboxFlags
,
1064 bool aSkipCheckForBrokenURLOrZeroSized
, nsIChannel
** aResult
) {
1065 return NewChannelFromURIWithProxyFlagsInternal(
1067 nullptr, // aProxyURI
1069 aLoadingNode
, aLoadingPrincipal
, aTriggeringPrincipal
, aLoadingClientInfo
,
1070 aController
, aSecurityFlags
, aContentPolicyType
, aSandboxFlags
,
1071 aSkipCheckForBrokenURLOrZeroSized
, aResult
);
1075 nsIOService::NewChannelFromURIWithLoadInfo(nsIURI
* aURI
, nsILoadInfo
* aLoadInfo
,
1076 nsIChannel
** result
) {
1077 return NewChannelFromURIWithProxyFlagsInternal(aURI
,
1078 nullptr, // aProxyURI
1083 nsresult
nsIOService::NewChannelFromURIWithProxyFlagsInternal(
1084 nsIURI
* aURI
, nsIURI
* aProxyURI
, uint32_t aProxyFlags
,
1085 nsINode
* aLoadingNode
, nsIPrincipal
* aLoadingPrincipal
,
1086 nsIPrincipal
* aTriggeringPrincipal
,
1087 const Maybe
<ClientInfo
>& aLoadingClientInfo
,
1088 const Maybe
<ServiceWorkerDescriptor
>& aController
, uint32_t aSecurityFlags
,
1089 nsContentPolicyType aContentPolicyType
, uint32_t aSandboxFlags
,
1090 bool aSkipCheckForBrokenURLOrZeroSized
, nsIChannel
** result
) {
1091 nsCOMPtr
<nsILoadInfo
> loadInfo
= new LoadInfo(
1092 aLoadingPrincipal
, aTriggeringPrincipal
, aLoadingNode
, aSecurityFlags
,
1093 aContentPolicyType
, aLoadingClientInfo
, aController
, aSandboxFlags
,
1094 aSkipCheckForBrokenURLOrZeroSized
);
1095 return NewChannelFromURIWithProxyFlagsInternal(aURI
, aProxyURI
, aProxyFlags
,
1099 nsresult
nsIOService::NewChannelFromURIWithProxyFlagsInternal(
1100 nsIURI
* aURI
, nsIURI
* aProxyURI
, uint32_t aProxyFlags
,
1101 nsILoadInfo
* aLoadInfo
, nsIChannel
** result
) {
1103 NS_ENSURE_ARG_POINTER(aURI
);
1104 // all channel creations must provide a valid loadinfo
1105 MOZ_ASSERT(aLoadInfo
, "can not create channel without aLoadInfo");
1106 NS_ENSURE_ARG_POINTER(aLoadInfo
);
1108 nsAutoCString scheme
;
1109 rv
= aURI
->GetScheme(scheme
);
1110 if (NS_FAILED(rv
)) return rv
;
1112 nsCOMPtr
<nsIProtocolHandler
> handler
;
1113 rv
= GetProtocolHandler(scheme
.get(), getter_AddRefs(handler
));
1114 if (NS_FAILED(rv
)) return rv
;
1116 nsCOMPtr
<nsIChannel
> channel
;
1117 nsCOMPtr
<nsIProxiedProtocolHandler
> pph
= do_QueryInterface(handler
);
1119 rv
= pph
->NewProxiedChannel(aURI
, nullptr, aProxyFlags
, aProxyURI
,
1120 aLoadInfo
, getter_AddRefs(channel
));
1122 rv
= handler
->NewChannel(aURI
, aLoadInfo
, getter_AddRefs(channel
));
1124 if (NS_FAILED(rv
)) return rv
;
1126 // Make sure that all the individual protocolhandlers attach a loadInfo.
1127 nsCOMPtr
<nsILoadInfo
> loadInfo
= channel
->LoadInfo();
1128 if (aLoadInfo
!= loadInfo
) {
1129 MOZ_ASSERT(false, "newly created channel must have a loadinfo attached");
1130 return NS_ERROR_UNEXPECTED
;
1133 // If we're sandboxed, make sure to clear any owner the channel
1134 // might already have.
1135 if (loadInfo
->GetLoadingSandboxed()) {
1136 channel
->SetOwner(nullptr);
1139 // Some extensions override the http protocol handler and provide their own
1140 // implementation. The channels returned from that implementation doesn't
1141 // seem to always implement the nsIUploadChannel2 interface, presumably
1142 // because it's a new interface.
1143 // Eventually we should remove this and simply require that http channels
1144 // implement the new interface.
1146 if (!gHasWarnedUploadChannel2
&& scheme
.EqualsLiteral("http")) {
1147 nsCOMPtr
<nsIUploadChannel2
> uploadChannel2
= do_QueryInterface(channel
);
1148 if (!uploadChannel2
) {
1149 nsCOMPtr
<nsIConsoleService
> consoleService
=
1150 do_GetService(NS_CONSOLESERVICE_CONTRACTID
);
1151 if (consoleService
) {
1152 consoleService
->LogStringMessage(
1153 u
"Http channel implementation "
1154 "doesn't support nsIUploadChannel2. An extension has "
1155 "supplied a non-functional http protocol handler. This will "
1156 "break behavior and in future releases not work at all.");
1158 gHasWarnedUploadChannel2
= true;
1162 channel
.forget(result
);
1167 nsIOService::NewChannelFromURIWithProxyFlags(
1168 nsIURI
* aURI
, nsIURI
* aProxyURI
, uint32_t aProxyFlags
,
1169 nsINode
* aLoadingNode
, nsIPrincipal
* aLoadingPrincipal
,
1170 nsIPrincipal
* aTriggeringPrincipal
, uint32_t aSecurityFlags
,
1171 nsContentPolicyType aContentPolicyType
, nsIChannel
** result
) {
1172 return NewChannelFromURIWithProxyFlagsInternal(
1173 aURI
, aProxyURI
, aProxyFlags
, aLoadingNode
, aLoadingPrincipal
,
1174 aTriggeringPrincipal
, Maybe
<ClientInfo
>(),
1175 Maybe
<ServiceWorkerDescriptor
>(), aSecurityFlags
, aContentPolicyType
, 0,
1176 /* aSkipCheckForBrokenURLOrZeroSized = */ false, result
);
1180 nsIOService::NewChannel(const nsACString
& aSpec
, const char* aCharset
,
1181 nsIURI
* aBaseURI
, nsINode
* aLoadingNode
,
1182 nsIPrincipal
* aLoadingPrincipal
,
1183 nsIPrincipal
* aTriggeringPrincipal
,
1184 uint32_t aSecurityFlags
,
1185 nsContentPolicyType aContentPolicyType
,
1186 nsIChannel
** result
) {
1188 nsCOMPtr
<nsIURI
> uri
;
1189 rv
= NewURI(aSpec
, aCharset
, aBaseURI
, getter_AddRefs(uri
));
1190 if (NS_FAILED(rv
)) return rv
;
1192 return NewChannelFromURI(uri
, aLoadingNode
, aLoadingPrincipal
,
1193 aTriggeringPrincipal
, aSecurityFlags
,
1194 aContentPolicyType
, result
);
1198 nsIOService::NewWebTransport(nsIWebTransport
** result
) {
1199 if (!XRE_IsParentProcess()) {
1200 return NS_ERROR_NOT_AVAILABLE
;
1203 nsCOMPtr
<nsIWebTransport
> webTransport
= new WebTransportSessionProxy();
1205 webTransport
.forget(result
);
1209 bool nsIOService::IsLinkUp() {
1210 InitializeNetworkLinkService();
1212 if (!mNetworkLinkService
) {
1213 // We cannot decide, assume the link is up
1219 rv
= mNetworkLinkService
->GetIsLinkUp(&isLinkUp
);
1220 if (NS_FAILED(rv
)) {
1228 nsIOService::GetOffline(bool* offline
) {
1229 if (StaticPrefs::network_offline_mirrors_connectivity()) {
1230 *offline
= mOffline
|| !mConnectivity
;
1232 *offline
= mOffline
;
1238 nsIOService::SetOffline(bool offline
) { return SetOfflineInternal(offline
); }
1240 nsresult
nsIOService::SetOfflineInternal(bool offline
,
1241 bool notifySocketProcess
) {
1242 LOG(("nsIOService::SetOffline offline=%d\n", offline
));
1243 // When someone wants to go online (!offline) after we got XPCOM shutdown
1244 // throw ERROR_NOT_AVAILABLE to prevent return to online state.
1245 if ((mShutdown
|| mOfflineForProfileChange
) && !offline
) {
1246 return NS_ERROR_NOT_AVAILABLE
;
1249 // SetOffline() may re-enter while it's shutting down services.
1250 // If that happens, save the most recent value and it will be
1251 // processed when the first SetOffline() call is done bringing
1252 // down the service.
1253 mSetOfflineValue
= offline
;
1254 if (mSettingOffline
) {
1258 mSettingOffline
= true;
1260 nsCOMPtr
<nsIObserverService
> observerService
= services::GetObserverService();
1262 NS_ASSERTION(observerService
, "The observer service should not be null");
1264 if (XRE_IsParentProcess()) {
1265 if (observerService
) {
1266 (void)observerService
->NotifyObservers(nullptr,
1267 NS_IPC_IOSERVICE_SET_OFFLINE_TOPIC
,
1268 offline
? u
"true" : u
"false");
1270 if (SocketProcessReady() && notifySocketProcess
) {
1271 Unused
<< mSocketProcess
->GetActor()->SendSetOffline(offline
);
1275 nsIIOService
* subject
= static_cast<nsIIOService
*>(this);
1276 while (mSetOfflineValue
!= mOffline
) {
1277 offline
= mSetOfflineValue
;
1279 if (offline
&& !mOffline
) {
1280 mOffline
= true; // indicate we're trying to shutdown
1282 // don't care if notifications fail
1283 if (observerService
) {
1284 observerService
->NotifyObservers(subject
,
1285 NS_IOSERVICE_GOING_OFFLINE_TOPIC
,
1286 u
"" NS_IOSERVICE_OFFLINE
);
1289 if (mSocketTransportService
) mSocketTransportService
->SetOffline(true);
1291 mLastOfflineStateChange
= PR_IntervalNow();
1292 if (observerService
) {
1293 observerService
->NotifyObservers(subject
,
1294 NS_IOSERVICE_OFFLINE_STATUS_TOPIC
,
1295 u
"" NS_IOSERVICE_OFFLINE
);
1297 } else if (!offline
&& mOffline
) {
1299 InitializeSocketTransportService();
1300 mOffline
= false; // indicate success only AFTER we've
1301 // brought up the services
1303 mLastOfflineStateChange
= PR_IntervalNow();
1304 // don't care if notification fails
1305 // Only send the ONLINE notification if there is connectivity
1306 if (observerService
&& mConnectivity
) {
1307 observerService
->NotifyObservers(subject
,
1308 NS_IOSERVICE_OFFLINE_STATUS_TOPIC
,
1309 (u
"" NS_IOSERVICE_ONLINE
));
1314 // Don't notify here, as the above notifications (if used) suffice.
1315 if ((mShutdown
|| mOfflineForProfileChange
) && mOffline
) {
1316 if (mSocketTransportService
) {
1317 DebugOnly
<nsresult
> rv
= mSocketTransportService
->Shutdown(mShutdown
);
1318 NS_ASSERTION(NS_SUCCEEDED(rv
),
1319 "socket transport service shutdown failed");
1323 mSettingOffline
= false;
1329 nsIOService::GetConnectivity(bool* aConnectivity
) {
1330 *aConnectivity
= mConnectivity
;
1335 nsIOService::SetConnectivity(bool aConnectivity
) {
1336 LOG(("nsIOService::SetConnectivity aConnectivity=%d\n", aConnectivity
));
1337 // This should only be called from ContentChild to pass the connectivity
1338 // value from the chrome process to the content process.
1339 if (XRE_IsParentProcess()) {
1340 return NS_ERROR_NOT_AVAILABLE
;
1342 return SetConnectivityInternal(aConnectivity
);
1345 nsresult
nsIOService::SetConnectivityInternal(bool aConnectivity
) {
1346 LOG(("nsIOService::SetConnectivityInternal aConnectivity=%d\n",
1348 if (mConnectivity
== aConnectivity
) {
1349 // Nothing to do here.
1352 mConnectivity
= aConnectivity
;
1354 // This is used for PR_Connect PR_Close telemetry so it is important that
1355 // we have statistic about network change event even if we are offline.
1356 mLastConnectivityChange
= PR_IntervalNow();
1358 if (mCaptivePortalService
) {
1359 if (aConnectivity
&& gCaptivePortalEnabled
) {
1360 // This will also trigger a captive portal check for the new network
1361 static_cast<CaptivePortalService
*>(mCaptivePortalService
.get())->Start();
1363 static_cast<CaptivePortalService
*>(mCaptivePortalService
.get())->Stop();
1367 nsCOMPtr
<nsIObserverService
> observerService
= services::GetObserverService();
1368 if (!observerService
) {
1371 // This notification sends the connectivity to the child processes
1372 if (XRE_IsParentProcess()) {
1373 observerService
->NotifyObservers(nullptr,
1374 NS_IPC_IOSERVICE_SET_CONNECTIVITY_TOPIC
,
1375 aConnectivity
? u
"true" : u
"false");
1376 if (SocketProcessReady()) {
1377 Unused
<< mSocketProcess
->GetActor()->SendSetConnectivity(aConnectivity
);
1382 // We don't need to send any notifications if we're offline
1386 if (aConnectivity
) {
1387 // If we were previously offline due to connectivity=false,
1388 // send the ONLINE notification
1389 observerService
->NotifyObservers(static_cast<nsIIOService
*>(this),
1390 NS_IOSERVICE_OFFLINE_STATUS_TOPIC
,
1391 (u
"" NS_IOSERVICE_ONLINE
));
1393 // If we were previously online and lost connectivity
1394 // send the OFFLINE notification
1395 observerService
->NotifyObservers(static_cast<nsIIOService
*>(this),
1396 NS_IOSERVICE_GOING_OFFLINE_TOPIC
,
1397 u
"" NS_IOSERVICE_OFFLINE
);
1398 observerService
->NotifyObservers(static_cast<nsIIOService
*>(this),
1399 NS_IOSERVICE_OFFLINE_STATUS_TOPIC
,
1400 u
"" NS_IOSERVICE_OFFLINE
);
1406 nsIOService::AllowPort(int32_t inPort
, const char* scheme
, bool* _retval
) {
1407 int32_t port
= inPort
;
1413 if (port
<= 0 || port
> std::numeric_limits
<uint16_t>::max()) {
1418 nsTArray
<int32_t> restrictedPortList
;
1420 AutoReadLock
lock(mLock
);
1421 restrictedPortList
.Assign(mRestrictedPortList
);
1423 // first check to see if the port is in our blacklist:
1424 int32_t badPortListCnt
= restrictedPortList
.Length();
1425 for (int i
= 0; i
< badPortListCnt
; i
++) {
1426 if (port
== restrictedPortList
[i
]) {
1429 // check to see if the protocol wants to override
1430 if (!scheme
) return NS_OK
;
1432 // We don't support get protocol handler off main thread.
1433 if (!NS_IsMainThread()) {
1436 nsCOMPtr
<nsIProtocolHandler
> handler
;
1437 nsresult rv
= GetProtocolHandler(scheme
, getter_AddRefs(handler
));
1438 if (NS_FAILED(rv
)) return rv
;
1440 // let the protocol handler decide
1441 return handler
->AllowPort(port
, scheme
, _retval
);
1449 ////////////////////////////////////////////////////////////////////////////////
1452 void nsIOService::PrefsChanged(const char* pref
, void* self
) {
1453 static_cast<nsIOService
*>(self
)->PrefsChanged(pref
);
1456 void nsIOService::PrefsChanged(const char* pref
) {
1457 // Look for extra ports to block
1458 if (!pref
|| strcmp(pref
, PORT_PREF("banned")) == 0) {
1459 ParsePortList(PORT_PREF("banned"), false);
1462 // ...as well as previous blocks to remove.
1463 if (!pref
|| strcmp(pref
, PORT_PREF("banned.override")) == 0) {
1464 ParsePortList(PORT_PREF("banned.override"), true);
1467 if (!pref
|| strcmp(pref
, MANAGE_OFFLINE_STATUS_PREF
) == 0) {
1469 if (mNetworkLinkServiceInitialized
&&
1471 Preferences::GetBool(MANAGE_OFFLINE_STATUS_PREF
, &manage
))) {
1472 LOG(("nsIOService::PrefsChanged ManageOfflineStatus manage=%d\n",
1474 SetManageOfflineStatus(manage
);
1478 if (!pref
|| strcmp(pref
, NECKO_BUFFER_CACHE_COUNT_PREF
) == 0) {
1481 Preferences::GetInt(NECKO_BUFFER_CACHE_COUNT_PREF
, &count
))) {
1482 /* check for bogus values and default if we find such a value */
1483 if (count
> 0) gDefaultSegmentCount
= count
;
1487 if (!pref
|| strcmp(pref
, NECKO_BUFFER_CACHE_SIZE_PREF
) == 0) {
1490 Preferences::GetInt(NECKO_BUFFER_CACHE_SIZE_PREF
, &size
))) {
1491 /* check for bogus values and default if we find such a value
1492 * the upper limit here is arbitrary. having a 1mb segment size
1493 * is pretty crazy. if you remove this, consider adding some
1494 * integer rollover test.
1496 if (size
> 0 && size
< 1024 * 1024) gDefaultSegmentSize
= size
;
1498 NS_WARNING_ASSERTION(!(size
& (size
- 1)),
1499 "network segment size is not a power of 2!");
1502 if (!pref
|| strcmp(pref
, NETWORK_CAPTIVE_PORTAL_PREF
) == 0) {
1503 nsresult rv
= Preferences::GetBool(NETWORK_CAPTIVE_PORTAL_PREF
,
1504 &gCaptivePortalEnabled
);
1505 if (NS_SUCCEEDED(rv
) && mCaptivePortalService
) {
1506 if (gCaptivePortalEnabled
) {
1507 static_cast<CaptivePortalService
*>(mCaptivePortalService
.get())
1510 static_cast<CaptivePortalService
*>(mCaptivePortalService
.get())->Stop();
1515 if (!pref
|| strncmp(pref
, FORCE_EXTERNAL_PREF_PREFIX
,
1516 strlen(FORCE_EXTERNAL_PREF_PREFIX
)) == 0) {
1517 nsTArray
<nsCString
> prefs
;
1518 if (nsIPrefBranch
* prefRootBranch
= Preferences::GetRootBranch()) {
1519 prefRootBranch
->GetChildList(FORCE_EXTERNAL_PREF_PREFIX
, prefs
);
1521 nsTArray
<nsCString
> forceExternalSchemes
;
1522 for (const auto& pref
: prefs
) {
1523 if (Preferences::GetBool(pref
.get(), false)) {
1524 forceExternalSchemes
.AppendElement(
1525 Substring(pref
, strlen(FORCE_EXTERNAL_PREF_PREFIX
)));
1528 AutoWriteLock
lock(mLock
);
1529 mForceExternalSchemes
= std::move(forceExternalSchemes
);
1533 void nsIOService::ParsePortList(const char* pref
, bool remove
) {
1534 nsAutoCString portList
;
1535 nsTArray
<int32_t> restrictedPortList
;
1537 AutoWriteLock
lock(mLock
);
1538 restrictedPortList
.Assign(std::move(mRestrictedPortList
));
1540 // Get a pref string and chop it up into a list of ports.
1541 Preferences::GetCString(pref
, portList
);
1542 if (!portList
.IsVoid()) {
1543 nsTArray
<nsCString
> portListArray
;
1544 ParseString(portList
, ',', portListArray
);
1546 for (index
= 0; index
< portListArray
.Length(); index
++) {
1547 portListArray
[index
].StripWhitespace();
1548 int32_t portBegin
, portEnd
;
1550 if (PR_sscanf(portListArray
[index
].get(), "%d-%d", &portBegin
,
1552 if ((portBegin
< 65536) && (portEnd
< 65536)) {
1555 for (curPort
= portBegin
; curPort
<= portEnd
; curPort
++) {
1556 restrictedPortList
.RemoveElement(curPort
);
1559 for (curPort
= portBegin
; curPort
<= portEnd
; curPort
++) {
1560 restrictedPortList
.AppendElement(curPort
);
1565 nsresult aErrorCode
;
1566 int32_t port
= portListArray
[index
].ToInteger(&aErrorCode
);
1567 if (NS_SUCCEEDED(aErrorCode
) && port
< 65536) {
1569 restrictedPortList
.RemoveElement(port
);
1571 restrictedPortList
.AppendElement(port
);
1578 AutoWriteLock
lock(mLock
);
1579 mRestrictedPortList
.Assign(std::move(restrictedPortList
));
1582 class nsWakeupNotifier
: public Runnable
{
1584 explicit nsWakeupNotifier(nsIIOServiceInternal
* ioService
)
1585 : Runnable("net::nsWakeupNotifier"), mIOService(ioService
) {}
1587 NS_IMETHOD
Run() override
{ return mIOService
->NotifyWakeup(); }
1590 virtual ~nsWakeupNotifier() = default;
1591 nsCOMPtr
<nsIIOServiceInternal
> mIOService
;
1595 nsIOService::NotifyWakeup() {
1596 nsCOMPtr
<nsIObserverService
> observerService
= services::GetObserverService();
1598 NS_ASSERTION(observerService
, "The observer service should not be null");
1600 if (observerService
&& StaticPrefs::network_notify_changed()) {
1601 (void)observerService
->NotifyObservers(nullptr, NS_NETWORK_LINK_TOPIC
,
1602 (u
"" NS_NETWORK_LINK_DATA_CHANGED
));
1605 RecheckCaptivePortal();
1610 void nsIOService::SetHttpHandlerAlreadyShutingDown() {
1611 if (!mShutdown
&& !mOfflineForProfileChange
) {
1612 mNetTearingDownStarted
= PR_IntervalNow();
1613 mHttpHandlerAlreadyShutingDown
= true;
1617 // nsIObserver interface
1619 nsIOService::Observe(nsISupports
* subject
, const char* topic
,
1620 const char16_t
* data
) {
1621 if (UseSocketProcess() && SocketProcessReady() &&
1622 mObserverTopicForSocketProcess
.Contains(nsDependentCString(topic
))) {
1623 nsCString
topicStr(topic
);
1624 nsString
dataStr(data
);
1625 Unused
<< mSocketProcess
->GetActor()->SendNotifyObserver(topicStr
, dataStr
);
1628 if (!strcmp(topic
, kProfileChangeNetTeardownTopic
)) {
1629 if (!mHttpHandlerAlreadyShutingDown
) {
1630 mNetTearingDownStarted
= PR_IntervalNow();
1632 mHttpHandlerAlreadyShutingDown
= false;
1634 mOfflineForProfileChange
= true;
1635 SetOfflineInternal(true, false);
1637 } else if (!strcmp(topic
, kProfileChangeNetRestoreTopic
)) {
1638 if (mOfflineForProfileChange
) {
1639 mOfflineForProfileChange
= false;
1640 SetOfflineInternal(false, false);
1642 } else if (!strcmp(topic
, kProfileDoChange
)) {
1643 if (data
&& u
"startup"_ns
.Equals(data
)) {
1644 // Lazy initialization of network link service (see bug 620472)
1645 InitializeNetworkLinkService();
1646 // Set up the initilization flag regardless the actuall result.
1647 // If we fail here, we will fail always on.
1648 mNetworkLinkServiceInitialized
= true;
1650 // And now reflect the preference setting
1651 PrefsChanged(MANAGE_OFFLINE_STATUS_PREF
);
1653 // Bug 870460 - Read cookie database at an early-as-possible time
1654 // off main thread. Hence, we have more chance to finish db query
1655 // before something calls into the cookie service.
1656 nsCOMPtr
<nsISupports
> cookieServ
=
1657 do_GetService(NS_COOKIESERVICE_CONTRACTID
);
1659 } else if (!strcmp(topic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
)) {
1660 // Remember we passed XPCOM shutdown notification to prevent any
1661 // changes of the offline status from now. We must not allow going
1662 // online after this point.
1665 if (!mHttpHandlerAlreadyShutingDown
&& !mOfflineForProfileChange
) {
1666 mNetTearingDownStarted
= PR_IntervalNow();
1668 mHttpHandlerAlreadyShutingDown
= false;
1670 SetOfflineInternal(true, false);
1672 if (mCaptivePortalService
) {
1673 static_cast<CaptivePortalService
*>(mCaptivePortalService
.get())->Stop();
1674 mCaptivePortalService
= nullptr;
1677 SSLTokensCache::Shutdown();
1679 DestroySocketProcess();
1681 if (IsSocketProcessChild()) {
1682 Preferences::UnregisterCallbacks(nsIOService::OnTLSPrefChange
,
1683 gCallbackSecurityPrefs
, this);
1684 PrepareForShutdownInSocketProcess();
1687 // We're in XPCOM shutdown now. Unregister any dynamic protocol handlers
1688 // after this point to avoid leaks.
1690 AutoWriteLock
lock(mLock
);
1691 mRuntimeProtocolHandlers
.Clear();
1693 } else if (!strcmp(topic
, NS_NETWORK_LINK_TOPIC
)) {
1694 OnNetworkLinkEvent(NS_ConvertUTF16toUTF8(data
).get());
1695 } else if (!strcmp(topic
, NS_NETWORK_ID_CHANGED_TOPIC
)) {
1696 LOG(("nsIOService::OnNetworkLinkEvent Network id changed"));
1697 } else if (!strcmp(topic
, NS_WIDGET_WAKE_OBSERVER_TOPIC
)) {
1698 // coming back alive from sleep
1699 // this indirection brought to you by:
1700 // https://bugzilla.mozilla.org/show_bug.cgi?id=1152048#c19
1701 nsCOMPtr
<nsIRunnable
> wakeupNotifier
= new nsWakeupNotifier(this);
1702 NS_DispatchToMainThread(wakeupNotifier
);
1708 // nsINetUtil interface
1710 nsIOService::ParseRequestContentType(const nsACString
& aTypeHeader
,
1711 nsACString
& aCharset
, bool* aHadCharset
,
1712 nsACString
& aContentType
) {
1713 net_ParseRequestContentType(aTypeHeader
, aContentType
, aCharset
, aHadCharset
);
1717 // nsINetUtil interface
1719 nsIOService::ParseResponseContentType(const nsACString
& aTypeHeader
,
1720 nsACString
& aCharset
, bool* aHadCharset
,
1721 nsACString
& aContentType
) {
1722 net_ParseContentType(aTypeHeader
, aContentType
, aCharset
, aHadCharset
);
1727 nsIOService::ProtocolHasFlags(nsIURI
* uri
, uint32_t flags
, bool* result
) {
1731 nsAutoCString scheme
;
1732 nsresult rv
= uri
->GetScheme(scheme
);
1733 NS_ENSURE_SUCCESS(rv
, rv
);
1735 auto handler
= LookupProtocolHandler(scheme
);
1737 uint32_t protocolFlags
;
1738 if (flags
& nsIProtocolHandler::DYNAMIC_URI_FLAGS
) {
1739 AssertIsOnMainThread();
1740 rv
= handler
.DynamicProtocolFlags(uri
, &protocolFlags
);
1741 NS_ENSURE_SUCCESS(rv
, rv
);
1743 protocolFlags
= handler
.StaticProtocolFlags();
1746 *result
= (protocolFlags
& flags
) == flags
;
1751 nsIOService::URIChainHasFlags(nsIURI
* uri
, uint32_t flags
, bool* result
) {
1752 nsresult rv
= ProtocolHasFlags(uri
, flags
, result
);
1753 NS_ENSURE_SUCCESS(rv
, rv
);
1759 // Dig deeper into the chain. Note that this is not a do/while loop to
1760 // avoid the extra addref/release on |uri| in the common (non-nested) case.
1761 nsCOMPtr
<nsINestedURI
> nestedURI
= do_QueryInterface(uri
);
1763 nsCOMPtr
<nsIURI
> innerURI
;
1764 rv
= nestedURI
->GetInnerURI(getter_AddRefs(innerURI
));
1765 NS_ENSURE_SUCCESS(rv
, rv
);
1767 rv
= ProtocolHasFlags(innerURI
, flags
, result
);
1773 nestedURI
= do_QueryInterface(innerURI
);
1780 nsIOService::SetManageOfflineStatus(bool aManage
) {
1781 LOG(("nsIOService::SetManageOfflineStatus aManage=%d\n", aManage
));
1782 mManageLinkStatus
= aManage
;
1784 // When detection is not activated, the default connectivity state is true.
1785 if (!mManageLinkStatus
) {
1786 SetConnectivityInternal(true);
1790 InitializeNetworkLinkService();
1791 // If the NetworkLinkService is already initialized, it does not call
1792 // OnNetworkLinkEvent. This is needed, when mManageLinkStatus goes from
1794 OnNetworkLinkEvent(NS_NETWORK_LINK_DATA_UNKNOWN
);
1799 nsIOService::GetManageOfflineStatus(bool* aManage
) {
1800 *aManage
= mManageLinkStatus
;
1804 // input argument 'data' is already UTF8'ed
1805 nsresult
nsIOService::OnNetworkLinkEvent(const char* data
) {
1806 if (IsNeckoChild() || IsSocketProcessChild()) {
1807 // There is nothing IO service could do on the child process
1808 // with this at the moment. Feel free to add functionality
1809 // here at will, though.
1814 return NS_ERROR_NOT_AVAILABLE
;
1817 nsCString
dataAsString(data
);
1818 for (auto* cp
: mozilla::dom::ContentParent::AllProcesses(
1819 mozilla::dom::ContentParent::eLive
)) {
1820 PNeckoParent
* neckoParent
= SingleManagedOrNull(cp
->ManagedPNeckoParent());
1824 Unused
<< neckoParent
->SendNetworkChangeNotification(dataAsString
);
1827 LOG(("nsIOService::OnNetworkLinkEvent data:%s\n", data
));
1828 if (!mNetworkLinkService
) {
1829 return NS_ERROR_FAILURE
;
1832 if (!mManageLinkStatus
) {
1833 LOG(("nsIOService::OnNetworkLinkEvent mManageLinkStatus=false\n"));
1838 if (!strcmp(data
, NS_NETWORK_LINK_DATA_CHANGED
)) {
1839 mLastNetworkLinkChange
= PR_IntervalNow();
1840 // CHANGED means UP/DOWN didn't change
1841 // but the status of the captive portal may have changed.
1842 RecheckCaptivePortal();
1845 if (!strcmp(data
, NS_NETWORK_LINK_DATA_DOWN
)) {
1847 } else if (!strcmp(data
, NS_NETWORK_LINK_DATA_UP
)) {
1849 } else if (!strcmp(data
, NS_NETWORK_LINK_DATA_UNKNOWN
)) {
1850 nsresult rv
= mNetworkLinkService
->GetIsLinkUp(&isUp
);
1851 NS_ENSURE_SUCCESS(rv
, rv
);
1853 NS_WARNING("Unhandled network event!");
1857 return SetConnectivityInternal(isUp
);
1861 nsIOService::EscapeString(const nsACString
& aString
, uint32_t aEscapeType
,
1862 nsACString
& aResult
) {
1863 NS_ENSURE_ARG_MAX(aEscapeType
, 4);
1865 nsAutoCString
stringCopy(aString
);
1868 if (!NS_Escape(stringCopy
, result
, (nsEscapeMask
)aEscapeType
)) {
1869 return NS_ERROR_OUT_OF_MEMORY
;
1872 aResult
.Assign(result
);
1878 nsIOService::EscapeURL(const nsACString
& aStr
, uint32_t aFlags
,
1879 nsACString
& aResult
) {
1881 NS_EscapeURL(aStr
.BeginReading(), aStr
.Length(), aFlags
| esc_AlwaysCopy
,
1887 nsIOService::UnescapeString(const nsACString
& aStr
, uint32_t aFlags
,
1888 nsACString
& aResult
) {
1890 NS_UnescapeURL(aStr
.BeginReading(), aStr
.Length(), aFlags
| esc_AlwaysCopy
,
1896 nsIOService::ExtractCharsetFromContentType(const nsACString
& aTypeHeader
,
1897 nsACString
& aCharset
,
1898 int32_t* aCharsetStart
,
1899 int32_t* aCharsetEnd
,
1900 bool* aHadCharset
) {
1901 nsAutoCString ignored
;
1902 net_ParseContentType(aTypeHeader
, ignored
, aCharset
, aHadCharset
,
1903 aCharsetStart
, aCharsetEnd
);
1904 if (*aHadCharset
&& *aCharsetStart
== *aCharsetEnd
) {
1905 *aHadCharset
= false;
1910 // nsISpeculativeConnect
1911 class IOServiceProxyCallback final
: public nsIProtocolProxyCallback
{
1912 ~IOServiceProxyCallback() = default;
1916 NS_DECL_NSIPROTOCOLPROXYCALLBACK
1918 IOServiceProxyCallback(nsIInterfaceRequestor
* aCallbacks
,
1919 nsIOService
* aIOService
,
1920 Maybe
<OriginAttributes
>&& aOriginAttributes
)
1921 : mCallbacks(aCallbacks
),
1922 mIOService(aIOService
),
1923 mOriginAttributes(std::move(aOriginAttributes
)) {}
1926 RefPtr
<nsIInterfaceRequestor
> mCallbacks
;
1927 RefPtr
<nsIOService
> mIOService
;
1928 Maybe
<OriginAttributes
> mOriginAttributes
;
1931 NS_IMPL_ISUPPORTS(IOServiceProxyCallback
, nsIProtocolProxyCallback
)
1934 IOServiceProxyCallback::OnProxyAvailable(nsICancelable
* request
,
1935 nsIChannel
* channel
, nsIProxyInfo
* pi
,
1937 // Checking proxy status for speculative connect
1939 if (NS_SUCCEEDED(status
) && pi
&& NS_SUCCEEDED(pi
->GetType(type
)) &&
1940 !type
.EqualsLiteral("direct")) {
1941 // proxies dont do speculative connect
1945 nsCOMPtr
<nsIURI
> uri
;
1946 nsresult rv
= channel
->GetURI(getter_AddRefs(uri
));
1947 if (NS_FAILED(rv
)) {
1951 nsAutoCString scheme
;
1952 rv
= uri
->GetScheme(scheme
);
1953 if (NS_FAILED(rv
)) return NS_OK
;
1955 nsCOMPtr
<nsIProtocolHandler
> handler
;
1956 rv
= mIOService
->GetProtocolHandler(scheme
.get(), getter_AddRefs(handler
));
1957 if (NS_FAILED(rv
)) return NS_OK
;
1959 nsCOMPtr
<nsISpeculativeConnect
> speculativeHandler
=
1960 do_QueryInterface(handler
);
1961 if (!speculativeHandler
) return NS_OK
;
1963 nsCOMPtr
<nsILoadInfo
> loadInfo
= channel
->LoadInfo();
1964 nsCOMPtr
<nsIPrincipal
> principal
= loadInfo
->GetLoadingPrincipal();
1966 nsLoadFlags loadFlags
= 0;
1967 channel
->GetLoadFlags(&loadFlags
);
1968 bool anonymous
= !!(loadFlags
& nsIRequest::LOAD_ANONYMOUS
);
1969 if (mOriginAttributes
) {
1970 speculativeHandler
->SpeculativeConnectWithOriginAttributesNative(
1971 uri
, std::move(mOriginAttributes
.ref()), mCallbacks
, anonymous
);
1973 speculativeHandler
->SpeculativeConnect(uri
, principal
, mCallbacks
,
1980 nsresult
nsIOService::SpeculativeConnectInternal(
1981 nsIURI
* aURI
, nsIPrincipal
* aPrincipal
,
1982 Maybe
<OriginAttributes
>&& aOriginAttributes
,
1983 nsIInterfaceRequestor
* aCallbacks
, bool aAnonymous
) {
1984 NS_ENSURE_ARG(aURI
);
1986 if (!aURI
->SchemeIs("http") && !aURI
->SchemeIs("https")) {
1987 // We don't speculatively connect to non-HTTP[S] URIs.
1991 if (IsNeckoChild()) {
1992 gNeckoChild
->SendSpeculativeConnect(
1993 aURI
, aPrincipal
, std::move(aOriginAttributes
), aAnonymous
);
1997 // Check for proxy information. If there is a proxy configured then a
1998 // speculative connect should not be performed because the potential
1999 // reward is slim with tcp peers closely located to the browser.
2001 nsCOMPtr
<nsIProtocolProxyService
> pps
=
2002 do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID
, &rv
);
2003 NS_ENSURE_SUCCESS(rv
, rv
);
2005 nsCOMPtr
<nsIPrincipal
> loadingPrincipal
= aPrincipal
;
2007 MOZ_ASSERT(aPrincipal
|| aOriginAttributes
,
2008 "We expect passing a principal or OriginAttributes here.");
2010 if (!aPrincipal
&& !aOriginAttributes
) {
2011 return NS_ERROR_INVALID_ARG
;
2014 if (aOriginAttributes
) {
2016 BasePrincipal::CreateContentPrincipal(aURI
, aOriginAttributes
.ref());
2019 // XXX Bug 1724080: Avoid TCP connections on port 80 when https-only
2020 // or https-first is enabled. Let's create a dummy loadinfo which we
2021 // only use to determine whether we need ot upgrade the speculative
2022 // connection from http to https.
2023 nsCOMPtr
<nsIURI
> httpsURI
;
2024 if (aURI
->SchemeIs("http")) {
2025 nsCOMPtr
<nsILoadInfo
> httpsOnlyCheckLoadInfo
=
2026 new LoadInfo(loadingPrincipal
, loadingPrincipal
, nullptr,
2027 nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK
,
2028 nsIContentPolicy::TYPE_SPECULATIVE
);
2030 // Check if https-only, or https-first would upgrade the request
2031 if (nsHTTPSOnlyUtils::ShouldUpgradeRequest(aURI
, httpsOnlyCheckLoadInfo
) ||
2032 nsHTTPSOnlyUtils::ShouldUpgradeHttpsFirstRequest(
2033 aURI
, httpsOnlyCheckLoadInfo
)) {
2034 rv
= NS_GetSecureUpgradedURI(aURI
, getter_AddRefs(httpsURI
));
2035 NS_ENSURE_SUCCESS(rv
, rv
);
2036 aURI
= httpsURI
.get();
2040 // dummy channel used to create a TCP connection.
2041 // we perform security checks on the *real* channel, responsible
2042 // for any network loads. this real channel just checks the TCP
2043 // pool if there is an available connection created by the
2044 // channel we create underneath - hence it's safe to use
2045 // the systemPrincipal as the loadingPrincipal for this channel.
2046 nsCOMPtr
<nsIChannel
> channel
;
2047 rv
= NewChannelFromURI(
2049 nullptr, // aLoadingNode,
2051 nullptr, // aTriggeringPrincipal,
2052 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL
,
2053 nsIContentPolicy::TYPE_SPECULATIVE
, getter_AddRefs(channel
));
2054 NS_ENSURE_SUCCESS(rv
, rv
);
2057 nsLoadFlags loadFlags
= 0;
2058 channel
->GetLoadFlags(&loadFlags
);
2059 loadFlags
|= nsIRequest::LOAD_ANONYMOUS
;
2060 channel
->SetLoadFlags(loadFlags
);
2063 nsCOMPtr
<nsICancelable
> cancelable
;
2064 RefPtr
<IOServiceProxyCallback
> callback
= new IOServiceProxyCallback(
2065 aCallbacks
, this, std::move(aOriginAttributes
));
2066 nsCOMPtr
<nsIProtocolProxyService2
> pps2
= do_QueryInterface(pps
);
2068 return pps2
->AsyncResolve2(channel
, 0, callback
, nullptr,
2069 getter_AddRefs(cancelable
));
2071 return pps
->AsyncResolve(channel
, 0, callback
, nullptr,
2072 getter_AddRefs(cancelable
));
2076 nsIOService::SpeculativeConnect(nsIURI
* aURI
, nsIPrincipal
* aPrincipal
,
2077 nsIInterfaceRequestor
* aCallbacks
,
2079 return SpeculativeConnectInternal(aURI
, aPrincipal
, Nothing(), aCallbacks
,
2083 NS_IMETHODIMP
nsIOService::SpeculativeConnectWithOriginAttributes(
2084 nsIURI
* aURI
, JS::Handle
<JS::Value
> aOriginAttributes
,
2085 nsIInterfaceRequestor
* aCallbacks
, bool aAnonymous
, JSContext
* aCx
) {
2086 OriginAttributes attrs
;
2087 if (!aOriginAttributes
.isObject() || !attrs
.Init(aCx
, aOriginAttributes
)) {
2088 return NS_ERROR_INVALID_ARG
;
2091 SpeculativeConnectWithOriginAttributesNative(aURI
, std::move(attrs
),
2092 aCallbacks
, aAnonymous
);
2096 NS_IMETHODIMP_(void)
2097 nsIOService::SpeculativeConnectWithOriginAttributesNative(
2098 nsIURI
* aURI
, OriginAttributes
&& aOriginAttributes
,
2099 nsIInterfaceRequestor
* aCallbacks
, bool aAnonymous
) {
2100 Maybe
<OriginAttributes
> originAttributes
;
2101 originAttributes
.emplace(aOriginAttributes
);
2102 Unused
<< SpeculativeConnectInternal(
2103 aURI
, nullptr, std::move(originAttributes
), aCallbacks
, aAnonymous
);
2107 nsIOService::NotImplemented() { return NS_ERROR_NOT_IMPLEMENTED
; }
2110 nsIOService::GetSocketProcessLaunched(bool* aResult
) {
2111 NS_ENSURE_ARG_POINTER(aResult
);
2113 *aResult
= SocketProcessReady();
2117 bool nsIOService::HasObservers(const char* aTopic
) {
2118 MOZ_ASSERT(false, "Calling this method is unexpected");
2123 nsIOService::GetSocketProcessId(uint64_t* aPid
) {
2124 NS_ENSURE_ARG_POINTER(aPid
);
2127 if (!mSocketProcess
) {
2131 if (SocketProcessParent
* actor
= mSocketProcess
->GetActor()) {
2132 *aPid
= (uint64_t)actor
->OtherPid();
2139 nsIOService::RegisterProtocolHandler(const nsACString
& aScheme
,
2140 nsIProtocolHandler
* aHandler
,
2141 uint32_t aProtocolFlags
,
2142 int32_t aDefaultPort
) {
2144 return NS_ERROR_NOT_AVAILABLE
;
2146 if (aScheme
.IsEmpty()) {
2147 return NS_ERROR_INVALID_ARG
;
2150 nsAutoCString
scheme(aScheme
);
2151 ToLowerCase(scheme
);
2153 AutoWriteLock
lock(mLock
);
2154 return mRuntimeProtocolHandlers
.WithEntryHandle(scheme
, [&](auto&& entry
) {
2156 NS_WARNING("Cannot override an existing dynamic protocol handler");
2157 return NS_ERROR_FACTORY_EXISTS
;
2159 if (xpcom::StaticProtocolHandler::Lookup(scheme
)) {
2160 NS_WARNING("Cannot override an existing static protocol handler");
2161 return NS_ERROR_FACTORY_EXISTS
;
2163 nsMainThreadPtrHandle
<nsIProtocolHandler
> handler(
2164 new nsMainThreadPtrHolder
<nsIProtocolHandler
>("RuntimeProtocolHandler",
2166 entry
.Insert(RuntimeProtocolHandler
{
2167 .mHandler
= std::move(handler
),
2168 .mProtocolFlags
= aProtocolFlags
,
2169 .mDefaultPort
= aDefaultPort
,
2176 nsIOService::UnregisterProtocolHandler(const nsACString
& aScheme
) {
2180 if (aScheme
.IsEmpty()) {
2181 return NS_ERROR_INVALID_ARG
;
2184 nsAutoCString
scheme(aScheme
);
2185 ToLowerCase(scheme
);
2187 AutoWriteLock
lock(mLock
);
2188 return mRuntimeProtocolHandlers
.Remove(scheme
)
2190 : NS_ERROR_FACTORY_NOT_REGISTERED
;
2194 } // namespace mozilla