michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim:set ts=2 sw=2 sts=2 et cindent: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "ProxyAutoConfig.h" michael@0: #include "nsICancelable.h" michael@0: #include "nsIDNSListener.h" michael@0: #include "nsIDNSRecord.h" michael@0: #include "nsIDNSService.h" michael@0: #include "nsThreadUtils.h" michael@0: #include "nsIConsoleService.h" michael@0: #include "nsJSUtils.h" michael@0: #include "jsfriendapi.h" michael@0: #include "prnetdb.h" michael@0: #include "nsITimer.h" michael@0: #include "mozilla/net/DNS.h" michael@0: #include "nsServiceManagerUtils.h" michael@0: #include "nsNetCID.h" michael@0: michael@0: namespace mozilla { michael@0: namespace net { michael@0: michael@0: // These are some global helper symbols the PAC format requires that we provide that michael@0: // are initialized as part of the global javascript context used for PAC evaluations. michael@0: // Additionally dnsResolve(host) and myIpAddress() are supplied in the same context michael@0: // but are implemented as c++ helpers. alert(msg) is similarly defined. michael@0: michael@0: static const char *sPacUtils = michael@0: "function dnsDomainIs(host, domain) {\n" michael@0: " return (host.length >= domain.length &&\n" michael@0: " host.substring(host.length - domain.length) == domain);\n" michael@0: "}\n" michael@0: "" michael@0: "function dnsDomainLevels(host) {\n" michael@0: " return host.split('.').length - 1;\n" michael@0: "}\n" michael@0: "" michael@0: "function convert_addr(ipchars) {\n" michael@0: " var bytes = ipchars.split('.');\n" michael@0: " var result = ((bytes[0] & 0xff) << 24) |\n" michael@0: " ((bytes[1] & 0xff) << 16) |\n" michael@0: " ((bytes[2] & 0xff) << 8) |\n" michael@0: " (bytes[3] & 0xff);\n" michael@0: " return result;\n" michael@0: "}\n" michael@0: "" michael@0: "function isInNet(ipaddr, pattern, maskstr) {\n" michael@0: " var test = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(ipaddr);\n" michael@0: " if (test == null) {\n" michael@0: " ipaddr = dnsResolve(ipaddr);\n" michael@0: " if (ipaddr == null)\n" michael@0: " return false;\n" michael@0: " } else if (test[1] > 255 || test[2] > 255 || \n" michael@0: " test[3] > 255 || test[4] > 255) {\n" michael@0: " return false; // not an IP address\n" michael@0: " }\n" michael@0: " var host = convert_addr(ipaddr);\n" michael@0: " var pat = convert_addr(pattern);\n" michael@0: " var mask = convert_addr(maskstr);\n" michael@0: " return ((host & mask) == (pat & mask));\n" michael@0: " \n" michael@0: "}\n" michael@0: "" michael@0: "function isPlainHostName(host) {\n" michael@0: " return (host.search('\\\\.') == -1);\n" michael@0: "}\n" michael@0: "" michael@0: "function isResolvable(host) {\n" michael@0: " var ip = dnsResolve(host);\n" michael@0: " return (ip != null);\n" michael@0: "}\n" michael@0: "" michael@0: "function localHostOrDomainIs(host, hostdom) {\n" michael@0: " return (host == hostdom) ||\n" michael@0: " (hostdom.lastIndexOf(host + '.', 0) == 0);\n" michael@0: "}\n" michael@0: "" michael@0: "function shExpMatch(url, pattern) {\n" michael@0: " pattern = pattern.replace(/\\./g, '\\\\.');\n" michael@0: " pattern = pattern.replace(/\\*/g, '.*');\n" michael@0: " pattern = pattern.replace(/\\?/g, '.');\n" michael@0: " var newRe = new RegExp('^'+pattern+'$');\n" michael@0: " return newRe.test(url);\n" michael@0: "}\n" michael@0: "" michael@0: "var wdays = {SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6};\n" michael@0: "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" michael@0: "" michael@0: "function weekdayRange() {\n" michael@0: " function getDay(weekday) {\n" michael@0: " if (weekday in wdays) {\n" michael@0: " return wdays[weekday];\n" michael@0: " }\n" michael@0: " return -1;\n" michael@0: " }\n" michael@0: " var date = new Date();\n" michael@0: " var argc = arguments.length;\n" michael@0: " var wday;\n" michael@0: " if (argc < 1)\n" michael@0: " return false;\n" michael@0: " if (arguments[argc - 1] == 'GMT') {\n" michael@0: " argc--;\n" michael@0: " wday = date.getUTCDay();\n" michael@0: " } else {\n" michael@0: " wday = date.getDay();\n" michael@0: " }\n" michael@0: " var wd1 = getDay(arguments[0]);\n" michael@0: " var wd2 = (argc == 2) ? getDay(arguments[1]) : wd1;\n" michael@0: " return (wd1 == -1 || wd2 == -1) ? false\n" michael@0: " : (wd1 <= wday && wday <= wd2);\n" michael@0: "}\n" michael@0: "" michael@0: "function dateRange() {\n" michael@0: " function getMonth(name) {\n" michael@0: " if (name in months) {\n" michael@0: " return months[name];\n" michael@0: " }\n" michael@0: " return -1;\n" michael@0: " }\n" michael@0: " var date = new Date();\n" michael@0: " var argc = arguments.length;\n" michael@0: " if (argc < 1) {\n" michael@0: " return false;\n" michael@0: " }\n" michael@0: " var isGMT = (arguments[argc - 1] == 'GMT');\n" michael@0: "\n" michael@0: " if (isGMT) {\n" michael@0: " argc--;\n" michael@0: " }\n" michael@0: " // function will work even without explict handling of this case\n" michael@0: " if (argc == 1) {\n" michael@0: " var tmp = parseInt(arguments[0]);\n" michael@0: " if (isNaN(tmp)) {\n" michael@0: " return ((isGMT ? date.getUTCMonth() : date.getMonth()) ==\n" michael@0: " getMonth(arguments[0]));\n" michael@0: " } else if (tmp < 32) {\n" michael@0: " return ((isGMT ? date.getUTCDate() : date.getDate()) == tmp);\n" michael@0: " } else { \n" michael@0: " return ((isGMT ? date.getUTCFullYear() : date.getFullYear()) ==\n" michael@0: " tmp);\n" michael@0: " }\n" michael@0: " }\n" michael@0: " var year = date.getFullYear();\n" michael@0: " var date1, date2;\n" michael@0: " date1 = new Date(year, 0, 1, 0, 0, 0);\n" michael@0: " date2 = new Date(year, 11, 31, 23, 59, 59);\n" michael@0: " var adjustMonth = false;\n" michael@0: " for (var i = 0; i < (argc >> 1); i++) {\n" michael@0: " var tmp = parseInt(arguments[i]);\n" michael@0: " if (isNaN(tmp)) {\n" michael@0: " var mon = getMonth(arguments[i]);\n" michael@0: " date1.setMonth(mon);\n" michael@0: " } else if (tmp < 32) {\n" michael@0: " adjustMonth = (argc <= 2);\n" michael@0: " date1.setDate(tmp);\n" michael@0: " } else {\n" michael@0: " date1.setFullYear(tmp);\n" michael@0: " }\n" michael@0: " }\n" michael@0: " for (var i = (argc >> 1); i < argc; i++) {\n" michael@0: " var tmp = parseInt(arguments[i]);\n" michael@0: " if (isNaN(tmp)) {\n" michael@0: " var mon = getMonth(arguments[i]);\n" michael@0: " date2.setMonth(mon);\n" michael@0: " } else if (tmp < 32) {\n" michael@0: " date2.setDate(tmp);\n" michael@0: " } else {\n" michael@0: " date2.setFullYear(tmp);\n" michael@0: " }\n" michael@0: " }\n" michael@0: " if (adjustMonth) {\n" michael@0: " date1.setMonth(date.getMonth());\n" michael@0: " date2.setMonth(date.getMonth());\n" michael@0: " }\n" michael@0: " if (isGMT) {\n" michael@0: " var tmp = date;\n" michael@0: " tmp.setFullYear(date.getUTCFullYear());\n" michael@0: " tmp.setMonth(date.getUTCMonth());\n" michael@0: " tmp.setDate(date.getUTCDate());\n" michael@0: " tmp.setHours(date.getUTCHours());\n" michael@0: " tmp.setMinutes(date.getUTCMinutes());\n" michael@0: " tmp.setSeconds(date.getUTCSeconds());\n" michael@0: " date = tmp;\n" michael@0: " }\n" michael@0: " return ((date1 <= date) && (date <= date2));\n" michael@0: "}\n" michael@0: "" michael@0: "function timeRange() {\n" michael@0: " var argc = arguments.length;\n" michael@0: " var date = new Date();\n" michael@0: " var isGMT= false;\n" michael@0: "" michael@0: " if (argc < 1) {\n" michael@0: " return false;\n" michael@0: " }\n" michael@0: " if (arguments[argc - 1] == 'GMT') {\n" michael@0: " isGMT = true;\n" michael@0: " argc--;\n" michael@0: " }\n" michael@0: "\n" michael@0: " var hour = isGMT ? date.getUTCHours() : date.getHours();\n" michael@0: " var date1, date2;\n" michael@0: " date1 = new Date();\n" michael@0: " date2 = new Date();\n" michael@0: "\n" michael@0: " if (argc == 1) {\n" michael@0: " return (hour == arguments[0]);\n" michael@0: " } else if (argc == 2) {\n" michael@0: " return ((arguments[0] <= hour) && (hour <= arguments[1]));\n" michael@0: " } else {\n" michael@0: " switch (argc) {\n" michael@0: " case 6:\n" michael@0: " date1.setSeconds(arguments[2]);\n" michael@0: " date2.setSeconds(arguments[5]);\n" michael@0: " case 4:\n" michael@0: " var middle = argc >> 1;\n" michael@0: " date1.setHours(arguments[0]);\n" michael@0: " date1.setMinutes(arguments[1]);\n" michael@0: " date2.setHours(arguments[middle]);\n" michael@0: " date2.setMinutes(arguments[middle + 1]);\n" michael@0: " if (middle == 2) {\n" michael@0: " date2.setSeconds(59);\n" michael@0: " }\n" michael@0: " break;\n" michael@0: " default:\n" michael@0: " throw 'timeRange: bad number of arguments'\n" michael@0: " }\n" michael@0: " }\n" michael@0: "\n" michael@0: " if (isGMT) {\n" michael@0: " date.setFullYear(date.getUTCFullYear());\n" michael@0: " date.setMonth(date.getUTCMonth());\n" michael@0: " date.setDate(date.getUTCDate());\n" michael@0: " date.setHours(date.getUTCHours());\n" michael@0: " date.setMinutes(date.getUTCMinutes());\n" michael@0: " date.setSeconds(date.getUTCSeconds());\n" michael@0: " }\n" michael@0: " return ((date1 <= date) && (date <= date2));\n" michael@0: "}\n" michael@0: ""; michael@0: michael@0: // sRunning is defined for the helper functions only while the michael@0: // Javascript engine is running and the PAC object cannot be deleted michael@0: // or reset. michael@0: static ProxyAutoConfig *sRunning = nullptr; michael@0: michael@0: // The PACResolver is used for dnsResolve() michael@0: class PACResolver MOZ_FINAL : public nsIDNSListener michael@0: , public nsITimerCallback michael@0: { michael@0: public: michael@0: NS_DECL_THREADSAFE_ISUPPORTS michael@0: michael@0: PACResolver() michael@0: : mStatus(NS_ERROR_FAILURE) michael@0: { michael@0: } michael@0: michael@0: // nsIDNSListener michael@0: NS_IMETHODIMP OnLookupComplete(nsICancelable *request, michael@0: nsIDNSRecord *record, michael@0: nsresult status) michael@0: { michael@0: if (mTimer) { michael@0: mTimer->Cancel(); michael@0: mTimer = nullptr; michael@0: } michael@0: michael@0: mRequest = nullptr; michael@0: mStatus = status; michael@0: mResponse = record; michael@0: return NS_OK; michael@0: } michael@0: michael@0: // nsITimerCallback michael@0: NS_IMETHODIMP Notify(nsITimer *timer) michael@0: { michael@0: if (mRequest) michael@0: mRequest->Cancel(NS_ERROR_NET_TIMEOUT); michael@0: mTimer = nullptr; michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult mStatus; michael@0: nsCOMPtr mRequest; michael@0: nsCOMPtr mResponse; michael@0: nsCOMPtr mTimer; michael@0: }; michael@0: NS_IMPL_ISUPPORTS(PACResolver, nsIDNSListener, nsITimerCallback) michael@0: michael@0: static michael@0: void PACLogToConsole(nsString &aMessage) michael@0: { michael@0: nsCOMPtr consoleService = michael@0: do_GetService(NS_CONSOLESERVICE_CONTRACTID); michael@0: if (!consoleService) michael@0: return; michael@0: michael@0: consoleService->LogStringMessage(aMessage.get()); michael@0: } michael@0: michael@0: // Javascript errors are logged to the main error console michael@0: static void michael@0: PACErrorReporter(JSContext *cx, const char *message, JSErrorReport *report) michael@0: { michael@0: nsString formattedMessage(NS_LITERAL_STRING("PAC Execution Error: ")); michael@0: formattedMessage += report->ucmessage; michael@0: formattedMessage += NS_LITERAL_STRING(" ["); michael@0: formattedMessage += report->uclinebuf; michael@0: formattedMessage += NS_LITERAL_STRING("]"); michael@0: PACLogToConsole(formattedMessage); michael@0: } michael@0: michael@0: // timeout of 0 means the normal necko timeout strategy, otherwise the dns request michael@0: // will be canceled after aTimeout milliseconds michael@0: static michael@0: bool PACResolve(const nsCString &aHostName, NetAddr *aNetAddr, michael@0: unsigned int aTimeout) michael@0: { michael@0: if (!sRunning) { michael@0: NS_WARNING("PACResolve without a running ProxyAutoConfig object"); michael@0: return false; michael@0: } michael@0: michael@0: return sRunning->ResolveAddress(aHostName, aNetAddr, aTimeout); michael@0: } michael@0: michael@0: ProxyAutoConfig::ProxyAutoConfig() michael@0: : mJSRuntime(nullptr) michael@0: , mJSNeedsSetup(false) michael@0: , mShutdown(false) michael@0: { michael@0: MOZ_COUNT_CTOR(ProxyAutoConfig); michael@0: } michael@0: michael@0: bool michael@0: ProxyAutoConfig::ResolveAddress(const nsCString &aHostName, michael@0: NetAddr *aNetAddr, michael@0: unsigned int aTimeout) michael@0: { michael@0: nsCOMPtr dns = do_GetService(NS_DNSSERVICE_CONTRACTID); michael@0: if (!dns) michael@0: return false; michael@0: michael@0: nsRefPtr helper = new PACResolver(); michael@0: michael@0: if (NS_FAILED(dns->AsyncResolve(aHostName, michael@0: nsIDNSService::RESOLVE_PRIORITY_MEDIUM, michael@0: helper, michael@0: NS_GetCurrentThread(), michael@0: getter_AddRefs(helper->mRequest)))) michael@0: return false; michael@0: michael@0: if (aTimeout && helper->mRequest) { michael@0: if (!mTimer) michael@0: mTimer = do_CreateInstance(NS_TIMER_CONTRACTID); michael@0: if (mTimer) { michael@0: mTimer->InitWithCallback(helper, aTimeout, nsITimer::TYPE_ONE_SHOT); michael@0: helper->mTimer = mTimer; michael@0: } michael@0: } michael@0: michael@0: // Spin the event loop of the pac thread until lookup is complete. michael@0: // nsPACman is responsible for keeping a queue and only allowing michael@0: // one PAC execution at a time even when it is called re-entrantly. michael@0: while (helper->mRequest) michael@0: NS_ProcessNextEvent(NS_GetCurrentThread()); michael@0: michael@0: if (NS_FAILED(helper->mStatus) || michael@0: NS_FAILED(helper->mResponse->GetNextAddr(0, aNetAddr))) michael@0: return false; michael@0: return true; michael@0: } michael@0: michael@0: static michael@0: bool PACResolveToString(const nsCString &aHostName, michael@0: nsCString &aDottedDecimal, michael@0: unsigned int aTimeout) michael@0: { michael@0: NetAddr netAddr; michael@0: if (!PACResolve(aHostName, &netAddr, aTimeout)) michael@0: return false; michael@0: michael@0: char dottedDecimal[128]; michael@0: if (!NetAddrToString(&netAddr, dottedDecimal, sizeof(dottedDecimal))) michael@0: return false; michael@0: michael@0: aDottedDecimal.Assign(dottedDecimal); michael@0: return true; michael@0: } michael@0: michael@0: // dnsResolve(host) javascript implementation michael@0: static michael@0: bool PACDnsResolve(JSContext *cx, unsigned int argc, JS::Value *vp) michael@0: { michael@0: JS::CallArgs args = CallArgsFromVp(argc, vp); michael@0: michael@0: if (NS_IsMainThread()) { michael@0: NS_WARNING("DNS Resolution From PAC on Main Thread. How did that happen?"); michael@0: return false; michael@0: } michael@0: michael@0: JS::Rooted arg1(cx); michael@0: if (!JS_ConvertArguments(cx, args, "S", arg1.address())) michael@0: return false; michael@0: michael@0: nsDependentJSString hostName; michael@0: nsAutoCString dottedDecimal; michael@0: michael@0: if (!hostName.init(cx, arg1)) michael@0: return false; michael@0: if (PACResolveToString(NS_ConvertUTF16toUTF8(hostName), dottedDecimal, 0)) { michael@0: JSString *dottedDecimalString = JS_NewStringCopyZ(cx, dottedDecimal.get()); michael@0: if (!dottedDecimalString) { michael@0: return false; michael@0: } michael@0: michael@0: args.rval().setString(dottedDecimalString); michael@0: } michael@0: else { michael@0: args.rval().setNull(); michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: // myIpAddress() javascript implementation michael@0: static michael@0: bool PACMyIpAddress(JSContext *cx, unsigned int argc, JS::Value *vp) michael@0: { michael@0: JS::CallArgs args = JS::CallArgsFromVp(argc, vp); michael@0: michael@0: if (NS_IsMainThread()) { michael@0: NS_WARNING("DNS Resolution From PAC on Main Thread. How did that happen?"); michael@0: return false; michael@0: } michael@0: michael@0: if (!sRunning) { michael@0: NS_WARNING("PAC myIPAddress without a running ProxyAutoConfig object"); michael@0: return false; michael@0: } michael@0: michael@0: return sRunning->MyIPAddress(args); michael@0: } michael@0: michael@0: // proxyAlert(msg) javascript implementation michael@0: static michael@0: bool PACProxyAlert(JSContext *cx, unsigned int argc, JS::Value *vp) michael@0: { michael@0: JS::CallArgs args = CallArgsFromVp(argc, vp); michael@0: michael@0: JS::Rooted arg1(cx); michael@0: if (!JS_ConvertArguments(cx, args, "S", arg1.address())) michael@0: return false; michael@0: michael@0: nsDependentJSString message; michael@0: if (!message.init(cx, arg1)) michael@0: return false; michael@0: michael@0: nsString alertMessage; michael@0: alertMessage.SetCapacity(32 + message.Length()); michael@0: alertMessage += NS_LITERAL_STRING("PAC-alert: "); michael@0: alertMessage += message; michael@0: PACLogToConsole(alertMessage); michael@0: michael@0: args.rval().setUndefined(); /* return undefined */ michael@0: return true; michael@0: } michael@0: michael@0: static const JSFunctionSpec PACGlobalFunctions[] = { michael@0: JS_FS("dnsResolve", PACDnsResolve, 1, 0), michael@0: JS_FS("myIpAddress", PACMyIpAddress, 0, 0), michael@0: JS_FS("alert", PACProxyAlert, 1, 0), michael@0: JS_FS_END michael@0: }; michael@0: michael@0: // JSRuntimeWrapper is a c++ object that manages the runtime and context michael@0: // for the JS engine used on the PAC thread. It is initialized and destroyed michael@0: // on the PAC thread. michael@0: class JSRuntimeWrapper michael@0: { michael@0: public: michael@0: static JSRuntimeWrapper *Create() michael@0: { michael@0: JSRuntimeWrapper *entry = new JSRuntimeWrapper(); michael@0: michael@0: if (NS_FAILED(entry->Init())) { michael@0: delete entry; michael@0: return nullptr; michael@0: } michael@0: michael@0: return entry; michael@0: } michael@0: michael@0: JSContext *Context() const michael@0: { michael@0: return mContext; michael@0: } michael@0: michael@0: JSObject *Global() const michael@0: { michael@0: return mGlobal; michael@0: } michael@0: michael@0: ~JSRuntimeWrapper() michael@0: { michael@0: MOZ_COUNT_DTOR(JSRuntimeWrapper); michael@0: if (mContext) { michael@0: JS_DestroyContext(mContext); michael@0: } michael@0: michael@0: if (mRuntime) { michael@0: JS_DestroyRuntime(mRuntime); michael@0: } michael@0: } michael@0: michael@0: void SetOK() michael@0: { michael@0: mOK = true; michael@0: } michael@0: michael@0: bool IsOK() michael@0: { michael@0: return mOK; michael@0: } michael@0: michael@0: private: michael@0: static const unsigned sRuntimeHeapSize = 2 << 20; michael@0: michael@0: JSRuntime *mRuntime; michael@0: JSContext *mContext; michael@0: JSObject *mGlobal; michael@0: bool mOK; michael@0: michael@0: static const JSClass sGlobalClass; michael@0: michael@0: JSRuntimeWrapper() michael@0: : mRuntime(nullptr), mContext(nullptr), mGlobal(nullptr), mOK(false) michael@0: { michael@0: MOZ_COUNT_CTOR(JSRuntimeWrapper); michael@0: } michael@0: michael@0: nsresult Init() michael@0: { michael@0: mRuntime = JS_NewRuntime(sRuntimeHeapSize, JS_NO_HELPER_THREADS); michael@0: NS_ENSURE_TRUE(mRuntime, NS_ERROR_OUT_OF_MEMORY); michael@0: michael@0: /* michael@0: * Not setting this will cause JS_CHECK_RECURSION to report false michael@0: * positives michael@0: */ michael@0: JS_SetNativeStackQuota(mRuntime, 128 * sizeof(size_t) * 1024); michael@0: michael@0: mContext = JS_NewContext(mRuntime, 0); michael@0: NS_ENSURE_TRUE(mContext, NS_ERROR_OUT_OF_MEMORY); michael@0: michael@0: JSAutoRequest ar(mContext); michael@0: michael@0: JS::CompartmentOptions options; michael@0: options.setZone(JS::SystemZone) michael@0: .setVersion(JSVERSION_LATEST); michael@0: mGlobal = JS_NewGlobalObject(mContext, &sGlobalClass, nullptr, michael@0: JS::DontFireOnNewGlobalHook, options); michael@0: NS_ENSURE_TRUE(mGlobal, NS_ERROR_OUT_OF_MEMORY); michael@0: JS::Rooted global(mContext, mGlobal); michael@0: michael@0: JSAutoCompartment ac(mContext, global); michael@0: js::SetDefaultObjectForContext(mContext, global); michael@0: JS_InitStandardClasses(mContext, global); michael@0: michael@0: JS_SetErrorReporter(mContext, PACErrorReporter); michael@0: michael@0: if (!JS_DefineFunctions(mContext, global, PACGlobalFunctions)) michael@0: return NS_ERROR_FAILURE; michael@0: michael@0: JS_FireOnNewGlobalObject(mContext, global); michael@0: michael@0: return NS_OK; michael@0: } michael@0: }; michael@0: michael@0: const JSClass JSRuntimeWrapper::sGlobalClass = { michael@0: "PACResolutionThreadGlobal", michael@0: JSCLASS_GLOBAL_FLAGS, michael@0: JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, michael@0: JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, michael@0: nullptr, nullptr, nullptr, nullptr, michael@0: JS_GlobalObjectTraceHook michael@0: }; michael@0: michael@0: nsresult michael@0: ProxyAutoConfig::Init(const nsCString &aPACURI, michael@0: const nsCString &aPACScript) michael@0: { michael@0: mPACURI = aPACURI; michael@0: mPACScript = sPacUtils; michael@0: mPACScript.Append(aPACScript); michael@0: michael@0: if (!sRunning) michael@0: return SetupJS(); michael@0: michael@0: mJSNeedsSetup = true; michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult michael@0: ProxyAutoConfig::SetupJS() michael@0: { michael@0: mJSNeedsSetup = false; michael@0: NS_ABORT_IF_FALSE(!sRunning, "JIT is running"); michael@0: michael@0: delete mJSRuntime; michael@0: mJSRuntime = nullptr; michael@0: michael@0: if (mPACScript.IsEmpty()) michael@0: return NS_ERROR_FAILURE; michael@0: michael@0: mJSRuntime = JSRuntimeWrapper::Create(); michael@0: if (!mJSRuntime) michael@0: return NS_ERROR_FAILURE; michael@0: michael@0: JSContext* cx = mJSRuntime->Context(); michael@0: JSAutoRequest ar(cx); michael@0: JSAutoCompartment ac(cx, mJSRuntime->Global()); michael@0: michael@0: // check if this is a data: uri so that we don't spam the js console with michael@0: // huge meaningless strings. this is not on the main thread, so it can't michael@0: // use nsIRUI scheme methods michael@0: bool isDataURI = nsDependentCSubstring(mPACURI, 0, 5).LowerCaseEqualsASCII("data:", 5); michael@0: michael@0: sRunning = this; michael@0: JS::Rooted global(cx, mJSRuntime->Global()); michael@0: JS::CompileOptions options(cx); michael@0: options.setFileAndLine(mPACURI.get(), 1); michael@0: JS::Rooted script(cx, JS_CompileScript(cx, global, mPACScript.get(), michael@0: mPACScript.Length(), options)); michael@0: if (!script || !JS_ExecuteScript(cx, global, script)) { michael@0: nsString alertMessage(NS_LITERAL_STRING("PAC file failed to install from ")); michael@0: if (isDataURI) { michael@0: alertMessage += NS_LITERAL_STRING("data: URI"); michael@0: } michael@0: else { michael@0: alertMessage += NS_ConvertUTF8toUTF16(mPACURI); michael@0: } michael@0: PACLogToConsole(alertMessage); michael@0: sRunning = nullptr; michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: sRunning = nullptr; michael@0: michael@0: mJSRuntime->SetOK(); michael@0: nsString alertMessage(NS_LITERAL_STRING("PAC file installed from ")); michael@0: if (isDataURI) { michael@0: alertMessage += NS_LITERAL_STRING("data: URI"); michael@0: } michael@0: else { michael@0: alertMessage += NS_ConvertUTF8toUTF16(mPACURI); michael@0: } michael@0: PACLogToConsole(alertMessage); michael@0: michael@0: // we don't need these now michael@0: mPACScript.Truncate(); michael@0: mPACURI.Truncate(); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult michael@0: ProxyAutoConfig::GetProxyForURI(const nsCString &aTestURI, michael@0: const nsCString &aTestHost, michael@0: nsACString &result) michael@0: { michael@0: if (mJSNeedsSetup) michael@0: SetupJS(); michael@0: michael@0: if (!mJSRuntime || !mJSRuntime->IsOK()) michael@0: return NS_ERROR_NOT_AVAILABLE; michael@0: michael@0: JSContext *cx = mJSRuntime->Context(); michael@0: JSAutoRequest ar(cx); michael@0: JSAutoCompartment ac(cx, mJSRuntime->Global()); michael@0: michael@0: // the sRunning flag keeps a new PAC file from being installed michael@0: // while the event loop is spinning on a DNS function. Don't early return. michael@0: sRunning = this; michael@0: mRunningHost = aTestHost; michael@0: michael@0: nsresult rv = NS_ERROR_FAILURE; michael@0: JS::RootedString uriString(cx, JS_NewStringCopyZ(cx, aTestURI.get())); michael@0: JS::RootedString hostString(cx, JS_NewStringCopyZ(cx, aTestHost.get())); michael@0: michael@0: if (uriString && hostString) { michael@0: JS::AutoValueArray<2> args(cx); michael@0: args[0].setString(uriString); michael@0: args[1].setString(hostString); michael@0: michael@0: JS::Rooted rval(cx); michael@0: JS::Rooted global(cx, mJSRuntime->Global()); michael@0: bool ok = JS_CallFunctionName(cx, global, "FindProxyForURL", args, &rval); michael@0: michael@0: if (ok && rval.isString()) { michael@0: nsDependentJSString pacString; michael@0: if (pacString.init(cx, rval.toString())) { michael@0: CopyUTF16toUTF8(pacString, result); michael@0: rv = NS_OK; michael@0: } michael@0: } michael@0: } michael@0: michael@0: mRunningHost.Truncate(); michael@0: sRunning = nullptr; michael@0: return rv; michael@0: } michael@0: michael@0: void michael@0: ProxyAutoConfig::GC() michael@0: { michael@0: if (!mJSRuntime || !mJSRuntime->IsOK()) michael@0: return; michael@0: michael@0: JSAutoCompartment ac(mJSRuntime->Context(), mJSRuntime->Global()); michael@0: JS_MaybeGC(mJSRuntime->Context()); michael@0: } michael@0: michael@0: ProxyAutoConfig::~ProxyAutoConfig() michael@0: { michael@0: MOZ_COUNT_DTOR(ProxyAutoConfig); michael@0: NS_ASSERTION(!mJSRuntime, michael@0: "~ProxyAutoConfig leaking JS runtime that " michael@0: "should have been deleted on pac thread"); michael@0: } michael@0: michael@0: void michael@0: ProxyAutoConfig::Shutdown() michael@0: { michael@0: NS_ABORT_IF_FALSE(!NS_IsMainThread(), "wrong thread for shutdown"); michael@0: michael@0: if (sRunning || mShutdown) michael@0: return; michael@0: michael@0: mShutdown = true; michael@0: delete mJSRuntime; michael@0: mJSRuntime = nullptr; michael@0: } michael@0: michael@0: bool michael@0: ProxyAutoConfig::SrcAddress(const NetAddr *remoteAddress, nsCString &localAddress) michael@0: { michael@0: PRFileDesc *fd; michael@0: fd = PR_OpenUDPSocket(remoteAddress->raw.family); michael@0: if (!fd) michael@0: return false; michael@0: michael@0: PRNetAddr prRemoteAddress; michael@0: NetAddrToPRNetAddr(remoteAddress, &prRemoteAddress); michael@0: if (PR_Connect(fd, &prRemoteAddress, 0) != PR_SUCCESS) { michael@0: PR_Close(fd); michael@0: return false; michael@0: } michael@0: michael@0: PRNetAddr localName; michael@0: if (PR_GetSockName(fd, &localName) != PR_SUCCESS) { michael@0: PR_Close(fd); michael@0: return false; michael@0: } michael@0: michael@0: PR_Close(fd); michael@0: michael@0: char dottedDecimal[128]; michael@0: if (PR_NetAddrToString(&localName, dottedDecimal, sizeof(dottedDecimal)) != PR_SUCCESS) michael@0: return false; michael@0: michael@0: localAddress.Assign(dottedDecimal); michael@0: michael@0: return true; michael@0: } michael@0: michael@0: // hostName is run through a dns lookup and then a udp socket is connected michael@0: // to the result. If that all works, the local IP address of the socket is michael@0: // returned to the javascript caller and |*aResult| is set to true. Otherwise michael@0: // |*aResult| is set to false. michael@0: bool michael@0: ProxyAutoConfig::MyIPAddressTryHost(const nsCString &hostName, michael@0: unsigned int timeout, michael@0: const JS::CallArgs &aArgs, michael@0: bool* aResult) michael@0: { michael@0: *aResult = false; michael@0: michael@0: NetAddr remoteAddress; michael@0: nsAutoCString localDottedDecimal; michael@0: JSContext *cx = mJSRuntime->Context(); michael@0: michael@0: if (PACResolve(hostName, &remoteAddress, timeout) && michael@0: SrcAddress(&remoteAddress, localDottedDecimal)) { michael@0: JSString *dottedDecimalString = michael@0: JS_NewStringCopyZ(cx, localDottedDecimal.get()); michael@0: if (!dottedDecimalString) { michael@0: return false; michael@0: } michael@0: michael@0: *aResult = true; michael@0: aArgs.rval().setString(dottedDecimalString); michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: bool michael@0: ProxyAutoConfig::MyIPAddress(const JS::CallArgs &aArgs) michael@0: { michael@0: nsAutoCString remoteDottedDecimal; michael@0: nsAutoCString localDottedDecimal; michael@0: JSContext *cx = mJSRuntime->Context(); michael@0: michael@0: // first, lookup the local address of a socket connected michael@0: // to the host of uri being resolved by the pac file. This is michael@0: // v6 safe.. but is the last step like that michael@0: bool rvalAssigned = false; michael@0: if (!MyIPAddressTryHost(mRunningHost, kTimeout, aArgs, &rvalAssigned) || michael@0: rvalAssigned) { michael@0: return rvalAssigned; michael@0: } michael@0: michael@0: // next, look for a route to a public internet address that doesn't need DNS. michael@0: // This is the google anycast dns address, but it doesn't matter if it michael@0: // remains operable (as we don't contact it) as long as the address stays michael@0: // in commonly routed IP address space. michael@0: remoteDottedDecimal.AssignLiteral("8.8.8.8"); michael@0: if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) || michael@0: rvalAssigned) { michael@0: return rvalAssigned; michael@0: } michael@0: michael@0: // next, use the old algorithm based on the local hostname michael@0: nsAutoCString hostName; michael@0: nsCOMPtr dns = do_GetService(NS_DNSSERVICE_CONTRACTID); michael@0: if (dns && NS_SUCCEEDED(dns->GetMyHostName(hostName)) && michael@0: PACResolveToString(hostName, localDottedDecimal, kTimeout)) { michael@0: JSString *dottedDecimalString = michael@0: JS_NewStringCopyZ(cx, localDottedDecimal.get()); michael@0: if (!dottedDecimalString) { michael@0: return false; michael@0: } michael@0: michael@0: aArgs.rval().setString(dottedDecimalString); michael@0: return true; michael@0: } michael@0: michael@0: // next try a couple RFC 1918 variants.. maybe there is a michael@0: // local route michael@0: remoteDottedDecimal.AssignLiteral("192.168.0.1"); michael@0: if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) || michael@0: rvalAssigned) { michael@0: return rvalAssigned; michael@0: } michael@0: michael@0: // more RFC 1918 michael@0: remoteDottedDecimal.AssignLiteral("10.0.0.1"); michael@0: if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) || michael@0: rvalAssigned) { michael@0: return rvalAssigned; michael@0: } michael@0: michael@0: // who knows? let's fallback to localhost michael@0: localDottedDecimal.AssignLiteral("127.0.0.1"); michael@0: JSString *dottedDecimalString = michael@0: JS_NewStringCopyZ(cx, localDottedDecimal.get()); michael@0: if (!dottedDecimalString) { michael@0: return false; michael@0: } michael@0: michael@0: aArgs.rval().setString(dottedDecimalString); michael@0: return true; michael@0: } michael@0: michael@0: } // namespace mozilla michael@0: } // namespace mozilla::net