Files
palemoon27/netwerk/base/ProxyAutoConfig.cpp
roytam1 7b6d9cb864 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1247982 - Lock request headers. r=mcmanus (8a5940a109)
- Bug 1251332 - add PAC support for reversed ranges; r=bagder (7ac8fd97cb)
- Bug 1178337 - Part 1: Supports all referrer policies for element atrributes. r=sicking, r=Gijs, r=mcmanus (85b7421b02)
- Bug 1187357 - rename referrer attribute to referrerpolicy in tests. r=hsivonen (da334bf712)
- Bug 1178337 - Part 2: Update/add test cases. r=sicking. (acec860fd8)
- Bug 1260766 - the comparison of OriginAttributes in nsFrameLoader::Swap* methods should consider the usercontextid attribute of the owning element, r=smaug (82f8895bec)
- bits of Bug 1110485 P1 (f8908eb35f)
- Bug 1195968 - Check how CanvasFilterChainObserver accesses the CanvasRenderingContext2D. r=mstange (eecc12329b)
- Bug 1260960 - Check skiaGL is enabled before calling skiaGLTex(), r=snorp (82c069fcc9)
- align test stuff (c0ccc11ed9)
- Bug 1245256 - GMP Plugins now installed in flat manner to accomodate widevine. r=spohl (ae0eb69979)
- Bug 1245649: Turn on use-isnan, no-unexpected-multiline (0633b3470f)
- Bug 1079665 - [e10s] Findbar focusContent doesn't work when a link was found. r=enndeakin (b349e62d5a)
- Bug 1174291 - Fix ctrl-return for e10s findbar. r=evilpie (6f0bf0b149)
- Bug 1174289 - Remove fake focus-ring after e10s findbar is closed. r=evilpie (302ffe7559)
- Bug 1079665 - follow up, remove accidental line included from different patch. r=me (0904fe927c)
- Bug 1260208 - part 1 - use C I/O facilities in TestWebGLElementArrayCache instead of C++ ones; r=BenWa The libc++ included with the Android NDK does not seem to work correctly with std::cerr; writing to it (or to std::cout, as confirmed by tests) causes the process to hang indefinitely, causing test failures.  Using fprintf and stderr, however, seems to work correctly. (4279c2d09d)
- Bug 1260208 - part 5 - add libc++ license to about:license when using it on Android; r=gerv,nalexander (4bcf23794a)
- Bug 1260208 - part 0 - correctly compare EHTable when sorting; r=froydnj operator< for EHTable compares the LHS start PC with the RHS *end* PC. Because the ranges are non-overlapping, this works fine for two distinct EHTables. However, the comparison doesn't work if LHS and RHS refer to the same EHTable; in that case operator< returns true, even though it should return false because the two operands are identical. (dc2af36cec)
- Bug 1254908 - ./mach bootstrap doesn't work on CentOS/Fedora when it attempts to upgrade Mercurial.  r=gps (d288b314ec)
- Bug 1239413. Clarify comment about the context flags. (c2b01ef6d1)
- Bug 1146875 - Fix the leak-gauge.html broken and add a encoding declaration. r=dbaron (8df2510774)
- Bug 1132499 - part 1 - convert nsTextEditorState::mValue to use Maybe instead of heap allocation; r=ehsan (2644faebbb)
- Bug 1132499 - part 2 - convert nsTextEditorState::mValue to be an nsString; r=ehsan (6e0df4d1dc)
- Bug 409885 - Use SetHostPort in nsHTMLDocument::SetDomain. r=bz (2d289a79c5)
- Bug 1269475 - Fix uninitialized variable warning. r=jdm (881fa29803)
- Bug 1263935 - Expose native version of mapURIToAddonId via amIAddonPathService. r=mossop (04da9fe703)
- Bug 1234974 - Handle null GetOwner() in |BluetoothAdapter::IsBluetoothCertifiedApp|, r=shuang (e4dde47d7f)
- Bug 1241117 - Fix mAppUuid access before assign in BluetoothGatt::Connect. r=joliu (3920535f2a)
- Bug 1238424 - Fix a missing header in Bluetooth module. r=brsun (438fd74375)
- Bug 1267958: Only complain for negative size, not merely zero. r=jrmuizel (194bd2a754)
- Bug 1320621 - Make sure --enable-system-hunspell picks up system headers. r=glandium (125c4ea215)
- Bug 1266430: Support offsets in DrawTargetD2D1::CopySurface when using PartialUploading. r=jrmuizel (de8630b117)
- Bug 1267363. Disable hinting on osx fonts only if we have expclity grayscale AA. r=mstange (c4c32fd7cc)
- Bug 1134549 - Switch FlattenBezier from floats to doubles. r=bas (5753ab16a3)
- Bug 1240437 part 2: Follow-up to fix implicit constrcutor static analysis failure. r=me (525d9d9a9f)
- Bug 1256678 - Backout diagnostic patch rev 39c895b67af2 - r=me (f63698de77)
- Bug 1256678 - Account for truncated font names in ScaledFontWin::GetFontFileData() - r=jfkthame (a6930e0a33)
- Bug 1256678 - Re-add nightly-only crash if ScaledFontWin::GetFontFileData fails to find a matching TrueType collection font - r=jfkthame (8bec2d43a2)
- Bug 1260350 - GFX: 2D: Use ConvolveHorizontally_LS3. r=jrmuizel (9d2f372593)
- Bug 1260112 - GFX: 2D: Fix unaligned access in ConvolveVertically/Horizontally_LS3. r=huangwenjun06 (43ba8f7b05)
- Bug 1260885 - Make SurfaceFormat::R5G6B5_UINT16 properly round-trip through SourceSurfaceCairo. r=lsalzman (bc8f0c0876)
- Bug 1262415 - make Accessible to keep weak pointers to parent and children, r=yzen (c0b987fe10)
- Bug 1267271 - skip empty surfaces in DrawTargetSkia::DrawSurfaceWithShadow. r=mchang (fd488c918a)
- Bug 1249600. Lookup font and font family from font face when requesting SkTypeface. r=bas (0281313c33)
- Bug 1268096. Sync the D3D11 rasterizer state if pointDrawMode or multisample changes. (25b2af8b26)
- Bug 1203132 - Add an SVG for the B2G flow of touch events. r=botond (2ce3b0ddc4)
- Bug 1180322. Add a document describing the history of layers (b3351dbba3)
- Bug 1235223. Update history document. (212d356bd0)
- Bug 1235223 - Fix typos in layers history document. (f19a5802d8)
- Bug 1235223 - Fix another typo in the layers history document. (9663fe5447)
- Bug 1265112 - Add support for NV_texture_barrier to GLContext. r=jrmuizel (f1f5fb1a3a)
- Bug 1240730 - Initialize all GLLibraryEGL symbols in the ctor. r=mattwoodrow (dae8955458)
- Bug 1240730 - Initialize all GLXLibrary members in the ctor. r=mattwoodrow (8218ed6fd9)
- bug 1250485 - make the ctor for GLXLibrary constexpr r=jrmuizel (a571491f0a)
- mitor spacing (0083550ab2)
- Bug 1256492 - Cast to proper width to avoid C4312 on VS2015; r=jrmuizel (1bb2ed20d3)
- Bug 1266878 - Fix off-by-one error in ParamTraits<StereoMode> - r=nical (f467d496b8)
- Bug 1258758 - rename GetEffectiveClipRect to GetLocalClipRect. r=kats (897798948f)
- Bug 1249936 - add a LayerComposite::GetShadowTransform method & simplify Layer::GetLocalTransform. r=botond (fe492a1327)
- Bug 1269032 - Add support for user multipliers to pan gesture inputs. r=mstange (ea7698dca2)
- Bug 1265510 - Add some scroll-snapping logging to APZC. r=botond (6f2369163a)
- Bug 1268523 - Avoid leaking tasks when they are posted to a destroyed APZC instance. r=botond (70e1e63b7b)
- Bug 1265510 - Ensure that new input blocks still allow APZCs with interrupted animations to scroll-snap. r=botond (01341b554b)
- Bug 1269068 - Zero out the axis velocity once the wheel scroll animation is terminating. r=botond (9a9f384485)
- Bug 1246056 - Ensure that the MockContentController's timestamp is always >= GetStartupTime(). r=botond (4fe53e1f24)
- Bug 1256341 - Add a gtest to catch scenarios where a tap timeout is interrupted by a non-touch block. r=botond (21a15f5a5a)
- Bug 1266833 - When the scroll position is clamped during a frame reconstruction, send a scroll offset update to APZ. r=tnikkel (c0acd70a3d)
- Bug 1268517 - Remove unused function. r=botond (534e4d9bae)
- Bug 1213095 - Fix APZEventState build with logging enabled. r=botond (ac7c1e9401)
- Bug 1250954 - Correct the SharedSurfaceTextureClient when forwarder changed. r=jgilbert (0a389bc0fa)
- Bug 1265873 - Use gfxSharedReadLock in TextureClientPool r=nical (e3ed936a8a)
- Bug 1265468 - Update the compositor pointer on all TextureSources in the list when recycling in ImageHost. r=nical (78f29244bb)
- Bug 1252237 - Remove the TextureHost shmem mapping failed assert. r=milan (d0b7230dff)
- Bug 1265112 - When rendering blend modes with CompositorOGL, use NV_texture_barrier (if available) to sample directly from the framebuffer. r=jrmuizel (6f3ae237a5)
- Bug 1268878 - Include various of gfxFontEntry's sub-objects in memory reporting. r=njn (b960415fa8)
- Bug 1268951 - Reallocate sanitized user font data into an appropriately-sized block, to reduce ongoing RAM footprint. r=jrmuizel (a26e9dd632)
- Bug 1123416 - Part 1: Make topsrcdir a valid Gradle project root. r=sebastian (77b0b35fc1)
- Bug 1260672: Remove 'nsAutoPtr.h' and clean up includes of Gonk diskspace watcher, r=gsvelto (99c4c35e3d)
- Bug 1167535 - Fix fanotify 4g size limit. r=fabrice (c62015e454)
- Bug 1167817 - Switch back to printf_stderr in GonkDiskSpaceWatcher.cpp r=dhylands (110445f628)
- Bug 1260672: Use |UniquePtr| for Gonk alarms, r=gsvelto (03678b9015)
- Bug 1260672: Use |UniquePtr| for Gonk sensors, r=gsvelto (545ec3fc70)
- Bug 1263845.  When a parent changes from auto height to non-auto height or vice versa, a percentage height non-block child needs to realize it's doing a vertical resize.  r=dbaron (05db492bc8)
- Bug 1268009 - If APZ is force-disabled, disable paint skipping even for apz-originated scrolls. r=kats (c02f8755cd)
- Bug 1267555 part 1 - [css-grid] Make grid-aligned abs.pos. descendants that span from 'auto' to the first/last line stretch to the outer edge of the first/last track respectively.  r=dholbert (88f6261043)
- Bug 1267555 part 2 - [css-grid] Adjust reftests for abs.pos. "auto/first-line" and "last-line/auto" change. (43d03ab15b)
2024-09-25 09:51:11 +08:00

