Quellcode-Bibliothek ProxyAutoConfig.cpp
Sprache: C
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:set ts=2 sw=2 sts=2 et cindent: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifdefined(XP_MACOSX) # include "nsMacUtilsImpl.h" #endif
#include"XPCSelfHostedShmem.h"
namespace mozilla { namespace net {
// These are some global helper symbols the PAC format requires that we provide // that are initialized as part of the global javascript context used for PAC // evaluations. Additionally dnsResolve(host) and myIpAddress() are supplied in // the same context but are implemented as c++ helpers. alert(msg) is similarly // defined. // // Per ProxyAutoConfig::Init, this data must be ASCII.
// sRunning is defined for the helper functions only while the // Javascript engine is running and the PAC object cannot be deleted // or reset. static Atomic<uint32_t, Relaxed>& RunningIndex() { static Atomic<uint32_t, Relaxed> sRunningIndex(0xdeadbeef); return sRunningIndex;
} static ProxyAutoConfig* GetRunning() {
MOZ_ASSERT(RunningIndex() != 0xdeadbeef); returnstatic_cast<ProxyAutoConfig*>(PR_GetThreadPrivate(RunningIndex()));
}
// The PACResolver is used for dnsResolve() class PACResolver final : public nsIDNSListener, public nsITimerCallback, public nsINamed { public:
NS_DECL_THREADSAFE_ISUPPORTS
// timeout of 0 means the normal necko timeout strategy, otherwise the dns // request will be canceled after aTimeout milliseconds staticbool PACResolve(const nsACString& aHostName, NetAddr* aNetAddr, unsignedint aTimeout) { if (!GetRunning()) {
NS_WARNING("PACResolve without a running ProxyAutoConfig object"); returnfalse;
}
bool ProxyAutoConfig::ResolveAddress(const nsACString& aHostName,
NetAddr* aNetAddr, unsignedint aTimeout) {
nsCOMPtr<nsIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID); if (!dns) returnfalse;
RefPtr<PACResolver> helper = new PACResolver(mMainThreadEventTarget);
OriginAttributes attrs;
// When the PAC script attempts to resolve a domain, we must make sure we // don't use TRR, otherwise the TRR channel might also attempt to resolve // a name and we'll have a deadlock.
nsIDNSService::DNSFlags flags =
nsIDNSService::RESOLVE_PRIORITY_MEDIUM |
nsIDNSService::GetFlagsFromTRRMode(nsIRequest::TRR_DISABLED_MODE);
if (aTimeout && helper->mRequest) { if (!mTimer) mTimer = NS_NewTimer(); if (mTimer) {
mTimer->SetTarget(mMainThreadEventTarget);
mTimer->InitWithCallback(helper, aTimeout, nsITimer::TYPE_ONE_SHOT);
helper->mTimer = mTimer;
}
}
// Spin the event loop of the pac thread until lookup is complete. // nsPACman is responsible for keeping a queue and only allowing // one PAC execution at a time even when it is called re-entrantly.
SpinEventLoopUntil("ProxyAutoConfig::ResolveAddress"_ns, [&, helper, this]() { if (!helper->mRequest) { returntrue;
} if (this->mShutdown) {
NS_WARNING("mShutdown set with PAC request not cancelled");
MOZ_ASSERT(NS_FAILED(helper->mStatus)); returntrue;
} returnfalse;
});
if (NS_IsMainThread()) {
NS_WARNING("DNS Resolution From PAC on Main Thread. How did that happen?"); returnfalse;
}
if (!args.requireAtLeast(cx, "dnsResolve", 1)) returnfalse;
// Previously we didn't check the type of the argument, so just converted it // to string. A badly written PAC file oculd pass null or undefined here // which could lead to odd results if there are any hosts called "null" // on the network. See bug 1724345 comment 6. if (!args[0].isString()) {
args.rval().setNull(); returntrue;
}
// a global "var pacUseMultihomedDNS = true;" will change behavior // of myIpAddress to actively use DNS
JS_FN("myIpAddress", PACMyIpAddress, 0, 0),
JS_FN("alert", PACProxyAlert, 1, 0), JS_FS_END};
// JSContextWrapper is a c++ object that manages the context for the JS engine // used on the PAC thread. It is initialized and destroyed on the PAC thread. class JSContextWrapper { public: static JSContextWrapper* Create(uint32_t aExtraHeapSize) {
JSContext* cx = JS_NewContext(JS::DefaultHeapMaxBytes + aExtraHeapSize); if (NS_WARN_IF(!cx)) return nullptr;
nsresult Init() { /* * Not setting this will cause JS_CHECK_RECURSION to report false * positives
*/
JS_SetNativeStackQuota(mContext, 128 * sizeof(size_t) * 1024);
// When available, set the self-hosted shared memory to be read, so that // we can decode the self-hosted content instead of parsing it.
{ auto& shm = xpc::SelfHostedShmem::GetSingleton();
JS::SelfHostedCache selfHostedContent = shm.Content();
if (!JS::InitSelfHostedCode(mContext, selfHostedContent)) { return NS_ERROR_OUT_OF_MEMORY;
}
}
nsresult ProxyAutoConfig::ConfigurePAC(const nsACString& aPACURI, const nsACString& aPACScriptData, bool aIncludePath,
uint32_t aExtraHeapSize,
nsISerialEventTarget* aEventTarget) {
mShutdown = false; // Shutdown needs to be called prior to destruction
mPACURI = aPACURI;
// The full PAC script data is the concatenation of 1) the various functions // exposed to PAC scripts in |sAsciiPacUtils| and 2) the user-provided PAC // script data. Historically this was single-byte Latin-1 text (usually just // ASCII, but bug 296163 has a real-world Latin-1 example). We now support // UTF-8 if the full data validates as UTF-8, before falling back to Latin-1. // (Technically this is a breaking change: intentional Latin-1 scripts that // happen to be valid UTF-8 may have different behavior. We assume such cases // are vanishingly rare.) // // Supporting both UTF-8 and Latin-1 requires that the functions exposed to // PAC scripts be both UTF-8- and Latin-1-compatible: that is, they must be // ASCII.
mConcatenatedPACData = sAsciiPacUtils; if (!mConcatenatedPACData.Append(aPACScriptData, mozilla::fallible)) { return NS_ERROR_OUT_OF_MEMORY;
}
// check if this is a data: uri so that we don't spam the js console with // huge meaningless strings. this is not on the main thread, so it can't // use nsIURI scheme methods bool isDataURI =
nsDependentCSubstring(mPACURI, 0, 5).LowerCaseEqualsASCII("data:", 5);
// Per ProxyAutoConfig::Init, compile as UTF-8 if the full data is UTF-8, // and otherwise inflate Latin-1 to UTF-16 and compile that. constchar* scriptData = this->mConcatenatedPACData.get();
size_t scriptLength = this->mConcatenatedPACData.Length(); if (mozilla::IsUtf8(mozilla::Span(scriptData, scriptLength))) {
JS::SourceText<Utf8Unit> srcBuf; if (!srcBuf.init(cx, scriptData, scriptLength,
JS::SourceOwnership::Borrowed)) { return nullptr;
}
return JS::Compile(cx, options, srcBuf);
}
// nsReadableUtils.h says that "ASCII" is a misnomer "for legacy reasons", // and this handles not just ASCII but Latin-1 too.
NS_ConvertASCIItoUTF16 inflated(this->mConcatenatedPACData);
// the sRunning flag keeps a new PAC file from being installed // while the event loop is spinning on a DNS function. Don't early return.
SetRunning(this);
mRunningHost = aTestHost;
ProxyAutoConfig::~ProxyAutoConfig() {
MOZ_COUNT_DTOR(ProxyAutoConfig);
MOZ_ASSERT(mShutdown, "Shutdown must be called before dtor.");
NS_ASSERTION(!mJSContext, "~ProxyAutoConfig leaking JS context that " "should have been deleted on pac thread");
}
void ProxyAutoConfig::Shutdown() {
MOZ_ASSERT(!NS_IsMainThread(), "wrong thread for shutdown");
if (NS_WARN_IF(GetRunning()) || mShutdown) { return;
}
// hostName is run through a dns lookup and then a udp socket is connected // to the result. If that all works, the local IP address of the socket is // returned to the javascript caller and |*aResult| is set to true. Otherwise // |*aResult| is set to false. bool ProxyAutoConfig::MyIPAddressTryHost(const nsACString& hostName, unsignedint timeout, const JS::CallArgs& aArgs, bool* aResult) {
*aResult = false;
// first, lookup the local address of a socket connected // to the host of uri being resolved by the pac file. This is // v6 safe.. but is the last step like that bool rvalAssigned = false; if (useMultihomedDNS) { if (!MyIPAddressTryHost(mRunningHost, kTimeout, aArgs, &rvalAssigned) ||
rvalAssigned) { return rvalAssigned;
}
} else { // we can still do the fancy multi homing thing if the host is a literal if (HostIsIPLiteral(mRunningHost) &&
(!MyIPAddressTryHost(mRunningHost, kTimeout, aArgs, &rvalAssigned) ||
rvalAssigned)) { return rvalAssigned;
}
}
// next, look for a route to a public internet address that doesn't need DNS. // This is the google anycast dns address, but it doesn't matter if it // remains operable (as we don't contact it) as long as the address stays // in commonly routed IP address space.
remoteDottedDecimal.AssignLiteral("8.8.8.8"); if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) ||
rvalAssigned) { return rvalAssigned;
}
// finally, use the old algorithm based on the local hostname
nsAutoCString hostName;
nsCOMPtr<nsIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID); // without multihomedDNS use such a short timeout that we are basically // just looking at the cache for raw dotted decimals
uint32_t timeout = useMultihomedDNS ? kTimeout : 1; if (dns && NS_SUCCEEDED(dns->GetMyHostName(hostName)) &&
PACResolveToString(hostName, localDottedDecimal, timeout)) {
JSString* dottedDecimalString =
JS_NewStringCopyZ(cx, localDottedDecimal.get()); if (!dottedDecimalString) { returnfalse;
}
// next try a couple RFC 1918 variants.. maybe there is a // local route
remoteDottedDecimal.AssignLiteral("192.168.0.1"); if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) ||
rvalAssigned) { return rvalAssigned;
}
// more RFC 1918
remoteDottedDecimal.AssignLiteral("10.0.0.1"); if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) ||
rvalAssigned) { return rvalAssigned;
}
// who knows? let's fallback to localhost
localDottedDecimal.AssignLiteral("127.0.0.1");
JSString* dottedDecimalString =
JS_NewStringCopyZ(cx, localDottedDecimal.get()); if (!dottedDecimalString) { returnfalse;
}
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.60Bemerkung:
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.