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/. */
6
7 #include "ProxyAutoConfig.h"
8 #include "nsICancelable.h"
9 #include "nsIDNSListener.h"
10 #include "nsIDNSRecord.h"
11 #include "nsIDNSService.h"
12 #include "nsINamed.h"
13 #include "nsThreadUtils.h"
14 #include "nsIConsoleService.h"
15 #include "nsIURLParser.h"
16 #include "nsJSUtils.h"
17 #include "jsfriendapi.h"
18 #include "js/CallAndConstruct.h" // JS_CallFunctionName
19 #include "js/CompilationAndEvaluation.h" // JS::Compile
20 #include "js/ContextOptions.h"
21 #include "js/Initialization.h"
22 #include "js/PropertyAndElement.h" // JS_DefineFunctions, JS_GetProperty
23 #include "js/PropertySpec.h"
24 #include "js/SourceText.h" // JS::Source{Ownership,Text}
25 #include "js/Utility.h"
26 #include "js/Warnings.h" // JS::SetWarningReporter
27 #include "prnetdb.h"
28 #include "nsITimer.h"
29 #include "mozilla/Atomics.h"
30 #include "mozilla/SpinEventLoopUntil.h"
31 #include "mozilla/ipc/Endpoint.h"
32 #include "mozilla/net/DNS.h"
33 #include "mozilla/net/SocketProcessChild.h"
34 #include "mozilla/net/SocketProcessParent.h"
35 #include "mozilla/net/ProxyAutoConfigChild.h"
36 #include "mozilla/net/ProxyAutoConfigParent.h"
37 #include "mozilla/Utf8.h" // mozilla::Utf8Unit
38 #include "nsServiceManagerUtils.h"
39 #include "nsNetCID.h"
40
41 #if defined(XP_MACOSX)
42 # include "nsMacUtilsImpl.h"
43 #endif
44
45 #include "XPCSelfHostedShmem.h"
46
47 namespace mozilla {
48 namespace net {
49
50 // These are some global helper symbols the PAC format requires that we provide
51 // that are initialized as part of the global javascript context used for PAC
52 // evaluations. Additionally dnsResolve(host) and myIpAddress() are supplied in
53 // the same context but are implemented as c++ helpers. alert(msg) is similarly
54 // defined.
55 //
56 // Per ProxyAutoConfig::Init, this data must be ASCII.
57
58 static const char sAsciiPacUtils[] =
59 #include "ascii_pac_utils.inc"
60 ;
61
62 // sRunning is defined for the helper functions only while the
63 // Javascript engine is running and the PAC object cannot be deleted
64 // or reset.
RunningIndex()65 static Atomic<uint32_t, Relaxed>& RunningIndex() {
66 static Atomic<uint32_t, Relaxed> sRunningIndex(0xdeadbeef);
67 return sRunningIndex;
68 }
GetRunning()69 static ProxyAutoConfig* GetRunning() {
70 MOZ_ASSERT(RunningIndex() != 0xdeadbeef);
71 return static_cast<ProxyAutoConfig*>(PR_GetThreadPrivate(RunningIndex()));
72 }
73
SetRunning(ProxyAutoConfig * arg)74 static void SetRunning(ProxyAutoConfig* arg) {
75 MOZ_ASSERT(RunningIndex() != 0xdeadbeef);
76 PR_SetThreadPrivate(RunningIndex(), arg);
77 }
78
79 // The PACResolver is used for dnsResolve()
80 class PACResolver final : public nsIDNSListener,
81 public nsITimerCallback,
82 public nsINamed {
83 public:
84 NS_DECL_THREADSAFE_ISUPPORTS
85
PACResolver(nsIEventTarget * aTarget)86 explicit PACResolver(nsIEventTarget* aTarget)
87 : mStatus(NS_ERROR_FAILURE),
88 mMainThreadEventTarget(aTarget),
89 mMutex("PACResolver::Mutex") {}
90
91 // nsIDNSListener
OnLookupComplete(nsICancelable * request,nsIDNSRecord * record,nsresult status)92 NS_IMETHOD OnLookupComplete(nsICancelable* request, nsIDNSRecord* record,
93 nsresult status) override {
94 nsCOMPtr<nsITimer> timer;
95 {
96 MutexAutoLock lock(mMutex);
97 timer.swap(mTimer);
98 mRequest = nullptr;
99 }
100
101 if (timer) {
102 timer->Cancel();
103 }
104
105 mStatus = status;
106 mResponse = record;
107 return NS_OK;
108 }
109
110 // nsITimerCallback
Notify(nsITimer * timer)111 NS_IMETHOD Notify(nsITimer* timer) override {
112 nsCOMPtr<nsICancelable> request;
113 {
114 MutexAutoLock lock(mMutex);
115 request.swap(mRequest);
116 mTimer = nullptr;
117 }
118 if (request) {
119 request->Cancel(NS_ERROR_NET_TIMEOUT);
120 }
121 return NS_OK;
122 }
123
124 // nsINamed
GetName(nsACString & aName)125 NS_IMETHOD GetName(nsACString& aName) override {
126 aName.AssignLiteral("PACResolver");
127 return NS_OK;
128 }
129
130 nsresult mStatus;
131 nsCOMPtr<nsICancelable> mRequest;
132 nsCOMPtr<nsIDNSRecord> mResponse;
133 nsCOMPtr<nsITimer> mTimer;
134 nsCOMPtr<nsIEventTarget> mMainThreadEventTarget;
135 Mutex mMutex;
136
137 private:
138 ~PACResolver() = default;
139 };
NS_IMPL_ISUPPORTS(PACResolver,nsIDNSListener,nsITimerCallback,nsINamed)140 NS_IMPL_ISUPPORTS(PACResolver, nsIDNSListener, nsITimerCallback, nsINamed)
141
142 static void PACLogToConsole(nsString& aMessage) {
143 if (XRE_IsSocketProcess()) {
144 auto task = [message(aMessage)]() {
145 SocketProcessChild* child = SocketProcessChild::GetSingleton();
146 if (child) {
147 Unused << child->SendOnConsoleMessage(message);
148 }
149 };
150 if (NS_IsMainThread()) {
151 task();
152 } else {
153 NS_DispatchToMainThread(NS_NewRunnableFunction("PACLogToConsole", task));
154 }
155 return;
156 }
157
158 nsCOMPtr<nsIConsoleService> consoleService =
159 do_GetService(NS_CONSOLESERVICE_CONTRACTID);
160 if (!consoleService) return;
161
162 consoleService->LogStringMessage(aMessage.get());
163 }
164
165 // Javascript errors and warnings are logged to the main error console
PACLogErrorOrWarning(const nsAString & aKind,JSErrorReport * aReport)166 static void PACLogErrorOrWarning(const nsAString& aKind,
167 JSErrorReport* aReport) {
168 nsString formattedMessage(u"PAC Execution "_ns);
169 formattedMessage += aKind;
170 formattedMessage += u": "_ns;
171 if (aReport->message()) {
172 formattedMessage.Append(NS_ConvertUTF8toUTF16(aReport->message().c_str()));
173 }
174 formattedMessage += u" ["_ns;
175 formattedMessage.Append(aReport->linebuf(), aReport->linebufLength());
176 formattedMessage += u"]"_ns;
177 PACLogToConsole(formattedMessage);
178 }
179
PACWarningReporter(JSContext * aCx,JSErrorReport * aReport)180 static void PACWarningReporter(JSContext* aCx, JSErrorReport* aReport) {
181 MOZ_ASSERT(aReport);
182 MOZ_ASSERT(aReport->isWarning());
183
184 PACLogErrorOrWarning(u"Warning"_ns, aReport);
185 }
186
187 class MOZ_STACK_CLASS AutoPACErrorReporter {
188 JSContext* mCx;
189
190 public:
AutoPACErrorReporter(JSContext * aCx)191 explicit AutoPACErrorReporter(JSContext* aCx) : mCx(aCx) {}
~AutoPACErrorReporter()192 ~AutoPACErrorReporter() {
193 if (!JS_IsExceptionPending(mCx)) {
194 return;
195 }
196 JS::ExceptionStack exnStack(mCx);
197 if (!JS::StealPendingExceptionStack(mCx, &exnStack)) {
198 return;
199 }
200
201 JS::ErrorReportBuilder report(mCx);
202 if (!report.init(mCx, exnStack, JS::ErrorReportBuilder::WithSideEffects)) {
203 JS_ClearPendingException(mCx);
204 return;
205 }
206
207 PACLogErrorOrWarning(u"Error"_ns, report.report());
208 }
209 };
210
211 // timeout of 0 means the normal necko timeout strategy, otherwise the dns
212 // request will be canceled after aTimeout milliseconds
PACResolve(const nsCString & aHostName,NetAddr * aNetAddr,unsigned int aTimeout)213 static bool PACResolve(const nsCString& aHostName, NetAddr* aNetAddr,
214 unsigned int aTimeout) {
215 if (!GetRunning()) {
216 NS_WARNING("PACResolve without a running ProxyAutoConfig object");
217 return false;
218 }
219
220 return GetRunning()->ResolveAddress(aHostName, aNetAddr, aTimeout);
221 }
222
ProxyAutoConfig()223 ProxyAutoConfig::ProxyAutoConfig()
224
225 {
226 MOZ_COUNT_CTOR(ProxyAutoConfig);
227 }
228
ResolveAddress(const nsCString & aHostName,NetAddr * aNetAddr,unsigned int aTimeout)229 bool ProxyAutoConfig::ResolveAddress(const nsCString& aHostName,
230 NetAddr* aNetAddr, unsigned int aTimeout) {
231 nsCOMPtr<nsIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID);
232 if (!dns) return false;
233
234 RefPtr<PACResolver> helper = new PACResolver(mMainThreadEventTarget);
235 OriginAttributes attrs;
236
237 // When the PAC script attempts to resolve a domain, we must make sure we
238 // don't use TRR, otherwise the TRR channel might also attempt to resolve
239 // a name and we'll have a deadlock.
240 uint32_t flags =
241 nsIDNSService::RESOLVE_PRIORITY_MEDIUM |
242 nsIDNSService::GetFlagsFromTRRMode(nsIRequest::TRR_DISABLED_MODE);
243
244 if (NS_FAILED(dns->AsyncResolveNative(
245 aHostName, nsIDNSService::RESOLVE_TYPE_DEFAULT, flags, nullptr,
246 helper, GetCurrentEventTarget(), attrs,
247 getter_AddRefs(helper->mRequest)))) {
248 return false;
249 }
250
251 if (aTimeout && helper->mRequest) {
252 if (!mTimer) mTimer = NS_NewTimer();
253 if (mTimer) {
254 mTimer->SetTarget(mMainThreadEventTarget);
255 mTimer->InitWithCallback(helper, aTimeout, nsITimer::TYPE_ONE_SHOT);
256 helper->mTimer = mTimer;
257 }
258 }
259
260 // Spin the event loop of the pac thread until lookup is complete.
261 // nsPACman is responsible for keeping a queue and only allowing
262 // one PAC execution at a time even when it is called re-entrantly.
263 SpinEventLoopUntil("ProxyAutoConfig::ResolveAddress"_ns, [&, helper, this]() {
264 if (!helper->mRequest) {
265 return true;
266 }
267 if (this->mShutdown) {
268 NS_WARNING("mShutdown set with PAC request not cancelled");
269 MOZ_ASSERT(NS_FAILED(helper->mStatus));
270 return true;
271 }
272 return false;
273 });
274
275 if (NS_FAILED(helper->mStatus)) {
276 return false;
277 }
278
279 nsCOMPtr<nsIDNSAddrRecord> rec = do_QueryInterface(helper->mResponse);
280 return !(!rec || NS_FAILED(rec->GetNextAddr(0, aNetAddr)));
281 }
282
PACResolveToString(const nsCString & aHostName,nsCString & aDottedDecimal,unsigned int aTimeout)283 static bool PACResolveToString(const nsCString& aHostName,
284 nsCString& aDottedDecimal,
285 unsigned int aTimeout) {
286 NetAddr netAddr;
287 if (!PACResolve(aHostName, &netAddr, aTimeout)) return false;
288
289 char dottedDecimal[128];
290 if (!netAddr.ToStringBuffer(dottedDecimal, sizeof(dottedDecimal))) {
291 return false;
292 }
293
294 aDottedDecimal.Assign(dottedDecimal);
295 return true;
296 }
297
298 // dnsResolve(host) javascript implementation
PACDnsResolve(JSContext * cx,unsigned int argc,JS::Value * vp)299 static bool PACDnsResolve(JSContext* cx, unsigned int argc, JS::Value* vp) {
300 JS::CallArgs args = CallArgsFromVp(argc, vp);
301
302 if (NS_IsMainThread()) {
303 NS_WARNING("DNS Resolution From PAC on Main Thread. How did that happen?");
304 return false;
305 }
306
307 if (!args.requireAtLeast(cx, "dnsResolve", 1)) return false;
308
309 // Previously we didn't check the type of the argument, so just converted it
310 // to string. A badly written PAC file oculd pass null or undefined here
311 // which could lead to odd results if there are any hosts called "null"
312 // on the network. See bug 1724345 comment 6.
313 if (!args[0].isString()) {
314 args.rval().setNull();
315 return true;
316 }
317
318 JS::RootedString arg1(cx);
319 arg1 = args[0].toString();
320
321 nsAutoJSString hostName;
322 nsAutoCString dottedDecimal;
323
324 if (!hostName.init(cx, arg1)) return false;
325 if (PACResolveToString(NS_ConvertUTF16toUTF8(hostName), dottedDecimal, 0)) {
326 JSString* dottedDecimalString = JS_NewStringCopyZ(cx, dottedDecimal.get());
327 if (!dottedDecimalString) {
328 return false;
329 }
330
331 args.rval().setString(dottedDecimalString);
332 } else {
333 args.rval().setNull();
334 }
335
336 return true;
337 }
338
339 // myIpAddress() javascript implementation
PACMyIpAddress(JSContext * cx,unsigned int argc,JS::Value * vp)340 static bool PACMyIpAddress(JSContext* cx, unsigned int argc, JS::Value* vp) {
341 JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
342
343 if (NS_IsMainThread()) {
344 NS_WARNING("DNS Resolution From PAC on Main Thread. How did that happen?");
345 return false;
346 }
347
348 if (!GetRunning()) {
349 NS_WARNING("PAC myIPAddress without a running ProxyAutoConfig object");
350 return false;
351 }
352
353 return GetRunning()->MyIPAddress(args);
354 }
355
356 // proxyAlert(msg) javascript implementation
PACProxyAlert(JSContext * cx,unsigned int argc,JS::Value * vp)357 static bool PACProxyAlert(JSContext* cx, unsigned int argc, JS::Value* vp) {
358 JS::CallArgs args = CallArgsFromVp(argc, vp);
359
360 if (!args.requireAtLeast(cx, "alert", 1)) return false;
361
362 JS::Rooted<JSString*> arg1(cx, JS::ToString(cx, args[0]));
363 if (!arg1) return false;
364
365 nsAutoJSString message;
366 if (!message.init(cx, arg1)) return false;
367
368 nsAutoString alertMessage;
369 alertMessage.AssignLiteral(u"PAC-alert: ");
370 alertMessage.Append(message);
371 PACLogToConsole(alertMessage);
372
373 args.rval().setUndefined(); /* return undefined */
374 return true;
375 }
376
377 static const JSFunctionSpec PACGlobalFunctions[] = {
378 JS_FN("dnsResolve", PACDnsResolve, 1, 0),
379
380 // a global "var pacUseMultihomedDNS = true;" will change behavior
381 // of myIpAddress to actively use DNS
382 JS_FN("myIpAddress", PACMyIpAddress, 0, 0),
383 JS_FN("alert", PACProxyAlert, 1, 0), JS_FS_END};
384
385 // JSContextWrapper is a c++ object that manages the context for the JS engine
386 // used on the PAC thread. It is initialized and destroyed on the PAC thread.
387 class JSContextWrapper {
388 public:
Create(uint32_t aExtraHeapSize)389 static JSContextWrapper* Create(uint32_t aExtraHeapSize) {
390 JSContext* cx = JS_NewContext(JS::DefaultHeapMaxBytes + aExtraHeapSize);
391 if (NS_WARN_IF(!cx)) return nullptr;
392
393 JS::ContextOptionsRef(cx).setDisableIon().setDisableEvalSecurityChecks();
394
395 JSContextWrapper* entry = new JSContextWrapper(cx);
396 if (NS_FAILED(entry->Init())) {
397 delete entry;
398 return nullptr;
399 }
400
401 return entry;
402 }
403
Context() const404 JSContext* Context() const { return mContext; }
405
Global() const406 JSObject* Global() const { return mGlobal; }
407
~JSContextWrapper()408 ~JSContextWrapper() {
409 mGlobal = nullptr;
410
411 MOZ_COUNT_DTOR(JSContextWrapper);
412
413 if (mContext) {
414 JS_DestroyContext(mContext);
415 }
416 }
417
SetOK()418 void SetOK() { mOK = true; }
419
IsOK()420 bool IsOK() { return mOK; }
421
422 private:
423 JSContext* mContext;
424 JS::PersistentRooted<JSObject*> mGlobal;
425 bool mOK;
426
427 static const JSClass sGlobalClass;
428
JSContextWrapper(JSContext * cx)429 explicit JSContextWrapper(JSContext* cx)
430 : mContext(cx), mGlobal(cx, nullptr), mOK(false) {
431 MOZ_COUNT_CTOR(JSContextWrapper);
432 }
433
Init()434 nsresult Init() {
435 /*
436 * Not setting this will cause JS_CHECK_RECURSION to report false
437 * positives
438 */
439 JS_SetNativeStackQuota(mContext, 128 * sizeof(size_t) * 1024);
440
441 JS::SetWarningReporter(mContext, PACWarningReporter);
442
443 // When available, set the self-hosted shared memory to be read, so that
444 // we can decode the self-hosted content instead of parsing it.
445 {
446 auto& shm = xpc::SelfHostedShmem::GetSingleton();
447 JS::SelfHostedCache selfHostedContent = shm.Content();
448
449 if (!JS::InitSelfHostedCode(mContext, selfHostedContent)) {
450 return NS_ERROR_OUT_OF_MEMORY;
451 }
452 }
453
454 JS::RealmOptions options;
455 options.creationOptions().setNewCompartmentInSystemZone();
456 options.behaviors().setClampAndJitterTime(false);
457 mGlobal = JS_NewGlobalObject(mContext, &sGlobalClass, nullptr,
458 JS::DontFireOnNewGlobalHook, options);
459 if (!mGlobal) {
460 JS_ClearPendingException(mContext);
461 return NS_ERROR_OUT_OF_MEMORY;
462 }
463 JS::Rooted<JSObject*> global(mContext, mGlobal);
464
465 JSAutoRealm ar(mContext, global);
466 AutoPACErrorReporter aper(mContext);
467 if (!JS_DefineFunctions(mContext, global, PACGlobalFunctions)) {
468 return NS_ERROR_FAILURE;
469 }
470
471 JS_FireOnNewGlobalObject(mContext, global);
472
473 return NS_OK;
474 }
475 };
476
477 const JSClass JSContextWrapper::sGlobalClass = {"PACResolutionThreadGlobal",
478 JSCLASS_GLOBAL_FLAGS,
479 &JS::DefaultGlobalClassOps};
480
SetThreadLocalIndex(uint32_t index)481 void ProxyAutoConfig::SetThreadLocalIndex(uint32_t index) {
482 RunningIndex() = index;
483 }
484
ConfigurePAC(const nsCString & aPACURI,const nsCString & aPACScriptData,bool aIncludePath,uint32_t aExtraHeapSize,nsIEventTarget * aEventTarget)485 nsresult ProxyAutoConfig::ConfigurePAC(const nsCString& aPACURI,
486 const nsCString& aPACScriptData,
487 bool aIncludePath,
488 uint32_t aExtraHeapSize,
489 nsIEventTarget* aEventTarget) {
490 mShutdown = false; // Shutdown needs to be called prior to destruction
491
492 mPACURI = aPACURI;
493
494 // The full PAC script data is the concatenation of 1) the various functions
495 // exposed to PAC scripts in |sAsciiPacUtils| and 2) the user-provided PAC
496 // script data. Historically this was single-byte Latin-1 text (usually just
497 // ASCII, but bug 296163 has a real-world Latin-1 example). We now support
498 // UTF-8 if the full data validates as UTF-8, before falling back to Latin-1.
499 // (Technically this is a breaking change: intentional Latin-1 scripts that
500 // happen to be valid UTF-8 may have different behavior. We assume such cases
501 // are vanishingly rare.)
502 //
503 // Supporting both UTF-8 and Latin-1 requires that the functions exposed to
504 // PAC scripts be both UTF-8- and Latin-1-compatible: that is, they must be
505 // ASCII.
506 mConcatenatedPACData = sAsciiPacUtils;
507 mConcatenatedPACData.Append(aPACScriptData);
508
509 mIncludePath = aIncludePath;
510 mExtraHeapSize = aExtraHeapSize;
511 mMainThreadEventTarget = aEventTarget;
512
513 if (!GetRunning()) return SetupJS();
514
515 mJSNeedsSetup = true;
516 return NS_OK;
517 }
518
SetupJS()519 nsresult ProxyAutoConfig::SetupJS() {
520 mJSNeedsSetup = false;
521 MOZ_ASSERT(!GetRunning(), "JIT is running");
522
523 #if defined(XP_MACOSX)
524 nsMacUtilsImpl::EnableTCSMIfAvailable();
525 #endif
526
527 delete mJSContext;
528 mJSContext = nullptr;
529
530 if (mConcatenatedPACData.IsEmpty()) return NS_ERROR_FAILURE;
531
532 NS_GetCurrentThread()->SetCanInvokeJS(true);
533
534 mJSContext = JSContextWrapper::Create(mExtraHeapSize);
535 if (!mJSContext) return NS_ERROR_FAILURE;
536
537 JSContext* cx = mJSContext->Context();
538 JSAutoRealm ar(cx, mJSContext->Global());
539 AutoPACErrorReporter aper(cx);
540
541 // check if this is a data: uri so that we don't spam the js console with
542 // huge meaningless strings. this is not on the main thread, so it can't
543 // use nsIURI scheme methods
544 bool isDataURI =
545 nsDependentCSubstring(mPACURI, 0, 5).LowerCaseEqualsASCII("data:", 5);
546
547 SetRunning(this);
548
549 JS::Rooted<JSObject*> global(cx, mJSContext->Global());
550
551 auto CompilePACScript = [this](JSContext* cx) -> JSScript* {
552 JS::CompileOptions options(cx);
553 options.setSkipFilenameValidation(true);
554 options.setFileAndLine(this->mPACURI.get(), 1);
555
556 // Per ProxyAutoConfig::Init, compile as UTF-8 if the full data is UTF-8,
557 // and otherwise inflate Latin-1 to UTF-16 and compile that.
558 const char* scriptData = this->mConcatenatedPACData.get();
559 size_t scriptLength = this->mConcatenatedPACData.Length();
560 if (mozilla::IsUtf8(mozilla::Span(scriptData, scriptLength))) {
561 JS::SourceText<Utf8Unit> srcBuf;
562 if (!srcBuf.init(cx, scriptData, scriptLength,
563 JS::SourceOwnership::Borrowed)) {
564 return nullptr;
565 }
566
567 return JS::Compile(cx, options, srcBuf);
568 }
569
570 // nsReadableUtils.h says that "ASCII" is a misnomer "for legacy reasons",
571 // and this handles not just ASCII but Latin-1 too.
572 NS_ConvertASCIItoUTF16 inflated(this->mConcatenatedPACData);
573
574 JS::SourceText<char16_t> source;
575 if (!source.init(cx, inflated.get(), inflated.Length(),
576 JS::SourceOwnership::Borrowed)) {
577 return nullptr;
578 }
579
580 return JS::Compile(cx, options, source);
581 };
582
583 JS::Rooted<JSScript*> script(cx, CompilePACScript(cx));
584 if (!script || !JS_ExecuteScript(cx, script)) {
585 nsString alertMessage(u"PAC file failed to install from "_ns);
586 if (isDataURI) {
587 alertMessage += u"data: URI"_ns;
588 } else {
589 alertMessage += NS_ConvertUTF8toUTF16(mPACURI);
590 }
591 PACLogToConsole(alertMessage);
592 SetRunning(nullptr);
593 return NS_ERROR_FAILURE;
594 }
595 SetRunning(nullptr);
596
597 mJSContext->SetOK();
598 nsString alertMessage(u"PAC file installed from "_ns);
599 if (isDataURI) {
600 alertMessage += u"data: URI"_ns;
601 } else {
602 alertMessage += NS_ConvertUTF8toUTF16(mPACURI);
603 }
604 PACLogToConsole(alertMessage);
605
606 // we don't need these now
607 mConcatenatedPACData.Truncate();
608 mPACURI.Truncate();
609
610 return NS_OK;
611 }
612
GetProxyForURIWithCallback(const nsCString & aTestURI,const nsCString & aTestHost,std::function<void (nsresult aStatus,const nsACString & aResult)> && aCallback)613 void ProxyAutoConfig::GetProxyForURIWithCallback(
614 const nsCString& aTestURI, const nsCString& aTestHost,
615 std::function<void(nsresult aStatus, const nsACString& aResult)>&&
616 aCallback) {
617 nsAutoCString result;
618 nsresult status = GetProxyForURI(aTestURI, aTestHost, result);
619 aCallback(status, result);
620 }
621
GetProxyForURI(const nsCString & aTestURI,const nsCString & aTestHost,nsACString & result)622 nsresult ProxyAutoConfig::GetProxyForURI(const nsCString& aTestURI,
623 const nsCString& aTestHost,
624 nsACString& result) {
625 if (mJSNeedsSetup) SetupJS();
626
627 if (!mJSContext || !mJSContext->IsOK()) return NS_ERROR_NOT_AVAILABLE;
628
629 JSContext* cx = mJSContext->Context();
630 JSAutoRealm ar(cx, mJSContext->Global());
631 AutoPACErrorReporter aper(cx);
632
633 // the sRunning flag keeps a new PAC file from being installed
634 // while the event loop is spinning on a DNS function. Don't early return.
635 SetRunning(this);
636 mRunningHost = aTestHost;
637
638 nsresult rv = NS_ERROR_FAILURE;
639 nsCString clensedURI = aTestURI;
640
641 if (!mIncludePath) {
642 nsCOMPtr<nsIURLParser> urlParser =
643 do_GetService(NS_STDURLPARSER_CONTRACTID);
644 int32_t pathLen = 0;
645 if (urlParser) {
646 uint32_t schemePos;
647 int32_t schemeLen;
648 uint32_t authorityPos;
649 int32_t authorityLen;
650 uint32_t pathPos;
651 rv = urlParser->ParseURL(aTestURI.get(), aTestURI.Length(), &schemePos,
652 &schemeLen, &authorityPos, &authorityLen,
653 &pathPos, &pathLen);
654 }
655 if (NS_SUCCEEDED(rv)) {
656 if (pathLen) {
657 // cut off the path but leave the initial slash
658 pathLen--;
659 }
660 aTestURI.Left(clensedURI, aTestURI.Length() - pathLen);
661 }
662 }
663
664 JS::RootedString uriString(cx, JS_NewStringCopyZ(cx, clensedURI.get()));
665 JS::RootedString hostString(cx, JS_NewStringCopyZ(cx, aTestHost.get()));
666
667 if (uriString && hostString) {
668 JS::RootedValueArray<2> args(cx);
669 args[0].setString(uriString);
670 args[1].setString(hostString);
671
672 JS::Rooted<JS::Value> rval(cx);
673 JS::Rooted<JSObject*> global(cx, mJSContext->Global());
674 bool ok = JS_CallFunctionName(cx, global, "FindProxyForURL", args, &rval);
675
676 if (ok && rval.isString()) {
677 nsAutoJSString pacString;
678 if (pacString.init(cx, rval.toString())) {
679 CopyUTF16toUTF8(pacString, result);
680 rv = NS_OK;
681 }
682 }
683 }
684
685 mRunningHost.Truncate();
686 SetRunning(nullptr);
687 return rv;
688 }
689
GC()690 void ProxyAutoConfig::GC() {
691 if (!mJSContext || !mJSContext->IsOK()) return;
692
693 JSAutoRealm ar(mJSContext->Context(), mJSContext->Global());
694 JS_MaybeGC(mJSContext->Context());
695 }
696
~ProxyAutoConfig()697 ProxyAutoConfig::~ProxyAutoConfig() {
698 MOZ_COUNT_DTOR(ProxyAutoConfig);
699 MOZ_ASSERT(mShutdown, "Shutdown must be called before dtor.");
700 NS_ASSERTION(!mJSContext,
701 "~ProxyAutoConfig leaking JS context that "
702 "should have been deleted on pac thread");
703 }
704
Shutdown()705 void ProxyAutoConfig::Shutdown() {
706 MOZ_ASSERT(!NS_IsMainThread(), "wrong thread for shutdown");
707
708 if (NS_WARN_IF(GetRunning()) || mShutdown) {
709 return;
710 }
711
712 mShutdown = true;
713 delete mJSContext;
714 mJSContext = nullptr;
715 }
716
SrcAddress(const NetAddr * remoteAddress,nsCString & localAddress)717 bool ProxyAutoConfig::SrcAddress(const NetAddr* remoteAddress,
718 nsCString& localAddress) {
719 PRFileDesc* fd;
720 fd = PR_OpenUDPSocket(remoteAddress->raw.family);
721 if (!fd) return false;
722
723 PRNetAddr prRemoteAddress;
724 NetAddrToPRNetAddr(remoteAddress, &prRemoteAddress);
725 if (PR_Connect(fd, &prRemoteAddress, 0) != PR_SUCCESS) {
726 PR_Close(fd);
727 return false;
728 }
729
730 PRNetAddr localName;
731 if (PR_GetSockName(fd, &localName) != PR_SUCCESS) {
732 PR_Close(fd);
733 return false;
734 }
735
736 PR_Close(fd);
737
738 char dottedDecimal[128];
739 if (PR_NetAddrToString(&localName, dottedDecimal, sizeof(dottedDecimal)) !=
740 PR_SUCCESS) {
741 return false;
742 }
743
744 localAddress.Assign(dottedDecimal);
745
746 return true;
747 }
748
749 // hostName is run through a dns lookup and then a udp socket is connected
750 // to the result. If that all works, the local IP address of the socket is
751 // returned to the javascript caller and |*aResult| is set to true. Otherwise
752 // |*aResult| is set to false.
MyIPAddressTryHost(const nsCString & hostName,unsigned int timeout,const JS::CallArgs & aArgs,bool * aResult)753 bool ProxyAutoConfig::MyIPAddressTryHost(const nsCString& hostName,
754 unsigned int timeout,
755 const JS::CallArgs& aArgs,
756 bool* aResult) {
757 *aResult = false;
758
759 NetAddr remoteAddress;
760 nsAutoCString localDottedDecimal;
761 JSContext* cx = mJSContext->Context();
762
763 if (PACResolve(hostName, &remoteAddress, timeout) &&
764 SrcAddress(&remoteAddress, localDottedDecimal)) {
765 JSString* dottedDecimalString =
766 JS_NewStringCopyZ(cx, localDottedDecimal.get());
767 if (!dottedDecimalString) {
768 return false;
769 }
770
771 *aResult = true;
772 aArgs.rval().setString(dottedDecimalString);
773 }
774 return true;
775 }
776
MyIPAddress(const JS::CallArgs & aArgs)777 bool ProxyAutoConfig::MyIPAddress(const JS::CallArgs& aArgs) {
778 nsAutoCString remoteDottedDecimal;
779 nsAutoCString localDottedDecimal;
780 JSContext* cx = mJSContext->Context();
781 JS::RootedValue v(cx);
782 JS::Rooted<JSObject*> global(cx, mJSContext->Global());
783
784 bool useMultihomedDNS =
785 JS_GetProperty(cx, global, "pacUseMultihomedDNS", &v) &&
786 !v.isUndefined() && ToBoolean(v);
787
788 // first, lookup the local address of a socket connected
789 // to the host of uri being resolved by the pac file. This is
790 // v6 safe.. but is the last step like that
791 bool rvalAssigned = false;
792 if (useMultihomedDNS) {
793 if (!MyIPAddressTryHost(mRunningHost, kTimeout, aArgs, &rvalAssigned) ||
794 rvalAssigned) {
795 return rvalAssigned;
796 }
797 } else {
798 // we can still do the fancy multi homing thing if the host is a literal
799 if (HostIsIPLiteral(mRunningHost) &&
800 (!MyIPAddressTryHost(mRunningHost, kTimeout, aArgs, &rvalAssigned) ||
801 rvalAssigned)) {
802 return rvalAssigned;
803 }
804 }
805
806 // next, look for a route to a public internet address that doesn't need DNS.
807 // This is the google anycast dns address, but it doesn't matter if it
808 // remains operable (as we don't contact it) as long as the address stays
809 // in commonly routed IP address space.
810 remoteDottedDecimal.AssignLiteral("8.8.8.8");
811 if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) ||
812 rvalAssigned) {
813 return rvalAssigned;
814 }
815
816 // finally, use the old algorithm based on the local hostname
817 nsAutoCString hostName;
818 nsCOMPtr<nsIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID);
819 // without multihomedDNS use such a short timeout that we are basically
820 // just looking at the cache for raw dotted decimals
821 uint32_t timeout = useMultihomedDNS ? kTimeout : 1;
822 if (dns && NS_SUCCEEDED(dns->GetMyHostName(hostName)) &&
823 PACResolveToString(hostName, localDottedDecimal, timeout)) {
824 JSString* dottedDecimalString =
825 JS_NewStringCopyZ(cx, localDottedDecimal.get());
826 if (!dottedDecimalString) {
827 return false;
828 }
829
830 aArgs.rval().setString(dottedDecimalString);
831 return true;
832 }
833
834 // next try a couple RFC 1918 variants.. maybe there is a
835 // local route
836 remoteDottedDecimal.AssignLiteral("192.168.0.1");
837 if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) ||
838 rvalAssigned) {
839 return rvalAssigned;
840 }
841
842 // more RFC 1918
843 remoteDottedDecimal.AssignLiteral("10.0.0.1");
844 if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) ||
845 rvalAssigned) {
846 return rvalAssigned;
847 }
848
849 // who knows? let's fallback to localhost
850 localDottedDecimal.AssignLiteral("127.0.0.1");
851 JSString* dottedDecimalString =
852 JS_NewStringCopyZ(cx, localDottedDecimal.get());
853 if (!dottedDecimalString) {
854 return false;
855 }
856
857 aArgs.rval().setString(dottedDecimalString);
858 return true;
859 }
860
861 RemoteProxyAutoConfig::RemoteProxyAutoConfig() = default;
862
863 RemoteProxyAutoConfig::~RemoteProxyAutoConfig() = default;
864
Init(nsIThread * aPACThread)865 nsresult RemoteProxyAutoConfig::Init(nsIThread* aPACThread) {
866 MOZ_ASSERT(NS_IsMainThread());
867
868 SocketProcessParent* socketProcessParent =
869 SocketProcessParent::GetSingleton();
870 if (!socketProcessParent) {
871 return NS_ERROR_NOT_AVAILABLE;
872 }
873
874 ipc::Endpoint<PProxyAutoConfigParent> parent;
875 ipc::Endpoint<PProxyAutoConfigChild> child;
876 nsresult rv = PProxyAutoConfig::CreateEndpoints(
877 base::GetCurrentProcId(), socketProcessParent->OtherPid(), &parent,
878 &child);
879 if (NS_FAILED(rv)) {
880 return rv;
881 }
882
883 Unused << socketProcessParent->SendInitProxyAutoConfigChild(std::move(child));
884 mProxyAutoConfigParent = new ProxyAutoConfigParent();
885 return aPACThread->Dispatch(
886 NS_NewRunnableFunction("ProxyAutoConfigParent::ProxyAutoConfigParent",
887 [proxyAutoConfigParent(mProxyAutoConfigParent),
888 endpoint{std::move(parent)}]() mutable {
889 proxyAutoConfigParent->Init(std::move(endpoint));
890 }));
891 }
892
ConfigurePAC(const nsCString & aPACURI,const nsCString & aPACScriptData,bool aIncludePath,uint32_t aExtraHeapSize,nsIEventTarget *)893 nsresult RemoteProxyAutoConfig::ConfigurePAC(const nsCString& aPACURI,
894 const nsCString& aPACScriptData,
895 bool aIncludePath,
896 uint32_t aExtraHeapSize,
897 nsIEventTarget*) {
898 Unused << mProxyAutoConfigParent->SendConfigurePAC(
899 aPACURI, aPACScriptData, aIncludePath, aExtraHeapSize);
900 return NS_OK;
901 }
902
Shutdown()903 void RemoteProxyAutoConfig::Shutdown() { mProxyAutoConfigParent->Close(); }
904
GC()905 void RemoteProxyAutoConfig::GC() {
906 // Do nothing. GC would be performed when there is not pending query in socket
907 // process.
908 }
909
GetProxyForURIWithCallback(const nsCString & aTestURI,const nsCString & aTestHost,std::function<void (nsresult aStatus,const nsACString & aResult)> && aCallback)910 void RemoteProxyAutoConfig::GetProxyForURIWithCallback(
911 const nsCString& aTestURI, const nsCString& aTestHost,
912 std::function<void(nsresult aStatus, const nsACString& aResult)>&&
913 aCallback) {
914 if (!mProxyAutoConfigParent->CanSend()) {
915 return;
916 }
917
918 mProxyAutoConfigParent->SendGetProxyForURI(
919 aTestURI, aTestHost,
920 [aCallback](Tuple<nsresult, nsCString>&& aResult) {
921 nsresult status;
922 nsCString result;
923 Tie(status, result) = aResult;
924 aCallback(status, result);
925 },
926 [aCallback](mozilla::ipc::ResponseRejectReason&& aReason) {
927 aCallback(NS_ERROR_FAILURE, ""_ns);
928 });
929 }
930
931 } // namespace net
932 } // namespace mozilla
933