1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */
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/. */
9 #include "mozilla/Preferences.h"
10 #include "nsContentUtils.h"
11 #include "nsComponentManagerUtils.h"
12 #include "nsIAsyncVerifyRedirectCallback.h"
13 #include "nsIAuthPrompt.h"
14 #include "nsIDHCPClient.h"
15 #include "nsIHttpChannel.h"
16 #include "nsIPrefBranch.h"
17 #include "nsIPromptFactory.h"
18 #include "nsIProtocolProxyService.h"
19 #include "nsISystemProxySettings.h"
20 #include "nsIOService.h"
21 #include "nsNetUtil.h"
22 #include "nsThreadUtils.h"
23 #include "mozilla/ResultExtensions.h"
24 #include "mozilla/StaticPrefs_network.h"
25 #include "mozilla/Telemetry.h"
26 #include "mozilla/Try.h"
28 //-----------------------------------------------------------------------------
33 LazyLogModule
gProxyLog("proxy");
36 #define LOG(args) MOZ_LOG(gProxyLog, LogLevel::Debug, args)
37 #define MOZ_WPAD_URL "http://wpad/wpad.dat"
38 #define MOZ_DHCP_WPAD_OPTION 252
40 // These pointers are declared in nsProtocolProxyService.cpp
41 extern const char kProxyType_HTTPS
[];
42 extern const char kProxyType_DIRECT
[];
44 // The PAC thread does evaluations of both PAC files and
45 // nsISystemProxySettings because they can both block the calling thread and we
46 // don't want that on the main thread
48 // Check to see if the underlying request was not an error page in the case of
49 // a HTTP request. For other types of channels, just return true.
50 static bool HttpRequestSucceeded(nsIStreamLoader
* loader
) {
51 nsCOMPtr
<nsIRequest
> request
;
52 loader
->GetRequest(getter_AddRefs(request
));
54 bool result
= true; // default to assuming success
56 nsCOMPtr
<nsIHttpChannel
> httpChannel
= do_QueryInterface(request
);
59 Unused
<< httpChannel
->GetRequestSucceeded(&result
);
65 // Read preference setting of extra JavaScript context heap size.
66 // PrefService tends to be run on main thread, where ProxyAutoConfig runs on
67 // ProxyResolution thread, so it's read here and passed to ProxyAutoConfig.
68 static uint32_t GetExtraJSContextHeapSize() {
69 MOZ_ASSERT(NS_IsMainThread());
71 static int32_t extraSize
= -1;
74 nsCOMPtr
<nsIPrefBranch
> prefs
= do_GetService(NS_PREFSERVICE_CONTRACTID
);
78 NS_SUCCEEDED(prefs
->GetIntPref(
79 "network.proxy.autoconfig_extra_jscontext_heap_size", &value
))) {
80 LOG(("autoconfig_extra_jscontext_heap_size: %d\n", value
));
86 return extraSize
< 0 ? 0 : extraSize
;
89 // Read network proxy type from preference
90 // Used to verify that the preference is WPAD in nsPACMan::ConfigureWPAD
91 nsresult
GetNetworkProxyTypeFromPref(int32_t* type
) {
93 nsCOMPtr
<nsIPrefBranch
> prefs
= do_GetService(NS_PREFSERVICE_CONTRACTID
);
96 LOG(("Failed to get a preference service object"));
97 return NS_ERROR_FACTORY_NOT_REGISTERED
;
99 nsresult rv
= prefs
->GetIntPref("network.proxy.type", type
);
101 LOG(("Failed to retrieve network.proxy.type from prefs"));
104 LOG(("network.proxy.type pref retrieved: %d\n", *type
));
108 //-----------------------------------------------------------------------------
110 // The ExecuteCallback runnable is triggered by
111 // nsPACManCallback::OnQueryComplete on the Main thread when its completion is
112 // discovered on the pac thread
114 class ExecuteCallback final
: public Runnable
{
116 ExecuteCallback(nsPACManCallback
* aCallback
, nsresult status
)
117 : Runnable("net::ExecuteCallback"),
118 mCallback(aCallback
),
121 void SetPACString(const nsACString
& pacString
) { mPACString
= pacString
; }
123 void SetPACURL(const nsACString
& pacURL
) { mPACURL
= pacURL
; }
125 NS_IMETHOD
Run() override
{
126 mCallback
->OnQueryComplete(mStatus
, mPACString
, mPACURL
);
132 RefPtr
<nsPACManCallback
> mCallback
;
134 nsCString mPACString
;
138 //-----------------------------------------------------------------------------
140 // The PAC thread must be deleted from the main thread, this class
141 // acts as a proxy to do that, as the PACMan is reference counted
142 // and might be destroyed on either thread
144 class ShutdownThread final
: public Runnable
{
146 explicit ShutdownThread(nsIThread
* thread
)
147 : Runnable("net::ShutdownThread"), mThread(thread
) {}
149 NS_IMETHOD
Run() override
{
150 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
156 nsCOMPtr
<nsIThread
> mThread
;
159 // Dispatch this to wait until the PAC thread shuts down.
161 class WaitForThreadShutdown final
: public Runnable
{
163 explicit WaitForThreadShutdown(nsPACMan
* aPACMan
)
164 : Runnable("net::WaitForThreadShutdown"), mPACMan(aPACMan
) {}
166 NS_IMETHOD
Run() override
{
167 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
168 if (mPACMan
->mPACThread
) {
169 mPACMan
->mPACThread
->Shutdown();
170 mPACMan
->mPACThread
= nullptr;
176 RefPtr
<nsPACMan
> mPACMan
;
179 //-----------------------------------------------------------------------------
181 // PACLoadComplete allows the PAC thread to tell the main thread that
182 // the javascript PAC file has been installed (perhaps unsuccessfully)
183 // and that there is no reason to queue executions anymore
185 class PACLoadComplete final
: public Runnable
{
187 explicit PACLoadComplete(nsPACMan
* aPACMan
)
188 : Runnable("net::PACLoadComplete"), mPACMan(aPACMan
) {}
190 NS_IMETHOD
Run() override
{
191 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
193 auto loader
= mPACMan
->mLoader
.Lock();
194 loader
.ref() = nullptr;
196 mPACMan
->PostProcessPendingQ();
201 RefPtr
<nsPACMan
> mPACMan
;
204 //-----------------------------------------------------------------------------
206 // ConfigureWPADComplete allows the PAC thread to tell the main thread that
207 // the URL for the PAC file has been found
208 class ConfigureWPADComplete final
: public Runnable
{
210 ConfigureWPADComplete(nsPACMan
* aPACMan
, const nsACString
& aPACURISpec
)
211 : Runnable("net::ConfigureWPADComplete"),
213 mPACURISpec(aPACURISpec
) {}
215 NS_IMETHOD
Run() override
{
216 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
217 mPACMan
->AssignPACURISpec(mPACURISpec
);
218 mPACMan
->ContinueLoadingAfterPACUriKnown();
223 RefPtr
<nsPACMan
> mPACMan
;
224 nsCString mPACURISpec
;
227 //-----------------------------------------------------------------------------
229 // ExecutePACThreadAction is used to proxy actions from the main
230 // thread onto the PAC thread. There are 4 options: process the queue,
231 // cancel the queue, query DHCP for the PAC option
232 // and setup the javascript context with a new PAC file
234 class ExecutePACThreadAction final
: public Runnable
{
236 // by default we just process the queue
237 explicit ExecutePACThreadAction(nsPACMan
* aPACMan
)
238 : Runnable("net::ExecutePACThreadAction"),
241 mCancelStatus(NS_OK
),
244 mConfigureWPAD(false),
247 void CancelQueue(nsresult status
, bool aShutdown
) {
249 mCancelStatus
= status
;
250 mShutdown
= aShutdown
;
253 void SetupPAC(const char* data
, uint32_t dataLen
, const nsACString
& pacURI
,
254 uint32_t extraHeapSize
) {
256 mSetupPACData
.Assign(data
, dataLen
);
257 mSetupPACURI
= pacURI
;
258 mExtraHeapSize
= extraHeapSize
;
261 void ConfigureWPAD() { mConfigureWPAD
= true; }
263 NS_IMETHOD
Run() override
{
264 MOZ_ASSERT(!NS_IsMainThread(), "wrong thread");
266 mPACMan
->CancelPendingQ(mCancelStatus
, mShutdown
);
274 nsCOMPtr
<nsISerialEventTarget
> target
= mPACMan
->GetNeckoTarget();
275 mPACMan
->mPAC
->ConfigurePAC(mSetupPACURI
, mSetupPACData
,
276 mPACMan
->mIncludePath
, mExtraHeapSize
,
279 RefPtr
<PACLoadComplete
> runnable
= new PACLoadComplete(mPACMan
);
280 mPACMan
->Dispatch(runnable
.forget());
284 if (mConfigureWPAD
) {
286 mConfigureWPAD
= false;
287 mPACMan
->ConfigureWPAD(spec
);
288 RefPtr
<ConfigureWPADComplete
> runnable
=
289 new ConfigureWPADComplete(mPACMan
, spec
);
290 mPACMan
->Dispatch(runnable
.forget());
294 mPACMan
->ProcessPendingQ();
299 RefPtr
<nsPACMan
> mPACMan
;
302 nsresult mCancelStatus
;
305 uint32_t mExtraHeapSize
;
306 nsCString mSetupPACData
;
307 nsCString mSetupPACURI
;
312 //-----------------------------------------------------------------------------
314 PendingPACQuery::PendingPACQuery(nsPACMan
* pacMan
, nsIURI
* uri
,
315 nsPACManCallback
* callback
, uint32_t flags
,
316 bool mainThreadResponse
)
317 : Runnable("net::PendingPACQuery"),
322 mOnMainThreadOnly(mainThreadResponse
) {
323 uri
->GetAsciiSpec(mSpec
);
324 uri
->GetAsciiHost(mHost
);
325 uri
->GetScheme(mScheme
);
326 uri
->GetPort(&mPort
);
329 void PendingPACQuery::Complete(nsresult status
, const nsACString
& pacString
) {
330 if (!mCallback
) return;
331 RefPtr
<ExecuteCallback
> runnable
= new ExecuteCallback(mCallback
, status
);
332 runnable
->SetPACString(pacString
);
333 if (mOnMainThreadOnly
) {
334 mPACMan
->Dispatch(runnable
.forget());
340 void PendingPACQuery::UseAlternatePACFile(const nsACString
& pacURL
) {
341 if (!mCallback
) return;
343 RefPtr
<ExecuteCallback
> runnable
= new ExecuteCallback(mCallback
, NS_OK
);
344 runnable
->SetPACURL(pacURL
);
345 if (mOnMainThreadOnly
) {
346 mPACMan
->Dispatch(runnable
.forget());
353 PendingPACQuery::Run() {
354 MOZ_ASSERT(!NS_IsMainThread(), "wrong thread");
355 mPACMan
->PostQuery(this);
359 //-----------------------------------------------------------------------------
361 static bool sThreadLocalSetup
= false;
362 static uint32_t sThreadLocalIndex
= 0xdeadbeef; // out of range
364 static const char* kPACIncludePath
=
365 "network.proxy.autoconfig_url.include_path";
367 nsPACMan::nsPACMan(nsISerialEventTarget
* mainThreadEventTarget
)
368 : NeckoTargetHolder(mainThreadEventTarget
),
369 mLoader("nsPACMan::mLoader"),
372 mLoadFailureCount(0),
375 mWPADOverDHCPEnabled(false),
376 mProxyConfigType(0) {
377 MOZ_ASSERT(NS_IsMainThread(), "pacman must be created on main thread");
378 mIncludePath
= Preferences::GetBool(kPACIncludePath
, false);
379 if (StaticPrefs::network_proxy_parse_pac_on_socket_process() &&
380 gIOService
->SocketProcessReady()) {
381 mPAC
= MakeUnique
<RemoteProxyAutoConfig
>();
383 mPAC
= MakeUnique
<ProxyAutoConfig
>();
384 if (!sThreadLocalSetup
) {
385 sThreadLocalSetup
= true;
386 PR_NewThreadPrivateIndex(&sThreadLocalIndex
, nullptr);
388 mPAC
->SetThreadLocalIndex(sThreadLocalIndex
);
392 nsPACMan::~nsPACMan() {
393 MOZ_ASSERT(mShutdown
, "Shutdown must be called before dtor.");
396 if (NS_IsMainThread()) {
397 mPACThread
->Shutdown();
398 mPACThread
= nullptr;
400 RefPtr
<ShutdownThread
> runnable
= new ShutdownThread(mPACThread
);
401 Dispatch(runnable
.forget());
407 auto loader
= mLoader
.Lock();
408 NS_ASSERTION(loader
.ref() == nullptr, "pac man not shutdown properly");
412 NS_ASSERTION(mPendingQ
.isEmpty(), "pac man not shutdown properly");
415 void nsPACMan::Shutdown() {
416 MOZ_ASSERT(NS_IsMainThread(), "pacman must be shutdown on main thread");
421 CancelExistingLoad();
424 PostCancelPendingQ(NS_ERROR_ABORT
, /*aShutdown =*/true);
426 // Shutdown is initiated from an observer. We don't want to block the
427 // observer service on thread shutdown so we post a shutdown runnable that
428 // will run after we return instead.
429 RefPtr
<WaitForThreadShutdown
> runnable
= new WaitForThreadShutdown(this);
430 Dispatch(runnable
.forget());
436 nsresult
nsPACMan::DispatchToPAC(already_AddRefed
<nsIRunnable
> aEvent
,
438 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
440 nsCOMPtr
<nsIRunnable
> e(aEvent
);
443 return NS_ERROR_NOT_AVAILABLE
;
446 // Lazily create the PAC thread. This method is main-thread only so we don't
447 // have to worry about threading issues here.
449 MOZ_TRY(NS_NewNamedThread("ProxyResolution", getter_AddRefs(mPACThread
)));
450 nsresult rv
= mPAC
->Init(mPACThread
);
457 return NS_DispatchAndSpinEventLoopUntilComplete(
458 "nsPACMan::DispatchToPAC"_ns
, mPACThread
, e
.forget());
460 return mPACThread
->Dispatch(e
.forget());
464 nsresult
nsPACMan::AsyncGetProxyForURI(nsIURI
* uri
, nsPACManCallback
* callback
,
466 bool mainThreadResponse
) {
467 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
468 if (mShutdown
) return NS_ERROR_NOT_AVAILABLE
;
471 if (!mPACURISpec
.IsEmpty() && !mScheduledReload
.IsNull() &&
472 TimeStamp::Now() > mScheduledReload
) {
473 LOG(("nsPACMan::AsyncGetProxyForURI reload as scheduled\n"));
475 LoadPACFromURI(mAutoDetect
? ""_ns
: mPACURISpec
, false);
478 RefPtr
<PendingPACQuery
> query
=
479 new PendingPACQuery(this, uri
, callback
, flags
, mainThreadResponse
);
482 // deal with this directly instead of queueing it
483 query
->Complete(NS_OK
, ""_ns
);
487 return DispatchToPAC(query
.forget());
490 nsresult
nsPACMan::PostQuery(PendingPACQuery
* query
) {
491 MOZ_ASSERT(!NS_IsMainThread(), "wrong thread");
494 query
->Complete(NS_ERROR_NOT_AVAILABLE
, ""_ns
);
498 // add a reference to the query while it is in the pending list
499 RefPtr
<PendingPACQuery
> addref(query
);
500 mPendingQ
.insertBack(addref
.forget().take());
505 // check if proxy settings are configured for WPAD
506 bool IsProxyConfigValidForWPAD(int proxyConfigType
, bool wpadSystemSettings
) {
507 return proxyConfigType
== nsIProtocolProxyService::PROXYCONFIG_WPAD
||
508 (proxyConfigType
== nsIProtocolProxyService::PROXYCONFIG_SYSTEM
&&
512 nsresult
nsPACMan::LoadPACFromURI(const nsACString
& aSpec
) {
513 return LoadPACFromURI(aSpec
, true);
516 nsresult
nsPACMan::LoadPACFromURI(const nsACString
& aSpec
,
517 bool aResetLoadFailureCount
) {
518 NS_ENSURE_STATE(!mShutdown
);
520 nsCOMPtr
<nsIStreamLoader
> loader
=
521 do_CreateInstance(NS_STREAMLOADER_CONTRACTID
);
522 NS_ENSURE_STATE(loader
);
524 LOG(("nsPACMan::LoadPACFromURI aSpec: %s, aResetLoadFailureCount: %s\n",
525 aSpec
.BeginReading(), aResetLoadFailureCount
? "true" : "false"));
527 CancelExistingLoad();
530 auto locked
= mLoader
.Lock();
531 locked
.ref() = loader
.forget();
533 mPACURIRedirectSpec
.Truncate();
534 mNormalPACURISpec
.Truncate(); // set at load time
535 if (aResetLoadFailureCount
) {
536 mLoadFailureCount
= 0;
538 mAutoDetect
= aSpec
.IsEmpty();
539 mPACURISpec
.Assign(aSpec
);
542 mScheduledReload
= TimeStamp();
544 // if we're on the main thread here so we can get hold of prefs,
545 // we check that we have WPAD preffed on if we're auto-detecting
546 if (mAutoDetect
&& NS_IsMainThread()) {
547 nsresult rv
= GetNetworkProxyTypeFromPref(&mProxyConfigType
);
551 if (!IsProxyConfigValidForWPAD(mProxyConfigType
, mAutoDetect
)) {
553 ("LoadPACFromURI - Aborting WPAD autodetection because the pref "
554 "doesn't match anymore"));
555 return NS_BINDING_ABORTED
;
558 // Since we might get called from nsProtocolProxyService::Init, we need to
559 // post an event back to the main thread before we try to use the IO service.
561 // But, we need to flag ourselves as loading, so that we queue up any PAC
562 // queries the enter between now and when we actually load the PAC file.
565 nsCOMPtr
<nsIRunnable
> runnable
= NewRunnableMethod(
566 "nsPACMan::StartLoading", this, &nsPACMan::StartLoading
);
569 ? Dispatch(runnable
.forget())
570 : GetCurrentSerialEventTarget()->Dispatch(runnable
.forget());
571 if (NS_FAILED(rv
)) return rv
;
578 nsresult
nsPACMan::GetPACFromDHCP(nsACString
& aSpec
) {
579 MOZ_ASSERT(!NS_IsMainThread(), "wrong thread");
582 ("nsPACMan::GetPACFromDHCP DHCP option %d query failed because there "
583 "is no DHCP client available\n",
584 MOZ_DHCP_WPAD_OPTION
));
585 return NS_ERROR_NOT_IMPLEMENTED
;
588 rv
= mDHCPClient
->GetOption(MOZ_DHCP_WPAD_OPTION
, aSpec
);
591 "nsPACMan::GetPACFromDHCP DHCP option %d query failed with result %d\n",
592 MOZ_DHCP_WPAD_OPTION
, (uint32_t)rv
));
595 ("nsPACMan::GetPACFromDHCP DHCP option %d query succeeded, finding PAC "
597 MOZ_DHCP_WPAD_OPTION
, aSpec
.BeginReading()));
602 nsresult
nsPACMan::ConfigureWPAD(nsACString
& aSpec
) {
603 MOZ_ASSERT(!NS_IsMainThread(), "wrong thread");
605 if (!IsProxyConfigValidForWPAD(mProxyConfigType
, mAutoDetect
)) {
607 ("ConfigureWPAD - Aborting WPAD autodetection because the pref "
608 "doesn't match anymore"));
609 return NS_BINDING_ABORTED
;
613 if (mWPADOverDHCPEnabled
) {
614 GetPACFromDHCP(aSpec
);
617 if (aSpec
.IsEmpty()) {
618 // We diverge from the WPAD spec here in that we don't walk the
619 // hosts's FQDN, stripping components until we hit a TLD. Doing so
620 // is dangerous in the face of an incomplete list of TLDs, and TLDs
621 // get added over time. We could consider doing only a single
622 // substitution of the first component, if that proves to help
624 aSpec
.AssignLiteral(MOZ_WPAD_URL
);
629 void nsPACMan::AssignPACURISpec(const nsACString
& aSpec
) {
630 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
631 mPACURISpec
.Assign(aSpec
);
634 void nsPACMan::StartLoading() {
635 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
636 mLoadPending
= false;
639 // CancelExistingLoad was called...
640 nsCOMPtr
<nsIStreamLoader
> loader
;
642 auto locked
= mLoader
.Lock();
643 loader
= locked
.ref();
646 PostCancelPendingQ(NS_ERROR_ABORT
);
652 nsresult rv
= GetNetworkProxyTypeFromPref(&mProxyConfigType
);
655 "Could not retrieve Network Proxy Type pref when auto-detecting "
659 RefPtr
<ExecutePACThreadAction
> wpadConfigurer
=
660 new ExecutePACThreadAction(this);
661 wpadConfigurer
->ConfigureWPAD();
662 DispatchToPAC(wpadConfigurer
.forget());
664 ContinueLoadingAfterPACUriKnown();
668 void nsPACMan::ContinueLoadingAfterPACUriKnown() {
669 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
671 nsCOMPtr
<nsIStreamLoader
> loader
;
673 auto locked
= mLoader
.Lock();
674 loader
= locked
.ref();
677 // CancelExistingLoad was called...
679 PostCancelPendingQ(NS_ERROR_ABORT
);
682 if (NS_SUCCEEDED(loader
->Init(this, nullptr))) {
683 // Always hit the origin server when loading PAC.
684 nsCOMPtr
<nsIIOService
> ios
= do_GetIOService();
686 nsCOMPtr
<nsIChannel
> channel
;
687 nsCOMPtr
<nsIURI
> pacURI
;
688 NS_NewURI(getter_AddRefs(pacURI
), mPACURISpec
);
690 // NOTE: This results in GetProxyForURI being called
692 nsresult rv
= pacURI
->GetSpec(mNormalPACURISpec
);
693 MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv
));
694 NS_NewChannel(getter_AddRefs(channel
), pacURI
,
695 nsContentUtils::GetSystemPrincipal(),
696 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL
,
697 nsIContentPolicy::TYPE_OTHER
,
698 nullptr, // nsICookieJarSettings
699 nullptr, // PerformanceStorage
700 nullptr, // aLoadGroup
701 nullptr, // aCallbacks
702 nsIRequest::LOAD_NORMAL
, ios
);
704 LOG(("nsPACMan::StartLoading Failed pacspec uri conversion %s\n",
709 // allow deprecated HTTP request from SystemPrincipal
710 nsCOMPtr
<nsILoadInfo
> loadInfo
= channel
->LoadInfo();
711 loadInfo
->SetAllowDeprecatedSystemRequests(true);
712 loadInfo
->SetHttpsOnlyStatus(nsILoadInfo::HTTPS_ONLY_EXEMPT
);
714 channel
->SetLoadFlags(nsIRequest::LOAD_BYPASS_CACHE
);
715 channel
->SetNotificationCallbacks(this);
716 channel
->SetTRRMode(nsIRequest::TRR_DISABLED_MODE
);
717 if (NS_SUCCEEDED(channel
->AsyncOpen(loader
))) return;
722 CancelExistingLoad();
723 PostCancelPendingQ(NS_ERROR_UNEXPECTED
);
726 void nsPACMan::OnLoadFailure() {
727 int32_t minInterval
= 5; // 5 seconds
728 int32_t maxInterval
= 300; // 5 minutes
730 nsCOMPtr
<nsIPrefBranch
> prefs
= do_GetService(NS_PREFSERVICE_CONTRACTID
);
732 prefs
->GetIntPref("network.proxy.autoconfig_retry_interval_min",
734 prefs
->GetIntPref("network.proxy.autoconfig_retry_interval_max",
738 int32_t interval
= minInterval
<< mLoadFailureCount
++; // seconds
739 if (!interval
|| interval
> maxInterval
) interval
= maxInterval
;
741 mScheduledReload
= TimeStamp::Now() + TimeDuration::FromSeconds(interval
);
743 LOG(("OnLoadFailure: retry in %d seconds (%d fails)\n", interval
,
744 (uint32_t)mLoadFailureCount
));
746 // while we wait for the retry queued members should try direct
747 // even if that means fast failure.
748 PostCancelPendingQ(NS_ERROR_NOT_AVAILABLE
);
751 void nsPACMan::CancelExistingLoad() {
752 nsCOMPtr
<nsIStreamLoader
> loader
;
754 auto locked
= mLoader
.Lock();
755 loader
.swap(*locked
);
758 nsCOMPtr
<nsIRequest
> request
;
759 loader
->GetRequest(getter_AddRefs(request
));
761 request
->Cancel(NS_ERROR_ABORT
);
766 void nsPACMan::PostProcessPendingQ() {
767 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
768 RefPtr
<ExecutePACThreadAction
> pending
= new ExecutePACThreadAction(this);
769 DispatchToPAC(pending
.forget());
772 void nsPACMan::PostCancelPendingQ(nsresult status
, bool aShutdown
) {
773 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
774 RefPtr
<ExecutePACThreadAction
> pending
= new ExecutePACThreadAction(this);
775 pending
->CancelQueue(status
, aShutdown
);
776 DispatchToPAC(pending
.forget());
779 void nsPACMan::CancelPendingQ(nsresult status
, bool aShutdown
) {
780 MOZ_ASSERT(!NS_IsMainThread(), "wrong thread");
781 RefPtr
<PendingPACQuery
> query
;
783 while (!mPendingQ
.isEmpty()) {
784 query
= dont_AddRef(mPendingQ
.popLast());
785 query
->Complete(status
, ""_ns
);
793 void nsPACMan::ProcessPendingQ() {
794 MOZ_ASSERT(!NS_IsMainThread(), "wrong thread");
795 while (ProcessPending()) {
802 // do GC while the thread has nothing pending
807 // returns true if progress was made by shortening the queue
808 bool nsPACMan::ProcessPending() {
809 if (mPendingQ
.isEmpty()) return false;
811 // queue during normal load, but if we are retrying a failed load then
812 // fast fail the queries
813 if (mInProgress
|| (IsLoading() && !mLoadFailureCount
)) return false;
815 RefPtr
<PendingPACQuery
> query(dont_AddRef(mPendingQ
.popFirst()));
817 // Having |mLoadFailureCount > 0| means we haven't had a sucessful PAC load
818 // yet. We should use DIRECT instead.
819 if (mShutdown
|| IsLoading() || mLoadFailureCount
> 0) {
820 query
->Complete(NS_ERROR_NOT_AVAILABLE
, ""_ns
);
824 nsAutoCString pacString
;
825 bool completed
= false;
827 nsAutoCString PACURI
;
829 // first we need to consider the system proxy changing the pac url
830 if (mSystemProxySettings
&&
831 NS_SUCCEEDED(mSystemProxySettings
->GetPACURI(PACURI
)) &&
832 !PACURI
.IsEmpty() && !PACURI
.Equals(mPACURISpec
)) {
833 query
->UseAlternatePACFile(PACURI
);
834 LOG(("Use PAC from system settings: %s\n", PACURI
.get()));
838 // now try the system proxy settings for this particular url if
839 // PAC was not specified
840 if (!completed
&& mSystemProxySettings
&& PACURI
.IsEmpty() &&
841 NS_SUCCEEDED(mSystemProxySettings
->GetProxyForURI(
842 query
->mSpec
, query
->mScheme
, query
->mHost
, query
->mPort
,
844 if (query
->mFlags
& nsIProtocolProxyService::RESOLVE_PREFER_SOCKS_PROXY
&&
845 query
->mFlags
& nsIProtocolProxyService::RESOLVE_PREFER_HTTPS_PROXY
) {
846 if (StringBeginsWith(pacString
, nsDependentCString(kProxyType_DIRECT
),
847 nsCaseInsensitiveUTF8StringComparator
)) {
848 // DIRECT indicates that system proxy settings are not configured to use
849 // SOCKS proxy. Try https proxy as a secondary preferrable proxy. This
850 // is mainly for websocket whose precedence is SOCKS > HTTPS > DIRECT.
851 NS_SUCCEEDED(mSystemProxySettings
->GetProxyForURI(
852 query
->mSpec
, nsDependentCString(kProxyType_HTTPS
), query
->mHost
,
853 query
->mPort
, pacString
));
856 LOG(("Use proxy from system settings: %s\n", pacString
.get()));
857 query
->Complete(NS_OK
, pacString
);
861 // the systemproxysettings didn't complete the resolution. try via PAC
863 auto callback
= [query(query
)](nsresult aStatus
,
864 const nsACString
& aResult
) {
865 LOG(("Use proxy from PAC: %s\n", PromiseFlatCString(aResult
).get()));
866 query
->Complete(aStatus
, aResult
);
868 mPAC
->GetProxyForURIWithCallback(query
->mSpec
, query
->mHost
,
869 std::move(callback
));
876 NS_IMPL_ISUPPORTS(nsPACMan
, nsIStreamLoaderObserver
, nsIInterfaceRequestor
,
880 nsPACMan::OnStreamComplete(nsIStreamLoader
* loader
, nsISupports
* context
,
881 nsresult status
, uint32_t dataLen
,
882 const uint8_t* data
) {
883 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
885 bool loadSucceeded
= NS_SUCCEEDED(status
) && HttpRequestSucceeded(loader
);
887 auto locked
= mLoader
.Lock();
888 if (locked
.ref() != loader
) {
889 // If this happens, then it means that LoadPACFromURI was called more
890 // than once before the initial call completed. In this case, status
891 // should be NS_ERROR_ABORT, and if so, then we know that we can and
892 // should delay any processing.
893 LOG(("OnStreamComplete: called more than once\n"));
894 if (status
== NS_ERROR_ABORT
) {
897 } else if (!loadSucceeded
) {
898 // We have to clear the loader to indicate that we are not loading PAC
900 // Note that we can only clear the loader when |loader| and |mLoader| are
902 locked
.ref() = nullptr;
906 LOG(("OnStreamComplete: entry\n"));
909 // Get the URI spec used to load this PAC script.
910 nsAutoCString pacURI
;
912 nsCOMPtr
<nsIRequest
> request
;
913 loader
->GetRequest(getter_AddRefs(request
));
914 nsCOMPtr
<nsIChannel
> channel
= do_QueryInterface(request
);
916 nsCOMPtr
<nsIURI
> uri
;
917 channel
->GetURI(getter_AddRefs(uri
));
918 if (uri
) uri
->GetAsciiSpec(pacURI
);
922 nsCOMPtr
<nsIProtocolProxyService
> pps
=
923 do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID
);
926 pps
->NotifyProxyConfigChangedInternal();
929 // We succeeded in loading the pac file using a bunch of interfaces that are
930 // main thread only. Unfortunately, we have to initialize the instance of
931 // the PAC evaluator (NS_PROXYAUTOCONFIG_CONTRACTID) on the PAC thread,
932 // because that's where it will be used.
933 RefPtr
<ExecutePACThreadAction
> pending
= new ExecutePACThreadAction(this);
934 pending
->SetupPAC(reinterpret_cast<const char*>(data
), dataLen
, pacURI
,
935 GetExtraJSContextHeapSize());
936 DispatchToPAC(pending
.forget());
938 LOG(("OnStreamComplete: process the PAC contents\n"));
940 // Even if the PAC file could not be parsed, we did succeed in loading the
942 mLoadFailureCount
= 0;
944 // We were unable to load the PAC file (presumably because of a network
945 // failure). Try again a little later.
946 LOG(("OnStreamComplete: unable to load PAC, retry later\n"));
950 if (NS_SUCCEEDED(status
)) {
951 PostProcessPendingQ();
953 PostCancelPendingQ(status
);
960 nsPACMan::GetInterface(const nsIID
& iid
, void** result
) {
961 // In case loading the PAC file requires authentication.
962 if (iid
.Equals(NS_GET_IID(nsIAuthPrompt
))) {
963 nsCOMPtr
<nsIPromptFactory
> promptFac
=
964 do_GetService("@mozilla.org/prompter;1");
965 NS_ENSURE_TRUE(promptFac
, NS_ERROR_NO_INTERFACE
);
967 promptFac
->GetPrompt(nullptr, iid
, reinterpret_cast<void**>(result
));
969 return NS_ERROR_NO_INTERFACE
;
974 // In case loading the PAC file results in a redirect.
975 if (iid
.Equals(NS_GET_IID(nsIChannelEventSink
))) {
977 *result
= static_cast<nsIChannelEventSink
*>(this);
981 return NS_ERROR_NO_INTERFACE
;
985 nsPACMan::AsyncOnChannelRedirect(nsIChannel
* oldChannel
, nsIChannel
* newChannel
,
987 nsIAsyncVerifyRedirectCallback
* callback
) {
988 MOZ_ASSERT(NS_IsMainThread(), "wrong thread");
991 nsCOMPtr
<nsIURI
> pacURI
;
992 if (NS_FAILED((rv
= newChannel
->GetURI(getter_AddRefs(pacURI
))))) return rv
;
994 rv
= pacURI
->GetSpec(mPACURIRedirectSpec
);
995 if (NS_FAILED(rv
)) return rv
;
997 LOG(("nsPACMan redirect from original %s to redirected %s\n",
998 mPACURISpec
.get(), mPACURIRedirectSpec
.get()));
1000 // do not update mPACURISpec - that needs to stay as the
1001 // configured URI so that we can determine when the config changes.
1002 // However do track the most recent URI in the redirect change
1003 // as mPACURIRedirectSpec so that URI can be allowed to bypass
1004 // the proxy and actually fetch the pac file.
1006 callback
->OnRedirectVerifyCallback(NS_OK
);
1010 nsresult
nsPACMan::Init(nsISystemProxySettings
* systemProxySettings
) {
1011 mSystemProxySettings
= systemProxySettings
;
1012 mDHCPClient
= do_GetService(NS_DHCPCLIENT_CONTRACTID
);
1017 } // namespace mozilla