1034 lines
29 KiB
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/. */
#include "ProxyAutoConfig.h"
#include "nsICancelable.h"
#include "nsIDNSListener.h"
#include "nsIDNSRecord.h"
#include "nsIDNSService.h"
#include "nsThreadUtils.h"
#include "nsIConsoleService.h"
#include "nsJSUtils.h"
#include "jsfriendapi.h"
#include "prnetdb.h"
#include "nsITimer.h"
#include "mozilla/net/DNS.h"
#include "nsServiceManagerUtils.h"
#include "nsNetCID.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.
static const char *sPacUtils =
"function dnsDomainIs(host, domain) {\n"
" return (host.length >= domain.length &&\n"
" host.substring(host.length - domain.length) == domain);\n"
"}\n"
""
"function dnsDomainLevels(host) {\n"
" return host.split('.').length - 1;\n"
"}\n"
""
"function convert_addr(ipchars) {\n"
" var bytes = ipchars.split('.');\n"
" var result = ((bytes[0] & 0xff) << 24) |\n"
" ((bytes[1] & 0xff) << 16) |\n"
" ((bytes[2] & 0xff) << 8) |\n"
" (bytes[3] & 0xff);\n"
" return result;\n"
"}\n"
""
"function isInNet(ipaddr, pattern, maskstr) {\n"
" var test = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(ipaddr);\n"
" if (test == null) {\n"
" ipaddr = dnsResolve(ipaddr);\n"
" if (ipaddr == null)\n"
" return false;\n"
" } else if (test[1] > 255 || test[2] > 255 || \n"
" test[3] > 255 || test[4] > 255) {\n"
" return false; // not an IP address\n"
" }\n"
" var host = convert_addr(ipaddr);\n"
" var pat = convert_addr(pattern);\n"
" var mask = convert_addr(maskstr);\n"
" return ((host & mask) == (pat & mask));\n"
" \n"
"}\n"
""
"function isPlainHostName(host) {\n"
" return (host.search('\\\\.') == -1);\n"
"}\n"
""
"function isResolvable(host) {\n"
" var ip = dnsResolve(host);\n"
" return (ip != null);\n"
"}\n"
""
"function localHostOrDomainIs(host, hostdom) {\n"
" return (host == hostdom) ||\n"
" (hostdom.lastIndexOf(host + '.', 0) == 0);\n"
"}\n"
""
"function shExpMatch(url, pattern) {\n"
" pattern = pattern.replace(/\\./g, '\\\\.');\n"
" pattern = pattern.replace(/\\*/g, '.*');\n"
" pattern = pattern.replace(/\\?/g, '.');\n"
" var newRe = new RegExp('^'+pattern+'$');\n"
" return newRe.test(url);\n"
"}\n"
""
"var wdays = {SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6};\n"
"var months = {JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11};\n"
""
"function weekdayRange() {\n"
" function getDay(weekday) {\n"
" if (weekday in wdays) {\n"
" return wdays[weekday];\n"
" }\n"
" return -1;\n"
" }\n"
" var date = new Date();\n"
" var argc = arguments.length;\n"
" var wday;\n"
" if (argc < 1)\n"
" return false;\n"
" if (arguments[argc - 1] == 'GMT') {\n"
" argc--;\n"
" wday = date.getUTCDay();\n"
" } else {\n"
" wday = date.getDay();\n"
" }\n"
" var wd1 = getDay(arguments[0]);\n"
" var wd2 = (argc == 2) ? getDay(arguments[1]) : wd1;\n"
" return (wd1 == -1 || wd2 == -1) ? false\n"
" : (wd1 <= wd2) ? (wd1 <= wday && wday <= wd2)\n"
" : (wd2 >= wday || wday >= wd1);\n"
"}\n"
""
"function dateRange() {\n"
" function getMonth(name) {\n"
" if (name in months) {\n"
" return months[name];\n"
" }\n"
" return -1;\n"
" }\n"
" var date = new Date();\n"
" var argc = arguments.length;\n"
" if (argc < 1) {\n"
" return false;\n"
" }\n"
" var isGMT = (arguments[argc - 1] == 'GMT');\n"
"\n"
" if (isGMT) {\n"
" argc--;\n"
" }\n"
" // function will work even without explict handling of this case\n"
" if (argc == 1) {\n"
" var tmp = parseInt(arguments[0]);\n"
" if (isNaN(tmp)) {\n"
" return ((isGMT ? date.getUTCMonth() : date.getMonth()) ==\n"
" getMonth(arguments[0]));\n"
" } else if (tmp < 32) {\n"
" return ((isGMT ? date.getUTCDate() : date.getDate()) == tmp);\n"
" } else { \n"
" return ((isGMT ? date.getUTCFullYear() : date.getFullYear()) ==\n"
" tmp);\n"
" }\n"
" }\n"
" var year = date.getFullYear();\n"
" var date1, date2;\n"
" date1 = new Date(year, 0, 1, 0, 0, 0);\n"
" date2 = new Date(year, 11, 31, 23, 59, 59);\n"
" var adjustMonth = false;\n"
" for (var i = 0; i < (argc >> 1); i++) {\n"
" var tmp = parseInt(arguments[i]);\n"
" if (isNaN(tmp)) {\n"
" var mon = getMonth(arguments[i]);\n"
" date1.setMonth(mon);\n"
" } else if (tmp < 32) {\n"
" adjustMonth = (argc <= 2);\n"
" date1.setDate(tmp);\n"
" } else {\n"
" date1.setFullYear(tmp);\n"
" }\n"
" }\n"
" for (var i = (argc >> 1); i < argc; i++) {\n"
" var tmp = parseInt(arguments[i]);\n"
" if (isNaN(tmp)) {\n"
" var mon = getMonth(arguments[i]);\n"
" date2.setMonth(mon);\n"
" } else if (tmp < 32) {\n"
" date2.setDate(tmp);\n"
" } else {\n"
" date2.setFullYear(tmp);\n"
" }\n"
" }\n"
" if (adjustMonth) {\n"
" date1.setMonth(date.getMonth());\n"
" date2.setMonth(date.getMonth());\n"
" }\n"
" if (isGMT) {\n"
" var tmp = date;\n"
" tmp.setFullYear(date.getUTCFullYear());\n"
" tmp.setMonth(date.getUTCMonth());\n"
" tmp.setDate(date.getUTCDate());\n"
" tmp.setHours(date.getUTCHours());\n"
" tmp.setMinutes(date.getUTCMinutes());\n"
" tmp.setSeconds(date.getUTCSeconds());\n"
" date = tmp;\n"
" }\n"
" return (date1 <= date2) ? (date1 <= date) && (date <= date2)\n"
" : (date2 >= date) || (date >= date1);\n"
"}\n"
""
"function timeRange() {\n"
" var argc = arguments.length;\n"
" var date = new Date();\n"
" var isGMT= false;\n"
""
" if (argc < 1) {\n"
" return false;\n"
" }\n"
" if (arguments[argc - 1] == 'GMT') {\n"
" isGMT = true;\n"
" argc--;\n"
" }\n"
"\n"
" var hour = isGMT ? date.getUTCHours() : date.getHours();\n"
" var date1, date2;\n"
" date1 = new Date();\n"
" date2 = new Date();\n"
"\n"
" if (argc == 1) {\n"
" return (hour == arguments[0]);\n"
" } else if (argc == 2) {\n"
" return ((arguments[0] <= hour) && (hour <= arguments[1]));\n"
" } else {\n"
" switch (argc) {\n"
" case 6:\n"
" date1.setSeconds(arguments[2]);\n"
" date2.setSeconds(arguments[5]);\n"
" case 4:\n"
" var middle = argc >> 1;\n"
" date1.setHours(arguments[0]);\n"
" date1.setMinutes(arguments[1]);\n"
" date2.setHours(arguments[middle]);\n"
" date2.setMinutes(arguments[middle + 1]);\n"
" if (middle == 2) {\n"
" date2.setSeconds(59);\n"
" }\n"
" break;\n"
" default:\n"
" throw 'timeRange: bad number of arguments'\n"
" }\n"
" }\n"
"\n"
" if (isGMT) {\n"
" date.setFullYear(date.getUTCFullYear());\n"
" date.setMonth(date.getUTCMonth());\n"
" date.setDate(date.getUTCDate());\n"
" date.setHours(date.getUTCHours());\n"
" date.setMinutes(date.getUTCMinutes());\n"
" date.setSeconds(date.getUTCSeconds());\n"
" }\n"
" return (date1 <= date2) ? (date1 <= date) && (date <= date2)\n"
" : (date2 >= date) || (date >= date1);\n"
"\n"
"}\n"
"";
// sRunning is defined for the helper functions only while the
// Javascript engine is running and the PAC object cannot be deleted
// or reset.
static uint32_t sRunningIndex = 0xdeadbeef;
static ProxyAutoConfig *GetRunning()
{
MOZ_ASSERT(sRunningIndex != 0xdeadbeef);
return static_cast<ProxyAutoConfig *>(PR_GetThreadPrivate(sRunningIndex));
}
static void SetRunning(ProxyAutoConfig *arg)
{
MOZ_ASSERT(sRunningIndex != 0xdeadbeef);
PR_SetThreadPrivate(sRunningIndex, arg);
}
// The PACResolver is used for dnsResolve()
class PACResolver final : public nsIDNSListener
, public nsITimerCallback
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
PACResolver()
: mStatus(NS_ERROR_FAILURE)
{
}
// nsIDNSListener
NS_IMETHODIMP OnLookupComplete(nsICancelable *request,
nsIDNSRecord *record,
nsresult status) override
{
if (mTimer) {
mTimer->Cancel();
mTimer = nullptr;
}
mRequest = nullptr;
mStatus = status;
mResponse = record;
return NS_OK;
}
// nsITimerCallback
NS_IMETHODIMP Notify(nsITimer *timer) override
{
if (mRequest)
mRequest->Cancel(NS_ERROR_NET_TIMEOUT);
mTimer = nullptr;
return NS_OK;
}
nsresult mStatus;
nsCOMPtr<nsICancelable> mRequest;
nsCOMPtr<nsIDNSRecord> mResponse;
nsCOMPtr<nsITimer> mTimer;
private:
~PACResolver() {}
};
NS_IMPL_ISUPPORTS(PACResolver, nsIDNSListener, nsITimerCallback)
static
void PACLogToConsole(nsString &aMessage)
{
nsCOMPtr<nsIConsoleService> consoleService =
do_GetService(NS_CONSOLESERVICE_CONTRACTID);
if (!consoleService)
return;
consoleService->LogStringMessage(aMessage.get());
}
// Javascript errors are logged to the main error console
static void
PACErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)
{
nsString formattedMessage(NS_LITERAL_STRING("PAC Execution Error: "));
formattedMessage += report->ucmessage;
formattedMessage += NS_LITERAL_STRING(" [");
formattedMessage.Append(report->linebuf(), report->linebufLength());
formattedMessage += NS_LITERAL_STRING("]");
PACLogToConsole(formattedMessage);
}
// timeout of 0 means the normal necko timeout strategy, otherwise the dns request
// will be canceled after aTimeout milliseconds
static
bool PACResolve(const nsCString &aHostName, NetAddr *aNetAddr,
unsigned int aTimeout)
{
if (!GetRunning()) {
NS_WARNING("PACResolve without a running ProxyAutoConfig object");
return false;
}
return GetRunning()->ResolveAddress(aHostName, aNetAddr, aTimeout);
}
ProxyAutoConfig::ProxyAutoConfig()
: mJSRuntime(nullptr)
, mJSNeedsSetup(false)
, mShutdown(false)
{
MOZ_COUNT_CTOR(ProxyAutoConfig);
}
bool
ProxyAutoConfig::ResolveAddress(const nsCString &aHostName,
NetAddr *aNetAddr,
unsigned int aTimeout)
{
nsCOMPtr<nsIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID);
if (!dns)
return false;
RefPtr<PACResolver> helper = new PACResolver();
if (NS_FAILED(dns->AsyncResolve(aHostName,
nsIDNSService::RESOLVE_PRIORITY_MEDIUM,
helper,
NS_GetCurrentThread(),
getter_AddRefs(helper->mRequest))))
return false;
if (aTimeout && helper->mRequest) {
if (!mTimer)
mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
if (mTimer) {
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.
while (helper->mRequest)
NS_ProcessNextEvent(NS_GetCurrentThread());
if (NS_FAILED(helper->mStatus) ||
NS_FAILED(helper->mResponse->GetNextAddr(0, aNetAddr)))
return false;
return true;
}
static
bool PACResolveToString(const nsCString &aHostName,
nsCString &aDottedDecimal,
unsigned int aTimeout)
{
NetAddr netAddr;
if (!PACResolve(aHostName, &netAddr, aTimeout))
return false;
char dottedDecimal[128];
if (!NetAddrToString(&netAddr, dottedDecimal, sizeof(dottedDecimal)))
return false;
aDottedDecimal.Assign(dottedDecimal);
return true;
}
// dnsResolve(host) javascript implementation
static
bool PACDnsResolve(JSContext *cx, unsigned int argc, JS::Value *vp)
{
JS::CallArgs args = CallArgsFromVp(argc, vp);
if (NS_IsMainThread()) {
NS_WARNING("DNS Resolution From PAC on Main Thread. How did that happen?");
return false;
}
if (!args.requireAtLeast(cx, "dnsResolve", 1))
return false;
JS::Rooted<JSString*> arg1(cx, JS::ToString(cx, args[0]));
if (!arg1)
return false;
nsAutoJSString hostName;
nsAutoCString dottedDecimal;
if (!hostName.init(cx, arg1))
return false;
if (PACResolveToString(NS_ConvertUTF16toUTF8(hostName), dottedDecimal, 0)) {
JSString *dottedDecimalString = JS_NewStringCopyZ(cx, dottedDecimal.get());
if (!dottedDecimalString) {
return false;
}
args.rval().setString(dottedDecimalString);
}
else {
args.rval().setNull();
}
return true;
}
// myIpAddress() javascript implementation
static
bool PACMyIpAddress(JSContext *cx, unsigned int argc, JS::Value *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (NS_IsMainThread()) {
NS_WARNING("DNS Resolution From PAC on Main Thread. How did that happen?");
return false;
}
if (!GetRunning()) {
NS_WARNING("PAC myIPAddress without a running ProxyAutoConfig object");
return false;
}
return GetRunning()->MyIPAddress(args);
}
// myAppId() javascript implementation
static
bool PACMyAppId(JSContext *cx, unsigned int argc, JS::Value *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (NS_IsMainThread()) {
NS_WARNING("PACMyAppId on Main Thread. How did that happen?");
return false;
}
if (!GetRunning()) {
NS_WARNING("PACMyAppId without a running ProxyAutoConfig object");
return false;
}
return GetRunning()->MyAppId(args);
}
// myAppOrigin() javascript implementation
static
bool PACMyAppOrigin(JSContext *cx, unsigned int argc, JS::Value *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (NS_IsMainThread()) {
NS_WARNING("PACMyAppOrigin on Main Thread. How did that happen?");
return false;
}
if (!GetRunning()) {
NS_WARNING("PACMyAppOrigin without a running ProxyAutoConfig object");
return false;
}
return GetRunning()->MyAppOrigin(args);
}
// IsInBrowser() javascript implementation
static
bool PACIsInBrowser(JSContext *cx, unsigned int argc, JS::Value *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (NS_IsMainThread()) {
NS_WARNING("PACIsInBrowser on Main Thread. How did that happen?");
return false;
}
if (!GetRunning()) {
NS_WARNING("PACIsInBrowser without a running ProxyAutoConfig object");
return false;
}
return GetRunning()->IsInBrowser(args);
}
// proxyAlert(msg) javascript implementation
static
bool PACProxyAlert(JSContext *cx, unsigned int argc, JS::Value *vp)
{
JS::CallArgs args = CallArgsFromVp(argc, vp);
if (!args.requireAtLeast(cx, "alert", 1))
return false;
JS::Rooted<JSString*> arg1(cx, JS::ToString(cx, args[0]));
if (!arg1)
return false;
nsAutoJSString message;
if (!message.init(cx, arg1))
return false;
nsAutoString alertMessage;
alertMessage.SetCapacity(32 + message.Length());
alertMessage += NS_LITERAL_STRING("PAC-alert: ");
alertMessage += message;
PACLogToConsole(alertMessage);
args.rval().setUndefined(); /* return undefined */
return true;
}
static const JSFunctionSpec PACGlobalFunctions[] = {
JS_FS("dnsResolve", PACDnsResolve, 1, 0),
// a global "var pacUseMultihomedDNS = true;" will change behavior
// of myIpAddress to actively use DNS
JS_FS("myIpAddress", PACMyIpAddress, 0, 0),
JS_FS("myAppId", PACMyAppId, 0, 0),
JS_FS("myAppOrigin", PACMyAppOrigin, 0, 0),
JS_FS("isInBrowser", PACIsInBrowser, 0, 0),
JS_FS("alert", PACProxyAlert, 1, 0),
JS_FS_END
};
// JSRuntimeWrapper is a c++ object that manages the runtime and context
// for the JS engine used on the PAC thread. It is initialized and destroyed
// on the PAC thread.
class JSRuntimeWrapper
{
public:
static JSRuntimeWrapper *Create()
{
JSRuntime *runtime = JS_NewRuntime(sRuntimeHeapSize);
if (NS_WARN_IF(!runtime))
return nullptr;
JSRuntimeWrapper *entry = new JSRuntimeWrapper(runtime);
if (NS_FAILED(entry->Init())) {
delete entry;
return nullptr;
}
return entry;
}
JSContext *Context() const
{
return mContext;
}
JSObject *Global() const
{
return mGlobal;
}
~JSRuntimeWrapper()
{
mGlobal = nullptr;
MOZ_COUNT_DTOR(JSRuntimeWrapper);
if (mContext) {
JS_DestroyContext(mContext);
}
if (mRuntime) {
JS_DestroyRuntime(mRuntime);
}
}
void SetOK()
{
mOK = true;
}
bool IsOK()
{
return mOK;
}
private:
static const unsigned sRuntimeHeapSize = 8 << 20; //8MB
JSRuntime *mRuntime;
JSContext *mContext;
JS::PersistentRooted<JSObject*> mGlobal;
bool mOK;
static const JSClass sGlobalClass;
explicit JSRuntimeWrapper(JSRuntime* rt)
: mRuntime(rt), mContext(nullptr), mGlobal(rt, nullptr), mOK(false)
{
MOZ_COUNT_CTOR(JSRuntimeWrapper);
}
nsresult Init()
{
/*
* Not setting this will cause JS_CHECK_RECURSION to report false
* positives
*/
JS_SetNativeStackQuota(mRuntime, 128 * sizeof(size_t) * 1024);
JS_SetErrorReporter(mRuntime, PACErrorReporter);
mContext = JS_NewContext(mRuntime, 0);
NS_ENSURE_TRUE(mContext, NS_ERROR_OUT_OF_MEMORY);
JSAutoRequest ar(mContext);
JS::CompartmentOptions options;
options.creationOptions().setZone(JS::SystemZone);
options.behaviors().setVersion(JSVERSION_LATEST);
mGlobal = JS_NewGlobalObject(mContext, &sGlobalClass, nullptr,
JS::DontFireOnNewGlobalHook, options);
NS_ENSURE_TRUE(mGlobal, NS_ERROR_OUT_OF_MEMORY);
JS::Rooted<JSObject*> global(mContext, mGlobal);
JSAutoCompartment ac(mContext, global);
JS_InitStandardClasses(mContext, global);
if (!JS_DefineFunctions(mContext, global, PACGlobalFunctions))
return NS_ERROR_FAILURE;
JS_FireOnNewGlobalObject(mContext, global);
return NS_OK;
}
};
static const JSClassOps sJSRuntimeWrapperGlobalClassOps = {
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr,
JS_GlobalObjectTraceHook
};
const JSClass JSRuntimeWrapper::sGlobalClass = {
"PACResolutionThreadGlobal",
JSCLASS_GLOBAL_FLAGS,
&sJSRuntimeWrapperGlobalClassOps
};
void
ProxyAutoConfig::SetThreadLocalIndex(uint32_t index)
{
sRunningIndex = index;
}
nsresult
ProxyAutoConfig::Init(const nsCString &aPACURI,
const nsCString &aPACScript)
{
mPACURI = aPACURI;
mPACScript = sPacUtils;
mPACScript.Append(aPACScript);
if (!GetRunning())
return SetupJS();
mJSNeedsSetup = true;
return NS_OK;
}
nsresult
ProxyAutoConfig::SetupJS()
{
mJSNeedsSetup = false;
MOZ_ASSERT(!GetRunning(), "JIT is running");
delete mJSRuntime;
mJSRuntime = nullptr;
if (mPACScript.IsEmpty())
return NS_ERROR_FAILURE;
mJSRuntime = JSRuntimeWrapper::Create();
if (!mJSRuntime)
return NS_ERROR_FAILURE;
JSContext* cx = mJSRuntime->Context();
JSAutoRequest ar(cx);
JSAutoCompartment ac(cx, mJSRuntime->Global());
// 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 nsIRUI scheme methods
bool isDataURI = nsDependentCSubstring(mPACURI, 0, 5).LowerCaseEqualsASCII("data:", 5);
SetRunning(this);
JS::Rooted<JSObject*> global(cx, mJSRuntime->Global());
JS::CompileOptions options(cx);
options.setFileAndLine(mPACURI.get(), 1);
JS::Rooted<JSScript*> script(cx);
if (!JS_CompileScript(cx, mPACScript.get(), mPACScript.Length(), options,
&script) ||
!JS_ExecuteScript(cx, script))
{
nsString alertMessage(NS_LITERAL_STRING("PAC file failed to install from "));
if (isDataURI) {
alertMessage += NS_LITERAL_STRING("data: URI");
}
else {
alertMessage += NS_ConvertUTF8toUTF16(mPACURI);
}
PACLogToConsole(alertMessage);
SetRunning(nullptr);
return NS_ERROR_FAILURE;
}
SetRunning(nullptr);
mJSRuntime->SetOK();
nsString alertMessage(NS_LITERAL_STRING("PAC file installed from "));
if (isDataURI) {
alertMessage += NS_LITERAL_STRING("data: URI");
}
else {
alertMessage += NS_ConvertUTF8toUTF16(mPACURI);
}
PACLogToConsole(alertMessage);
// we don't need these now
mPACScript.Truncate();
mPACURI.Truncate();
return NS_OK;
}
nsresult
ProxyAutoConfig::GetProxyForURI(const nsCString &aTestURI,
const nsCString &aTestHost,
uint32_t aAppId,
const nsString &aAppOrigin,
bool aIsInBrowser,
nsACString &result)
{
if (mJSNeedsSetup)
SetupJS();
if (!mJSRuntime || !mJSRuntime->IsOK())
return NS_ERROR_NOT_AVAILABLE;
JSContext *cx = mJSRuntime->Context();
JSAutoRequest ar(cx);
JSAutoCompartment ac(cx, mJSRuntime->Global());
// 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;
mRunningAppId = aAppId;
mRunningAppOrigin = aAppOrigin;
mRunningIsInBrowser = aIsInBrowser;
nsresult rv = NS_ERROR_FAILURE;
JS::RootedString uriString(cx, JS_NewStringCopyZ(cx, aTestURI.get()));
JS::RootedString hostString(cx, JS_NewStringCopyZ(cx, aTestHost.get()));
if (uriString && hostString) {
JS::AutoValueArray<2> args(cx);
args[0].setString(uriString);
args[1].setString(hostString);
JS::Rooted<JS::Value> rval(cx);
JS::Rooted<JSObject*> global(cx, mJSRuntime->Global());
bool ok = JS_CallFunctionName(cx, global, "FindProxyForURL", args, &rval);
if (ok && rval.isString()) {
nsAutoJSString pacString;
if (pacString.init(cx, rval.toString())) {
CopyUTF16toUTF8(pacString, result);
rv = NS_OK;
}
}
}
mRunningHost.Truncate();
SetRunning(nullptr);
return rv;
}
void
ProxyAutoConfig::GC()
{
if (!mJSRuntime || !mJSRuntime->IsOK())
return;
JSAutoCompartment ac(mJSRuntime->Context(), mJSRuntime->Global());
JS_MaybeGC(mJSRuntime->Context());
}
ProxyAutoConfig::~ProxyAutoConfig()
{
MOZ_COUNT_DTOR(ProxyAutoConfig);
NS_ASSERTION(!mJSRuntime,
"~ProxyAutoConfig leaking JS runtime that "
"should have been deleted on pac thread");
}
void
ProxyAutoConfig::Shutdown()
{
MOZ_ASSERT(!NS_IsMainThread(), "wrong thread for shutdown");
if (GetRunning() || mShutdown)
return;
mShutdown = true;
delete mJSRuntime;
mJSRuntime = nullptr;
}
bool
ProxyAutoConfig::SrcAddress(const NetAddr *remoteAddress, nsCString &localAddress)
{
PRFileDesc *fd;
fd = PR_OpenUDPSocket(remoteAddress->raw.family);
if (!fd)
return false;
PRNetAddr prRemoteAddress;
NetAddrToPRNetAddr(remoteAddress, &prRemoteAddress);
if (PR_Connect(fd, &prRemoteAddress, 0) != PR_SUCCESS) {
PR_Close(fd);
return false;
}
PRNetAddr localName;
if (PR_GetSockName(fd, &localName) != PR_SUCCESS) {
PR_Close(fd);
return false;
}
PR_Close(fd);
char dottedDecimal[128];
if (PR_NetAddrToString(&localName, dottedDecimal, sizeof(dottedDecimal)) != PR_SUCCESS)
return false;
localAddress.Assign(dottedDecimal);
return true;
}
// 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 nsCString &hostName,
unsigned int timeout,
const JS::CallArgs &aArgs,
bool* aResult)
{
*aResult = false;
NetAddr remoteAddress;
nsAutoCString localDottedDecimal;
JSContext *cx = mJSRuntime->Context();
if (PACResolve(hostName, &remoteAddress, timeout) &&
SrcAddress(&remoteAddress, localDottedDecimal)) {
JSString *dottedDecimalString =
JS_NewStringCopyZ(cx, localDottedDecimal.get());
if (!dottedDecimalString) {
return false;
}
*aResult = true;
aArgs.rval().setString(dottedDecimalString);
}
return true;
}
bool
ProxyAutoConfig::MyIPAddress(const JS::CallArgs &aArgs)
{
nsAutoCString remoteDottedDecimal;
nsAutoCString localDottedDecimal;
JSContext *cx = mJSRuntime->Context();
JS::RootedValue v(cx);
JS::Rooted<JSObject*> global(cx, mJSRuntime->Global());
bool useMultihomedDNS =
JS_GetProperty(cx, global, "pacUseMultihomedDNS", &v) &&
!v.isUndefined() && ToBoolean(v);
// 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
PRNetAddr tempAddr;
memset(&tempAddr, 0, sizeof(PRNetAddr));
if ((PR_StringToNetAddr(mRunningHost.get(), &tempAddr) == PR_SUCCESS) &&
(!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) {
return false;
}
aArgs.rval().setString(dottedDecimalString);
return true;
}
// 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) {
return false;
}
aArgs.rval().setString(dottedDecimalString);
return true;
}
bool
ProxyAutoConfig::MyAppId(const JS::CallArgs &aArgs)
{
aArgs.rval().setNumber(mRunningAppId);
return true;
}
bool
ProxyAutoConfig::MyAppOrigin(const JS::CallArgs &aArgs)
{
JSContext *cx = mJSRuntime->Context();
JSString *origin =
JS_NewStringCopyZ(cx, NS_ConvertUTF16toUTF8(mRunningAppOrigin).get());
if (!origin) {
return false;
}
aArgs.rval().setString(origin);
return true;
}
bool
ProxyAutoConfig::IsInBrowser(const JS::CallArgs &aArgs)
{
aArgs.rval().setBoolean(mRunningIsInBrowser);
return true;
}
} // namespace net
} // namespace mozilla